@opencoredev/sandbox-sdk 1.0.3 → 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.
Files changed (87) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +9 -6
  3. package/dist/ai.js +1 -1
  4. package/dist/chunk-0eeyc0aq.js +4 -0
  5. package/dist/chunk-0wp6x4wb.js +2 -0
  6. package/dist/chunk-2999xbh7.js +2 -0
  7. package/dist/chunk-3h6c1ack.js +2 -0
  8. package/dist/{chunk-19gteae8.js → chunk-7rkcx5cx.js} +2 -2
  9. package/dist/{chunk-rnksrxfc.js → chunk-7s9pxk1v.js} +3 -3
  10. package/dist/chunk-aek8n3a4.js +78 -0
  11. package/dist/{chunk-r8xnq6v3.js → chunk-aq6fmgdx.js} +2 -2
  12. package/dist/chunk-drhcb2hx.js +2 -0
  13. package/dist/{chunk-2z6fxyg5.js → chunk-ek44atpe.js} +2 -2
  14. package/dist/chunk-g5n5xcmp.js +0 -0
  15. package/dist/{chunk-6bemkxcx.js → chunk-kdecey83.js} +12 -12
  16. package/dist/{chunk-drgkmewv.js → chunk-pdgnaxp9.js} +2 -2
  17. package/dist/{chunk-3zd78ha4.js → chunk-qfhee1t8.js} +2 -2
  18. package/dist/chunk-rx9318sh.js +5 -0
  19. package/dist/chunk-sjnk17y5.js +26 -0
  20. package/dist/chunk-w8nk1xf2.js +17 -0
  21. package/dist/{chunk-g0vk7g1k.js → chunk-x05t86n3.js} +2 -2
  22. package/dist/{chunk-c1wemt0y.js → chunk-x4rrgmxf.js} +11 -11
  23. package/dist/chunk-xqtzts2q.js +1 -0
  24. package/dist/errors.d.ts +19 -9
  25. package/dist/files.d.ts +2 -5
  26. package/dist/index.d.ts +24 -3
  27. package/dist/index.js +1 -1
  28. package/dist/mastra.js +1 -1
  29. package/dist/memory.js +1 -1
  30. package/dist/openai.js +1 -1
  31. package/dist/provider.d.ts +102 -7
  32. package/dist/provider.js +1 -1
  33. package/dist/providers/agentos/index.js +2 -2
  34. package/dist/providers/baseten/errors.d.ts +6 -0
  35. package/dist/providers/baseten/execute.d.ts +68 -0
  36. package/dist/providers/baseten/index.d.ts +3 -0
  37. package/dist/providers/baseten/index.js +97 -0
  38. package/dist/providers/baseten/provider.d.ts +39 -0
  39. package/dist/providers/boat/index.js +1 -1
  40. package/dist/providers/boxd/errors.d.ts +25 -3
  41. package/dist/providers/boxd/index.js +7 -5
  42. package/dist/providers/boxd/provider.d.ts +16 -2
  43. package/dist/providers/daytona/api.d.ts +2 -2
  44. package/dist/providers/daytona/index.js +15 -15
  45. package/dist/providers/e2b/envd.d.ts +32 -2
  46. package/dist/providers/e2b/errors.d.ts +1 -2
  47. package/dist/providers/e2b/index.d.ts +40 -4
  48. package/dist/providers/e2b/index.js +1 -1
  49. package/dist/providers/e2b/narrow.d.ts +7 -0
  50. package/dist/providers/freestyle/index.js +6 -6
  51. package/dist/providers/instabox/api.d.ts +56 -0
  52. package/dist/providers/instabox/errors.d.ts +49 -0
  53. package/dist/providers/instabox/index.d.ts +4 -0
  54. package/dist/providers/instabox/index.js +7 -0
  55. package/dist/providers/instabox/provider.d.ts +28 -0
  56. package/dist/providers/local/index.js +2 -2
  57. package/dist/providers/modal/errors.d.ts +4 -0
  58. package/dist/providers/modal/index.d.ts +14 -0
  59. package/dist/providers/modal/index.js +2 -0
  60. package/dist/providers/modal/provider.d.ts +94 -0
  61. package/dist/providers/modal/transport.d.ts +50 -0
  62. package/dist/providers/railway/index.js +1 -1
  63. package/dist/providers/sandboxer/index.js +1 -1
  64. package/dist/providers/superserve/index.js +5 -5
  65. package/dist/providers/tenki/deadline.d.ts +1 -1
  66. package/dist/providers/tenki/index.js +13 -13
  67. package/dist/providers/tenki/provider.d.ts +12 -12
  68. package/dist/providers/tenki/records.d.ts +1 -1
  69. package/dist/providers/upstash/index.js +11 -11
  70. package/dist/providers/vercel/index.js +1 -1
  71. package/dist/providers/vercel/transport.d.ts +1 -1
  72. package/dist/shared/native-error.d.ts +2 -0
  73. package/dist/streams.d.ts +2 -1
  74. package/dist/testing.js +3 -3
  75. package/dist/tools.js +1 -1
  76. package/dist/types.d.ts +32 -13
  77. package/dist/version.d.ts +4 -0
  78. package/package.json +28 -4
  79. package/dist/chunk-11mbpwem.js +0 -17
  80. package/dist/chunk-1k6yz176.js +0 -1
  81. package/dist/chunk-305dymgq.js +0 -2
  82. package/dist/chunk-348pdz09.js +0 -5
  83. package/dist/chunk-5gnqph3c.js +0 -78
  84. package/dist/chunk-6nf686jb.js +0 -26
  85. package/dist/chunk-ea8y7y2p.js +0 -2
  86. package/dist/chunk-n7x9ha44.js +0 -4
  87. package/dist/chunk-tvw3kb8b.js +0 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
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
+
3
20
  ## 1.0.3
4
21
 
