@opencoredev/sandbox-sdk 1.0.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +9 -6
- package/dist/ai.js +1 -1
- package/dist/chunk-0eeyc0aq.js +4 -0
- package/dist/chunk-0wp6x4wb.js +2 -0
- package/dist/chunk-2999xbh7.js +2 -0
- package/dist/chunk-3h6c1ack.js +2 -0
- package/dist/{chunk-q5vqajhg.js → chunk-7rkcx5cx.js} +2 -2
- package/dist/{chunk-hzbssbep.js → chunk-7s9pxk1v.js} +4 -4
- package/dist/chunk-aek8n3a4.js +78 -0
- package/dist/{chunk-8786zrns.js → chunk-aq6fmgdx.js} +2 -2
- package/dist/chunk-drhcb2hx.js +2 -0
- package/dist/chunk-ek44atpe.js +2 -0
- package/dist/chunk-g5n5xcmp.js +0 -0
- package/dist/chunk-kdecey83.js +290 -0
- package/dist/{chunk-bd481sb7.js → chunk-pdgnaxp9.js} +2 -2
- package/dist/{chunk-k60b4r27.js → chunk-qfhee1t8.js} +2 -2
- package/dist/chunk-rx9318sh.js +5 -0
- package/dist/chunk-sjnk17y5.js +26 -0
- package/dist/chunk-w8nk1xf2.js +17 -0
- package/dist/{chunk-bfzdkjjw.js → chunk-x05t86n3.js} +2 -2
- package/dist/{chunk-nw845a93.js → chunk-x4rrgmxf.js} +10 -10
- package/dist/chunk-xqtzts2q.js +1 -0
- package/dist/errors.d.ts +19 -9
- package/dist/files.d.ts +2 -5
- package/dist/http.d.ts +3 -0
- package/dist/index.d.ts +24 -3
- package/dist/index.js +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.js +1 -1
- package/dist/openai.js +1 -1
- package/dist/provider.d.ts +127 -7
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/baseten/errors.d.ts +6 -0
- package/dist/providers/baseten/execute.d.ts +68 -0
- package/dist/providers/baseten/index.d.ts +3 -0
- package/dist/providers/baseten/index.js +97 -0
- package/dist/providers/baseten/provider.d.ts +39 -0
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/errors.d.ts +25 -3
- package/dist/providers/boxd/index.js +14 -14
- package/dist/providers/boxd/provider.d.ts +16 -2
- package/dist/providers/daytona/api.d.ts +2 -2
- package/dist/providers/daytona/index.js +15 -15
- package/dist/providers/e2b/envd.d.ts +32 -2
- package/dist/providers/e2b/errors.d.ts +1 -2
- package/dist/providers/e2b/index.d.ts +40 -4
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/e2b/narrow.d.ts +7 -0
- package/dist/providers/freestyle/execute.d.ts +3 -1
- package/dist/providers/freestyle/index.js +7 -16
- package/dist/providers/instabox/api.d.ts +56 -0
- package/dist/providers/instabox/errors.d.ts +49 -0
- package/dist/providers/instabox/index.d.ts +4 -0
- package/dist/providers/instabox/index.js +7 -0
- package/dist/providers/instabox/provider.d.ts +28 -0
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/modal/errors.d.ts +4 -0
- package/dist/providers/modal/index.d.ts +14 -0
- package/dist/providers/modal/index.js +2 -0
- package/dist/providers/modal/provider.d.ts +94 -0
- package/dist/providers/modal/transport.d.ts +50 -0
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/execute.d.ts +3 -1
- package/dist/providers/superserve/index.js +22 -24
- package/dist/providers/tenki/deadline.d.ts +1 -1
- package/dist/providers/tenki/index.js +16 -26
- package/dist/providers/tenki/provider.d.ts +12 -12
- package/dist/providers/tenki/records.d.ts +1 -1
- package/dist/providers/upstash/index.js +11 -11
- package/dist/providers/upstash/provider.d.ts +1 -1
- package/dist/providers/vercel/index.js +1 -1
- package/dist/providers/vercel/transport.d.ts +1 -1
- package/dist/run.d.ts +9 -0
- package/dist/shared/guest.d.ts +28 -1
- package/dist/shared/native-error.d.ts +2 -0
- package/dist/streams.d.ts +2 -1
- package/dist/testing.js +3 -3
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +37 -14
- package/dist/version.d.ts +4 -0
- package/package.json +28 -4
- package/dist/chunk-23tjmd39.js +0 -8
- package/dist/chunk-6a3wkj84.js +0 -2
- package/dist/chunk-8wq767xb.js +0 -17
- package/dist/chunk-9w9rddra.js +0 -2
- package/dist/chunk-ckym4cht.js +0 -23
- package/dist/chunk-hgrwyjrb.js +0 -2
- package/dist/chunk-kk1hw8wa.js +0 -1
- package/dist/chunk-vz47a139.js +0 -5
- package/dist/chunk-x681p5d2.js +0 -68
- package/dist/chunk-xgxfy2n8.js +0 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 62bd329: Add the Baseten provider, `baseten()` from `@opencoredev/sandbox-sdk/baseten`. It runs Baseten Sandboxes through Baseten's official `@basetenlabs/sandbox` SDK (0.5.0), an optional peer. Keys are exact (unique sandbox names). It supports `size` presets and the exact sizes 1 vCPU / 2048 MiB, 2 / 4096 and 4 / 8192 (Baseten sets CPU from memory), `timeoutMs` and `idleTimeoutMs` as Baseten lifecycle policies, public preview URLs without declared ports, and a `volume` option that creates, mounts and deletes a volume per sandbox, for workspaces too large to keep in memory. There is no pause call: Baseten puts an idle sandbox on standby by itself and resumes it on the next request. There are no snapshots, network policies or terminal, and outbound traffic is IPv6-only. Set `BASETEN_API_KEY`, and optionally pass `teamId`, `image`, `region` and `readyTimeoutMs`.
|
|
8
|
+
- a40e3b6: Add the Instabox provider, `instabox()` from `@opencoredev/sandbox-sdk/instabox`. It runs Instabox machines (InsForge's Firecracker microVMs) through Instabox's REST API, with no peer package. It supports commands streamed over server-sent events, files, background processes, public previews, pause and resume with memory, snapshots and `deleteSnapshot`, `size` presets (2/4, 4/8 and 8/16 vCPU/GiB) and exact sizes the plan offers, `idleTimeoutMs` (5 to 30 minutes) and `timeoutMs` (1 minute to 24 hours). Keys are best-effort, stored as a metadata label. `/workspace` links to the persistent 20 GiB `/data` disk. Errors keep Instabox's HTTP status, error code and request ID, never its message.
|
|
9
|
+
- 592c85a: Add the Modal provider, `modal()` from `@opencoredev/sandbox-sdk/modal`. It runs Modal Sandboxes through Modal's official `modal` SDK (0.11.1 or later), an optional peer. Keys are exact (unique sandbox names within one Modal App). It supports `size` presets and exact CPU and memory (request and limit pinned together), `network: "none"` and allow lists of domains, wildcards, IPs and CIDRs, declared preview ports, `timeoutMs` and `idleTimeoutMs` in whole seconds, file-system snapshots with `expiresInMs`, `deleteSnapshot()`, and `buildTemplate()` for Modal images. There is no pause or terminal. Set `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`, and optionally `MODAL_SANDBOX_REGION`.
|
|
10
|
+
- aeae333: Add provider extensions (`box.ext`) for provider-specific features, and two provider-level capabilities with root functions: `deleteSnapshot(provider, id)` (`"snapshot-delete"`) and `buildTemplate(provider, spec)` (`"templates"`). E2B implements both, plus a PTY `box.terminal()`, native `files.watch` events through envd, and its metrics in `box.usage()` and `box.ext.e2b.metrics()`. `box.usage()` gains optional `cpuCount`, `cpuPercent`, `memoryBytes`, `memoryLimitBytes`, `diskBytes`, `diskLimitBytes` and `metricsAt` fields. Requests the SDK sends now carry `User-Agent: sandbox-sdk/<version>`. `/provider` now exports `SandboxError`, the error helpers and the Connect stream codec, so an adapter can live in its own package; the E2B adapter imports from nothing else. For adapter authors: `terminal()` receives `cwd` and `env`, and `Terminal` gains an optional `wait()`.
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- 7d571e0: boxd failures carry the gRPC status, boxd's reason and request ID, and, for control-plane calls, boxd's message, in the error's cause. Error codes and messages are unchanged. Supports `@boxd-sh/sdk` 0.3.x.
|
|
15
|
+
- 592c85a: boxd: `listSandboxes()` and `reapSandboxes()` no longer read the guest of a suspended or hibernated machine, which woke it, and boxd bills a woken machine. A keyless machine without custom labels is read from its name in any state. A sleeping machine created with a key, custom labels or `from` is left out of the listing until it runs again, because its labels are only in its guest; the new `listSleeping()` on the boxd provider returns those machines without waking them. `reapSandboxes({ idleOnly: true })` still runs an activity check in each listed sandbox, which wakes a sleeping keyless one. Finding a sandbox by key still reaches a sleeping one, and reads sleeping machines only when no running machine has the key.
|
|
16
|
+
- c0be02d: Daytona: a buffered run whose large output is still downloading when its deadline passes now returns `timedOut: true` instead of sometimes rejecting with a `timeout` error from the download request, and a forward wall-clock step no longer cuts that download short.
|
|
17
|
+
- e3d6dd7: Tenki is now Luxor Agent Cloud. Error messages and docs from the `tenki()` adapter say Luxor, and its doc links point to luxor.ai. Nothing else changes: the `tenki()` factory, the `@opencoredev/sandbox-sdk/tenki` import path, the `@tenkicloud/sandbox` peer package and the `TENKI_*` environment variables keep working, as Luxor still supports them.
|
|
18
|
+
- 592c85a: Vercel: restoring a snapshot this provider took, with no `size`, now starts the sandbox with the source's vCPUs instead of Vercel's 2 vCPU default. A restore of a snapshot taken by another provider instance still gets Vercel's default.
|
|
19
|
+
|
|
20
|
+
## 1.0.3
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- 83ff7b9: Commands add less overhead on top of each provider's own SDK. Freestyle and Superserve keep one guest supervisor per sandbox instead of starting Python for every command. boxd, Freestyle, Superserve and Tenki supervisors start faster. E2B and Upstash no longer wrap each command in an activity script; `reapSandboxes({ idleOnly: true })` finds running commands by scanning for the `SANDBOX_SDK_RUN=1` tag instead, and still treats a sandbox it can't inspect as busy. On E2B and Upstash, `files.edit` takes one call and changes the file the way that provider's own write does: in place on E2B, by replacing it on Upstash. `files.search` takes one call wherever the guest can walk files in the provider's own listing order (E2B, Upstash, boxd, Freestyle, Superserve, Tenki, Boat, Sandboxer and local), so `maxMatches` returns the same files as before; elsewhere it lists and reads as before. Upstash creates poll for readiness every 200 ms, honor `requestTimeoutMs`, ride out transient errors while the new box boots, and report `outcome_unknown` when the create answer is lost or unreadable, or when cleanup after a failed create can't be confirmed. A create whose first read of the new box stalls or keeps failing stops at the create deadline or `requestTimeoutMs`, deletes the box and reports `timeout`, or `aborted` when the caller cancels. If the guest call behind `files.edit` fails after it may have run, the edit reports `outcome_unknown`, so read the file before retrying; failures that prove nothing ran keep their own code.
|
|
25
|
+
|
|
3
26
|
## 1.0.2
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Sandbox SDK
|
|
2
2
|
|
|
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,
|
|
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, Luxor, 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
|
|
|
@@ -10,7 +10,7 @@ One TypeScript API for running code in a sandbox. The same `createSandbox`, `run
|
|
|
10
10
|
npm install @opencoredev/sandbox-sdk
|
|
11
11
|
```
|
|
12
12
|
|
|
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,
|
|
13
|
+
That is the whole install for E2B, Daytona, Freestyle, Superserve, Instabox, Boat, and Sandboxer, which call the provider's HTTP API directly. Vercel, Modal, Baseten, Upstash Box, Railway, Luxor, 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
|
|
|
@@ -98,9 +98,12 @@ Import each provider from its own subpath. The root entry never loads a provider
|
|
|
98
98
|
| [E2B](https://sandbox-sdk.app/docs/providers/e2b) | `/e2b` | `e2b()` | `E2B_API_KEY` |
|
|
99
99
|
| [Daytona](https://sandbox-sdk.app/docs/providers/daytona) | `/daytona` | `daytona()` | `DAYTONA_API_KEY` (optional `DAYTONA_API_URL`, `DAYTONA_TARGET`) |
|
|
100
100
|
| [Vercel](https://sandbox-sdk.app/docs/providers/vercel) | `/vercel` | `vercel()` | `VERCEL_OIDC_TOKEN`, or `VERCEL_TOKEN` + `VERCEL_TEAM_ID` + `VERCEL_PROJECT_ID` |
|
|
101
|
+
| [Modal](https://sandbox-sdk.app/docs/providers/modal) | `/modal` | `modal()` | `MODAL_TOKEN_ID`, `MODAL_TOKEN_SECRET` (optional `MODAL_SANDBOX_REGION`) |
|
|
102
|
+
| [Baseten](https://sandbox-sdk.app/docs/providers/baseten) | `/baseten` | `baseten()` | `BASETEN_API_KEY` |
|
|
103
|
+
| [Instabox](https://sandbox-sdk.app/docs/providers/instabox) | `/instabox` | `instabox()` | `INSTABOX_API_KEY` (optional `INSTABOX_API_URL`) |
|
|
101
104
|
| [Upstash Box](https://sandbox-sdk.app/docs/providers/upstash) | `/upstash` | `upstash()` | `UPSTASH_BOX_API_KEY` (optional `UPSTASH_BOX_BASE_URL`) |
|
|
102
105
|
| [Railway](https://sandbox-sdk.app/docs/providers/railway) | `/railway` | `railway()` | `RAILWAY_API_TOKEN`, `RAILWAY_ENVIRONMENT_ID` |
|
|
103
|
-
| [
|
|
106
|
+
| [Luxor](https://sandbox-sdk.app/docs/providers/tenki) | `/tenki` | `tenki()` | `TENKI_AUTH_TOKEN` or `TENKI_API_KEY` |
|
|
104
107
|
| boxd | `/boxd` | `boxd()` | `BOXD_API_KEY` (optional `BOXD_BASE_URL`) |
|
|
105
108
|
| Freestyle | `/freestyle` | `freestyle()` | `FREESTYLE_API_KEY` |
|
|
106
109
|
| Superserve | `/superserve` | `superserve()` | `SUPERSERVE_API_KEY` |
|
|
@@ -110,9 +113,9 @@ Import each provider from its own subpath. The root entry never loads a provider
|
|
|
110
113
|
| [agentOS](https://sandbox-sdk.app/docs/providers/agentos) | `/agentos` | `agentos()` | none |
|
|
111
114
|
| Memory | `/memory` | `memory()` | none |
|
|
112
115
|
|
|
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: [...] }`.
|
|
116
|
+
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: [...] }`. `terminal` adds `box.terminal()`, an interactive PTY (E2B). Two capabilities gate root functions that need no sandbox: `snapshot-delete` for `deleteSnapshot(provider, id)` and `templates` for `buildTemplate(provider, spec)`. Features only one provider has live on `box.ext`, such as `box.ext.e2b.metrics()`.
|
|
114
117
|
|
|
115
|
-
Every factory also accepts its credential as an option, such as `e2b({ apiKey })` or `railway({ token, environmentId })`. Endpoints use `baseUrl` (boxd, Daytona,
|
|
118
|
+
Every factory also accepts its credential as an option, such as `e2b({ apiKey })` or `railway({ token, environmentId })`. Endpoints use `baseUrl` (boxd, Daytona, Luxor, Upstash, Boat), and Boat's default machine size uses `machine`:
|
|
116
119
|
|
|
117
120
|
```ts
|
|
118
121
|
import { boat } from "@opencoredev/sandbox-sdk/boat";
|
|
@@ -361,7 +364,7 @@ Time the SDK adds on top of each provider's own SDK, as median milliseconds. "Co
|
|
|
361
364
|
| Daytona | ±0 | ±0 | +38 |
|
|
362
365
|
| Upstash Box | +27 | +69 | +15 |
|
|
363
366
|
| Freestyle | ±0 | +51 | +23 |
|
|
364
|
-
|
|
|
367
|
+
| Luxor | ±0 | +119 | +15 |
|
|
365
368
|
| Superserve | ±0 | +73 | +9 |
|
|
366
369
|
| boxd | +272 | +370 | +52 |
|
|
367
370
|
|
package/dist/ai.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Q}from"./chunk-sjnk17y5.js";import{B}from"./chunk-x4rrgmxf.js";import"./chunk-aek8n3a4.js";import{tool as u}from"ai";function b(p,m){return Object.fromEntries(B(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 Q,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,4 @@
|
|
|
1
|
+
function t(n){return typeof n==="string"}function o(n){return typeof n==="number"}function U(n){return typeof n==="boolean"}function r(n){return typeof n==="object"&&n!==null}var m={auth:"Set the provider's API key environment variable or pass it to the provider factory.",not_found:"Create a new sandbox, or pass a key to createSandbox so it recreates one for you.",quota:"Wait and retry, destroy unused sandboxes with reapSandboxes, or raise the provider plan.",unavailable:"Retry with backoff. Check the provider's status page if it persists.",unsupported:"Remove the option or choose a provider that supports it. Check box.capabilities.",timeout:"Retry, or raise the relevant timeout option.",aborted:"Retry with a fresh AbortSignal if you still need the result.",outcome_unknown:"Check the sandbox state before retrying. If in doubt, destroy it.",process_exited:"Read the exit code and log tail in the message, fix the command, and start it again.",port_not_ready:"Check that the server listens on 0.0.0.0 and the right port, then read its logs.",edit_not_found:"Read the file again and use text that is in it.",edit_not_unique:"Add surrounding lines to find so it matches exactly once.",file_not_found:"Check the path. Relative paths resolve against /workspace.",invalid_argument:"Fix the input. Retrying the same call will not help.",provider:"Read the message and cause. Report it if it looks like an SDK bug."};class e extends Error{code;retryable;hint;provider;sandboxId;constructor(n,u){super(n,{cause:u.cause});this.name="SandboxError",this.code=u.code,this.retryable=u.retryable??!1,this.hint=u.hint??m[u.code]??m.provider,this.provider=u.provider??"unknown",this.sandboxId=u.sandboxId}static{Object.defineProperty(this,"name",{value:"SandboxError"})}[Symbol.for("nodejs.util.inspect.custom")](n,u,c){let l=this.stack??"",p=l.indexOf(`
|
|
2
|
+
at `)>=0?l.slice(l.indexOf(`
|
|
3
|
+
at `)):"",h={code:this.code,provider:this.provider,sandboxId:this.sandboxId,retryable:this.retryable,hint:this.hint,cause:this.cause};return`SandboxError [${this.code}]: ${this.message}${p} ${c(h,u)}`}}function M(n){return n instanceof e&&(n.code==="file_not_found"||n.code==="not_found")}class k{values=new Set;add(n){for(let u of n)if(u)this.values.add(u)}text(n){for(let u of[...this.values].sort((c,l)=>l.length-c.length))n=n.split(u).join("[REDACTED]");return n}get secrets(){return[...this.values].sort((n,u)=>u.length-n.length)}get maxLength(){return Math.max(1,...[...this.values].map((n)=>n.length))}error(n,u,c){if(n instanceof e)return new e(x(this.text(n.message)),{code:n.code,retryable:n.retryable,hint:x(this.text(n.hint)),provider:u,sandboxId:c??n.sandboxId,cause:n.cause===void 0?void 0:C(n.cause instanceof Error?n.cause.message:String(n.cause),(p)=>this.text(p))});let l=I(this.text(n instanceof Error?n.message:t(n)?n:"Non-Error value thrown"));return new e(`${l}. Provider request failed. Check the provider settings and retry.`,{code:"provider",hint:m.provider,provider:u,sandboxId:c,cause:y(n,(p)=>this.text(p))})}}var _=[[/https?:\/\/[^\s"'<>]+/gi,"[URL REDACTED]"],[/(\bauthorization["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\r\n;]+)/gi,"$1[REDACTED]"],[/\bBearer\s+[^\s"',;]+/gi,"Bearer [REDACTED]"],[/((?:["']?(?:api[-_]?key|access[-_]?token|token|password|secret)["']?)\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/gi,"$1[REDACTED]"]];function x(n){for(let[u,c]of _)n=n.replace(u,c);return n}function I(n,u=1000){return x(n).replace(/\p{Cc}+/gu," ").slice(0,u)}var E=/(?:api[-_]?key|token|password|secret|authorization)$/i;function w(n){if(!n.startsWith("{"))return;let u;try{u=JSON.parse(n)}catch{return}if(!r(u)||Array.isArray(u))return;let c=[];for(let[l,p]of Object.entries(u)){if(!(t(p)||o(p)||U(p)||p===null))return;c.push([l,p])}return c}function C(n,u){let c=w(n);if(c===void 0)return I(u(n));let l=c.map(([g,f])=>{let b=I(u(g)).slice(0,64);if(E.test(g)&&f!==null)return[b,"[REDACTED]"];if(t(f))return[b,I(u(f))];return[b,f!==null&&u(String(f))!==String(f)?"[REDACTED]":f]}),p=(g,f)=>JSON.stringify(Object.fromEntries(g.map(([b,v])=>[b,t(v)?v.slice(0,f):v])));for(let g of[300,120,40]){let f=p(l,g);if(f.length<=1000)return f}let h=[...l];while(h.length>0&&p(h,40).length>1000)h.pop();return p(h,40)}function y(n,u=(l)=>l,c=0){if(!(n instanceof Error))return;let l=I(u(n.message?`${n.name}: ${n.message}`:n.name)),p=c<2?y(n.cause,u,c+1):void 0;return p===void 0?l:`${l}; caused by ${p}`}var R={auth:"the credentials are missing or were rejected",not_found:"the sandbox does not exist",quota:"a provider limit or billing stopped the request",unavailable:"the service is down or unreachable",unsupported:"the provider cannot do what was asked",timeout:"the operation took too long",aborted:"the request was aborted",outcome_unknown:"the request may or may not have happened",process_exited:"the process exited before it was ready",port_not_ready:"the port did not become ready",edit_not_found:"the text to replace was not found",edit_not_unique:"the text to replace matched more than once",file_not_found:"the path does not exist",invalid_argument:"the provider rejected the request as invalid",provider:"the provider returned an unexpected error"};function i(n,u){let l=!(u.known??u.code!=="provider")&&u.status===void 0?y(n,u.redact):void 0,p=[n instanceof Error?n.name:void 0,u.status].filter((h)=>h!==void 0).join(" ");return{detail:l,cause:l??(p||void 0)}}function T(n){return Object.assign(Error(JSON.stringify(n)),n)}function d(n){let u=new k;for(let c of n)if(c)u.add([c]);return(c)=>u.text(c)}function a(n,u){return u??R[n]}function F(n){if(n===400||n===422)return"invalid_argument";if(n===401||n===403)return"auth";if(n===402||n===429)return"quota";if(n===404||n===410)return"not_found";if(n===408||n===504)return"timeout";if(n===413)return"unsupported";if(n>=500&&n<=599)return"unavailable";return"provider"}function s(n){throw new e(`${n}. The request is invalid. Check the supplied options.`,{code:"invalid_argument"})}
|
|
4
|
+
export{t,o,U,r,e,M,k,I,y,i,T,d,a,F,s};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{x}from"./chunk-drhcb2hx.js";import{c}from"./chunk-0wp6x4wb.js";import{t,r,e,I,y,d,F}from"./chunk-0eeyc0aq.js";function ze(a){return["localhost","127.0.0.1","[::1]"].includes(a)||/\.(test|invalid|example|localhost)$/.test(a)}function f(a,s){let u=Date.now()+a,g=AbortSignal.timeout(Math.max(0,a));return{signal:s?AbortSignal.any([s,g]):g,timeout:g,parent:s,remaining:()=>Math.max(0,u-Date.now())}}function w(a,s,u){return new Promise((g,H)=>{let S=()=>{clearTimeout(Z),s.signal.removeEventListener("abort",T)},T=()=>{S(),H(Ve(s,u))},Z=setTimeout(()=>{S(),g()},a);if(s.signal.aborted)T();else s.signal.addEventListener("abort",T,{once:!0})})}function ge(a,s){if(s.aborted)return Promise.reject(s.reason);return new Promise((u,g)=>{let H=()=>g(s.reason);s.addEventListener("abort",H,{once:!0}),a.then(u,g).finally(()=>s.removeEventListener("abort",H))})}function Ve(a,s,u){return a.parent?.aborted&&!a.timeout.aborted?new e("Request aborted. The signal was cancelled.",{code:"aborted",provider:s,sandboxId:u}):new e("Request timed out. The operation took too long.",{code:"timeout",provider:s,sandboxId:u,retryable:!0})}var Ce=new WeakMap;function ee(a){return a instanceof e?Ce.get(a):void 0}var Je=65536,Ge=33554432,Ze=20000,Ae=1e4,$e=5,Ie=new Set([429,502,503,504]),Ke=new Set([301,302,303,307,308]),ye=new Set(["GET","HEAD","PUT","DELETE"]),We=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"]),Xe=/^(?:authorization|proxy-authorization|cookie|x-api-key|api-key|apikey)$|[-_](?:token|key|secret|password)$/,Ye=/^(?:x-)?idempotency-key$/,Qe=/^\s*(?:bearer|basic|token|bot|digest)\s+(\S.*?)\s*$/i,qe=/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,_e=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/,et=/^[A-Za-z0-9_.:-]{1,128}$/;function Oe(a,s=0){if(!r(a)||s>3)return[];return[..."code"in a&&t(a.code)?[a.code]:[],...Oe("cause"in a?a.cause:void 0,s+1)]}var Le=new WeakSet,K=(a)=>a instanceof e&&Le.has(a)||Oe(a).some((s)=>We.has(s));function tt(a){return typeof a==="string"||a instanceof Uint8Array||a instanceof ArrayBuffer||ArrayBuffer.isView(a)||a instanceof Blob||a instanceof FormData||a instanceof URLSearchParams||a instanceof ReadableStream}function nt(a){let s=a.get("retry-after");if(s===null)return;if(/^\d+$/.test(s.trim()))return Number(s.trim())*1000;let u=Date.parse(s);return Number.isNaN(u)?void 0:Math.max(0,u-Date.now())}function se(a,s){if(!c(a))return;for(let u of s){let g=Object.hasOwn(a,u)?a[u]:void 0;if(t(g)&&g)return g}return}function we(a){let s;try{s=a?JSON.parse(a):void 0}catch{s=void 0}let u=c(s)?s.error:void 0,g=se(s,["code","error_code","errorCode","type"])??se(u,["code","type"])??(t(u)&&_e.test(u)?u:void 0),H=se(s,["message","detail","error_description","title"])??se(u,["message"])??(t(u)?u:void 0)??(s===void 0&&a.trim()?a.trim():void 0),S={text:a,json:s};if(g!==void 0)S.code=g;if(H!==void 0)S.message=H;return S}async function Ue(a,s,u){if(!a)return new Uint8Array;let g=a.getReader(),H=[],S=0;try{for(;;){let{done:W,value:A}=await g.read();if(W)break;if(S+A.byteLength>s){let Y=u();if(H.push(A.subarray(0,s-S)),S=s,await g.cancel().catch(()=>{}),Y)throw Y;break}H.push(A),S+=A.byteLength}}finally{g.releaseLock()}let T=new Uint8Array(S),Z=0;for(let W of H)T.set(W,Z),Z+=W.byteLength;return T}var Re=new TextDecoder;function rt(a,s,u,g){return{status:a,headers:s,body:u,text:()=>Re.decode(u),json(){let H=Re.decode(u);if(!H.trim())return;try{return JSON.parse(H)}catch{throw g("returned a body that is not JSON. Use fetch for text, bytes or streams")}}}}function v(a){let{provider:s,label:u}=a,g=a.timeoutMs??60000,H=a.retries??2,S=a.backoffMs??250,T=new Set,Z=(n)=>{T.delete(n),T.add(n);for(let o of T){if(T.size<=256)break;T.delete(o)}},W=(n)=>{if(!n)return;Z(n);let o=Qe.exec(n)?.[1];if(o)Z(o)},A=(n)=>I(d([...T,...a.secrets?.()??[]])(n)),Y=new Map,xe=(n,o)=>{let i=o.toLowerCase();return Y.get(n)?.has(i)===!0||Xe.test(i)&&!Ye.test(i)},ie=new Map,de=a.planes;function ce(n){let o=n??a.defaultPlane,i=Object.hasOwn(de,o)?de[o]:void 0;if(!i)throw j(`Unknown plane "${String(o).slice(0,32)}". Use one of: ${Object.keys(de).join(", ")}`);return{name:o,plane:i}}function j(n,o){return new e(`${A(n)}. The request is invalid. Check the supplied options.`,{code:"invalid_argument",provider:s,sandboxId:o})}function ue(n){let o=/^[a-z][a-z0-9+.-]*:/i.test(n.path)?"[absolute URL]":(n.path.split("?")[0]??"").slice(0,200);return`${n.method} ${I(o)}`}function Me(n){let o=n.params??{},i=new Set,l=n.path.replace(qe,(m,b)=>{if(!Object.hasOwn(o,b))throw j(`The path has a {${b}} placeholder but params.${b} is missing`,n.sandboxId);let k=String(o[b]);if(k===""||k==="."||k==="..")throw j(`params.${b} must not be empty, "." or ".."`,n.sandboxId);return i.add(b),encodeURIComponent(k)}),h=Object.keys(o).filter((m)=>!i.has(m));if(h.length)throw j(`params.${h[0]} has no {${h[0]}} placeholder in the path`,n.sandboxId);return l}function Ne(n,o){let i=Me(o),l;if(/^[a-z][a-z0-9+.-]*:/i.test(i)){try{l=new URL(i)}catch{throw j("The path is not a valid URL",o.sandboxId)}if(l.protocol!=="https:"&&l.protocol!=="http:")throw j("Only http and https URLs are supported",o.sandboxId)}else{if(!i.startsWith("/"))throw j('The path must start with "/" or be an absolute URL',o.sandboxId);if(i.split("?")[0]?.split("/").some((h)=>h==="."||h===".."))throw j('The path must not contain "." or ".." segments',o.sandboxId);l=new URL(n.replace(/\/+$/,"")+i)}for(let[h,m]of Object.entries(o.query??{}))if(m!==void 0)l.searchParams.append(h,String(m));return l}function E(n,o,i,l,h=n==="unavailable"||n==="quota"){let m=n==="auth"?a.authHint:void 0;return new e(A(`${u} ${ue(o)} failed${i}`),{code:n,provider:s,sandboxId:o.sandboxId,retryable:h,hint:m,cause:l===void 0?void 0:A(l)})}function U(n,o,i,l=!1){let h=De(n,o,i,l),m=a.cause?.(n,{method:o.method,plane:i,operation:ue(o),sandboxId:o.sandboxId}),b=m===void 0?h:new e(h.message,{code:h.code,provider:s,sandboxId:h.sandboxId,retryable:h.retryable,hint:h.hint,cause:m});if(n.kind==="network"&&!n.sent)Le.add(b);return b}function De(n,o,i,l){let h=!ye.has(o.method)&&!o.readOnly,m=a.mapError?.(n,{method:o.method,plane:i,operation:ue(o),sandboxId:o.sandboxId});switch(n.kind){case"status":{let b=m??F(n.status);if(h&&(b==="timeout"||l))b="outcome_unknown";let k=n.body.code!==void 0&&_e.test(n.body.code)?` ${n.body.code}`:"",X=["x-request-id","request-id","x-amzn-requestid","cf-ray"].map((z)=>n.headers.get(z)).find((z)=>z!==null&&et.test(z)),C=`HTTP ${n.status}${k}`,M=o.detail==="message"&&n.body.message?`: ${I(A(n.body.message)).slice(0,300)}`:"",J=`${C}${X?` (request ${X})`:""}${M}`,D=E(b,o,` (${C})${M}.${b==="outcome_unknown"?" The request may or may not have taken effect; check before repeating it.":""}`,J,b==="unavailable"||b==="quota"||b==="timeout");return Ce.set(D,k?{status:n.status,code:k.trim()}:{status:n.status}),D}case"network":{let b=y(n.error,A);if(h&&n.sent)return E(m??"outcome_unknown",o,": the connection failed after the request was sent, so it may or may not have taken effect. Check before repeating it.",b,!1);return E(m??"unavailable",o,`: ${n.sent?"the connection failed":"the service is unreachable"}.`,b,!0)}case"timeout":if(h&&n.sent)return E(m??"outcome_unknown",o,": no response before the deadline, so it may or may not have taken effect. Check before repeating it.",void 0,!1);return E(m??"timeout",o,": no response before the deadline.",void 0,!0);case"aborted":return E(m??"aborted",o,": the signal was cancelled.",void 0,!1);default:return n}}function Be(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(tt(n.body))return{body:n.body,replayable:!(n.body instanceof ReadableStream)};return{body:JSON.stringify(n.body),contentType:"application/json",replayable:!0}}async function ke(n,o){let{name:i,plane:l}=ce(n.plane),{body:h,contentType:m,replayable:b}=Be(n),k=!ye.has(n.method),X=b&&(!k||n.idempotencyKey!==void 0),{signal:C}=o,M={signal:C};if(n.sandboxId!==void 0)M.sandboxId=n.sandboxId;let J=a.fetch??((O,N)=>globalThis.fetch(O,N)),D=`${i}\x00${n.sandboxId??""}`,z=!1,_=()=>o.parent?.aborted&&!o.timeout.aborted?{kind:"aborted"}:C.aborted?{kind:"timeout",sent:!1}:void 0,Q=async(O)=>{try{return Re.decode(await Ue(O.body,Je,()=>{return}))}catch{let N=_();if(N)throw U(N,n,i);return""}};for(let O=0;;O++){let N=_();if(N)throw U(N,n,i);let fe,te,{baseUrl:he,auth:Ee}=l;try{fe=t(he)?he:await ge(Promise.resolve().then(()=>he(M)),C),te=n.auth===!1||!Ee?{}:await ge(Promise.resolve().then(()=>Ee(M)),C)}catch(P){if(P instanceof e)throw P;let R=_();if(R)throw U(R,n,i);throw E("auth",n,`: resolving ${u} credentials failed.`,y(P,A),!1)}let Pe=_();if(Pe)throw U(Pe,n,i);let pe=Y.get(i);if(!pe)Y.set(i,pe=new Set);for(let[P,R]of Object.entries(te))pe.add(P.toLowerCase()),W(R);let Fe=ie.get(D)?.generation??0,re,oe;try{oe=new URL(fe)}catch{throw E("provider",n,`: the ${u} base URL is invalid.`,void 0,!1)}if(re=oe.origin,Object.keys(te).length>0&&oe.protocol==="http:"&&!ze(oe.hostname))throw E("invalid_argument",n,`: the ${u} base URL uses plain HTTP, which would send credentials unencrypted. Use an https URL.`,void 0,!1);let G=Ne(fe,n),me=n.method,ae=h,p,V;for(let P=0;;P++){let R=new Headers({"user-agent":x});for(let[L,B]of Object.entries(l.headers??{}))R.set(L,B);if(m&&ae!==void 0)R.set("content-type",m);if(n.idempotencyKey!==void 0&&a.idempotencyHeader)R.set(a.idempotencyHeader,n.idempotencyKey);if(G.origin===re)for(let[L,B]of Object.entries(te))R.set(L,B);for(let[L,B]of Object.entries(n.headers??{}))R.set(L,B);if(G.origin!==re){for(let L of Array.from(R.keys()))if(xe(i,L))R.delete(L)}for(let[L,B]of R)if(xe(i,L))W(B);let ne={method:me,headers:R,body:ae,signal:C,redirect:"manual"};if(ae instanceof ReadableStream)ne.duplex="half";try{p=await J(G.href,ne)}catch(L){p=void 0;let B=_();V=B?.kind==="timeout"?{kind:"timeout",sent:!0}:B??{kind:"network",sent:!K(L),error:L};break}let ve=p.headers.get("location");if(!Ke.has(p.status)||ve===null)break;if(await p.body?.cancel().catch(()=>{}),P>=$e)throw E("provider",n,`: more than ${$e} redirects.`,void 0,!1);try{G=new URL(ve,G)}catch{throw E("provider",n,": the redirect location is invalid.",void 0,!1)}if(G.protocol!=="https:"&&G.protocol!=="http:")throw E("provider",n,": the redirect left http and https.",void 0,!1);if(p.status===303||(p.status===301||p.status===302)&&me==="POST")me="GET",ae=void 0;else if(!b)throw E("provider",n,": the server redirected a streamed upload, which cannot be sent twice.",void 0,!1)}let He=p!==void 0&&l.refresh!==void 0&&!z&&b&&n.auth!==!1&&G.origin===re,q;if(He&&l.stale&&p&&p.status>=400&&p.status!==401)q=we(await Q(p));let Se=!He||!p?void 0:p.status===401?"refused":q!==void 0?l.stale?.({status:p.status,body:q,credentials:te},M):void 0;if(Se!==void 0&&l.refresh&&p){if(q===void 0)await p.body?.cancel().catch(()=>{});z=!0;let P=ie.get(D)??{generation:0};if(ie.set(D,P),P.generation===Fe){P.pending??=l.refresh(M).then(()=>{P.generation++}).finally(()=>{P.pending=void 0});try{await ge(P.pending,C)}catch(R){let ne=_();if(ne)throw U(ne,n,i);if(R instanceof e)throw R;throw E("auth",n,`: refreshing ${u} credentials failed.`,y(R,A),!1)}}if(Se==="refused"||X){O--;continue}throw U({kind:"status",status:p.status,headers:p.headers,body:q??we("")},n,i,!0)}let Te;if(p&&p.status>=200&&p.status<300)return p;if(p){let P=q??we(await Q(p));if(V={kind:"status",status:p.status,headers:p.headers,body:P},Ie.has(p.status)){let R=nt(p.headers);Te=R===void 0?void 0:R<=Ze?R:1/0}if(!Ie.has(p.status))throw U(V,n,i)}if(!V)throw new e(`${u} request produced no response`,{code:"provider",provider:s});if(V.kind==="aborted"||V.kind==="timeout")throw U(V,n,i);let be=Te??S*2**O*(0.5+Math.random()/2);if(!X||O>=H||be===1/0||be>=o.remaining())throw U(V,n,i);try{await w(be,o,s)}catch{throw U(_()??V,n,i)}}}async function le(n){let o=n.deadline??f(n.timeoutMs??g,n.signal),i=await ke(n,o),l=n.maxBytes??Ge,h;try{h=await Ue(i.body,l,()=>E("unsupported",n,`: the response is larger than ${l} bytes.`,void 0,!1))}catch(m){if(m instanceof e)throw m;let{name:b}=ce(n.plane);if(o.parent?.aborted&&!o.timeout.aborted)throw U({kind:"aborted"},n,b);throw U(o.signal.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:m},n,b)}return rt(i.status,i.headers,h,(m)=>E("provider",{...n,detail:"status"},` (HTTP ${i.status}): the response ${m}.`,void 0,!1))}async function je(n){let o=n.deadline??(n.timeoutMs===void 0?f(2147483647,n.signal):f(n.timeoutMs,n.signal)),i=f(n.startupTimeoutMs??g),l=new AbortController,h=()=>l.abort(),m=AbortSignal.any([o.signal,i.signal]);if(m.addEventListener("abort",h,{once:!0}),m.aborted)h();let b={signal:l.signal,timeout:o.timeout,parent:o.parent,remaining:()=>Math.min(o.remaining(),i.remaining())},k;try{k=await ke(n,b)}finally{m.removeEventListener("abort",h)}if(!k.body||k.status===204||k.status===205)return k;o.signal.addEventListener("abort",h,{once:!0});let{name:X}=ce(n.plane),C=k.body.getReader(),M,J=!1,D=()=>{clearTimeout(M),o.signal.removeEventListener("abort",h)},z=new ReadableStream({async pull(_){if(n.idleTimeoutMs!==void 0)M=setTimeout(()=>{J=!0,C.cancel().catch(()=>{}),l.abort()},n.idleTimeoutMs);try{let{done:Q,value:O}=await C.read();if(clearTimeout(M),J)throw Error("idle");if(Q){D(),_.close();return}_.enqueue(O)}catch(Q){D();let O=o.parent?.aborted&&!o.timeout.aborted?{kind:"aborted"}:J||o.timeout.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:Q},N=!ye.has(n.method)&&!n.readOnly;_.error(J&&O.kind==="timeout"?E(N?"outcome_unknown":"timeout",n,`: no data for ${n.idleTimeoutMs} ms${N?", so its result is unconfirmed. Check before repeating it.":"."}`,void 0,!N):U(O,n,X))}},async cancel(_){D(),await C.cancel(_).catch(()=>{}),l.abort()}},{highWaterMark:0});return new Response(z,{status:k.status,statusText:k.statusText,headers:k.headers})}return{provider:s,label:u,redact:A,request:le,async json(n){return(await le(n)).json()},stream:je,cleanup(n){let{signal:o,deadline:i,...l}=n;return le({...l,timeoutMs:Math.min(n.timeoutMs??Ae,Ae)})}}}
|
|
2
|
+
export{f,w,ee,K,v};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{e,M,k,s}from"./chunk-0eeyc0aq.js";var u=new WeakMap,P=(n,t)=>u.get(n)?.get(t);function g(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 b(n,t){u.get(n)?.delete(t)}function X(n,t){let a=u.get(n);if(!a)return;for(let[r,o]of a)if(o===t)a.delete(r)}var x=new WeakMap;async function re(n,t,a,r){let o=x.get(n);if(!o)o=new Map,x.set(n,o);let i=o.get(t)??Promise.resolve(),c=a.locator,d=i.catch(()=>{}).then(()=>a.keyMode==="exact"&&n.keyMode==="best-effort"&&c?.withLock?c.withLock(t,r):r());o.set(t,d);try{return await d}finally{if(o.get(t)===d)o.delete(t)}}var w=new WeakMap;function ie(n,t){let a=w.get(n);if(!a)a=new Map,w.set(n,a);a.set(t,(a.get(t)??0)+1)}function he(n,t){let a=w.get(n),r=a?.get(t)??0;if(r>1)return a?.set(t,r-1),!1;return a?.delete(t),!0}function ae(n,t){return n.capabilities.has(t)}var v={"sandbox-sdk":"1"};function C(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||a==="snapshot-delete"&&!n.deleteSnapshot||a==="templates"&&!n.buildTemplate)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 D(n,t={}){let a=new k;a.add(Object.values(t.secrets??{}));async function r(){let o;try{if(C(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 m=await t.locator?.get(t.key)??P(n,t.key);if(m)try{i=await n.connect(m)}catch(p){if(!(p instanceof e)||p.code!=="not_found")throw p;b(n,t.key)}if(i?.state==="stopped")i=void 0,b(n,t.key);i??=await n.find(t.key)}let c=!i;if(!i){let{secrets:m,locator:p,keyMode:F,trackChanges:A,...O}=t,h=n.create({...O,env:{...t.env,...m},labels:{...t.labels,...v}}).catch(async(f)=>{if(t.key&&n.keyMode==="exact"&&!t.signal?.aborted){let l=await n.find(t.key);if(l)return c=!1,l}throw f});if(t.signal){let f=t.signal,l=()=>{},K=new Promise((y,R)=>{if(l=()=>R(new e("Creation aborted. The signal was cancelled. Any late sandbox will be destroyed.",{code:"aborted"})),f.addEventListener("abort",l,{once:!0}),f.aborted)l()}),L=h.then(async(y)=>{if(f.aborted){if(c)await n.destroy(y.id);throw new e("Creation aborted. Late sandbox destroyed. Retry with a fresh signal.",{code:"aborted"})}return y});try{i=await Promise.race([L,K])}finally{f.removeEventListener("abort",l)}}else i=await h;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),g(n,t.key,i.id);let{makeHandle:d}=await import("./chunk-w8nk1xf2.js");return await d(n,i,c,t,a)}catch(i){if(o)X(n,o.id),await n.destroy(o.id).catch(()=>{});throw a.error(i,n.name)}}if(!t.key)return r();return re(n,t.key,t,r)}async function V(n,t,a={}){let r=new k;r.add(Object.values(a.secrets??{}));try{C(n,a);let o=await n.connect(t),{makeHandle:i}=await import("./chunk-w8nk1xf2.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 oe(n,t={}){try{return(await n.list({...t.labels,...v})).filter((a)=>a.labels["sandbox-sdk"]==="1")}catch(a){throw new k().error(a,n.name)}}async function de(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-xqtzts2q.js")).isRunActive:()=>!1,r=t.olderThanMs??0,o=0;try{for(let i of await oe(n,t)){if(Date.now()-i.createdAt<r)continue;if(t.idleOnly){if(a(n.name,i.id))continue;let c=await B(n,i.id);if(c==="gone"){o++;continue}if(c==="busy")continue}if(a(n.name,i.id))continue;X(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 k().error(i,n.name)}}function T(n,t,a,r){if(!n.capabilities.has(t))throw new e(`${a} unavailable. Provider ${n.name} lacks the "${t}" capability. Choose a provider that has it.`,{code:"unsupported",provider:n.name});if(r===void 0)throw new e("Invalid adapter capabilities. A declared method is missing. Fix the adapter contract.",{code:"provider",provider:n.name});return r}async function be(n,t){try{let a=T(n,"snapshot-delete","Snapshot deletion",n.deleteSnapshot);if(!t)s("snapshotId cannot be empty");return await a.call(n,t)}catch(a){throw new k().error(a,n.name)}}async function ge(n,t,a={}){try{let r=T(n,"templates","Template building",n.buildTemplate),o=t;if(!o.name)s("Template name cannot be empty");if(o.run?.some((i)=>!i.trim()))s("Template run steps must be non-empty commands");if(a.timeoutMs!==void 0&&(!Number.isFinite(a.timeoutMs)||a.timeoutMs<=0))s("Timeouts must be positive milliseconds");return await r.call(n,o,a)}catch(r){throw new k().error(r,n.name)}}var S="/tmp/.sandbox-sdk/runs";async function I(n,t){if(!n.procActivity)return!1;let{activityScanCommand:a}=await import("./chunk-xqtzts2q.js");try{let r=await n.exec(t,{command:a,cwd:"/",env:{},timeoutMs:30000,onChunk(){}});return r.timedOut||r.exitCode!==0}catch{return!0}}async function B(n,t){let a;try{let r=await n.connect(t),{makeHandle:o}=await import("./chunk-w8nk1xf2.js");a=await o(n,r,!1,{},new k,!1)}catch(r){if(r instanceof e&&r.code==="not_found")return"gone";throw r}try{let[r,o,i]=await Promise.all([a.processes(),j(a),I(n,t)]);return r.some((d)=>d.status==="running"||d.status==="starting")||o.length>0||i?"busy":"idle"}finally{await a.close()}}async function j(n){try{return await n.files.list(S)}catch(t){if(M(t))return[];if(t instanceof e&&t.code==="provider"&&!await n.files.exists(S))return[];throw t}}
|
|
2
|
+
export{X,re,ie,he,ae,D,V,oe,de,be,ge};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{
|
|
1
|
+
import{c}from"./chunk-0wp6x4wb.js";import{t,o}from"./chunk-0eeyc0aq.js";function s(n){if(!c(n))return;let e={};for(let[a,r]of Object.entries(n)){if(!t(r))return;Object.defineProperty(e,a,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}function j(n,e){let a;try{a=JSON.parse(n)}catch{e("metadata")}if(!c(a)||!c(a.labels))e("metadata");let{key:r,version:d,createdAt:l}=a;if(r!==void 0&&r!==null&&!t(r)||d!==void 0&&!o(d)||l!==void 0&&!o(l))e("metadata");let u=s(a.labels)??e("label");return{key:r,labels:u,version:d,createdAt:l}}
|
|
2
|
+
export{j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{m}from"./chunk-kdecey83.js";import{n}from"./chunk-2ts3evzh.js";import{t,o,U,r,e}from"./chunk-0eeyc0aq.js";function I(s){return Array.isArray(s)&&(s[0]==="stdout"||s[0]==="stderr")&&t(s[1])&&s[1].length<=21848}function N(s){return r(s)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)}function D(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&&U(s.result.timedOut)&&"chunks"in s&&Array.isArray(s.chunks)&&"offset"in s&&o(s.offset)&&"size"in s&&o(s.size)}var T=`import os,sys,fcntl,signal,shutil,time,json
|
|
2
2
|
root=sys.argv[1]
|
|
3
3
|
os.makedirs(root,mode=0o700,exist_ok=True)
|
|
4
4
|
with open(root+'/lock','w') as lock:
|
|
@@ -26,6 +26,6 @@ try:
|
|
|
26
26
|
except FileNotFoundError: pass
|
|
27
27
|
print(json.dumps(dict(chunks=chunks,offset=start)))
|
|
28
28
|
# Retain a tombstone if a delayed supervisor can still arrive.
|
|
29
|
-
if pid: shutil.rmtree(root,ignore_errors=True)`;async function
|
|
30
|
-
`);k=
|
|
31
|
-
export{
|
|
29
|
+
if pid: shutil.rmtree(root,ignore_errors=True)`;async function H(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,z=setTimeout(()=>E.abort(),a.timeoutMs),p=a.signal?AbortSignal.any([a.signal,E.signal]):E.signal,w=0,g={stdout:new TextDecoder,stderr:new TextDecoder};async function S(){let y=await d.raw(m(T,l,String(w))),i=JSON.parse(y);if(!N(i)||i.chunks.length>65536||!Number.isSafeInteger(i.offset)||i.offset<w)throw u("Invalid cancellation output");if(i.offset!==w)P(g,a);for(let h of i.chunks){if(!I(h))throw u("Invalid output record");C(h,g,a)}P(g,a)}let O=!1;async function x(){try{await S()}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,p)}catch(c){if(c instanceof e&&c.code==="unsupported")throw c;try{await S()}catch{throw u("Process cancellation could not be confirmed","outcome_unknown")}if(p.aborted)return{exitCode:null,timedOut:!0};throw c}let i=JSON.parse(y);if(!D(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,p.aborted)return await x();for(let c of i.chunks){if(!I(c))throw u("Invalid output record");C(c,g,a)}w=i.offset;let h=i.offset,k="";while(h<i.size){if(p.aborted)return await x();let c;try{c=await d.read(l+"/out",{offset:h,length:Math.min(65536,i.size-h)},p)}catch(b){if(p.aborted)return await x();throw b}if(p.aborted)return await x();if(!c.length)throw u("Incomplete output read");h+=c.length,k+=new TextDecoder().decode(c);let A=k.split(`
|
|
30
|
+
`);k=A.pop()??"";for(let b of A){let R=JSON.parse(b);if(!I(R))throw u("Invalid output record");C(R,g,a),w+=Buffer.byteLength(b)+1}}if(k)throw u("Incomplete output record");return P(g,a),{exitCode:i.result.exitCode,timedOut:i.result.timedOut}}finally{if(clearTimeout(z),O)await d.raw(`rm -rf -- ${n(l)}`).catch(()=>{})}}function C(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 P(s,d){for(let a of["stdout","stderr"]){let f=s[a].decode();if(f)d.onChunk({stream:a,text:f})}}
|
|
31
|
+
export{H};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import{p,l,O}from"./chunk-sjnk17y5.js";import{n}from"./chunk-2ts3evzh.js";import{K}from"./chunk-2999xbh7.js";import{t,r,e,M,s}from"./chunk-0eeyc0aq.js";import{posix as A,resolve as I,relative as ge}from"node:path";import{tmpdir as Q}from"node:os";import{execFile as he}from"node:child_process";import{promisify as xe}from"node:util";import{promises as P}from"node:fs";function be(d,a,x){let b=(k)=>k?k.replace(/\n$/,"").split(`
|
|
2
|
+
`):[],C=b(a),c=b(x),R=(k,j)=>j&&!k?.endsWith(`
|
|
3
|
+
`)?`\
|
|
4
|
+
`:"";return[`--- ${a===void 0?"/dev/null":`a/${d}`}
|
|
5
|
+
`,`+++ ${x===void 0?"/dev/null":`b/${d}`}
|
|
6
|
+
`,`@@ -${C.length?1:0},${C.length} +${c.length?1:0},${c.length} @@
|
|
7
|
+
`,...C.map((k)=>`-${k}
|
|
8
|
+
`),R(a,C.length),...c.map((k)=>`+${k}
|
|
9
|
+
`),R(x,c.length)].join("")}async function Z(d,a){try{await d.remove(a)}catch(x){if(M(x))return;if(x instanceof e&&x.code==="provider"&&!await d.exists(a))return;throw x}}function ee(d){return t(d)||d instanceof Uint8Array}var re=(d)=>d.split(/(\*\*\/|\*\*|\*|\?)/);function te(d,a){let x=re(a).map((b)=>b==="**/"?"(?:.*/)?":b==="**"?".*":b==="*"?"[^/]*":b==="?"?".":b.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")).join("");return new RegExp(`^${x}$`).test(d)||!a.includes("/")&&new RegExp(`^${x}$`).test(A.basename(d))}function ve(d){let x=(b)=>Array.from({length:b.length},(C,c)=>`\\u${b.charCodeAt(c).toString(16).padStart(4,"0")}`).join("");return re(d).map((b)=>b==="**/"?"(?:[^\\n\\r\\u2028\\u2029]*/)?":b==="**"?"[^\\n\\r\\u2028\\u2029]*":b==="*"?"[^/]*":b==="?"?"[^\\n\\r\\u2028\\u2029]":x(b)).join("")}var ke=`import json,os,stat,sys
|
|
10
|
+
try:
|
|
11
|
+
a=json.loads(os.environ.get("SANDBOX_SDK_INPUT") or sys.stdin.buffer.read());p=os.path.realpath(a["path"]);f=a["find"].encode();r=a["replace"].encode();w=a["write"]
|
|
12
|
+
s=os.stat(p)
|
|
13
|
+
if not stat.S_ISREG(s.st_mode) or (w!="in-place" and s.st_nlink>1):sys.exit(70)
|
|
14
|
+
with open(p,"rb") as h:d=h.read()
|
|
15
|
+
except Exception:sys.exit(70)
|
|
16
|
+
m=[];n=1;q=0;i=d.find(f)
|
|
17
|
+
while i>=0:n+=d.count(b"\\n",q,i);q=i;m.append(n);i=d.find(f,i+1)
|
|
18
|
+
if len(m)!=1:print(" ".join(map(str,m)));sys.exit(3)
|
|
19
|
+
i=d.find(f);o=d[:i]+r+d[i+len(f):]
|
|
20
|
+
def put(fd,b):
|
|
21
|
+
os.lseek(fd,0,0);v=memoryview(b)
|
|
22
|
+
while v:v=v[os.write(fd,v):]
|
|
23
|
+
os.ftruncate(fd,len(b))
|
|
24
|
+
if w=="in-place":
|
|
25
|
+
try:fd=os.open(p,os.O_WRONLY)
|
|
26
|
+
except Exception:sys.exit(70)
|
|
27
|
+
try:put(fd,o)
|
|
28
|
+
except Exception:
|
|
29
|
+
try:put(fd,d)
|
|
30
|
+
except Exception:sys.exit(71)
|
|
31
|
+
sys.exit(70)
|
|
32
|
+
sys.exit(0)
|
|
33
|
+
t="%s/.%s.%s.sdk-edit"%(os.path.dirname(p),os.path.basename(p),os.urandom(6).hex())
|
|
34
|
+
try:fd=os.open(t,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
35
|
+
except Exception:sys.exit(70)
|
|
36
|
+
try:
|
|
37
|
+
with os.fdopen(fd,"wb") as h:h.write(o)
|
|
38
|
+
if (s.st_uid,s.st_gid)!=(os.geteuid(),os.getegid()):os.chown(t,s.st_uid,s.st_gid)
|
|
39
|
+
os.chmod(t,stat.S_IMODE(s.st_mode));os.rename(t,p)
|
|
40
|
+
except Exception:
|
|
41
|
+
os.unlink(t);sys.exit(70)`,$e=`import base64,json,os,re,stat,sys
|
|
42
|
+
def u(s):
|
|
43
|
+
if all(c<="\\uffff" for c in s):return s
|
|
44
|
+
b=s.encode("utf-16-le","surrogatepass");return "".join(chr(int.from_bytes(b[i:i+2],"little")) for i in range(0,len(b),2))
|
|
45
|
+
files=[]
|
|
46
|
+
def walk(d,rel):
|
|
47
|
+
names=os.listdir(d)
|
|
48
|
+
for b in sorted(names) if order=="name" else names:
|
|
49
|
+
p=os.path.join(d,b);s=os.lstat(p);name=b.decode("utf-8","replace");r=rel+name
|
|
50
|
+
if stat.S_ISREG(s.st_mode) and (g is None or g.fullmatch(u(r)) or (base and g.fullmatch(u(name)))):files.append((p,os.path.join(root,r)))
|
|
51
|
+
elif stat.S_ISDIR(s.st_mode):walk(p,r+"/")
|
|
52
|
+
try:
|
|
53
|
+
a=json.loads(os.environ.get("SANDBOX_SDK_INPUT") or sys.stdin.buffer.read())
|
|
54
|
+
root=a["root"];q=a["query"].encode();g=re.compile(a["pattern"]) if a["pattern"] else None;base=a["base"]is True;mx=int(a["max"]);order=a["order"]
|
|
55
|
+
walk(os.fsencode(root),"");n=0
|
|
56
|
+
for p,shown in files:
|
|
57
|
+
with open(p,"rb") as h:lines=h.read().split(b"\\n")
|
|
58
|
+
for i,line in enumerate(lines):
|
|
59
|
+
if q in line:
|
|
60
|
+
print(json.dumps([shown,i+1,base64.b64encode(line).decode()]));n+=1
|
|
61
|
+
if n>=mx:sys.exit(0)
|
|
62
|
+
except Exception:sys.exit(70)`,ne=(d)=>!/\p{Cs}|[\uFEFF\uFFFD]/u.test(d),L=(d)=>!/\p{Cs}/u.test(d),Se=(d)=>`python3 -I -S -c ${n(d)}`,_e=new Set(["auth","invalid_argument","unsupported","quota","not_found"]),Ce=(d)=>K(d)||d instanceof e&&_e.has(d.code),ie=(d,a)=>new e(`Edit failed at ${d}. ${a.length?`Matches on lines ${a.join(", ")}`:"Text not found"}. Supply a unique exact match.`,{code:a.length?"edit_not_unique":"edit_not_found"});function Pe(d){return Array.isArray(d)&&d.length===3&&t(d[0])&&Number.isSafeInteger(d[1])&&t(d[2])}var se=new WeakMap;function we(d,a,x){let b=se.get(d);return b?b(a,x):d.read(a,{as:"bytes"})}function ce(d,a,x,b=()=>{},C=async()=>{}){let c=d.files,R=new Set,k=xe(he);async function j(i){if((await d.exec(a,{command:i,cwd:"/workspace",env:p,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 X=d.name!=="memory";async function q(i,o,f){if(!X)return{exitCode:70,stdout:""};let m="",u=JSON.stringify(o),w=Buffer.byteLength(u)<=32768,h=await c.guestInput?.(a)??"stdin";if(h==="none"||h==="env"&&!w)return{exitCode:70,stdout:""};let g;try{g=await d.exec(a,{command:Se(i),cwd:"/",env:{...p,SANDBOX_SDK_INPUT:w?u:""},stdin:w?void 0:u,timeoutMs:120000,onChunk(y){if(y.stream==="stdout")m+=y.text}})}catch(y){if(!f||Ce(y))throw y;throw new e("File edit outcome unknown. The guest command may have run before the call failed. Read the file to check its state before retrying.",{code:"outcome_unknown",provider:d.name,sandboxId:a,cause:x.error(y,d.name,a)})}if(g.timedOut||g.exitCode===null||g.exitCode>=128){if(!f)return{exitCode:70,stdout:""};throw new e("File edit outcome unknown. The guest command was stopped before it reported. Read the file to check its state before retrying.",{code:"outcome_unknown"})}if(g.exitCode===126||g.exitCode===127)X=!1;return{exitCode:g.exitCode,stdout:m}}let E=async(i)=>{try{return b(),await C().finally(b),await i()}catch(o){throw x.error(o,d.name,a)}};async function W(i=".",o={}){let f=l(i),m=[];async function u(w){for(let h of await c.list(a,w)){if(!o.glob||te(A.relative(f,h.path),o.glob))m.push(h);if(o.recursive&&h.type==="directory")await u(h.path)}}return await u(f),m}async function G(i,o){let f=await E(()=>c.read(a,l(i)));return o?.as==="bytes"?f:new TextDecoder().decode(f)}async function D(i,o,f){let m=t(i),u=m?[[i,ee(o)?o:""]]:Object.entries(i),w=(m?f:ee(o)?void 0:o)??{},{mode:h}=w,g=new Set;await E(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 y=[];for(let[T,F]of u){let _=l(T),v=A.dirname(_);if(!c.writeCreatesParents&&!g.has(v))await c.mkdir(a,v),g.add(v);await c.write(a,_,t(F)?new TextEncoder().encode(F):F,w),y.push(_)}if(h===void 0||c.writeSupportsMode||!y.length)return;let S=await d.exec(a,{command:`chmod ${h.toString(8)} ${y.map(n).join(" ")}`,cwd:"/workspace",env:p,timeoutMs:30000,onChunk(){}});if(S.timedOut||S.exitCode!==0)throw new e(`File mode not applied. chmod ${S.timedOut?"timed out":`exited with ${S.exitCode}`}; the files were written with default permissions. Check that the paths are writable and retry.`,{code:"provider"})})}let N="/tmp/.sandbox-sdk/changes.git";async function U(i,o){let f="";if((await d.exec(a,{command:`git --git-dir=${n(N)} --work-tree=/workspace ${i}`,cwd:"/workspace",env:{...p,GIT_INDEX_FILE:`${N}/sdk.index`},stdin:o,timeoutMs:120000,onChunk(u){if(u.stream==="stdout")f+=u.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 f}async function z(i){let o=["-name .git",...(c.internal??[]).map((w)=>`-path ${n(`./${A.relative("/workspace",l(w))}`)}`)].join(" -o "),f=`command -v git >/dev/null 2>&1 || exit 69
|
|
63
|
+
command -v find >/dev/null 2>&1 || exit 78
|
|
64
|
+
g=${n(N)}
|
|
65
|
+
# A fresh index per call: a killed attempt leaves no index.lock to block later checkpoints.
|
|
66
|
+
export GIT_INDEX_FILE="$g/tree.$$.index"; paths="$g/tree.$$.paths"; trap 'rm -f "$GIT_INDEX_FILE" "$GIT_INDEX_FILE.lock" "$paths"' EXIT
|
|
67
|
+
[ -d "$g" ] || git init -q --bare "$g" >/dev/null || exit 69
|
|
68
|
+
cd /workspace && find . \\( ${o} \\) -prune -o ! -type d -print0 > "$paths" || exit 1
|
|
69
|
+
git --git-dir="$g" --work-tree=/workspace read-tree --empty || exit 1
|
|
70
|
+
git --git-dir="$g" --work-tree=/workspace update-index --add --remove -z --stdin < "$paths" || exit 1
|
|
71
|
+
tree=$(git --git-dir="$g" --work-tree=/workspace write-tree) || exit 1
|
|
72
|
+
${i?`mkdir -p ${n(A.dirname(i))} && printf '%s' "$tree" > ${n(i)} || exit 1
|
|
73
|
+
`:""}printf '%s\\n' "$tree"`,m="",u=await d.exec(a,{command:f,cwd:"/workspace",env:p,timeoutMs:120000,onChunk(w){if(w.stream==="stdout")m+=w.text}});if(u.exitCode===78){let w=await de();if(i)await D(i,w);return w}if(u.exitCode===69)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"});if(u.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 m.trim()}async function de(){if(!await J(N)){if((await d.exec(a,{command:`git init --bare ${n(N)}`,cwd:"/workspace",env:p,timeoutMs:1e4,onChunk(){}})).exitCode!==0)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"})}let i=[],o=new Set((c.internal??[]).map((m)=>l(m)));async function f(m){for(let u of await c.list(a,m)){if(A.basename(u.path)===".git"||o.has(u.path))continue;if(u.type==="directory")await f(u.path);else i.push(A.relative("/workspace",u.path))}}if(await f("/workspace"),await U("read-tree --empty"),i.length)await U("update-index --add --remove -z --stdin",i.join("\x00")+"\x00");return(await U("write-tree")).trim()}async function J(i){try{return await c.stat(a,i),!0}catch(o){if(M(o))return!1;throw o}}async function Y(){let i={};for(let o of await W(".",{recursive:!0}))if(o.type==="file")i[o.path]=Buffer.from(await c.read(a,o.path)).toString("base64");return i}let B=(i)=>`/tmp/.sandbox-sdk/marks/${encodeURIComponent(i)}.json`;async function fe(i){let o=JSON.parse(new TextDecoder().decode(await c.read(a,B(i))));if(!r(o)||Array.isArray(o))s("Invalid file checkpoint");let f={};for(let[m,u]of Object.entries(o)){if(!t(u))s("Invalid file checkpoint content");f[m]=u}return f}async function V(i,o){try{return await o()}catch(f){if((i??"start")==="start"&&!await J(B("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 f}}let pe=(i)=>V(i,()=>G(B(i??"start"))),H={[Symbol.dispose](){for(let i of R)i()},read:G,write:D,list:(i,o)=>E(()=>W(i,o)),stat:(i)=>E(()=>c.stat(a,l(i))),exists:(i)=>E(async()=>{try{return await c.stat(a,l(i)),!0}catch(o){if(M(o))return!1;throw o}}),remove:(i,o)=>E(()=>c.remove(a,l(i),{recursive:o?.recursive??!1})),edit:(i,{find:o,replace:f})=>E(async()=>{if(!o)s("find cannot be empty");let m=l(i);if(c.editInGuest&&ne(o)&&L(f)&&L(m)){let{exitCode:g,stdout:y}=await q(ke,{path:m,find:o,replace:f,write:c.editInGuest},!0);if(g===0)return;if(g===3)throw ie(i,y.trim()?y.trim().split(" ").map(Number):[]);if(g===71)throw new e(`File edit outcome unknown at ${i}. Writing the file failed and its original contents could not be restored. Read the file to check its state before retrying.`,{code:"outcome_unknown"})}let u=await G(i),w=[],h=u.indexOf(o);while(h!==-1)w.push(u.slice(0,h).split(`
|
|
74
|
+
`).length),h=u.indexOf(o,h+1);if(w.length!==1)throw ie(i,w);await c.write(a,m,new TextEncoder().encode(u.replace(o,()=>f)))}),upload:(i,o,f)=>E(async()=>{let m=I(i);if(c.transfer!=="files"&&(await P.lstat(m)).isDirectory()){let w=await P.mkdtemp(I(Q(),"sandbox-sdk-upload-")),h=`/tmp/.sandbox-sdk/upload-${crypto.randomUUID()}.tar`;try{let g=I(w,"files.tar");await k("tar",["-cf",g,"-C",m,...(f?.ignore??[]).flatMap((y)=>["--exclude",y]),"."],{timeout:120000}),await D(h,new Uint8Array(await P.readFile(g))),await c.mkdir(a,l(o)),await j(`tar -xf ${n(h)} -C ${n(l(o))} --no-same-owner`)}finally{await P.rm(w,{recursive:!0,force:!0}),await c.remove(a,h,{recursive:!1}).catch(()=>{})}return}async function u(w,h){let g=await P.lstat(w);if(g.isSymbolicLink())s("Uploading symlinks is unsupported");if(g.isDirectory()){await c.mkdir(a,l(h));for(let y of await P.readdir(w))if(!f?.ignore?.some((S)=>te(ge(m,I(w,y)),S)||S===y))await u(I(w,y),A.join(h,y))}else await D(h,new Uint8Array(await P.readFile(w)))}await u(m,o)}),download:(i,o)=>E(async()=>{if(c.transfer!=="files"&&(await c.stat(a,l(i))).type==="directory"){let m=await P.mkdtemp(I(Q(),"sandbox-sdk-download-")),u=`/tmp/.sandbox-sdk/download-${crypto.randomUUID()}.tar`;try{await j(`mkdir -p ${n(A.dirname(u))} && tar -cf ${n(u)} -C ${n(l(i))} .`);let w=I(m,"files.tar");await P.writeFile(w,await c.read(a,u)),await P.mkdir(I(o),{recursive:!0}),await k("tar",["-xf",w,"-C",I(o),"--no-same-owner","--no-same-permissions"],{timeout:120000})}finally{await P.rm(m,{recursive:!0,force:!0}),await c.remove(a,u,{recursive:!1}).catch(()=>{})}return}async function f(m,u){let w=await c.stat(a,m);if(w.type==="symlink")s("Downloading symlinks is unsupported");if(w.type==="directory"){await P.mkdir(u,{recursive:!0});for(let h of await c.list(a,m))await f(h.path,I(u,A.basename(h.path)))}else await P.mkdir(I(u,".."),{recursive:!0}),await P.writeFile(u,await c.read(a,m))}await f(l(i),I(o))}),search:(i,o={})=>E(async()=>{let f=[],m=o.maxMatches??200;if(!Number.isSafeInteger(m)||m<1)s("maxMatches must be positive");let u=l(o.path);if(c.listOrder&&i&&!i.includes(`
|
|
75
|
+
`)&&ne(i)&&L(u)){let w=o.glob??"",{exitCode:h,stdout:g}=await q($e,{root:u,query:i,pattern:w&&ve(w),base:w!==""&&!w.includes("/"),max:m,order:c.listOrder},!1);if(h===0){for(let y of g.split(`
|
|
76
|
+
`)){if(!y)continue;let S=JSON.parse(y);if(!Pe(S)){f.length=0;break}let T=new TextDecoder("utf-8",{ignoreBOM:S[1]!==1}).decode(Buffer.from(S[2],"base64"));if(!T.includes(i)){f.length=0;break}f.push({path:S[0],line:S[1],text:x.text(T)})}if(f.length||!g)return f}}for(let w of await W(o.path,{recursive:!0,glob:o.glob}))if(w.type==="file"){let h=(await G(w.path)).split(`
|
|
77
|
+
`);for(let[g,y]of h.entries())if(y.includes(i)){if(f.push({path:w.path,line:g+1,text:x.text(y)}),f.length>=m)return f}}return f}),watch(i,o,f={}){b();let m=!1,u,w,h=()=>{},g=new AbortController,y=async()=>{try{if(await C(),m)return;let _=new Map((await W(i,f)).map((v)=>[v.path,`${v.size}:${v.modifiedAt}`]));if(u){for(let[v,me]of _)if(!u.has(v)||u.get(v)!==me){if(!m)o({type:u.has(v)?"modified":"added",path:v})}for(let v of u.keys())if(!_.has(v)&&!m)o({type:"removed",path:v})}u=_}catch(_){f.onError?.(x.error(_,d.name,a))}if(!m)w=setTimeout(()=>void y(),f.intervalMs??250),w.unref?.()},S=(_)=>new Promise((v)=>{h=v,w=setTimeout(v,_),w.unref?.()}),T=async(_)=>{while(!m){try{if(await C(),m)return;await _.call(c,a,l(i),{recursive:f.recursive??!1,signal:g.signal,onEvent(v){if(!m)o(v)}})}catch(v){if(m)return;if(v instanceof e&&v.code==="unsupported"){y();return}f.onError?.(x.error(v,d.name,a))}if(!m)await S(1000)}},F=()=>{m=!0,clearTimeout(w),h(),g.abort(),R.delete(F)};if(R.add(F),c.watch)T(c.watch);else y();return F},mark:(i=`mark-${Date.now()}-${Math.random().toString(36).slice(2)}`)=>E(async()=>{if(c.checkpoints==="files")await D(B(i),JSON.stringify(await Y()));else await z(B(i));return i}),changes:(i={})=>E(async()=>{if(c.checkpoints!=="files"){let g=(await pe(i.since)).trim(),y=await z();if(!/^[0-9a-f]{40,64}$/.test(g))s("Invalid git checkpoint");let S=(await U(`diff --no-renames --name-status -z ${g} ${y}`)).split("\x00"),T={added:[],modified:[],removed:[],patch:x.text(await U(`diff --no-ext-diff --binary ${g} ${y}`))};for(let F=0;F+1<S.length;F+=2){let _=S[F],v=S[F+1];if(v)(_==="A"?T.added:_==="D"?T.removed:T.modified).push(l(v))}return T}let o=await V(i.since,()=>fe(i.since??"start")),f=await Y(),m=Object.keys(f).filter((g)=>!(g in o)),u=Object.keys(o).filter((g)=>!(g in f)),w=Object.keys(f).filter((g)=>(g in o)&&o[g]!==f[g]),h=[...m,...w,...u].map((g)=>be(A.relative("/workspace",g),g in o?Buffer.from(o[g]??"","base64").toString():void 0,g in f?Buffer.from(f[g]??"","base64").toString():void 0)).join("");return{added:m,modified:w,removed:u,patch:x.text(h)}})};return se.set(H,(i,o)=>E(()=>c.readRange?c.readRange(a,l(i),{offset:0,length:o+1}):c.read(a,l(i)))),H}import{stripVTControlCharacters as Ee}from"node:util";var oe=new WeakMap;function ye(d,a){oe.set(d,a)}function ae(d){let a=oe.get(d);if(!a)throw Error("Unknown sandbox handle. Secret redaction cannot be guaranteed. Use createSandbox or connectSandbox.");return a}function ue(d,a){return ae(d).text(Ee(a))}function le(d,a){let x={stdout:"plain",stderr:"plain"},b=O(ae(d),a,!0);return{push(C){let c=x[C.stream],R="";for(let k of C.text)switch(c){case"plain":if(k==="\x1B")c="escape";else if(k==="")c="csi";else if("".includes(k))c="string";else R+=k;break;case"escape":c=k==="["?"csi":"]PX^_".includes(k)?"string":k>=" "&&k<="/"?"escape":"plain";break;case"csi":if(k>="@"&&k<="~")c="plain";break;case"string":if(k==="\x07"||k==="")c="plain";else if(k==="\x1B")c="string_escape";break;case"string_escape":c=k==="\\"?"plain":"string";break;default:return c}if(x[C.stream]=c,R)b.push({stream:C.stream,text:R})},flush(){b.flush()}}}
|
|
78
|
+
export{Z,we,ce,ye,ue,le};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t,o}from"./chunk-
|
|
2
|
-
export{
|
|
1
|
+
import{t,o}from"./chunk-0eeyc0aq.js";function A(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{A};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{se}from"./chunk-qfhee1t8.js";import{t,r,e,y,s}from"./chunk-0eeyc0aq.js";function g(a){return a instanceof Function||r(a)&&!Array.isArray(a)}function N(a,o,l){if(!g(a))s(`${o} from ${l} is not an object. Install a supported version of ${l}`);return a}var x=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE"]);function b(a){let{http:o,placeholder:l,sandboxId:i,sdk:d}=a,u=t(l)?[l]:l;function h(p,c,n={}){if(!t(p)||!x.has(p))s(`Unsupported HTTP method ${String(p).slice(0,16)}`);if(!t(c))s("The path must be a string");let m=u.filter((f)=>c.includes(`{${f}}`)&&n.params?.[f]===void 0),k=i===void 0||m.length===0?n.params:{...n.params,...Object.fromEntries(m.map((f)=>[f,i]))};return{method:p,path:c,plane:n.plane,sandboxId:i,params:k,query:n.query,body:n.body,headers:n.headers,signal:n.signal,timeoutMs:n.timeoutMs,detail:"message"}}async function v(p){if(!d)throw new e(`${o.label} has no official SDK binding. Use native.request or native.fetch.`,{code:"unsupported",provider:o.provider,sandboxId:i});if(!(p instanceof Function))s(`Pass a function that imports the SDK: native.sdk(() => import("${d.package}"))`);let c;try{c=se(await p())}catch(n){if(n instanceof Error&&(("code"in n)&&(n.code==="ERR_MODULE_NOT_FOUND"||n.code==="MODULE_NOT_FOUND")||/Cannot find (?:package|module)/.test(n.message)))throw new e(`${d.package} could not be imported. Install it next to @opencoredev/sandbox-sdk to use native.sdk().`,{code:"unavailable",provider:o.provider,sandboxId:i,hint:`npm i ${d.package}`,cause:y(n,o.redact)});throw new e(`Loading ${d.package} failed: ${y(n,o.redact)??"a non-Error value was thrown"}. Check the import passed to native.sdk().`,{code:"provider",provider:o.provider,sandboxId:i})}if(!g(c)||Array.isArray(c))s(`native.sdk() needs the module object. Pass () => import("${d.package}")`);try{return await d.connect(c,i)}catch(n){if(n instanceof e)throw n;throw new e(`${d.package} failed in native.sdk(): ${y(n,o.redact)??"a non-Error value was thrown"}. Check the SDK version and the sandbox.`,{code:"provider",provider:o.provider,sandboxId:i,cause:y(n,o.redact)})}}return{sandboxId:i,async request(p,c,n){return await o.json(h(p,c,n))},fetch(p,c,n){let{timeoutMs:m,...k}=h(p,c,n);return o.stream({...k,startupTimeoutMs:m})},sdk:v}}function S(a,o,l,i){let d=a[o];if(!(d instanceof Function))s(`The module passed to native.sdk() has no ${o} export. Pass () => import("${i}")`);try{return N(Reflect.construct(d,l),o,i)}catch(u){if(u instanceof TypeError&&/constructor/i.test(u.message))s(`${o} from the module passed to native.sdk() is not a class. Pass () => import("${i}")`);throw u}}async function P(a,o,l,i){let d=g(a)?a[o]:void 0;if(!(d instanceof Function))s(`The ${i} object has no ${o} method. Install a supported version of ${i}`);return await d.apply(a,l)}
|
|
2
|
+
export{N,b,S,P};
|
|
File without changes
|