5
22
  ### 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, Tenki, boxd, Freestyle, Superserve, Boat, Sandboxer, Docker on your machine, and an in-process fake for tests. Changing provider means changing one import.
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, 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.
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
- | [Tenki](https://sandbox-sdk.app/docs/providers/tenki) | `/tenki` | `tenki()` | `TENKI_AUTH_TOKEN` or `TENKI_API_KEY` |
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: [...] }`. The SDK also defines `terminal` (`box.terminal()`, an interactive PTY), but no built-in provider supports it yet.
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, Tenki, Upstash, Boat), and Boat's default machine size uses `machine`:
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
- | Tenki | ±0 | +119 | +15 |
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{Y}from"./chunk-6nf686jb.js";import{R}from"./chunk-c1wemt0y.js";import"./chunk-5gnqph3c.js";import{tool as u}from"ai";function b(p,m){return Object.fromEntries(R(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 Y,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};
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{r}from"./chunk-0eeyc0aq.js";function c(e){return r(e)&&!Array.isArray(e)}
2
+ export{c};
@@ -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{f}from"./chunk-tvw3kb8b.js";import{t,o}from"./chunk-n7x9ha44.js";function s(n){if(!f(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 D(n,e){let a;try{a=JSON.parse(n)}catch{e("metadata")}if(!f(a)||!f(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{D};
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{p}from"./chunk-6bemkxcx.js";import{n}from"./chunk-2ts3evzh.js";import{t,o,_,r,e}from"./chunk-n7x9ha44.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&&_(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
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 q(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),m=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(p(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,m)}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(m.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,m.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(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 A=k.split(`
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
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{q};
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-n7x9ha44.js";function C(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{C};
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
+ var x="sandbox-sdk/1.1.0";
2
+ export{x};
@@ -1,2 +1,2 @@
1
- import{ee}from"./chunk-3zd78ha4.js";import{t,r,e,h,s}from"./chunk-n7x9ha44.js";function b(a){return a instanceof Function||r(a)&&!Array.isArray(a)}function T(a,o,l){if(!b(a))s(`${o} from ${l} is not an object. Install a supported version of ${l}`);return a}var y=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE"]);function w(a){let{http:o,placeholder:l,sandboxId:i,sdk:d}=a,u=t(l)?[l]:l;function S(p,c,n={}){if(!t(p)||!y.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),g=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:g,query:n.query,body:n.body,headers:n.headers,signal:n.signal,timeoutMs:n.timeoutMs,detail:"message"}}async function P(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=ee(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:h(n,o.redact)});throw new e(`Loading ${d.package} failed: ${h(n,o.redact)??"a non-Error value was thrown"}. Check the import passed to native.sdk().`,{code:"provider",provider:o.provider,sandboxId:i})}if(!b(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(): ${h(n,o.redact)??"a non-Error value was thrown"}. Check the SDK version and the sandbox.`,{code:"provider",provider:o.provider,sandboxId:i,cause:h(n,o.redact)})}}return{sandboxId:i,async request(p,c,n){return await o.json(S(p,c,n))},fetch(p,c,n){let{timeoutMs:m,...g}=S(p,c,n);return o.stream({...g,startupTimeoutMs:m})},sdk:P}}function v(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 T(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 k(a,o,l,i){let d=b(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{T,w,v,k};
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
@@ -1,4 +1,4 @@
1
- import{n}from"./chunk-2ts3evzh.js";import{t,o,r,e}from"./chunk-n7x9ha44.js";import{createHash as g}from"node:crypto";var p=(s,...l)=>`python3 -S -c ${n(s)} ${l.map(n).join(" ")}`;function j(s,l="exec(c,{'__name__':'__main__','__builtins__':__builtins__})",f="True"){if(s.includes("'''")||s.endsWith("\\"))throw Error("Supervisor source cannot be embedded");let i=g("sha256").update(s).digest("hex").slice(0,16);return`import os,sys,marshal
1
+ import{n}from"./chunk-2ts3evzh.js";import{t,o,r,e}from"./chunk-0eeyc0aq.js";import{createHash as x}from"node:crypto";var m=(s,...l)=>`python3 -S -c ${n(s)} ${l.map(n).join(" ")}`;function R(s,l="exec(c,{'__name__':'__main__','__builtins__':__builtins__})",f="True"){if(s.includes("'''")||s.endsWith("\\"))throw Error("Supervisor source cannot be embedded");let i=x("sha256").update(s).digest("hex").slice(0,16);return`import os,sys,marshal
2
2
  s=r'''${s}'''
3
3
  p='/tmp/.sandbox-sdk/py-${i}.'+sys.implementation.cache_tag
4
4
  c=None
@@ -20,7 +20,7 @@ if w and ${f}:
20
20
  try: os.unlink(t)
21
21
  except OSError: pass
22
22
  ${l}
23
- `}var y=`def serve(code,z):
23
+ `}var w=`def serve(code,z):
24
24
  import fcntl,_signal as signal
25
25
  base=os.path.dirname(z)
26
26
  try:
@@ -170,10 +170,10 @@ def gone(c,start,claim):
170
170
  if birth(c)!=start:
171
171
  os.unlink(claim); return
172
172
  time.sleep(.001)
173
- `,w=(s)=>`/tmp/.sandbox-sdk/z-${g("sha256").update(s).digest("hex").slice(0,16)}`;function x(s){if(y.includes("'''"))throw Error("Zygote source cannot be embedded");return j(s,`if sys.argv[1:2]==['--serve']:
174
- exec(r'''${y}''')
173
+ `,b=(s)=>`/tmp/.sandbox-sdk/z-${x("sha256").update(s).digest("hex").slice(0,16)}`;function v(s){if(w.includes("'''"))throw Error("Zygote source cannot be embedded");return R(s,`if sys.argv[1:2]==['--serve']:
174
+ exec(r'''${w}''')
175
175
  serve(c,sys.argv[2])
176
- else: exec(c,{'__name__':'__main__','__builtins__':__builtins__})`,"sys.argv[1:2]==['--serve']")}function _(s,l){let f=w(s);return`{ P=${n(s)}; r=${n(l)}; z=${n(f)}; f="$z/c-\${r##*/run-}"; n=1
176
+ else: exec(c,{'__name__':'__main__','__builtins__':__builtins__})`,"sys.argv[1:2]==['--serve']")}function y(s,l){let f=b(s);return`{ P=${n(s)}; r=${n(l)}; z=${n(f)}; f="$z/c-\${r##*/run-}"; n=1
177
177
  if [ ! -e "$z/off" ] && read -r k b 2>/dev/null <"$z/pid" && read -r o </proc/sys/kernel/random/boot_id && [ "$b" = "$o" ] && kill -0 "$k" 2>/dev/null; then
178
178
  trap 'kill "$w" 2>/dev/null; { read -r o; read -r c; } <"$f"; exit "\${c:-70}"' USR1
179
179
  trap 'kill "$w" 2>/dev/null; n=1' USR2
@@ -198,9 +198,9 @@ python3 -S -c "$P" "$r"; c=$?
198
198
  if [ -e "$z.seen" ]; then
199
199
  { [ -e "$z/off" ] || ! command -v setsid >/dev/null || exec setsid env -i PATH="$PATH" python3 -S -c "$P" --serve "$z"; } </dev/null >/dev/null 2>&1 &
200
200
  else : >"$z.seen" 2>/dev/null; fi
201
- exit "$c"; }`}function z(s){let l=x(s),f=`${w(l)}.seen`,i=new Set;return{command(a,c,d){if(d!==void 0&&!/^[0-9a-f]*$/.test(d))throw Error("Supervisor spec must be hex");if(i.has(a))return d===void 0?_(l,c):`${_(l,c)} <<'SDKSPEC'
201
+ exit "$c"; }`}function J(s){let l=v(s),f=`${b(l)}.seen`,i=new Set;return{command(a,c,d){if(d!==void 0&&!/^[0-9a-f]*$/.test(d))throw Error("Supervisor spec must be hex");if(i.has(a))return d===void 0?y(l,c):`${y(l,c)} <<'SDKSPEC'
202
202
  ${d}
203
- SDKSPEC`;if(i.size>=1e4)i.clear();return i.add(a),`{ python3 -S -c ${n(s)} ${n(c)}${d===void 0?"":` ${d}`}; c=$?; : >${n(f)} 2>/dev/null; exit "$c"; }`},zygote:(a)=>_(l,a)}}var b=`def stdin_file():
203
+ SDKSPEC`;if(i.size>=1e4)i.clear();return i.add(a),`{ python3 -S -c ${n(s)} ${n(c)}${d===void 0?"":` ${d}`}; c=$?; : >${n(f)} 2>/dev/null; exit "$c"; }`},zygote:(a)=>y(l,a)}}var g=`def stdin_file():
204
204
  try: return os.fdopen(os.memfd_create('sandbox-sdk-stdin'),'w+b')
205
205
  except (AttributeError,OSError):
206
206
  import tempfile
@@ -255,7 +255,7 @@ class Process:
255
255
  if hasattr(self,'child'): return self.child.wait()
256
256
  if self.code is None: self.code=os.waitstatus_to_exitcode(os.waitpid(self.pid,0)[1])
257
257
  return self.code
258
- `,M=`def pump(p,emit,end):
258
+ `,C=`def pump(p,emit,end):
259
259
  r,w=os.pipe(); os.set_blocking(w,False)
260
260
  signal.set_wakeup_fd(w,warn_on_full_buffer=False)
261
261
  signal.signal(signal.SIGCHLD,lambda *_:None)
@@ -273,18 +273,18 @@ class Process:
273
273
  if data: emit(streams[fd][0],data)
274
274
  else: streams.pop(fd)[1].close()
275
275
  return timed
276
- `,h=(s,l,f="provider")=>new e(`${l}. Check the ${s.name} sandbox before retrying.`,{code:f,provider:s.name}),v=`import os,sys,json,stat
276
+ `,h=(s,l,f="provider")=>new e(`${l}. Check the ${s.name} sandbox before retrying.`,{code:f,provider:s.name}),k=`import os,sys,json,stat
277
277
  p=sys.argv[1]
278
278
  def info(p):
279
279
  s=os.lstat(p)
280
280
  return dict(path=p,type='symlink' if stat.S_ISLNK(s.st_mode) else 'directory' if stat.S_ISDIR(s.st_mode) else 'file',size=s.st_size,modifiedAt=s.st_mtime*1000)
281
281
  try: print(json.dumps([info(os.path.join(p,n)) for n in os.listdir(p)] if sys.argv[2]=='list' else info(p)))
282
- except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`,k="import os,sys; os.makedirs(os.path.dirname(sys.argv[1]),exist_ok=True)",S="import os,sys; os.makedirs(sys.argv[1],exist_ok=True)",O=`import os,sys,shutil
282
+ except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`,S="import os,sys; os.makedirs(os.path.dirname(sys.argv[1]),exist_ok=True)",O="import os,sys; os.makedirs(sys.argv[1],exist_ok=True)",E=`import os,sys,shutil
283
283
  p=sys.argv[1]
284
284
  try:
285
285
  if os.path.isdir(p) and not os.path.islink(p):
286
286
  if sys.argv[2]=='true': shutil.rmtree(p)
287
287
  else: os.rmdir(p)
288
288
  else: os.unlink(p)
289
- except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`;function H(s){return r(s)&&"path"in s&&t(s.path)&&"type"in s&&(s.type==="file"||s.type==="directory"||s.type==="symlink")&&"size"in s&&o(s.size)&&"modifiedAt"in s&&o(s.modifiedAt)}function V(s){return{path:s.path,type:s.type,size:s.size,modifiedAt:s.modifiedAt}}function N(s,l){let f=async(i,a,c)=>{let d=await s(i),u=await d.raw(p(v,a,c));if(u.trim()==="SDK_FILE_NOT_FOUND")throw h(d,"File does not exist","file_not_found");let m=JSON.parse(u);return{g:d,value:m}};return{writeCreatesParents:!0,listOrder:"directory",readRange:(i,a,c)=>l(i,async()=>(await s(i)).read(a,c)),read:(i,a)=>l(i,async()=>(await s(i)).read(a)),write:(i,a,c,d)=>l(i,async()=>{let u=await s(i);try{await l(i,()=>u.upload(a,c,d?.mode))}catch(m){if(!(m instanceof e)||!["not_found","file_not_found"].includes(m.code))throw m;await u.raw(p(k,a)),await u.upload(a,c,d?.mode)}}),stat:(i,a)=>l(i,async()=>{let{g:c,value:d}=await f(i,a,"stat");if(!H(d))throw h(c,"Invalid file metadata");return V(d)}),list:(i,a)=>l(i,async()=>{let{g:c,value:d}=await f(i,a,"list");if(!Array.isArray(d))throw h(c,"Invalid directory listing");return d.map((u)=>{if(!H(u))throw h(c,"Invalid file metadata");return V(u)})}),mkdir:(i,a)=>l(i,async()=>{await(await s(i)).raw(p(S,a))}),remove:(i,a,c)=>l(i,async()=>{let d=await s(i);if((await d.raw(p(O,a,String(c.recursive)))).trim()==="SDK_FILE_NOT_FOUND")throw h(d,"File does not exist","file_not_found")})}}
290
- export{p,j,z,b,M,H,V,N};
289
+ except FileNotFoundError: print('SDK_FILE_NOT_FOUND')`;function G(s){return r(s)&&"path"in s&&t(s.path)&&"type"in s&&(s.type==="file"||s.type==="directory"||s.type==="symlink")&&"size"in s&&o(s.size)&&"modifiedAt"in s&&o(s.modifiedAt)}function W(s){return{path:s.path,type:s.type,size:s.size,modifiedAt:s.modifiedAt}}function _(s,l){let f=async(i,a,c)=>{let d=await s(i),p=await d.raw(m(k,a,c));if(p.trim()==="SDK_FILE_NOT_FOUND")throw h(d,"File does not exist","file_not_found");let u=JSON.parse(p);return{g:d,value:u}};return{writeCreatesParents:!0,listOrder:"directory",readRange:(i,a,c)=>l(i,async()=>(await s(i)).read(a,c)),read:(i,a)=>l(i,async()=>(await s(i)).read(a)),write:(i,a,c,d)=>l(i,async()=>{let p=await s(i);try{await l(i,()=>p.upload(a,c,d?.mode))}catch(u){if(!(u instanceof e)||!["not_found","file_not_found"].includes(u.code))throw u;await p.raw(m(S,a)),await p.upload(a,c,d?.mode)}}),stat:(i,a)=>l(i,async()=>{let{g:c,value:d}=await f(i,a,"stat");if(!G(d))throw h(c,"Invalid file metadata");return W(d)}),list:(i,a)=>l(i,async()=>{let{g:c,value:d}=await f(i,a,"list");if(!Array.isArray(d))throw h(c,"Invalid directory listing");return d.map((p)=>{if(!G(p))throw h(c,"Invalid file metadata");return W(p)})}),mkdir:(i,a)=>l(i,async()=>{await(await s(i)).raw(m(O,a))}),remove:(i,a,c)=>l(i,async()=>{let d=await s(i);if((await d.raw(m(E,a,String(c.recursive)))).trim()==="SDK_FILE_NOT_FOUND")throw h(d,"File does not exist","file_not_found")})}}
290
+ export{m,R,J,g,C,G,W,_};
@@ -1,2 +1,2 @@
1
- import{t,o,r}from"./chunk-n7x9ha44.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};
1
+ import{t,o,r}from"./chunk-0eeyc0aq.js";function u(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("reason"in n&&t(n.reason))e.reason=n.reason;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{u};
@@ -1,2 +1,2 @@
1
- import{r,e}from"./chunk-n7x9ha44.js";var c=(n)=>`Bundle with a createRequire banner (import { createRequire } from "node:module"; const require = createRequire(import.meta.url);) or mark @opencoredev/sandbox-sdk and ${n} as external.`;async function g(n,i,o){let a;try{a=await o()}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ERR_MODULE_NOT_FOUND"&&t.message.includes(`'${n}'`))throw new e(`${n} is not installed. The ${i} adapter loads it as an optional peer. Install ${n} next to @opencoredev/sandbox-sdk.`,{code:"unavailable",provider:i,cause:t});let s=t instanceof Error?/Dynamic require of "[^"]{1,100}" is not supported/.exec(t.message)?.[0]:void 0;if(s===void 0)throw t;throw new e(`${n} could not load in this bundle: ${s}. ${c(n)}`,{code:"unavailable",provider:i,hint:c(n),cause:s})}return ee(a)}function ee(n){if(!r(n)||!("default"in n))return n;let i=n.default;if(!r(i))return n;if(Object.keys(i).every((o)=>(o in n)))return n;return Object.assign({},i,n)}
2
- export{g,ee};
1
+ import{r,e}from"./chunk-0eeyc0aq.js";var c=(n)=>`Bundle with a createRequire banner (import { createRequire } from "node:module"; const require = createRequire(import.meta.url);) or mark @opencoredev/sandbox-sdk and ${n} as external.`;async function h(n,i,o){let a;try{a=await o()}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ERR_MODULE_NOT_FOUND"&&t.message.includes(`'${n}'`))throw new e(`${n} is not installed. The ${i} adapter loads it as an optional peer. Install ${n} next to @opencoredev/sandbox-sdk.`,{code:"unavailable",provider:i,cause:t});let s=t instanceof Error?/Dynamic require of "[^"]{1,100}" is not supported/.exec(t.message)?.[0]:void 0;if(s===void 0)throw t;throw new e(`${n} could not load in this bundle: ${s}. ${c(n)}`,{code:"unavailable",provider:i,hint:c(n),cause:s})}return se(a)}function se(n){if(!r(n)||!("default"in n))return n;let i=n.default;if(!r(i))return n;if(Object.keys(i).every((o)=>(o in n)))return n;return Object.assign({},i,n)}
2
+ export{h,se};
@@ -0,0 +1,5 @@
1
+ import{p}from"./chunk-sjnk17y5.js";import{u}from"./chunk-pdgnaxp9.js";import{z,pe}from"./chunk-x05t86n3.js";import{b,S,P}from"./chunk-ek44atpe.js";import{f,w,v}from"./chunk-2999xbh7.js";import{c}from"./chunk-0wp6x4wb.js";import{t,o,r,e,i,d,a}from"./chunk-0eeyc0aq.js";import{deflateRawSync as Ue,inflateRawSync as ze}from"node:zlib";import{posix as Fe}from"node:path";var Te=/^[a-z][a-z0-9_]{0,63}$/;function q(n="boat",s="Boat",l="BOAT_API_KEY",k=!1){function y(T,j){if(T instanceof e)return T;let C=u(T),I=C.responseStatus,N="provider";if(I===401||I===403)N="auth";else if(I===404)N="not_found";else if(I===402||I===429)N="quota";else if(I===400)N="invalid_argument";else if(I===408||C.name==="TimeoutError")N="timeout";else if(I!==void 0&&I>=500)N="unavailable";else if(C.name==="AbortError")N="aborted";let M=N==="auth"?`Set ${l} to a valid ${s} API key.`:`Check the sandbox and ${s} service before retrying.`,K=C.apiCode!==void 0&&Te.test(C.apiCode)?` ${C.apiCode}`:"",X=k&&I!==void 0?` (HTTP ${I}${K})`:"",H=i(T,{code:N,status:I===void 0?void 0:`HTTP ${I}${K}`,redact:d([process.env[l]])});return new e(`${s} request failed${X}: ${a(N,H.detail)}. ${M}`,{code:N,provider:n,sandboxId:j,hint:M,retryable:N==="unavailable"||N==="quota",cause:H.cause})}function _(T,j="provider",C){let I=T.replaceAll("Boat",s);return new e(j==="auth"?I:`${I}. Check the ${s} provider configuration and retry.`,{code:j,provider:n,sandboxId:C})}return{boatError:y,failure:_}}var Ee={idleMs:60000,retryWindowMs:60000,retryDelayMs:1000},ue=(n,s)=>{let l=n[s];return o(l)&&Number.isSafeInteger(l)&&l>=0?l:void 0};function Ne(n,s){if(!c(n)||!t(n.type))throw s("a frame has no type");switch(n.type){case"stdout":case"stderr":{if(!("data"in n)||!t(n.data))throw s("an output frame has no data");let l=ue(n,"nextOffset");return{type:n.type,data:n.data,nextOffset:l}}case"attached":case"heartbeat":case"reconnect":{let l=ue(n,"stdoutOffset"),k=ue(n,"stderrOffset");return{type:n.type,stdoutOffset:l,stderrOffset:k}}case"exit":{let l="exitCode"in n?n.exitCode:void 0;if(l!==null&&!o(l))throw s("the exit frame has no exit code","outcome_unknown");return{type:"exit",exitCode:l,timedOut:"timedOut"in n&&n.timedOut===!0}}case"error":return{type:"error"};default:return{type:"other"}}}function je(n){let s=z(n);if(s)return s==="disconnected"||s==="truncated";return n instanceof e&&(n.code==="unavailable"||n.code==="timeout")}async function*ge(n,s,l,k){let{signal:y}=k,_=k.timing??Ee,T=n.label,j=()=>new e(`${T} command stream aborted. The signal was cancelled.`,{code:"aborted",provider:n.provider,sandboxId:s}),C=(K,X="provider")=>new e(`${T} command stream is invalid: ${K}. Check the ${T} service and retry.`,{code:X,provider:n.provider,sandboxId:s}),I={stdout:0,stderr:0},N=!1,M;for(;;){if(y.aborted)throw j();try{let K=await n.stream({method:"GET",path:"/sandboxes/{sandboxId}/commands/{processId}/stream",params:{sandboxId:s,processId:l},sandboxId:s,query:{stdoutOffset:I.stdout,stderrOffset:I.stderr},signal:y,startupTimeoutMs:_.idleMs,idleTimeoutMs:_.idleMs});if(N=!0,!K.body)throw new e(`${T} command stream has no body. The connection will be retried.`,{code:"unavailable",provider:n.provider,sandboxId:s,retryable:!0});let X=!1;for await(let H of pe(K.body,{provider:n.provider,sandboxId:s,signal:y})){M=void 0;let U=Ne(H,C);switch(U.type){case"stdout":case"stderr":if(U.nextOffset!==void 0){if(U.nextOffset<=I[U.type])break;I[U.type]=U.nextOffset}if(U.data)yield{type:U.type,data:U.data};break;case"exit":case"error":yield U;return;case"attached":I.stdout=U.stdoutOffset??I.stdout,I.stderr=U.stderrOffset??I.stderr;break;case"heartbeat":case"reconnect":I.stdout=Math.max(I.stdout,U.stdoutOffset??0),I.stderr=Math.max(I.stderr,U.stderrOffset??0),X=U.type==="reconnect";break;case"other":break;default:return U}if(X)break}if(X)continue;throw new e(`${T} command stream ended before the command did. The connection will be retried.`,{code:"unavailable",provider:n.provider,sandboxId:s,retryable:!0})}catch(K){if(y.aborted)throw j();if(M??=Date.now(),!N||!je(K)||Date.now()-M>=_.retryWindowMs)throw K;try{await w(_.retryDelayMs,f(_.retryWindowMs,y),n.provider)}catch{throw j()}}}}function fe(n){return v({provider:n.provider,label:n.label,defaultPlane:"api",planes:{api:{baseUrl:n.baseUrl,auth:()=>({authorization:`Bearer ${n.credentials()}`})}},timeoutMs:n.timeoutMs,secrets:n.secrets,idempotencyHeader:"Idempotency-Key",authHint:`Set ${n.keyEnv} to a valid ${n.label} API key.`,retries:n.retries,fetch:n.fetch})}function ke(n,s,l,k){return new e(`${s} returned an invalid ${l}. Check the ${s} provider configuration and retry.`,{code:"provider",provider:n,sandboxId:k})}function Se(n,s,l){if(!r(n)||n===null||!("id"in n)||!t(n.id)||!n.id)throw ke(s,l,"sandbox");let k="name"in n&&t(n.name)?n.name:"",y="state"in n&&t(n.state)?n.state:"",_="createdAt"in n&&(t(n.createdAt)||o(n.createdAt))?new Date(n.createdAt).getTime():Number.NaN;return{id:n.id,name:k,state:y,createdAt:_,raw:n}}function ve(n,s,l){return Se(r(n)&&"sandbox"in n?n.sandbox:void 0,s,l)}function $e(n,s,l){if(!r(n)||n===null||!("sandboxes"in n)||!Array.isArray(n.sandboxes))throw ke(s,l,"sandbox list");let k=n.sandboxes.map((C)=>Se(C,s,l)),y="pageInfo"in n?n.pageInfo:void 0,_=r(y)&&"hasMore"in y&&y.hasMore===!0,T=r(y)&&y!==null&&"nextCursor"in y&&t(y.nextCursor)?y.nextCursor:void 0,j={sandboxes:k,hasMore:_};if(T!==void 0)j.nextCursor=T;return j}function qe(n){if(!r(n)||n===null)return{kind:"unknown"};if("stdout"in n&&t(n.stdout)&&"stderr"in n&&t(n.stderr)&&"exitCode"in n&&(n.exitCode===null||o(n.exitCode))){let s="stdoutTruncated"in n&&n.stdoutTruncated===!0||"stderrTruncated"in n&&n.stderrTruncated===!0;return{kind:"finished",stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,truncated:s}}if("processId"in n&&o(n.processId))return{kind:"started",processId:n.processId};return{kind:"unknown"}}async function te(n,s,l,k=!1){let y={method:"POST",path:"/sandboxes/{sandboxId}/commands",params:{sandboxId:s},sandboxId:s,body:l};return qe((await(k?n.cleanup(y):n.request(y))).json())}async function se(n,s,l){await n.request({method:"PUT",path:"/sandboxes/{sandboxId}/files",params:{sandboxId:s},sandboxId:s,body:l})}async function Ie(n,s,l){let k=await n.json({method:"DELETE",path:"/sandboxes/{sandboxId}/commands/{processId}",params:{sandboxId:s,processId:l},sandboxId:s});return r(k)&&"running"in k?k.running:void 0}var me=`flock -x /tmp/.sandbox-sdk-workspace-ready.lock sh -c 'if [ ! -f /tmp/.sandbox-sdk/prepared-workspace ]; then sudo mkdir -p /workspace && sudo chown "$(id -u):$(id -g)" /workspace && command -v node git tar setsid nohup mkfifo sed base64 >/dev/null && mkdir -p /tmp/.sandbox-sdk && touch /tmp/.sandbox-sdk/prepared-workspace || exit 1; fi' || exit 1`,A=(n)=>`'${n.replaceAll("'","'\\''")}'`,ie=4194304;async function le(n,s,l,k,y){let _=Array.from({length:Math.max(1,Math.ceil(k.length/ie))},(j,C)=>`${l}/part-${C}`),T=await te(n,s,{command:`mkdir -p /tmp/.sandbox-sdk && mkdir -m 700 -- ${A(l)} && (umask 077 && touch -- ${_.map(A).join(" ")})`,timeoutSeconds:60});if(T.kind!=="finished"||T.exitCode!==0)throw y("Boat could not prepare private staging","provider",s);for(let[j,C]of _.entries())await se(n,s,{path:C,content:Buffer.from(k.subarray(j*ie,(j+1)*ie)).toString("base64"),encoding:"base64"});return _}async function Be(n,s,l,k={},y=new Map,_=q(),T={}){let{boatError:j,failure:C}=_;if(l.signal?.aborted)return{exitCode:null,timedOut:!0};let I=new AbortController,N=!1,M=()=>{},K=new Promise((h)=>{M=()=>{N=!0,h("cancelled")}}),X=setTimeout(M,l.timeoutMs);l.signal?.addEventListener("abort",M,{once:!0});let H,U=!1,G=!1,Z,ae=!1,Q,m=`/tmp/.sandbox-sdk-setup-${crypto.randomUUID()}`;async function x(){if(H===void 0)return;try{if(await Ie(n,s,H)!==!1)throw C("Boat did not confirm process-tree cancellation","outcome_unknown",s)}catch{throw C("Remote cancellation could not be confirmed; destroy the sandbox before retrying","outcome_unknown",s)}}try{let h=Object.entries(l.env).filter(([B,D])=>!Object.entries(p).some(([ne,de])=>B===ne&&D===de)&&k[B]!==D),g=Object.entries(p).filter(([B,D])=>l.env[B]===D).map(([B,D])=>`export ${A(`${B}=${D}`)}`).join("; ");if(g)g+="; ";let E="/tmp/.sandbox-sdk/changes.git/sdk.index",J=h.filter(([B,D])=>B==="GIT_INDEX_FILE"&&D===E);h=h.filter(([B,D])=>B!=="GIT_INDEX_FILE"||D!==E);for(let[B,D]of J)g+=`export ${A(`${B}=${D}`)}; `;if(h.length){let B=JSON.stringify(h),D=l.envMode==="sandbox"?y.get(B):void 0;if(D)g+=`. ${A(await D)} || exit 1; `;else{Q=`/tmp/.sandbox-sdk/env-${crypto.randomUUID()}`;let ne=`${Q}/env`,de=Q,he=(async()=>{let we=await te(n,s,{command:`node -e ${A("const f=require('fs');f.mkdirSync('/tmp/.sandbox-sdk',{recursive:true});f.mkdirSync(process.argv[1],{mode:0o700});f.writeFileSync(process.argv[1]+'/env','',{flag:'wx',mode:0o600})")} ${A(de)}`,timeoutSeconds:60});if(we.kind!=="finished"||we.exitCode!==0)throw C("Boat could not prepare command environment","provider",s);return await se(n,s,{path:ne,content:h.map(([Ae,Pe])=>`export ${A(`${Ae}=${Pe}`)}`).join(`
2
+ `)+`
3
+ `,encoding:"utf8"}),ne})();if(l.envMode==="sandbox")y.set(B,he);try{await he}catch(xe){if(l.envMode==="sandbox")y.delete(B);throw xe}if(l.envMode==="sandbox")Q=void 0,g+=`. ${A(ne)} || exit 1; `;else g+=`chmod 600 ${A(ne)} && . ${A(ne)} && /bin/rm -f -- ${A(ne)} && /bin/rmdir -- ${A(de)} || exit 1; `}}let V=Buffer.from(l.stdin??""),F="/dev/null",W="",re="";if(V.length){Z=`/tmp/.sandbox-sdk/stdin-${crypto.randomUUID()}`;let B=await le(n,s,Z,V,C);if(F=B.length===1?`${Z}/part-0`:`${Z}/stdin`,B.length>1)re=`(umask 077 && cat -- ${B.map(A).join(" ")} > ${A(F)}) || { echo setup-failed > ${A(m)}; exit 125; }; `;W=`/bin/rm -rf -- ${A(Z)}; `}if(N)return{exitCode:null,timedOut:!0};let ee=`(${me}) || { echo setup-failed > ${A(m)}; exit 125; }; ${re}{ ${W}(${g}cd ${A(l.cwd)} && exec sh -c ${A(l.command)}); } < ${A(F)}`;G=!0;let L=await te(n,s,{command:ee,detached:!0});if(L.kind!=="started"||!Number.isSafeInteger(L.processId)||L.processId<1)throw C("Boat did not confirm a detached process ID","outcome_unknown",s);if(H=L.processId,l.signal?.aborted)M();let R=(async()=>{for await(let B of ge(T.http??n,s,L.processId,{signal:I.signal,timing:T.timing}))if(B.type==="stdout"||B.type==="stderr")l.onChunk({stream:B.type,text:B.data});else if(B.type==="exit")return U=!0,ae=B.exitCode!==125,{exitCode:B.exitCode,timedOut:B.timedOut};else if(B.type==="error")throw C("Boat command stream failed","provider",s);throw C("Boat stream ended without an exit result","outcome_unknown",s)})();R.catch(()=>{});let oe=await Promise.race([R,K]);if(oe==="cancelled"||N)return await x(),I.abort(),await R.catch(()=>{}),{exitCode:null,timedOut:!0};if(!oe.timedOut&&oe.exitCode===125){let B=await te(n,s,{command:`if [ -f ${A(m)} ]; then cat ${A(m)}; rm -f -- ${A(m)}; fi`,timeoutSeconds:10});if(B.kind!=="finished"||B.exitCode!==0)throw C("Boat could not confirm command initialization","outcome_unknown",s);if(B.stdout.trim()==="setup-failed")throw C("Boat workspace initialization failed; the requested command did not run","provider",s)}return oe}catch(h){if(H!==void 0&&!U)await x();if(G&&H===void 0&&!["auth","quota","invalid_argument","not_found"].includes(j(h,s).code))throw C("Command launch outcome is unknown; inspect or destroy the sandbox before retrying","outcome_unknown",s);throw h}finally{if(I.abort(),clearTimeout(X),l.signal?.removeEventListener("abort",M),Q)await te(n,s,{command:`rm -rf -- ${A(Q)}`,timeoutSeconds:10},!0).catch(()=>{});if(Z&&!ae)await te(n,s,{command:`rm -rf -- ${A(Z)}`,timeoutSeconds:10},!0).catch(()=>{})}}var He={name:"boat",label:"Boat",keyEnv:"BOAT_API_KEY",baseEnv:"BOAT_API_BASE",baseUrl:"https://boat.dev/api/v1"},ce="@boatdev/sdk",ye="sandbox-sdk:1:",Ce={"sandbox-sdk":"1"},Je={small:"small",medium:"default",large:"large"};function De(n,s,l){let k={...n.labels};delete k["sandbox-sdk"];let y=JSON.stringify([n.key??null,k]);if(Buffer.byteLength(y)>65536)throw s("Key and labels exceed the metadata size limit","unsupported");let _=ye+Ue(y).toString("base64url");if(_.length>120)throw s(`Key and labels exceed ${l}'s encoded name budget; shorten them`,"unsupported");return _}function Me(n){if(!n.startsWith(ye))return;try{let s=JSON.parse(ze(Buffer.from(n.slice(ye.length),"base64url"),{maxOutputLength:65536}).toString());if(!Array.isArray(s)||s.length!==2)return;let[l,k]=s;if(l!==null&&!t(l))return;if(!r(k)||k===null||Array.isArray(k))return;let y={};for(let[_,T]of Object.entries(k)){if(!t(T))return;Object.defineProperty(y,_,{value:T,enumerable:!0,writable:!0,configurable:!0})}return l===null?{labels:{...y,...Ce}}:{key:l,labels:{...y,...Ce}}}catch{return}}function be(n,s,l,k=[]){let y=Me(n.name);if(!y)throw s("Sandbox has no valid SDK metadata; connect an SDK-created sandbox","not_found",n.id);let _=n.createdAt;if(!Number.isFinite(_))throw s(`${l} returned no valid creation timestamp`,"provider",n.id);return{id:n.id,...y,createdAt:_,state:k.includes(n.state)?"paused":["ready","idle","running"].includes(n.state)?"running":"stopped"}}function Oe(n,s,l){if(!r(n)||n===null||!("path"in n)||!t(n.path)||!("type"in n)||!("size"in n)||!o(n.size)||!("modifiedAt"in n)||!o(n.modifiedAt))throw s(`Invalid file metadata from ${l}`);let k=n.type;if(k!=="file"&&k!=="directory"&&k!=="symlink")throw s(`Invalid file type from ${l}`);return{path:n.path,type:k,size:n.size,modifiedAt:n.modifiedAt}}var _e="const fs=require('fs'),p=require('path');const stat=x=>{const s=fs.lstatSync(x);return {path:x,type:s.isSymbolicLink()?'symlink':s.isDirectory()?'directory':'file',size:s.size,modifiedAt:s.mtimeMs}};";function Y(n={},s=He){let{failure:l,boatError:k}=q(s.name,s.label,s.keyEnv,s.name!=="boat"),y=s.label,_=new Map,T=new Map,j=n.requestTimeoutMs??90000,C=()=>n.apiKey??process.env[s.keyEnv];function I(){let m=C();if(!m)throw l(`${y} API key is missing. Authentication is required. Set ${s.keyEnv} or pass apiKey.`,"auth");if(!Number.isSafeInteger(j)||j<=0)throw l("requestTimeoutMs must be a positive integer","invalid_argument");return m}let N={provider:s.name,label:y,keyEnv:s.keyEnv,baseUrl:()=>n.baseUrl??n.apiUrl??(s.baseEnv?process.env[s.baseEnv]:void 0)??s.baseUrl,credentials:I,secrets:()=>[C()],timeoutMs:Number.isSafeInteger(j)&&j>0?j:90000},M=fe(N),K=fe({...N,retries:0}),X=(m)=>{let x=ve(m,s.name,y);return s.observe?.(x),x};async function H(m,x){try{return await m()}catch(h){throw k(h,x)}}async function U(m,x,h=!1,O=!1){let g=await te(M,m,{command:O?`${me}; ${x}`:x,timeoutSeconds:60});if(g.kind!=="finished")throw l(`${y} returned an unexpected detached result`,"outcome_unknown",m);if(g.truncated)throw l(`${y} truncated operation output; no partial file data was returned`,"provider",m);if(g.exitCode!==0)throw l(h&&g.exitCode===44?"File does not exist":`${y} file or setup operation failed`,h&&g.exitCode===44?"file_not_found":"provider",m);return g.stdout}let G=(m,x,h=[])=>H(()=>U(m,`node -e ${A(`try {${x}} catch(e) {process.exit(e.code==='ENOENT'?44:45)}`)} ${h.map(A).join(" ")}`,!0,h.some((O)=>O==="/workspace"||O.startsWith("/workspace/"))),m);async function Z(m,x,h,O){let g=[];for(let E=0;E<O;E+=16384){let J=Math.min(16384,O-E),V=await G(m,"const f=require('fs'),fd=f.openSync(process.argv[1],'r');try{const b=Buffer.alloc(Number(process.argv[3]));const n=f.readSync(fd,b,0,b.length,Number(process.argv[2]));process.stdout.write(b.subarray(0,n).toString('base64'))}finally{f.closeSync(fd)}",[x,String(h+E),String(J)]),F=Buffer.from(V,"base64");if(g.push(F),F.length<J)break}return new Uint8Array(Buffer.concat(g))}let ae={package:ce,async connect(m,x){let h=S(m,"Configuration",[{...s.sdkConfiguration,basePath:N.baseUrl(),accessToken:I()}],ce),O=S(m,"BoatApi",[h],ce);if(x===void 0)return O;let g=await P(O,"get",[{sandboxId:x}],ce);return{client:O,sandbox:r(g)?"sandbox"in g?g.sandbox:void 0:void 0}}},Q={name:s.name,keyMode:"best-effort",capabilities:new Set(["size"]),create:(m)=>H(async()=>{if(m.network!==void 0&&m.network!=="all")throw l(`${y} network policy is unsupported by this adapter`,"unsupported");if(m.size!==void 0&&!t(m.size))throw l(`${y} supports small, medium and large presets; custom sizes are unavailable`,"unsupported");if(m.timeoutMs!==void 0)throw l(`${y} auto-stop archives the VM and restarts while its agent works, so it is not a hard lifetime; timeoutMs is unsupported. Set the provider's ttlSeconds option instead`,"unsupported");if(m.idleTimeoutMs!==void 0&&!s.idleStop)throw l(`${y} has no idle timer; idleTimeoutMs is unsupported`,"unsupported");let{ttlSeconds:x,snapshots:h,monitoring:O,org:g}=n;if(x!==void 0&&x!==null&&(!Number.isSafeInteger(x)||x<1||x>2592000))throw l("ttlSeconds must be null or an integer from 1 to 2592000","invalid_argument");let E;if(m.idleTimeoutMs!==void 0){if(E=Math.ceil(m.idleTimeoutMs/60000),E>10080)throw l(`${y} idle pause is at most 7 days`,"invalid_argument");if(h===!1)throw l(`${y} idle pause needs snapshots; drop idleTimeoutMs or snapshots: false`,"invalid_argument")}if(m.from!==void 0&&!s.createFrom)throw l(`${y} snapshots are not supported by this adapter`,"unsupported");let J=De(m,l,y);if(m.signal?.aborted)throw l("Creation was aborted","aborted");let V=crypto.randomUUID(),F={noEnv:!0,from:m.from,env:m.env,type:m.size===void 0?n.machine??n.type:Je[m.size],ttlSeconds:x,snapshots:h,monitoring:O,org:g,idleStopMinutes:E,...s.createFields},W=f(N.timeoutMs),re=()=>l(`${y} create outcome remains unknown; recover with idempotency key ${V} and the same request body within 24 hours`,"outcome_unknown"),ee;for(let R=0;R<3;R++)try{ee=X(await K.json({method:"POST",path:"/sandboxes",body:F,idempotencyKey:V,deadline:W}));break}catch(oe){let B=k(oe).code;if(["auth","invalid_argument","quota","not_found"].includes(B))throw oe;let D=250*(R+1);if(R===2||D>=W.remaining())throw re();await w(D,W,s.name).catch(()=>{throw re()})}if(!ee)throw l(`${y} returned no sandbox after create`,"outcome_unknown");let L=ee.id;T.set(L,{...m.env});try{if(m.signal?.aborted)throw l("Creation was aborted","aborted");let R=X(await M.json({method:"PATCH",path:"/sandboxes/{sandboxId}",params:{sandboxId:L},sandboxId:L,body:{name:J},deadline:W}));if(m.signal?.aborted)throw l("Creation was aborted","aborted");if(R.name!==J)return await Q.connect(L);return{...be(R,l,y,s.pausedStates),state:"running"}}catch(R){throw await Q.destroy(L),R}}),connect:(m)=>H(async()=>be(X(await M.json({method:"GET",path:"/sandboxes/{sandboxId}",params:{sandboxId:m},sandboxId:m})),l,y,s.pausedStates),m),list:(m)=>H(async()=>{let x=[],h,O=new Set;do{let g=$e(await M.json({method:"GET",path:"/sandboxes",query:{limit:200,cursor:h}}),s.name,y);for(let J of g.sandboxes){if(s.observe?.(J),!Me(J.name))continue;let V=be(J,l,y,s.pausedStates);if(Object.entries(m).every(([F,W])=>V.labels[F]===W))x.push(V)}if(!g.hasMore)break;let E=g.nextCursor;if(!E||O.has(E))throw l(`${y} returned an invalid pagination cursor`);O.add(E),h=E}while(h!==void 0);return x}),async find(m){return(await Q.list({})).find((x)=>x.key===m)},destroy:(m)=>H(async()=>{try{if(s.destroy)await s.destroy(M,m);else await M.request({method:"DELETE",path:"/sandboxes/{sandboxId}",params:{sandboxId:m},sandboxId:m,headers:{"X-Ascii-Confirm-Delete":m}})}catch(x){if(k(x).code!=="not_found")throw x}T.delete(m),_.delete(m)},m),exec:(m,x)=>H(async()=>{let h=_.get(m);if(!h)h=new Map,_.set(m,h);return Be(M,m,x,T.get(m),h,{failure:l,boatError:k},{http:K})},m),files:{writeCreatesParents:!0,writeSupportsMode:!0,listOrder:"name",readRange:(m,x,h)=>Z(m,x,h.offset,h.length),read:async(m,x)=>{let h=await G(m,"const f=require('fs'),fd=f.openSync(process.argv[1],'r');try{const size=f.fstatSync(fd).size,b=Buffer.alloc(Math.min(size,16384)),n=f.readSync(fd,b,0,b.length,0);process.stdout.write(size+'\\n'+b.subarray(0,n).toString('base64'))}finally{f.closeSync(fd)}",[x]),O=h.indexOf(`
4
+ `),g=Number(h.slice(0,O));if(O<0||!Number.isSafeInteger(g)||g<0)throw l(`Invalid ${y} file size`);let E=Buffer.from(h.slice(O+1),"base64");if(g<=16384)return new Uint8Array(E);if(g<=1048576)return new Uint8Array(Buffer.concat([E,await Z(m,x,E.length,g-E.length)]));if(s.downloadMaxBytes!==void 0&&g>s.downloadMaxBytes)return new Uint8Array(Buffer.concat([E,await Z(m,x,E.length,g-E.length)]));return H(async()=>{let J=`/tmp/.sandbox-sdk/download-${crypto.randomUUID()}`,V=`${J}/file`;try{let F=Number(await G(m,"const f=require('fs');f.mkdirSync('/tmp/.sandbox-sdk',{recursive:true});f.mkdirSync(process.argv[2],{mode:0o700});f.copyFileSync(process.argv[1],process.argv[2]+'/file');process.stdout.write(String(f.statSync(process.argv[2]+'/file').size))",[x,J]));if(!Number.isSafeInteger(F)||F<0)throw l("Invalid staged file size","provider",m);if(s.download){let L=await s.download(M,m,V);if(L.length!==F)throw l("Incomplete artifact download","provider",m);return L}let W=await M.json({method:"POST",path:"/sandboxes/{sandboxId}/files/download-url",params:{sandboxId:m},sandboxId:m,body:{path:V,ttlSeconds:300},readOnly:!0}),re=r(W)&&W!==null&&"url"in W&&t(W.url)?W.url:void 0;if(!re)throw l(`${y} returned no signed download URL`,"provider",m);let ee;try{ee=(await M.request({method:"GET",path:re,auth:!1,sandboxId:m,maxBytes:F+1})).body}catch(L){let R=k(L,m).code;throw l("Signed file download failed",R==="aborted"||R==="timeout"?R:"unavailable",m)}if(ee.length!==F)throw l("Incomplete signed file download","provider",m);return ee}finally{await G(m,"require('fs').rmSync(process.argv[1],{recursive:true,force:true})",[J]).catch(()=>{})}},m)},write:(m,x,h,O={})=>H(async()=>{let{mode:g}=O;if(g!==void 0&&(!Number.isSafeInteger(g)||g<0||g>4095))throw l("mode must be an integer from 0 to 0o7777","invalid_argument",m);let E=Fe.normalize(x);if(g===void 0&&h.length<=ie&&(E.startsWith("/home/user/")||E.startsWith("/tmp/")))try{await se(M,m,{path:x,content:Buffer.from(h).toString("base64"),encoding:"base64"});return}catch(F){if(k(F).code!=="invalid_argument")throw F}let J=`/tmp/.sandbox-sdk/write-${crypto.randomUUID()}`,V=!1;try{let F=await le(M,m,J,h,l);await G(m,"const f=require('fs'),[d,dir,n,m]=process.argv.slice(1);try{f.mkdirSync(require('path').dirname(d),{recursive:true});const fd=f.openSync(d,'w',m?0o600:0o666);try{if(m)f.fchmodSync(fd,Number(m));for(let i=0;i<Number(n);i++)f.writeFileSync(fd,f.readFileSync(dir+'/part-'+i))}finally{f.closeSync(fd)}}finally{f.rmSync(dir,{recursive:true,force:true})}",[x,J,String(F.length),g===void 0?"":String(g)]),V=!0}finally{if(!V)await G(m,"require('fs').rmSync(process.argv[1],{recursive:true,force:true})",[J]).catch(()=>{})}},m),stat:async(m,x)=>{let h=JSON.parse(await G(m,_e+"process.stdout.write(JSON.stringify(stat(process.argv[1])))",[x]));return Oe(h,l,y)},list:async(m,x)=>{let h=JSON.parse(await G(m,_e+"process.stdout.write(JSON.stringify(fs.readdirSync(process.argv[1]).map(x=>stat(p.join(process.argv[1],x)))))",[x]));if(!Array.isArray(h))throw l(`Invalid ${y} directory listing`);return h.map((O)=>Oe(O,l,y))},mkdir:async(m,x)=>{await G(m,"require('fs').mkdirSync(process.argv[1],{recursive:true})",[x])},remove:async(m,x,h)=>{await G(m,"require('fs').rmSync(process.argv[1],{recursive:process.argv[2]==='true'})",[x,String(h.recursive)])}},previewUrl:(m,x)=>H(async()=>{let h=await M.json({method:"POST",path:"/sandboxes/{sandboxId}/host",params:{sandboxId:m},sandboxId:m,body:{port:x}});if(!r(h)||h===null||!("url"in h)||!t(h.url)||!h.url)throw l(`${y} returned no preview URL`,"provider",m);if(s.preview)return s.preview(h.url);let O=new URL(h.url),g=O.searchParams.get("_token");if(g){if(!/^[A-Za-z0-9._~-]+$/.test(g))throw l("Invalid preview token","provider",m);return O.searchParams.delete("_token"),{url:O.toString(),headers:{Cookie:`_port_auth=${g}`}}}if("isProtected"in h&&h.isProtected===!0||"access"in h&&h.access==="private")throw l("Protected preview returned no token","provider",m);return{url:O.toString()}},m),native:(m)=>b({http:M,placeholder:"sandboxId",sandboxId:m,sdk:ae}),api:b({http:M,placeholder:"sandboxId",sdk:ae})};return{provider:Q,http:M}}
5
+ export{q,Y};
@@ -0,0 +1,26 @@
1
+ import{n}from"./chunk-2ts3evzh.js";import{s}from"./chunk-0eeyc0aq.js";import{posix as H}from"node:path";var I="SANDBOX_SDK_RUN",p={CI:"1",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",DEBIAN_FRONTEND:"noninteractive",TERM:"dumb",NO_COLOR:"1",[I]:"1"},l=(t=".")=>H.resolve("/workspace",t),fe="if [ -f /tmp/.sandbox-sdk/secret-names.json ]; then cat /tmp/.sandbox-sdk/secret-names.json || exit 1; printf '\\000'; env -0; fi",z=`[ -d "\${2%/*}" ] || (umask 077; mkdir -p "\${2%/*}") || exit 1
2
+ trap 'rm -f -- "$2"' EXIT
3
+ : > "$2" || exit 1
4
+ { { "$3" -c "$1" 3>&- 4>&-; printf '%s\\n' "$?" > "$2"; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat
5
+ read -r code < "$2"
6
+ exit "$code"`,G=(t,e,o="sh")=>`sh -c ${n(z)} sh ${n(t)} ${n(e)} ${n(o)}`,U=`exec 7>&1
7
+ c=$({ { { "$2" -c "$1" 3>&- 4>&- 6>&- 7>&-; echo "$?" >&6; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat >&7; } 6>&1)
8
+ exit "\${c:-1}"`,W=(t,e="sh")=>`sh -c ${n(U)} sh ${n(t)} ${n(e)}`,xe=`t=${I}=1
9
+ set -- /proc/[0-9]*/environ
10
+ [ -e "$1" ] || exit 2
11
+ grep -s -q -a -F -e "$t" -- "$@"; c=$?
12
+ [ "$c" = 0 ] && exit 10
13
+ [ "$c" = 1 ] && exit 0
14
+ [ "$c" = 2 ] || exit 2
15
+ u=
16
+ for f in "$@"; do
17
+ grep -s -q -a -F -e "$t" -- "$f"; c=$?
18
+ [ "$c" = 0 ] && exit 10
19
+ [ "$c" = 2 ] && [ -d "\${f%/environ}" ] && u="$u $f"
20
+ done
21
+ [ -z "$u" ] && exit 0
22
+ [ "$(id -u)" = 0 ] && exit 11
23
+ sudo -n sh -c 'for f; do grep -s -q -a -F -e "$0" -- "$f"; c=$?; [ "$c" = 0 ] && exit 10; [ "$c" = 2 ] && [ -d "\${f%/environ}" ] && exit 11; done; exit 0' "$t" $u </dev/null 2>/dev/null`,_=new Map,ve=(t,e)=>(_.get(t)?.get(e)??0)>0;function X(t,e){let o=_.get(t);if(!o)o=new Map,_.set(t,o);let a=o;return a.set(e,(a.get(e)??0)+1),()=>{let c=(a.get(e)??1)-1;if(c)a.set(e,c);else a.delete(e);if(!a.size)_.delete(t)}}class L{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+`
24
+ [${this.total-Buffer.byteLength(t)-Buffer.byteLength(o)} bytes cut]
25
+ `+o}}class Q{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=(c)=>{if(c){let f=Buffer.byteLength(c.text)>1048576?Buffer.from(c.text).subarray(-1048576).toString():c.text;t.push({...c,text:f}),e+=Buffer.byteLength(f);while(e>1048576&&t.length>1)e-=Buffer.byteLength(t.shift()?.text??"")}o()};this.listeners.add(a);try{while(!this.ended||t.length){let c=t.shift();if(c)e-=Buffer.byteLength(c.text),yield c;else await new Promise((f)=>{o=f})}if(this.failure)throw this.failure}finally{this.listeners.delete(a)}}}function O(t,e,o=!1){let a=[];function c(f=!1){let y=t.secrets,w=new Set(y.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(""),b=y.find((r)=>v.startsWith(r));if(b){e({stream:i.stream,text:"[REDACTED]"});let r=b.length;for(let m of a)if((o||m.stream===i.stream)&&r){let g=Math.min(r,m.text.length);m.text=m.text.slice(g),r-=g}}else{if(!f&&y.some((m)=>m.startsWith(v))){if(a.reduce((m,g)=>m+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(f){if(!t.secrets.length){e(f);return}a.push({...f}),c()},flush(){c(!0)}}}function me(t,e,o,a,c,f=()=>{}){return(y,w={})=>{let i={...w},v,b=new Q,r=(u=!1)=>v??=m(u).catch((x)=>{let h=o.error(x,t.name,e);throw b.fail(h),h});async function m(u){await f();let x=i.timeoutMs??120000,h=i.maxOutputBytes??1048576;if(!Number.isFinite(x)||x<=0||!Number.isSafeInteger(h)||h<1)s("timeoutMs and maxOutputBytes must be positive");let P=l(i.cwd),q=Date.now(),C=new L(h),S=new L(h),B=new L(h*2),k=new AbortController,R=i.signal?.aborted??!1,E=()=>{R=!0,k.abort()};i.signal?.addEventListener("abort",E,{once:!0});let j=setTimeout(E,x),A=`/tmp/.sandbox-sdk/runs/${crypto.randomUUID()}`,N=!1,F=X(t.name,e),T=O(o,(d)=>{B.add(d.text),b.emit(d)},!0),D=O(o,(d)=>{(d.stream==="stdout"?C:S).add(d.text),T.push(d)});try{if(R)k.abort();let d=R?{exitCode:null,timedOut:!0}:await t.exec(e,{command:t.inlineActivity?y:t.procActivity?W(y,t.commandShell):G(y,A,t.commandShell),cwd:P,env:{...a,...i.env,...p},stdin:i.stdin,timeoutMs:x,signal:k.signal,streaming:u,envMode:i.env===void 0?"sandbox":void 0,activityPath:t.inlineActivity?A:void 0,onChunk:(M)=>D.push(M)});return N=d.exitCode!==null&&d.exitCode>=0&&d.exitCode<128&&!d.timedOut&&!k.signal.aborted,R||=d.timedOut,D.flush(),T.flush(),c(C.total+S.total),{ok:!R&&d.exitCode===0,exitCode:R?null:d.exitCode,stdout:C.text(),stderr:S.text(),output:B.text(),durationMs:Date.now()-q,truncated:C.truncated||S.truncated||B.truncated,timedOut:R,cwd:P,command:o.text(y)}}catch(d){D.flush(),T.flush();let M=o.error(d,t.name,e);throw b.fail(M),M}finally{if(clearTimeout(j),i.signal?.removeEventListener("abort",E),!N&&!t.inlineActivity&&!t.procActivity)await Promise.resolve().then(()=>t.files.remove(e,A,{recursive:!0})).catch(()=>{});F(),b.end()}}let g={[Symbol.toStringTag]:"RunHandle",then(u,x){return r().then(u,x)},catch(u){return r().catch(u)},finally(u){return r().finally(u)},[Symbol.asyncIterator](){let u=b.stream(),x=u.next();r(!0).catch(()=>{});let h=!0;return{next:()=>{if(h)return h=!1,x;return u.next()},return:()=>u.return(void 0)}},cwd(u){if(v)s("Run already started");return i.cwd=u,g},env(u){if(v)s("Run already started");return i.env={...i.env,...u},g},timeout(u){if(v)s("Run already started");return i.timeoutMs=u,g}};return g}}
26
+ export{p,l,fe,xe,ve,L,Q,O,me};