withruntime 0.50.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generated/apps.d.ts +309 -0
- package/dist/generated/apps.js +333 -0
- package/dist/generated/audit.d.ts +47 -0
- package/dist/generated/audit.js +14 -0
- package/dist/generated/browsers.d.ts +309 -0
- package/dist/generated/browsers.js +333 -0
- package/dist/generated/builds.d.ts +309 -0
- package/dist/generated/builds.js +333 -0
- package/dist/generated/ci.d.ts +309 -0
- package/dist/generated/ci.js +333 -0
- package/dist/generated/containers.d.ts +309 -0
- package/dist/generated/containers.js +333 -0
- package/dist/generated/desktops.d.ts +309 -0
- package/dist/generated/desktops.js +333 -0
- package/dist/generated/domains.d.ts +80 -0
- package/dist/generated/domains.js +58 -0
- package/dist/generated/egressIps.d.ts +36 -0
- package/dist/generated/egressIps.js +14 -0
- package/dist/generated/events.d.ts +37 -0
- package/dist/generated/events.js +14 -0
- package/dist/generated/feedback.d.ts +44 -0
- package/dist/generated/feedback.js +13 -0
- package/dist/generated/functions.d.ts +309 -0
- package/dist/generated/functions.js +333 -0
- package/dist/generated/identities.d.ts +36 -0
- package/dist/generated/identities.js +22 -0
- package/dist/generated/images.d.ts +200 -0
- package/dist/generated/images.js +65 -0
- package/dist/generated/index.d.ts +143 -0
- package/dist/generated/index.js +184 -0
- package/dist/generated/jobRuns.d.ts +68 -0
- package/dist/generated/jobRuns.js +22 -0
- package/dist/generated/jobs.d.ts +144 -0
- package/dist/generated/jobs.js +85 -0
- package/dist/generated/keys.d.ts +105 -0
- package/dist/generated/keys.js +26 -0
- package/dist/generated/me.d.ts +33 -0
- package/dist/generated/me.js +13 -0
- package/dist/generated/networks.d.ts +32 -0
- package/dist/generated/networks.js +14 -0
- package/dist/generated/notebooks.d.ts +309 -0
- package/dist/generated/notebooks.js +333 -0
- package/dist/generated/otel.d.ts +46 -0
- package/dist/generated/otel.js +22 -0
- package/dist/generated/ports.d.ts +55 -0
- package/dist/generated/ports.js +22 -0
- package/dist/generated/previews.d.ts +86 -0
- package/dist/generated/previews.js +67 -0
- package/dist/generated/projects.d.ts +47 -0
- package/dist/generated/projects.js +26 -0
- package/dist/generated/roles.d.ts +36 -0
- package/dist/generated/roles.js +22 -0
- package/dist/generated/routes.d.ts +3 -0
- package/dist/generated/routes.js +4 -0
- package/dist/generated/runtime.d.ts +176 -0
- package/dist/generated/runtime.js +416 -0
- package/dist/generated/sandboxes.d.ts +952 -0
- package/dist/generated/sandboxes.js +342 -0
- package/dist/generated/secrets.d.ts +116 -0
- package/dist/generated/secrets.js +54 -0
- package/dist/generated/sessions.d.ts +47 -0
- package/dist/generated/sessions.js +17 -0
- package/dist/generated/signing.d.ts +68 -0
- package/dist/generated/signing.js +187 -0
- package/dist/generated/sites.d.ts +309 -0
- package/dist/generated/sites.js +333 -0
- package/dist/generated/snapshots.d.ts +27 -0
- package/dist/generated/snapshots.js +22 -0
- package/dist/generated/tunnels.d.ts +68 -0
- package/dist/generated/tunnels.js +14 -0
- package/dist/generated/usage.d.ts +155 -0
- package/dist/generated/usage.js +17 -0
- package/dist/generated/volumes.d.ts +36 -0
- package/dist/generated/volumes.js +26 -0
- package/dist/generated/webhooks.d.ts +44 -0
- package/dist/generated/webhooks.js +22 -0
- package/dist/generated/workspaces.d.ts +309 -0
- package/dist/generated/workspaces.js +333 -0
- package/dist/v2/cli.d.ts +7 -0
- package/dist/v2/cli.js +283 -0
- package/dist/v2/index.d.ts +1 -0
- package/dist/v2/index.js +4 -0
- package/dist/v2/login.d.ts +35 -0
- package/dist/v2/login.js +225 -0
- package/dist/v2/mcp.d.ts +1 -0
- package/dist/v2/mcp.js +49 -0
- package/dist/v2/openapi.json +75750 -0
- package/dist/v2/shims/base.d.ts +33 -0
- package/dist/v2/shims/base.js +54 -0
- package/dist/v2/shims/blaxel.d.ts +60 -0
- package/dist/v2/shims/blaxel.js +71 -0
- package/dist/v2/shims/cloudflare.d.ts +52 -0
- package/dist/v2/shims/cloudflare.js +55 -0
- package/dist/v2/shims/daytona.d.ts +58 -0
- package/dist/v2/shims/daytona.js +74 -0
- package/dist/v2/shims/e2b.d.ts +142 -0
- package/dist/v2/shims/e2b.js +238 -0
- package/dist/v2/shims/fly.d.ts +6 -0
- package/dist/v2/shims/fly.js +91 -0
- package/dist/v2/shims/modal.d.ts +54 -0
- package/dist/v2/shims/modal.js +79 -0
- package/dist/v2/shims/morph.d.ts +60 -0
- package/dist/v2/shims/morph.js +87 -0
- package/dist/v2/shims/vercel.d.ts +53 -0
- package/dist/v2/shims/vercel.js +90 -0
- package/dist/v2/table.d.ts +53 -0
- package/dist/v2/table.js +122 -0
- package/package.json +20 -310
- package/BLAXEL.md +0 -290
- package/COMPATIBILITY.md +0 -447
- package/DAYTONA.md +0 -237
- package/E2B.md +0 -314
- package/README.md +0 -331
- package/README.src.md +0 -333
- package/VERCEL.md +0 -230
- package/agent-platforms-inventory.json +0 -387
- package/compatibility-lock.json +0 -305
- package/dist/agents/browser.d.ts +0 -12
- package/dist/agents/browser.js +0 -12
- package/dist/agents/index.d.ts +0 -11
- package/dist/agents/index.js +0 -11
- package/dist/agents-cli.d.ts +0 -16
- package/dist/agents-cli.js +0 -1237
- package/dist/agents-deploy.d.ts +0 -196
- package/dist/agents-deploy.js +0 -872
- package/dist/agents-file.d.ts +0 -19
- package/dist/agents-file.js +0 -135
- package/dist/ai/index.d.ts +0 -49
- package/dist/ai/index.js +0 -31
- package/dist/ai-harness/index.d.ts +0 -194
- package/dist/ai-harness/index.js +0 -522
- package/dist/api-defaults.d.ts +0 -17
- package/dist/api-defaults.js +0 -22
- package/dist/apps/index.d.ts +0 -10
- package/dist/apps/index.js +0 -11
- package/dist/apps-cli.d.ts +0 -16
- package/dist/apps-cli.js +0 -1021
- package/dist/billing-cli.d.ts +0 -23
- package/dist/billing-cli.js +0 -264
- package/dist/blaxel/client.d.ts +0 -59
- package/dist/blaxel/client.js +0 -86
- package/dist/blaxel/context.d.ts +0 -59
- package/dist/blaxel/context.js +0 -162
- package/dist/blaxel/errors.d.ts +0 -130
- package/dist/blaxel/errors.js +0 -315
- package/dist/blaxel/filesystem.d.ts +0 -147
- package/dist/blaxel/filesystem.js +0 -585
- package/dist/blaxel/index.d.ts +0 -287
- package/dist/blaxel/index.js +0 -351
- package/dist/blaxel/interpreter.d.ts +0 -71
- package/dist/blaxel/interpreter.js +0 -256
- package/dist/blaxel/lookup.d.ts +0 -39
- package/dist/blaxel/lookup.js +0 -84
- package/dist/blaxel/pagination.d.ts +0 -39
- package/dist/blaxel/pagination.js +0 -88
- package/dist/blaxel/preview.d.ts +0 -136
- package/dist/blaxel/preview.js +0 -304
- package/dist/blaxel/process.d.ts +0 -126
- package/dist/blaxel/process.js +0 -581
- package/dist/blaxel/sandbox.d.ts +0 -198
- package/dist/blaxel/sandbox.js +0 -856
- package/dist/blaxel/session.d.ts +0 -31
- package/dist/blaxel/session.js +0 -136
- package/dist/blaxel/snapshot.d.ts +0 -123
- package/dist/blaxel/snapshot.js +0 -199
- package/dist/blaxel/types.d.ts +0 -145
- package/dist/blaxel/types.js +0 -60
- package/dist/blaxel/unsupported.d.ts +0 -20
- package/dist/blaxel/unsupported.js +0 -32
- package/dist/browser-stub.d.ts +0 -1
- package/dist/browser-stub.js +0 -1
- package/dist/browsers/index.d.ts +0 -9
- package/dist/browsers/index.js +0 -10
- package/dist/browsers-cli.d.ts +0 -13
- package/dist/browsers-cli.js +0 -279
- package/dist/builds/index.d.ts +0 -10
- package/dist/builds/index.js +0 -11
- package/dist/ci/index.d.ts +0 -13
- package/dist/ci/index.js +0 -14
- package/dist/ci-cli.d.ts +0 -20
- package/dist/ci-cli.js +0 -537
- package/dist/ci-import.d.ts +0 -23
- package/dist/ci-import.js +0 -565
- package/dist/claude-agent-sdk/index.d.ts +0 -7
- package/dist/claude-agent-sdk/index.js +0 -65
- package/dist/cli/logs.d.ts +0 -21
- package/dist/cli/logs.js +0 -188
- package/dist/cli-extras.d.ts +0 -39
- package/dist/cli-extras.js +0 -267
- package/dist/cli-name.d.ts +0 -6
- package/dist/cli-name.js +0 -8
- package/dist/cli-update.d.ts +0 -11
- package/dist/cli-update.js +0 -46
- package/dist/cli-words.d.ts +0 -36
- package/dist/cli-words.js +0 -167
- package/dist/cli.d.ts +0 -92
- package/dist/cli.js +0 -5463
- package/dist/client.d.ts +0 -189
- package/dist/client.js +0 -205
- package/dist/cloudflare/errors.d.ts +0 -166
- package/dist/cloudflare/errors.js +0 -183
- package/dist/cloudflare/identity.d.ts +0 -7
- package/dist/cloudflare/identity.js +0 -13
- package/dist/cloudflare/index.d.ts +0 -545
- package/dist/cloudflare/index.js +0 -1106
- package/dist/cloudflare/interpreter.d.ts +0 -119
- package/dist/cloudflare/interpreter.js +0 -232
- package/dist/cloudflare/mime.d.ts +0 -1
- package/dist/cloudflare/mime.js +0 -66
- package/dist/cloudflare/streams.d.ts +0 -46
- package/dist/cloudflare/streams.js +0 -175
- package/dist/cloudflare/types.d.ts +0 -338
- package/dist/cloudflare/types.js +0 -80
- package/dist/cloudflare/watch.d.ts +0 -9
- package/dist/cloudflare/watch.js +0 -24
- package/dist/cloudflare/worker.d.ts +0 -706
- package/dist/cloudflare/worker.js +0 -633
- package/dist/codesandbox/guest-service.d.ts +0 -31
- package/dist/codesandbox/guest-service.js +0 -490
- package/dist/codesandbox/index.d.ts +0 -574
- package/dist/codesandbox/index.js +0 -1747
- package/dist/compat/core.d.ts +0 -58
- package/dist/compat/core.js +0 -267
- package/dist/compat/files.d.ts +0 -27
- package/dist/compat/files.js +0 -157
- package/dist/compat/lease.d.ts +0 -37
- package/dist/compat/lease.js +0 -93
- package/dist/compat/shell.d.ts +0 -4
- package/dist/compat/shell.js +0 -165
- package/dist/containers/index.d.ts +0 -10
- package/dist/containers/index.js +0 -11
- package/dist/credentials.d.ts +0 -71
- package/dist/credentials.js +0 -340
- package/dist/daytona/client.d.ts +0 -48
- package/dist/daytona/client.js +0 -45
- package/dist/daytona/computer-use.d.ts +0 -171
- package/dist/daytona/computer-use.js +0 -382
- package/dist/daytona/context.d.ts +0 -41
- package/dist/daytona/context.js +0 -50
- package/dist/daytona/daytona.d.ts +0 -213
- package/dist/daytona/daytona.js +0 -578
- package/dist/daytona/errors.d.ts +0 -117
- package/dist/daytona/errors.js +0 -201
- package/dist/daytona/filesystem.d.ts +0 -99
- package/dist/daytona/filesystem.js +0 -300
- package/dist/daytona/git.d.ts +0 -33
- package/dist/daytona/git.js +0 -128
- package/dist/daytona/image.d.ts +0 -49
- package/dist/daytona/image.js +0 -146
- package/dist/daytona/index.d.ts +0 -87
- package/dist/daytona/index.js +0 -102
- package/dist/daytona/process.d.ts +0 -143
- package/dist/daytona/process.js +0 -565
- package/dist/daytona/sandbox.d.ts +0 -222
- package/dist/daytona/sandbox.js +0 -505
- package/dist/desktops/index.d.ts +0 -9
- package/dist/desktops/index.js +0 -10
- package/dist/domains/index.d.ts +0 -9
- package/dist/domains/index.js +0 -10
- package/dist/e2b/client.d.ts +0 -76
- package/dist/e2b/client.js +0 -124
- package/dist/e2b/code-interpreter.d.ts +0 -134
- package/dist/e2b/code-interpreter.js +0 -239
- package/dist/e2b/commands.d.ts +0 -135
- package/dist/e2b/commands.js +0 -452
- package/dist/e2b/errors.d.ts +0 -125
- package/dist/e2b/errors.js +0 -247
- package/dist/e2b/filesystem.d.ts +0 -111
- package/dist/e2b/filesystem.js +0 -374
- package/dist/e2b/index.d.ts +0 -35
- package/dist/e2b/index.js +0 -69
- package/dist/e2b/pty.d.ts +0 -24
- package/dist/e2b/pty.js +0 -83
- package/dist/e2b/sandbox.d.ts +0 -248
- package/dist/e2b/sandbox.js +0 -781
- package/dist/e2b/unsupported.d.ts +0 -38
- package/dist/e2b/unsupported.js +0 -48
- package/dist/e2b/users.d.ts +0 -39
- package/dist/e2b/users.js +0 -207
- package/dist/errors.d.ts +0 -100
- package/dist/errors.js +0 -198
- package/dist/file-source.d.ts +0 -16
- package/dist/file-source.js +0 -162
- package/dist/fly/index.d.ts +0 -102
- package/dist/fly/index.js +0 -930
- package/dist/freestyle/index.d.ts +0 -629
- package/dist/freestyle/index.js +0 -1187
- package/dist/functions/index.d.ts +0 -10
- package/dist/functions/index.js +0 -11
- package/dist/identity.d.ts +0 -30
- package/dist/identity.js +0 -141
- package/dist/image-context.d.ts +0 -39
- package/dist/image-context.js +0 -176
- package/dist/images/index.d.ts +0 -9
- package/dist/images/index.js +0 -10
- package/dist/index.d.ts +0 -87
- package/dist/index.js +0 -51
- package/dist/inngest/index.d.ts +0 -96
- package/dist/inngest/index.js +0 -183
- package/dist/ips/index.d.ts +0 -9
- package/dist/ips/index.js +0 -10
- package/dist/jobs/index.d.ts +0 -9
- package/dist/jobs/index.js +0 -10
- package/dist/jobs-code/cron.d.ts +0 -12
- package/dist/jobs-code/cron.js +0 -93
- package/dist/jobs-code/registry.d.ts +0 -31
- package/dist/jobs-code/registry.js +0 -30
- package/dist/jobs-code/runner.d.ts +0 -1
- package/dist/jobs-code/runner.js +0 -74
- package/dist/jobs-deploy.d.ts +0 -22
- package/dist/jobs-deploy.js +0 -247
- package/dist/jobs-import.d.ts +0 -15
- package/dist/jobs-import.js +0 -231
- package/dist/keys.d.ts +0 -55
- package/dist/keys.js +0 -211
- package/dist/login.d.ts +0 -88
- package/dist/login.js +0 -369
- package/dist/machine.d.ts +0 -222
- package/dist/machine.js +0 -578
- package/dist/mcp.d.ts +0 -16
- package/dist/mcp.js +0 -377
- package/dist/modal/index.d.ts +0 -532
- package/dist/modal/index.js +0 -1284
- package/dist/morph/index.d.ts +0 -255
- package/dist/morph/index.js +0 -641
- package/dist/network-cli.d.ts +0 -17
- package/dist/network-cli.js +0 -523
- package/dist/networks/index.d.ts +0 -11
- package/dist/networks/index.js +0 -10
- package/dist/openai-agents/index.d.ts +0 -132
- package/dist/openai-agents/index.js +0 -738
- package/dist/page.d.ts +0 -13
- package/dist/page.js +0 -39
- package/dist/ports/index.d.ts +0 -9
- package/dist/ports/index.js +0 -10
- package/dist/product-names.d.ts +0 -52
- package/dist/product-names.js +0 -174
- package/dist/product-renames.d.ts +0 -103
- package/dist/product-renames.js +0 -189
- package/dist/products/agents.d.ts +0 -935
- package/dist/products/agents.js +0 -581
- package/dist/products/api-keys.d.ts +0 -113
- package/dist/products/api-keys.js +0 -32
- package/dist/products/apps.d.ts +0 -409
- package/dist/products/apps.js +0 -231
- package/dist/products/audit.d.ts +0 -51
- package/dist/products/audit.js +0 -10
- package/dist/products/balancers.d.ts +0 -87
- package/dist/products/balancers.js +0 -8
- package/dist/products/billing.d.ts +0 -76
- package/dist/products/billing.js +0 -26
- package/dist/products/browser.d.ts +0 -73
- package/dist/products/browser.js +0 -29
- package/dist/products/browsers.d.ts +0 -184
- package/dist/products/browsers.js +0 -180
- package/dist/products/builds.d.ts +0 -175
- package/dist/products/builds.js +0 -234
- package/dist/products/ci.d.ts +0 -406
- package/dist/products/ci.js +0 -133
- package/dist/products/containers.d.ts +0 -71
- package/dist/products/containers.js +0 -6
- package/dist/products/desktop.d.ts +0 -141
- package/dist/products/desktop.js +0 -83
- package/dist/products/desktops.d.ts +0 -71
- package/dist/products/desktops.js +0 -27
- package/dist/products/functions.d.ts +0 -2
- package/dist/products/functions.js +0 -5
- package/dist/products/images.d.ts +0 -229
- package/dist/products/images.js +0 -235
- package/dist/products/index.d.ts +0 -84
- package/dist/products/index.js +0 -105
- package/dist/products/interpreter.d.ts +0 -97
- package/dist/products/interpreter.js +0 -106
- package/dist/products/jobs.d.ts +0 -408
- package/dist/products/jobs.js +0 -256
- package/dist/products/limits.d.ts +0 -61
- package/dist/products/limits.js +0 -10
- package/dist/products/logs.d.ts +0 -245
- package/dist/products/logs.js +0 -274
- package/dist/products/mcp.d.ts +0 -88
- package/dist/products/mcp.js +0 -58
- package/dist/products/mounts.d.ts +0 -49
- package/dist/products/mounts.js +0 -21
- package/dist/products/network-products.d.ts +0 -268
- package/dist/products/network-products.js +0 -127
- package/dist/products/network.d.ts +0 -62
- package/dist/products/network.js +0 -19
- package/dist/products/observability.d.ts +0 -264
- package/dist/products/observability.js +0 -123
- package/dist/products/plans.d.ts +0 -133
- package/dist/products/plans.js +0 -24
- package/dist/products/previews.d.ts +0 -70
- package/dist/products/previews.js +0 -39
- package/dist/products/private-network.d.ts +0 -22
- package/dist/products/private-network.js +0 -10
- package/dist/products/queues.d.ts +0 -149
- package/dist/products/queues.js +0 -213
- package/dist/products/referrals.d.ts +0 -50
- package/dist/products/referrals.js +0 -8
- package/dist/products/reservations.d.ts +0 -108
- package/dist/products/reservations.js +0 -41
- package/dist/products/resources.d.ts +0 -55
- package/dist/products/resources.js +0 -122
- package/dist/products/secrets.d.ts +0 -316
- package/dist/products/secrets.js +0 -333
- package/dist/products/signed-requests.d.ts +0 -21
- package/dist/products/signed-requests.js +0 -11
- package/dist/products/sso.d.ts +0 -44
- package/dist/products/sso.js +0 -8
- package/dist/products/streams.d.ts +0 -73
- package/dist/products/streams.js +0 -17
- package/dist/products/switching.d.ts +0 -123
- package/dist/products/switching.js +0 -26
- package/dist/products/tailscale.d.ts +0 -57
- package/dist/products/tailscale.js +0 -17
- package/dist/products/uptime.d.ts +0 -97
- package/dist/products/uptime.js +0 -42
- package/dist/products/volumes.d.ts +0 -190
- package/dist/products/volumes.js +0 -114
- package/dist/products/watch.d.ts +0 -112
- package/dist/products/watch.js +0 -249
- package/dist/proxy.d.ts +0 -30
- package/dist/proxy.js +0 -200
- package/dist/record-cli.d.ts +0 -23
- package/dist/record-cli.js +0 -308
- package/dist/renamed-products.d.ts +0 -38
- package/dist/renamed-products.js +0 -34
- package/dist/resumable.d.ts +0 -32
- package/dist/resumable.js +0 -201
- package/dist/runloop/index.d.ts +0 -333
- package/dist/runloop/index.js +0 -560
- package/dist/runloop/pagination.d.ts +0 -46
- package/dist/runloop/pagination.js +0 -82
- package/dist/runloop/sdk.d.ts +0 -131
- package/dist/runloop/sdk.js +0 -167
- package/dist/runloop/snapshots.d.ts +0 -52
- package/dist/runloop/snapshots.js +0 -244
- package/dist/sandbox.d.ts +0 -371
- package/dist/sandbox.js +0 -1500
- package/dist/sandboxes/index.d.ts +0 -11
- package/dist/sandboxes/index.js +0 -12
- package/dist/sealing.d.ts +0 -6
- package/dist/sealing.js +0 -14
- package/dist/snapshots/index.d.ts +0 -9
- package/dist/snapshots/index.js +0 -11
- package/dist/snapshots.d.ts +0 -82
- package/dist/snapshots.js +0 -65
- package/dist/sprites/index.d.ts +0 -563
- package/dist/sprites/index.js +0 -1370
- package/dist/ssh.d.ts +0 -56
- package/dist/ssh.js +0 -416
- package/dist/switched-off.d.ts +0 -5
- package/dist/switched-off.js +0 -8
- package/dist/tar.d.ts +0 -15
- package/dist/tar.js +0 -526
- package/dist/terminal.d.ts +0 -24
- package/dist/terminal.js +0 -32
- package/dist/tools/index.d.ts +0 -62
- package/dist/tools/index.js +0 -181
- package/dist/transport.d.ts +0 -165
- package/dist/transport.js +0 -883
- package/dist/trigger/index.d.ts +0 -202
- package/dist/trigger/index.js +0 -244
- package/dist/tunnel.d.ts +0 -70
- package/dist/tunnel.js +0 -316
- package/dist/types.d.ts +0 -585
- package/dist/types.js +0 -1
- package/dist/vercel/client.d.ts +0 -40
- package/dist/vercel/client.js +0 -39
- package/dist/vercel/command.d.ts +0 -117
- package/dist/vercel/command.js +0 -391
- package/dist/vercel/errors.d.ts +0 -53
- package/dist/vercel/errors.js +0 -131
- package/dist/vercel/filesystem.d.ts +0 -153
- package/dist/vercel/filesystem.js +0 -297
- package/dist/vercel/index.d.ts +0 -24
- package/dist/vercel/index.js +0 -36
- package/dist/vercel/sandbox-user.d.ts +0 -70
- package/dist/vercel/sandbox-user.js +0 -207
- package/dist/vercel/sandbox.d.ts +0 -372
- package/dist/vercel/sandbox.js +0 -1037
- package/dist/vercel/snapshot.d.ts +0 -94
- package/dist/vercel/snapshot.js +0 -137
- package/dist/volumes/index.d.ts +0 -9
- package/dist/volumes/index.js +0 -10
- package/dist/wait.d.ts +0 -12
- package/dist/wait.js +0 -47
- package/dist/wallet.d.ts +0 -45
- package/dist/wallet.js +0 -56
- package/dist/wireguard.d.ts +0 -7
- package/dist/wireguard.js +0 -13
package/dist/sandbox.js
DELETED
|
@@ -1,1500 +0,0 @@
|
|
|
1
|
-
import { STREAMED_EXEC_TIMEOUT_MS } from "./api-defaults.js";
|
|
2
|
-
import { CommandError, ConnectionError, DELIBERATE, errorFor, NotFoundError, RateLimitError, RuntimeError, ServiceUnavailableError, } from "./errors.js";
|
|
3
|
-
import { sandboxWatches, watchDirectory, } from "./products/watch.js";
|
|
4
|
-
import { Transport, timeoutSignal } from "./transport.js";
|
|
5
|
-
import { sandboxFactories } from "./products/index.js";
|
|
6
|
-
import { Tunnel } from "./tunnel.js";
|
|
7
|
-
import { ResumableSocket } from "./resumable.js";
|
|
8
|
-
import { pause } from "./wait.js";
|
|
9
|
-
import { Machine, machinePage, requestOnly } from "./machine.js";
|
|
10
|
-
/** Sandboxes, as a product of the machine engine (machine.ts). */
|
|
11
|
-
export const SANDBOXES = { plural: "sandboxes", noun: "Sandbox" };
|
|
12
|
-
const CHUNK = 1_048_576;
|
|
13
|
-
/** Chunks of a large write in flight at once. Each chunk's reply waits on the
|
|
14
|
-
* API and the guest, and the link idles while every chunk in flight waits:
|
|
15
|
-
* from a home link (12.6 MB/s up, 27 September 2026) 100 MB took 17-18 s at
|
|
16
|
-
* four and 11 s at eight, and sixteen was no faster. The guest takes 128
|
|
17
|
-
* connections at once. */
|
|
18
|
-
const PARALLEL = 8;
|
|
19
|
-
const enc = (id) => encodeURIComponent(id);
|
|
20
|
-
/** One explicit deadline across a composed operation and its queue/retries. */
|
|
21
|
-
function requestScope(options) {
|
|
22
|
-
const deadline = options.timeoutMs === undefined || options.timeoutMs === 0
|
|
23
|
-
? undefined
|
|
24
|
-
: timeoutSignal(options.timeoutMs);
|
|
25
|
-
const signal = deadline && options.signal
|
|
26
|
-
? AbortSignal.any([deadline, options.signal])
|
|
27
|
-
: (deadline ?? options.signal);
|
|
28
|
-
const request = {
|
|
29
|
-
...options,
|
|
30
|
-
...(deadline ? { timeoutMs: 0 } : {}),
|
|
31
|
-
...(signal ? { signal } : {}),
|
|
32
|
-
};
|
|
33
|
-
const cancelled = () => new ConnectionError({
|
|
34
|
-
message: "The call was cancelled or ran past its deadline.",
|
|
35
|
-
code: "timeout",
|
|
36
|
-
status: 0,
|
|
37
|
-
cause: signal?.reason,
|
|
38
|
-
});
|
|
39
|
-
const check = () => {
|
|
40
|
-
if (signal?.aborted)
|
|
41
|
-
throw cancelled();
|
|
42
|
-
};
|
|
43
|
-
const wait = (pending) => {
|
|
44
|
-
if (!signal)
|
|
45
|
-
return pending;
|
|
46
|
-
return new Promise((resolve, reject) => {
|
|
47
|
-
const abort = () => reject(cancelled());
|
|
48
|
-
if (signal.aborted)
|
|
49
|
-
abort();
|
|
50
|
-
else
|
|
51
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
52
|
-
pending.then((value) => {
|
|
53
|
-
signal.removeEventListener("abort", abort);
|
|
54
|
-
resolve(value);
|
|
55
|
-
}, (error) => {
|
|
56
|
-
signal.removeEventListener("abort", abort);
|
|
57
|
-
reject(error instanceof Error ? error : new Error(String(error), { cause: error }));
|
|
58
|
-
});
|
|
59
|
-
});
|
|
60
|
-
};
|
|
61
|
-
return { request, check, wait };
|
|
62
|
-
}
|
|
63
|
-
/* Web APIs only, so the sandbox's commands, processes and files work in a
|
|
64
|
-
browser with a session token (Sandbox.fromSession): no Buffer, no
|
|
65
|
-
node:crypto. */
|
|
66
|
-
const utf8 = (data) => typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
67
|
-
function base64(bytes) {
|
|
68
|
-
let text = "";
|
|
69
|
-
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
70
|
-
text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
71
|
-
return btoa(text);
|
|
72
|
-
}
|
|
73
|
-
const toBase64 = (data) => base64(utf8(data));
|
|
74
|
-
async function sha256Hex(data) {
|
|
75
|
-
const digest = await crypto.subtle.digest("SHA-256", utf8(data));
|
|
76
|
-
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
77
|
-
}
|
|
78
|
-
function commandBody(command, options) {
|
|
79
|
-
return {
|
|
80
|
-
...(typeof command === "string" ? { command } : { argv: [...command] }),
|
|
81
|
-
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
|
82
|
-
...(options.env === undefined ? {} : { env: options.env }),
|
|
83
|
-
...(options.user === undefined ? {} : { user: options.user }),
|
|
84
|
-
...(options.stdin === undefined
|
|
85
|
-
? {}
|
|
86
|
-
: typeof options.stdin === "string"
|
|
87
|
-
? { stdin: options.stdin }
|
|
88
|
-
: { stdinBase64: toBase64(options.stdin) }),
|
|
89
|
-
...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
|
|
90
|
-
...(options.traceFiles ? { traceFiles: true } : {}),
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
/** How long past its timeoutMs a streamed exec waits for an exit that never came. */
|
|
94
|
-
export const EXEC_EXIT_GRACE = { ms: 120_000 };
|
|
95
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
|
|
96
|
-
export class Sandbox extends Machine {
|
|
97
|
-
#t;
|
|
98
|
-
files;
|
|
99
|
-
processes;
|
|
100
|
-
/** Short-lived tokens that let a browser reach this sandbox directly. */
|
|
101
|
-
sessions;
|
|
102
|
-
constructor(transport, info) {
|
|
103
|
-
super(SANDBOXES, transport, info);
|
|
104
|
-
this.#t = transport;
|
|
105
|
-
this.files = new Files(transport, info.id);
|
|
106
|
-
this.processes = new Processes(transport, info.id);
|
|
107
|
-
this.sessions = new SandboxSessions(transport, info.id);
|
|
108
|
-
for (const [name, make] of sandboxFactories())
|
|
109
|
-
Object.defineProperty(this, name, { value: make(transport, this), enumerable: false });
|
|
110
|
-
}
|
|
111
|
-
/** A sandbox reached with a session token instead of an API key, for code in
|
|
112
|
-
* a browser: commands and their streams, processes, files and previews of
|
|
113
|
-
* this one sandbox. Makes no call; `info` holds only the id until
|
|
114
|
-
* `refresh()`. Your backend makes the session with `sbx.sessions.create()`
|
|
115
|
-
* and hands the page `token` and `sandboxId`.
|
|
116
|
-
*
|
|
117
|
-
* const sbx = Sandbox.fromSession({ token, sandboxId });
|
|
118
|
-
* const { stdout } = await sbx.exec("ls /workspace");
|
|
119
|
-
*/
|
|
120
|
-
static fromSession(session) {
|
|
121
|
-
if (!/^rtsess_/.test(session.token))
|
|
122
|
-
throw new RuntimeError({
|
|
123
|
-
message: "That is not a sandbox session token (they start rtsess_).",
|
|
124
|
-
code: "invalid_request",
|
|
125
|
-
status: 0,
|
|
126
|
-
hint: "Make one on your backend with sbx.sessions.create() and pass its token.",
|
|
127
|
-
});
|
|
128
|
-
const transport = new Transport({
|
|
129
|
-
apiKey: session.token,
|
|
130
|
-
...(session.apiUrl ? { baseUrl: session.apiUrl } : {}),
|
|
131
|
-
...(session.fetch ? { fetch: session.fetch } : {}),
|
|
132
|
-
});
|
|
133
|
-
return new Sandbox(transport, { id: session.sandboxId });
|
|
134
|
-
}
|
|
135
|
-
/** Runs a command and returns its exit code and output. A string runs under
|
|
136
|
-
* `bash -c`; an array runs without a shell. With onStdout/onStderr the output
|
|
137
|
-
* streams as it happens. A timeout is a result (timedOut: true, the output so
|
|
138
|
-
* far), never an error; `check: true` throws CommandError on a non-zero exit. */
|
|
139
|
-
async exec(command, options = {}) {
|
|
140
|
-
const streaming = options.onStdout || options.onStderr || (options.timeoutMs ?? 0) > 60_000;
|
|
141
|
-
let result;
|
|
142
|
-
if (!streaming) {
|
|
143
|
-
result = await this.#t.json({
|
|
144
|
-
method: "POST",
|
|
145
|
-
path: `/v1/sandboxes/${enc(this.id)}:exec`,
|
|
146
|
-
body: commandBody(command, options),
|
|
147
|
-
...pick(options),
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
else {
|
|
151
|
-
const out = { stdout: "", stderr: "" };
|
|
152
|
-
let exit;
|
|
153
|
-
let processId;
|
|
154
|
-
let dropped = false;
|
|
155
|
-
// A command with a time limit ends by it, the server killing it if need
|
|
156
|
-
// be; an exit that never comes after (a follow that resumes forever)
|
|
157
|
-
// ends the wait past the limit and EXEC_EXIT_GRACE.ms, as a timeout,
|
|
158
|
-
// its process named and sent SIGTERM. The hub's release train waited
|
|
159
|
-
// 29 min on a 10 min command (15 October 2026).
|
|
160
|
-
// A timer cleared when the call ends, so none outlives the exec.
|
|
161
|
-
const deadline = options.timeoutMs === undefined ? undefined : new AbortController();
|
|
162
|
-
const timer = deadline
|
|
163
|
-
? setTimeout(() => deadline.abort(), options.timeoutMs + EXEC_EXIT_GRACE.ms)
|
|
164
|
-
: undefined;
|
|
165
|
-
timer?.unref?.();
|
|
166
|
-
const signal = deadline && options.signal
|
|
167
|
-
? AbortSignal.any([options.signal, deadline.signal])
|
|
168
|
-
: (deadline?.signal ?? options.signal);
|
|
169
|
-
try {
|
|
170
|
-
for await (const event of this.execStream(command, { ...options, signal })) {
|
|
171
|
-
if (event.type === "start")
|
|
172
|
-
processId = event.processId;
|
|
173
|
-
else if (event.type === "stdout" || event.type === "stderr") {
|
|
174
|
-
out[event.type] += event.data;
|
|
175
|
-
await (event.type === "stdout" ? options.onStdout : options.onStderr)?.(event.data);
|
|
176
|
-
}
|
|
177
|
-
else if (event.type === "truncated")
|
|
178
|
-
dropped = true;
|
|
179
|
-
else if (event.type === "exit")
|
|
180
|
-
exit = event;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
catch (error) {
|
|
184
|
-
if (!deadline?.signal.aborted || options.signal?.aborted)
|
|
185
|
-
throw await this.#unfinished(error, processId, signal);
|
|
186
|
-
if (processId)
|
|
187
|
-
await new Process(this.#t, this.id, { id: processId })
|
|
188
|
-
.kill("SIGTERM")
|
|
189
|
-
.catch(() => { });
|
|
190
|
-
exit = { type: "exit", exitCode: null, timedOut: true };
|
|
191
|
-
}
|
|
192
|
-
finally {
|
|
193
|
-
clearTimeout(timer);
|
|
194
|
-
}
|
|
195
|
-
// A stream the server ended (continue) is followed to its exit, which
|
|
196
|
-
// names no files: they are the process's own to read.
|
|
197
|
-
const files = exit?.files ??
|
|
198
|
-
(options.traceFiles && processId && exit?.state
|
|
199
|
-
? await new Process(this.#t, this.id, { id: processId }).files()
|
|
200
|
-
: undefined);
|
|
201
|
-
result = {
|
|
202
|
-
exitCode: exit?.exitCode ?? null,
|
|
203
|
-
...out,
|
|
204
|
-
timedOut: exit?.timedOut ?? false,
|
|
205
|
-
...truncation(dropped),
|
|
206
|
-
...(exit?.durationMs === undefined ? {} : { durationMs: exit.durationMs }),
|
|
207
|
-
...(processId ? { processId } : {}),
|
|
208
|
-
...(exit?.outOfMemory ? { outOfMemory: exit.outOfMemory } : {}),
|
|
209
|
-
...(files ? { files } : {}),
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
if (options.check && (result.exitCode !== 0 || result.timedOut))
|
|
213
|
-
throw new CommandError(result);
|
|
214
|
-
return result;
|
|
215
|
-
}
|
|
216
|
-
/** An exec that ended before its command did. Cancelled through `signal`,
|
|
217
|
-
* its command is sent SIGTERM, as Ctrl-C would stop it at a terminal; cut
|
|
218
|
-
* off, it is left running. Either way the error names the process, so the
|
|
219
|
-
* caller can read or stop what is still there. */
|
|
220
|
-
async #unfinished(error, processId, signal) {
|
|
221
|
-
if (!processId)
|
|
222
|
-
return error;
|
|
223
|
-
const id = `${this.id} ${processId}`;
|
|
224
|
-
if (signal?.aborted) {
|
|
225
|
-
const stopped = await new Process(this.#t, this.id, { id: processId })
|
|
226
|
-
.kill("SIGTERM")
|
|
227
|
-
.then(() => true, () => false);
|
|
228
|
-
return new RuntimeError({
|
|
229
|
-
message: stopped
|
|
230
|
-
? `Cancelled; process ${processId} was sent SIGTERM.`
|
|
231
|
-
: `Cancelled, but process ${processId} may still be running: stopping it failed.`,
|
|
232
|
-
code: "cancelled",
|
|
233
|
-
status: 0,
|
|
234
|
-
hint: stopped
|
|
235
|
-
? `See what it printed: runtime sandboxes logs ${id}`
|
|
236
|
-
: `Stop it: runtime sandboxes kill ${id}, or sandbox.processes.get("${processId}") and kill().`,
|
|
237
|
-
details: { sandboxId: this.id, processId, stopped },
|
|
238
|
-
cause: error,
|
|
239
|
-
});
|
|
240
|
-
}
|
|
241
|
-
if (error instanceof RuntimeError && !(error instanceof ConnectionError))
|
|
242
|
-
return error;
|
|
243
|
-
return new ConnectionError({
|
|
244
|
-
message: `Lost the output of process ${processId}; the command may still be running.`,
|
|
245
|
-
code: "connection_error",
|
|
246
|
-
status: 0,
|
|
247
|
-
hint: `Follow it: runtime sandboxes logs ${id} -f (sandbox.processes.get("${processId}")), or stop it: runtime sandboxes kill ${id}.`,
|
|
248
|
-
details: { sandboxId: this.id, processId },
|
|
249
|
-
cause: error,
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
/** The command's events as they happen: start, stdout, stderr, exit. Resumes
|
|
253
|
-
* by itself when the server ends a long stream or the connection drops after
|
|
254
|
-
* the command started, and yields `truncated` for any output it did not
|
|
255
|
-
* receive, so lost output never passes as whole. */
|
|
256
|
-
async *execStream(command, options = {}) {
|
|
257
|
-
let processId;
|
|
258
|
-
const read = new OutputCursor();
|
|
259
|
-
const events = this.#t.events({
|
|
260
|
-
method: "POST",
|
|
261
|
-
path: `/v1/sandboxes/${enc(this.id)}:exec`,
|
|
262
|
-
body: {
|
|
263
|
-
...commandBody(command, { timeoutMs: STREAMED_EXEC_TIMEOUT_MS, ...options }),
|
|
264
|
-
stream: true,
|
|
265
|
-
},
|
|
266
|
-
...pick(options),
|
|
267
|
-
timeoutMs: options.timeoutMs === undefined ? STREAMED_EXEC_TIMEOUT_MS : options.timeoutMs + 60_000,
|
|
268
|
-
});
|
|
269
|
-
try {
|
|
270
|
-
for await (const event of events) {
|
|
271
|
-
if (event.type === "start")
|
|
272
|
-
processId = event.processId;
|
|
273
|
-
if (event.type === "continue") {
|
|
274
|
-
yield* this.processes.follow(event.processId, {
|
|
275
|
-
cursor: event.cursor,
|
|
276
|
-
signal: options.signal,
|
|
277
|
-
});
|
|
278
|
-
return;
|
|
279
|
-
}
|
|
280
|
-
yield* read.pass(event);
|
|
281
|
-
if (event.type === "exit")
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
catch (error) {
|
|
286
|
-
if (options.signal?.aborted || !processId || !cutOff(error))
|
|
287
|
-
throw error;
|
|
288
|
-
}
|
|
289
|
-
// The connection closed after the command started: its output is kept on
|
|
290
|
-
// the sandbox, so follow it from where this stream stopped.
|
|
291
|
-
if (!processId)
|
|
292
|
-
throw new ConnectionError({
|
|
293
|
-
message: "The exec stream closed before the command started.",
|
|
294
|
-
code: "connection_error",
|
|
295
|
-
status: 0,
|
|
296
|
-
hint: "Run it again; to be sure it runs once, pass the same idempotencyKey.",
|
|
297
|
-
});
|
|
298
|
-
yield* this.processes.follow(processId, { cursor: read.cursor, signal: options.signal });
|
|
299
|
-
}
|
|
300
|
-
/** Starts a background process (a server, a watcher, a REPL) and returns at
|
|
301
|
-
* once. `stdin: "pipe"` keeps its input open for write(); `pty` gives it a
|
|
302
|
-
* terminal. */
|
|
303
|
-
async spawn(command, options = {}) {
|
|
304
|
-
const { stdin, pty, outputEncoding, request, ...rest } = options;
|
|
305
|
-
const info = await this.#t.json({
|
|
306
|
-
method: "POST",
|
|
307
|
-
path: `/v1/sandboxes/${enc(this.id)}/processes`,
|
|
308
|
-
body: {
|
|
309
|
-
...commandBody(command, rest),
|
|
310
|
-
...(stdin === "pipe" ? { stdinMode: "pipe" } : stdin === undefined ? {} : { stdin }),
|
|
311
|
-
...(pty ? { pty } : {}),
|
|
312
|
-
...(outputEncoding ? { outputEncoding } : {}),
|
|
313
|
-
},
|
|
314
|
-
...pick(rest),
|
|
315
|
-
...request,
|
|
316
|
-
});
|
|
317
|
-
return new Process(this.#t, this.id, info);
|
|
318
|
-
}
|
|
319
|
-
/** An interactive terminal over a WebSocket. Bytes you write are typed;
|
|
320
|
-
* onData receives what the terminal prints. */
|
|
321
|
-
async terminal(options = {}) {
|
|
322
|
-
const path = `/v1/sandboxes/${enc(this.id)}/terminal`;
|
|
323
|
-
// Resumes across a restart of the API with nothing lost (resumable.ts).
|
|
324
|
-
const socket = await ResumableSocket.open((resume) => this.#t.websocket(path, resume
|
|
325
|
-
? { resume }
|
|
326
|
-
: {
|
|
327
|
-
cols: options.cols,
|
|
328
|
-
rows: options.rows,
|
|
329
|
-
command: options.command,
|
|
330
|
-
cwd: options.cwd,
|
|
331
|
-
user: options.user,
|
|
332
|
-
processId: options.processId,
|
|
333
|
-
}));
|
|
334
|
-
return Terminal.open(socket, options.onData);
|
|
335
|
-
}
|
|
336
|
-
/** A tunnel into the sandbox: TCP connections to any port on its loopback,
|
|
337
|
-
* and SSH logins, over one authenticated WebSocket. No port is opened to the
|
|
338
|
-
* internet. `tunnel.connect(5432)` gives one connection;
|
|
339
|
-
* `tunnel.forward(5432)` listens locally (Node and Bun). */
|
|
340
|
-
async tunnel() {
|
|
341
|
-
const path = `/v1/sandboxes/${enc(this.id)}/tunnel`;
|
|
342
|
-
const socket = await ResumableSocket.open((resume) => this.#t.websocket(path, resume ? { resume } : undefined));
|
|
343
|
-
return Tunnel.open(socket);
|
|
344
|
-
}
|
|
345
|
-
/** Listens on a local port (the same number unless `localPort` says, 0 for
|
|
346
|
-
* any) and forwards each connection to `port` inside the sandbox, until
|
|
347
|
-
* `close()`. Node and Bun. */
|
|
348
|
-
async forwardPort(port, options = {}) {
|
|
349
|
-
const tunnel = await this.tunnel();
|
|
350
|
-
try {
|
|
351
|
-
const forward = await tunnel.forward(port, options);
|
|
352
|
-
return {
|
|
353
|
-
...forward,
|
|
354
|
-
close: async () => {
|
|
355
|
-
await forward.close();
|
|
356
|
-
tunnel.close();
|
|
357
|
-
},
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
catch (error) {
|
|
361
|
-
tunnel.close();
|
|
362
|
-
throw error;
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
async fork(options = {}) {
|
|
366
|
-
const { idempotencyKey, signal, timeoutMs, ...body } = options;
|
|
367
|
-
const reply = await this.#t.json({
|
|
368
|
-
method: "POST",
|
|
369
|
-
path: `/v1/sandboxes/${enc(this.id)}:fork`,
|
|
370
|
-
body,
|
|
371
|
-
wait: 60,
|
|
372
|
-
// Its key replays a refusal for room or a limit, so it is told at once.
|
|
373
|
-
waitForCapacityMs: 0,
|
|
374
|
-
...requestOnly({ idempotencyKey, signal, timeoutMs }),
|
|
375
|
-
});
|
|
376
|
-
const sandboxes = reply.sandboxes.map((info) => new Sandbox(this.#t, info));
|
|
377
|
-
return options.count === undefined ? sandboxes[0] : sandboxes;
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
/** Where a reader of a process's output is, in bytes of stdout and stderr
|
|
381
|
-
* together. Output it did not receive, named by the server or not, becomes a
|
|
382
|
-
* `truncated` event: the next chunk starting past the cursor means the bytes
|
|
383
|
-
* between were lost. A server error event becomes a thrown error. */
|
|
384
|
-
class OutputCursor {
|
|
385
|
-
cursor;
|
|
386
|
-
constructor(cursor = 0) {
|
|
387
|
-
this.cursor = cursor;
|
|
388
|
-
}
|
|
389
|
-
*pass(event) {
|
|
390
|
-
// As the status the API would have answered it, so a passing failure (a
|
|
391
|
-
// host restarting) is followed again rather than ending the read.
|
|
392
|
-
if (event.type === "error")
|
|
393
|
-
throw errorFor(event.error.status ?? 0, event);
|
|
394
|
-
if (event.type === "truncated")
|
|
395
|
-
this.cursor = Math.max(this.cursor, event.resumeAt);
|
|
396
|
-
if (event.type === "stdout" || event.type === "stderr") {
|
|
397
|
-
if (event.offset > this.cursor)
|
|
398
|
-
yield {
|
|
399
|
-
type: "truncated",
|
|
400
|
-
droppedBytes: event.offset - this.cursor,
|
|
401
|
-
resumeAt: event.offset,
|
|
402
|
-
};
|
|
403
|
-
this.cursor = Math.max(this.cursor, event.offset +
|
|
404
|
-
(event.base64 === undefined
|
|
405
|
-
? utf8(event.data).byteLength
|
|
406
|
-
: processBytes(event.base64).length));
|
|
407
|
-
}
|
|
408
|
-
yield event;
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
function processBytes(encoded) {
|
|
412
|
-
try {
|
|
413
|
-
return atob(encoded);
|
|
414
|
-
}
|
|
415
|
-
catch (cause) {
|
|
416
|
-
throw new RuntimeError({
|
|
417
|
-
code: "invalid_process_output",
|
|
418
|
-
status: 502,
|
|
419
|
-
message: "The process returned invalid base64 output.",
|
|
420
|
-
cause,
|
|
421
|
-
});
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
/** A stream cut off by the network, or refused by a failure that passes by
|
|
425
|
-
* itself (a busy API, a 429, a host restarting), rather than refused for good:
|
|
426
|
-
* worth reconnecting to from the cursor. */
|
|
427
|
-
function cutOff(error) {
|
|
428
|
-
return (!(error instanceof RuntimeError) ||
|
|
429
|
-
error instanceof ConnectionError ||
|
|
430
|
-
// The API says whether it passes; an older server is judged by status.
|
|
431
|
-
(error.sentRetryable ??
|
|
432
|
-
((error instanceof RateLimitError || error instanceof ServiceUnavailableError) &&
|
|
433
|
-
[429, 502, 503, 504].includes(error.status) &&
|
|
434
|
-
!DELIBERATE.has(error.code))));
|
|
435
|
-
}
|
|
436
|
-
/** How long a follow keeps reconnecting while every attempt fails. A command
|
|
437
|
-
* runs for hours whether or not anyone reads it; a few minutes of a deploy, a
|
|
438
|
-
* network blip or a busy API must not end the read of it. */
|
|
439
|
-
const FOLLOW_OUTAGE_MS = 300_000;
|
|
440
|
-
/** A streamed command keeps all its output unless the reader fell more than the
|
|
441
|
-
* process's output buffer behind, which the server marks with a "truncated"
|
|
442
|
-
* event. That event does not say which stream lost bytes, so both flags carry
|
|
443
|
-
* it; without one, both are false, as a synchronous result's are. */
|
|
444
|
-
function truncation(dropped) {
|
|
445
|
-
return { stdoutTruncated: dropped, stderrTruncated: dropped };
|
|
446
|
-
}
|
|
447
|
-
/** A command's request options: its `timeoutMs` is the command's own limit
|
|
448
|
-
* in the guest, so the call is given a minute more for the answer. */
|
|
449
|
-
function pick(options) {
|
|
450
|
-
return {
|
|
451
|
-
...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),
|
|
452
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
453
|
-
...(options.timeoutMs ? { timeoutMs: options.timeoutMs + 60_000 } : {}),
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
/** Sessions: a token your backend makes and hands to your own frontend, which
|
|
457
|
-
* then runs commands, reads and writes files and reaches previews in this one
|
|
458
|
-
* sandbox directly, without proxying through your servers. A session cannot
|
|
459
|
-
* stop, pause, extend, fork, snapshot or change the sandbox, create anything,
|
|
460
|
-
* or reach anything else. It lasts an hour unless asked (a day at most), ends
|
|
461
|
-
* when the key that made it is revoked, and is revocable at once. */
|
|
462
|
-
export class SandboxSessions {
|
|
463
|
-
t;
|
|
464
|
-
sandboxId;
|
|
465
|
-
constructor(t, sandboxId) {
|
|
466
|
-
this.t = t;
|
|
467
|
-
this.sandboxId = sandboxId;
|
|
468
|
-
}
|
|
469
|
-
/** A new session. `origins` are the exact pages that will use it
|
|
470
|
-
* (`https://app.example.com`, or `http://localhost:5173` while developing):
|
|
471
|
-
* the API answers CORS for them and refuses any other page. */
|
|
472
|
-
async create(input = {}, options = {}) {
|
|
473
|
-
const path = `/v1/sandboxes/${enc(this.sandboxId)}/sessions`;
|
|
474
|
-
const made = await this.t.json({
|
|
475
|
-
method: "POST",
|
|
476
|
-
path,
|
|
477
|
-
body: input,
|
|
478
|
-
...options,
|
|
479
|
-
});
|
|
480
|
-
if (made.token)
|
|
481
|
-
return made;
|
|
482
|
-
/* The answer replayed an earlier create whose reply was lost, and a token
|
|
483
|
-
is shown only once: end that session and make a fresh one. */
|
|
484
|
-
await this.revoke(made.id).catch(() => undefined);
|
|
485
|
-
const fresh = await this.t.json({
|
|
486
|
-
method: "POST",
|
|
487
|
-
path,
|
|
488
|
-
body: input,
|
|
489
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
490
|
-
...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),
|
|
491
|
-
});
|
|
492
|
-
if (!fresh.token)
|
|
493
|
-
throw new RuntimeError({
|
|
494
|
-
message: "The session was made but its token did not arrive.",
|
|
495
|
-
code: "session_token_lost",
|
|
496
|
-
status: 0,
|
|
497
|
-
hint: `Revoke session ${fresh.id} and create another.`,
|
|
498
|
-
});
|
|
499
|
-
return fresh;
|
|
500
|
-
}
|
|
501
|
-
/** Sessions still active, and those that ended in the last day, newest first. */
|
|
502
|
-
async list(options = {}) {
|
|
503
|
-
return (await this.t.json({
|
|
504
|
-
method: "GET",
|
|
505
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/sessions`,
|
|
506
|
-
...options,
|
|
507
|
-
})).data;
|
|
508
|
-
}
|
|
509
|
-
/** Ends a session now; its next request is refused. */
|
|
510
|
-
async revoke(sessionId, options = {}) {
|
|
511
|
-
return this.t.json({
|
|
512
|
-
method: "POST",
|
|
513
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/sessions/${enc(sessionId)}:revoke`,
|
|
514
|
-
body: {},
|
|
515
|
-
...options,
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
export class Processes {
|
|
520
|
-
t;
|
|
521
|
-
sandboxId;
|
|
522
|
-
constructor(t, sandboxId) {
|
|
523
|
-
this.t = t;
|
|
524
|
-
this.sandboxId = sandboxId;
|
|
525
|
-
}
|
|
526
|
-
async list(options = {}) {
|
|
527
|
-
return (await this.t.json({
|
|
528
|
-
method: "GET",
|
|
529
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes`,
|
|
530
|
-
...options,
|
|
531
|
-
})).data;
|
|
532
|
-
}
|
|
533
|
-
async get(processId, options = {}) {
|
|
534
|
-
const info = await this.t.json({
|
|
535
|
-
method: "GET",
|
|
536
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes/${enc(processId)}`,
|
|
537
|
-
...options,
|
|
538
|
-
});
|
|
539
|
-
return new Process(this.t, this.sandboxId, info);
|
|
540
|
-
}
|
|
541
|
-
/** Output events from `cursor` until the process exits, across stream slices. */
|
|
542
|
-
async *follow(processId, options = {}) {
|
|
543
|
-
const read = new OutputCursor(options.cursor ?? 0);
|
|
544
|
-
// Reconnections in a row that closed cleanly with nothing: a stream that
|
|
545
|
-
// keeps closing without output or an exit is given up, not followed
|
|
546
|
-
// forever.
|
|
547
|
-
let idle = 0;
|
|
548
|
-
// Since when every reconnection has failed (a cut, a busy API, a host
|
|
549
|
-
// restarting). The command runs on regardless, so these are waited out
|
|
550
|
-
// for FOLLOW_OUTAGE_MS, with backoff, before the follow gives up.
|
|
551
|
-
let failingSince;
|
|
552
|
-
let failures = 0;
|
|
553
|
-
for (;;) {
|
|
554
|
-
const before = read.cursor;
|
|
555
|
-
let resumed = false;
|
|
556
|
-
let failure;
|
|
557
|
-
try {
|
|
558
|
-
for await (const event of this.t.events({
|
|
559
|
-
method: "GET",
|
|
560
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes/${enc(processId)}/output`,
|
|
561
|
-
query: { cursor: read.cursor, follow: true },
|
|
562
|
-
timeoutMs: 180_000,
|
|
563
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
564
|
-
})) {
|
|
565
|
-
if (event.type === "continue") {
|
|
566
|
-
read.cursor = Math.max(read.cursor, event.cursor);
|
|
567
|
-
resumed = true;
|
|
568
|
-
break;
|
|
569
|
-
}
|
|
570
|
-
yield* read.pass(event);
|
|
571
|
-
if (event.type === "exit")
|
|
572
|
-
return;
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
catch (error) {
|
|
576
|
-
if (options.signal?.aborted || !cutOff(error))
|
|
577
|
-
throw error;
|
|
578
|
-
failure = error;
|
|
579
|
-
}
|
|
580
|
-
if (resumed || read.cursor > before) {
|
|
581
|
-
idle = failures = 0;
|
|
582
|
-
failingSince = undefined;
|
|
583
|
-
continue;
|
|
584
|
-
}
|
|
585
|
-
if (failure === undefined)
|
|
586
|
-
idle++;
|
|
587
|
-
else {
|
|
588
|
-
failingSince ??= performance.now();
|
|
589
|
-
if (performance.now() - failingSince >= FOLLOW_OUTAGE_MS)
|
|
590
|
-
throw new ConnectionError({
|
|
591
|
-
message: `Lost the output stream of process ${processId} for ${FOLLOW_OUTAGE_MS / 60_000} minutes; the command may still be running.`,
|
|
592
|
-
code: "connection_error",
|
|
593
|
-
status: 0,
|
|
594
|
-
hint: `Follow it again: runtime sandboxes logs ${this.sandboxId} ${processId} -f`,
|
|
595
|
-
details: { sandboxId: this.sandboxId, processId },
|
|
596
|
-
cause: failure,
|
|
597
|
-
});
|
|
598
|
-
await pause(Math.min(5000, 50 * 2 ** failures++), options.signal);
|
|
599
|
-
}
|
|
600
|
-
if (idle > 3)
|
|
601
|
-
throw new ConnectionError({
|
|
602
|
-
message: `The output stream of process ${processId} keeps closing before it ends.`,
|
|
603
|
-
code: "connection_error",
|
|
604
|
-
status: 0,
|
|
605
|
-
hint: `Read what it printed so far: runtime sandboxes logs ${this.sandboxId} ${processId}`,
|
|
606
|
-
details: { sandboxId: this.sandboxId, processId },
|
|
607
|
-
});
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
/** A background process: its output, its input, its end. */
|
|
612
|
-
export class Process {
|
|
613
|
-
t;
|
|
614
|
-
sandboxId;
|
|
615
|
-
info;
|
|
616
|
-
#inputOffset;
|
|
617
|
-
#inputWrites = Promise.resolve();
|
|
618
|
-
constructor(t, sandboxId, info) {
|
|
619
|
-
this.t = t;
|
|
620
|
-
this.sandboxId = sandboxId;
|
|
621
|
-
this.info = info;
|
|
622
|
-
this.#inputOffset = info.stdinOffset ?? 0;
|
|
623
|
-
}
|
|
624
|
-
get id() {
|
|
625
|
-
return this.info.id;
|
|
626
|
-
}
|
|
627
|
-
/** The command line as the sandbox reports it. */
|
|
628
|
-
get command() {
|
|
629
|
-
return this.info.command;
|
|
630
|
-
}
|
|
631
|
-
/** As of the last answer: spawn, `wait()` or `refresh()`. */
|
|
632
|
-
get state() {
|
|
633
|
-
return this.info.state;
|
|
634
|
-
}
|
|
635
|
-
/** null while it runs, and when it was killed or timed out. */
|
|
636
|
-
get exitCode() {
|
|
637
|
-
return this.info.exitCode;
|
|
638
|
-
}
|
|
639
|
-
toJSON() {
|
|
640
|
-
return this.info;
|
|
641
|
-
}
|
|
642
|
-
/** console.log shows what the process is, not the client inside it. */
|
|
643
|
-
[Symbol.for("nodejs.util.inspect.custom")](_depth, options, show) {
|
|
644
|
-
const { id, sandboxId, command, state, exitCode } = this;
|
|
645
|
-
return `Process ${show({ id, sandboxId, command, state, exitCode }, options)}`;
|
|
646
|
-
}
|
|
647
|
-
/** Every output event from the start (or `cursor`) until exit. */
|
|
648
|
-
output(options = {}) {
|
|
649
|
-
return new Processes(this.t, this.sandboxId).follow(this.id, options);
|
|
650
|
-
}
|
|
651
|
-
/** Lossless output for a process spawned with outputEncoding: "base64".
|
|
652
|
-
* Refuses text-only output rather than inventing bytes that were discarded. */
|
|
653
|
-
async *outputBytes(options = {}) {
|
|
654
|
-
if (this.info.outputEncoding !== "base64")
|
|
655
|
-
throw new RuntimeError({
|
|
656
|
-
code: "binary_output_unavailable",
|
|
657
|
-
status: 409,
|
|
658
|
-
message: "Spawn the process with outputEncoding: base64 to read lossless bytes.",
|
|
659
|
-
});
|
|
660
|
-
for await (const event of this.output(options)) {
|
|
661
|
-
if (event.type === "stdout" || event.type === "stderr") {
|
|
662
|
-
if (event.base64 === undefined)
|
|
663
|
-
throw new RuntimeError({
|
|
664
|
-
code: "binary_output_unavailable",
|
|
665
|
-
status: 502,
|
|
666
|
-
message: "The process returned text without its original bytes.",
|
|
667
|
-
});
|
|
668
|
-
const raw = processBytes(event.base64);
|
|
669
|
-
yield {
|
|
670
|
-
type: event.type,
|
|
671
|
-
offset: event.offset,
|
|
672
|
-
data: Uint8Array.from(raw, (c) => c.charCodeAt(0)),
|
|
673
|
-
};
|
|
674
|
-
}
|
|
675
|
-
else
|
|
676
|
-
yield event;
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
/** Waits for the process to end and returns its result. */
|
|
680
|
-
async wait(options = {}) {
|
|
681
|
-
const out = { stdout: "", stderr: "" };
|
|
682
|
-
let exit;
|
|
683
|
-
let dropped = false;
|
|
684
|
-
for await (const event of this.output(options)) {
|
|
685
|
-
if (event.type === "stdout" || event.type === "stderr")
|
|
686
|
-
out[event.type] += event.data;
|
|
687
|
-
if (event.type === "truncated")
|
|
688
|
-
dropped = true;
|
|
689
|
-
if (event.type === "exit")
|
|
690
|
-
exit = event;
|
|
691
|
-
}
|
|
692
|
-
if (exit)
|
|
693
|
-
this.info = {
|
|
694
|
-
...this.info,
|
|
695
|
-
state: exit.state,
|
|
696
|
-
exitCode: exit.exitCode,
|
|
697
|
-
...(exit.outOfMemory ? { outOfMemory: exit.outOfMemory } : {}),
|
|
698
|
-
};
|
|
699
|
-
return {
|
|
700
|
-
exitCode: exit?.exitCode ?? null,
|
|
701
|
-
...out,
|
|
702
|
-
timedOut: exit?.timedOut ?? false,
|
|
703
|
-
...truncation(dropped),
|
|
704
|
-
processId: this.id,
|
|
705
|
-
...(exit?.outOfMemory ? { outOfMemory: exit.outOfMemory } : {}),
|
|
706
|
-
};
|
|
707
|
-
}
|
|
708
|
-
/** Sends input. Offsets protect transport retries; signal and timeoutMs cover
|
|
709
|
-
* the whole logical write, including its queue and backpressure. */
|
|
710
|
-
write(data, options = {}) {
|
|
711
|
-
if (options.idempotencyKey !== undefined)
|
|
712
|
-
return Promise.reject(new RuntimeError({
|
|
713
|
-
message: "Process input writes do not accept caller idempotency keys; offsets protect transport retries.",
|
|
714
|
-
code: "unsupported_process_write_option",
|
|
715
|
-
status: 400,
|
|
716
|
-
}));
|
|
717
|
-
// Copy before queuing: callers may reuse their buffer while a previous
|
|
718
|
-
// write waits for the guest to drain its pipe.
|
|
719
|
-
const bytes = new Uint8Array(utf8(data));
|
|
720
|
-
const eof = options.eof === true;
|
|
721
|
-
const { eof: _eof, ...requestOptions } = options;
|
|
722
|
-
const scope = requestScope(requestOptions);
|
|
723
|
-
const write = this.#inputWrites.then(async () => {
|
|
724
|
-
let sent = 0;
|
|
725
|
-
let chunkSize = CHUNK;
|
|
726
|
-
do {
|
|
727
|
-
scope.check();
|
|
728
|
-
const chunk = bytes.subarray(sent, sent + chunkSize);
|
|
729
|
-
const reply = await this.t.json({
|
|
730
|
-
method: "POST",
|
|
731
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes/${enc(this.id)}:write`,
|
|
732
|
-
body: {
|
|
733
|
-
base64: base64(chunk),
|
|
734
|
-
offset: this.#inputOffset,
|
|
735
|
-
...(eof && sent + chunk.length === bytes.length ? { eof: true } : {}),
|
|
736
|
-
},
|
|
737
|
-
...scope.request,
|
|
738
|
-
});
|
|
739
|
-
const accepted = reply.offset - this.#inputOffset;
|
|
740
|
-
if (!Number.isSafeInteger(reply.offset) || accepted < 0 || accepted > chunk.length)
|
|
741
|
-
throw new ConnectionError({
|
|
742
|
-
message: "The process returned an invalid input offset.",
|
|
743
|
-
code: "connection_error",
|
|
744
|
-
status: 0,
|
|
745
|
-
});
|
|
746
|
-
sent += accepted;
|
|
747
|
-
this.#inputOffset = reply.offset;
|
|
748
|
-
// A slow pipe may take only part of a chunk. Keep later uploads within
|
|
749
|
-
// that observed capacity instead of resending almost a MiB each time.
|
|
750
|
-
// Zero is legitimate backpressure: retry a bounded probe at the same
|
|
751
|
-
// offset without discarding bytes or inventing progress.
|
|
752
|
-
if (accepted < chunk.length) {
|
|
753
|
-
chunkSize = accepted > 0 ? accepted : Math.min(chunkSize, 65_536);
|
|
754
|
-
// A full pipe must yield even if a proxy answers immediately; don't
|
|
755
|
-
// spin requests while the guest has accepted none of this input.
|
|
756
|
-
if (accepted === 0)
|
|
757
|
-
await scope.wait(new Promise((resolve) => setTimeout(resolve, 100)));
|
|
758
|
-
}
|
|
759
|
-
} while (sent < bytes.length);
|
|
760
|
-
});
|
|
761
|
-
this.#inputWrites = write.catch(() => undefined);
|
|
762
|
-
return scope.wait(write);
|
|
763
|
-
}
|
|
764
|
-
async kill(signal = "SIGTERM", options = {}) {
|
|
765
|
-
await this.t.json({
|
|
766
|
-
method: "POST",
|
|
767
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes/${enc(this.id)}:signal`,
|
|
768
|
-
body: { signal },
|
|
769
|
-
...options,
|
|
770
|
-
});
|
|
771
|
-
}
|
|
772
|
-
async resize(cols, rows, options = {}) {
|
|
773
|
-
await this.t.json({
|
|
774
|
-
method: "POST",
|
|
775
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes/${enc(this.id)}:resize`,
|
|
776
|
-
body: { cols, rows },
|
|
777
|
-
...options,
|
|
778
|
-
});
|
|
779
|
-
}
|
|
780
|
-
/** What a process spawned with `traceFiles` opened and wrote. Known once it
|
|
781
|
-
* has ended: a running one answers 409 process_running. */
|
|
782
|
-
files() {
|
|
783
|
-
return this.t.json({
|
|
784
|
-
method: "GET",
|
|
785
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes/${enc(this.id)}/files`,
|
|
786
|
-
});
|
|
787
|
-
}
|
|
788
|
-
async refresh() {
|
|
789
|
-
this.info = await this.t.json({
|
|
790
|
-
method: "GET",
|
|
791
|
-
path: `/v1/sandboxes/${enc(this.sandboxId)}/processes/${enc(this.id)}`,
|
|
792
|
-
});
|
|
793
|
-
return this.info;
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
export class Terminal {
|
|
797
|
-
socket;
|
|
798
|
-
exited;
|
|
799
|
-
#processId;
|
|
800
|
-
constructor(socket, exited) {
|
|
801
|
-
this.socket = socket;
|
|
802
|
-
this.exited = exited;
|
|
803
|
-
}
|
|
804
|
-
get processId() {
|
|
805
|
-
return this.#processId;
|
|
806
|
-
}
|
|
807
|
-
static open(socket, onData) {
|
|
808
|
-
socket.binaryType = "arraybuffer";
|
|
809
|
-
let settle;
|
|
810
|
-
const exited = new Promise((resolve) => (settle = resolve));
|
|
811
|
-
let exitCode = null;
|
|
812
|
-
return new Promise((resolve, reject) => {
|
|
813
|
-
let terminal;
|
|
814
|
-
socket.onmessage = (event) => {
|
|
815
|
-
if (typeof event.data === "string") {
|
|
816
|
-
const message = JSON.parse(event.data);
|
|
817
|
-
if (message.type === "ready") {
|
|
818
|
-
terminal = new Terminal(socket, exited);
|
|
819
|
-
terminal.#processId = message.processId;
|
|
820
|
-
resolve(terminal);
|
|
821
|
-
}
|
|
822
|
-
else if (message.type === "exit")
|
|
823
|
-
exitCode = message.exitCode ?? null;
|
|
824
|
-
else if (message.type === "error" && !terminal)
|
|
825
|
-
reject(new RuntimeError({
|
|
826
|
-
message: message.error?.message ?? "Terminal failed.",
|
|
827
|
-
code: message.error?.code ?? "terminal_failed",
|
|
828
|
-
status: 0,
|
|
829
|
-
}));
|
|
830
|
-
}
|
|
831
|
-
else
|
|
832
|
-
onData?.(new Uint8Array(event.data));
|
|
833
|
-
};
|
|
834
|
-
socket.onclose = () => {
|
|
835
|
-
settle(exitCode);
|
|
836
|
-
if (!terminal)
|
|
837
|
-
reject(new RuntimeError({
|
|
838
|
-
message: "The terminal could not be opened (check the key and that the sandbox is running).",
|
|
839
|
-
code: "terminal_refused",
|
|
840
|
-
status: 0,
|
|
841
|
-
}));
|
|
842
|
-
};
|
|
843
|
-
socket.onerror = () => undefined;
|
|
844
|
-
});
|
|
845
|
-
}
|
|
846
|
-
write(data) {
|
|
847
|
-
// A view of shared memory is refused by WebSocket.send: the bytes it
|
|
848
|
-
// takes are an ArrayBuffer's, which TypeScript 7's DOM types ask for.
|
|
849
|
-
this.socket.send(typeof data === "string" ? new TextEncoder().encode(data) : data);
|
|
850
|
-
}
|
|
851
|
-
resize(cols, rows) {
|
|
852
|
-
this.socket.send(JSON.stringify({ type: "resize", cols, rows }));
|
|
853
|
-
}
|
|
854
|
-
close() {
|
|
855
|
-
this.socket.close(1000);
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
/** Files in the sandbox. Paths are absolute; any path the sandbox user may use. */
|
|
859
|
-
export class Files {
|
|
860
|
-
t;
|
|
861
|
-
sandboxId;
|
|
862
|
-
constructor(t, sandboxId) {
|
|
863
|
-
this.t = t;
|
|
864
|
-
this.sandboxId = sandboxId;
|
|
865
|
-
}
|
|
866
|
-
#path = (suffix) => `/v1/sandboxes/${enc(this.sandboxId)}${suffix}`;
|
|
867
|
-
/** Watch a directory: `onEvent` gets create, write, remove, rename and
|
|
868
|
-
* chmod events until `handle.stop()`. E2B's `watchDir`, plus filters,
|
|
869
|
-
* batches, and a watch that loses nothing across a pause:
|
|
870
|
-
*
|
|
871
|
-
* const watch = await sbx.files.watch("/workspace", (e) => console.log(e.type, e.path),
|
|
872
|
-
* { recursive: true, exclude: ["node_modules"] });
|
|
873
|
-
* ...
|
|
874
|
-
* await watch.stop();
|
|
875
|
-
*/
|
|
876
|
-
watch(path, onEvent, options) {
|
|
877
|
-
return watchDirectory(this.t, this.sandboxId, path, onEvent, options);
|
|
878
|
-
}
|
|
879
|
-
/** The watches running in the sandbox, and polling reads by cursor. */
|
|
880
|
-
get watches() {
|
|
881
|
-
return sandboxWatches(this.t, this.sandboxId);
|
|
882
|
-
}
|
|
883
|
-
/** A file's bytes, any size, checked against the length (and for a small
|
|
884
|
-
* file the SHA-256) the API sends first: a read that arrives short is read
|
|
885
|
-
* again, then throws `download_incomplete`, never returns short. For a file
|
|
886
|
-
* too big to hold in memory use `readStream` or `download`. */
|
|
887
|
-
async read(path, options = {}) {
|
|
888
|
-
return this.t.fileBytes({
|
|
889
|
-
method: "GET",
|
|
890
|
-
path: this.#path("/files/content"),
|
|
891
|
-
query: { path },
|
|
892
|
-
accept: "application/octet-stream",
|
|
893
|
-
...options,
|
|
894
|
-
});
|
|
895
|
-
}
|
|
896
|
-
/** A file's bytes as they arrive, for files of any size without holding
|
|
897
|
-
* them in memory (Daytona's `downloadFileStream`). The stream errors with
|
|
898
|
-
* `download_incomplete` if it ends short of the file's length.
|
|
899
|
-
*
|
|
900
|
-
* const stream = await sbx.files.readStream("/workspace/big.tar");
|
|
901
|
-
* await stream.pipeTo(Writable.toWeb(fs.createWriteStream("big.tar")));
|
|
902
|
-
*/
|
|
903
|
-
async readStream(path, options = {}) {
|
|
904
|
-
return this.t.fileStream({
|
|
905
|
-
method: "GET",
|
|
906
|
-
path: this.#path("/files/content"),
|
|
907
|
-
query: { path },
|
|
908
|
-
accept: "application/octet-stream",
|
|
909
|
-
...options,
|
|
910
|
-
});
|
|
911
|
-
}
|
|
912
|
-
async readText(path, options = {}) {
|
|
913
|
-
return new TextDecoder().decode(await this.read(path, options));
|
|
914
|
-
}
|
|
915
|
-
/** Writes a file, atomically, making parent directories. Under /workspace
|
|
916
|
-
* any size, large ones in parallel 1 MiB chunks checked against their
|
|
917
|
-
* SHA-256; elsewhere, with the sandbox user's rights, up to 1 MiB. `mode`
|
|
918
|
-
* sets its permissions (0o755 for a program); 0o644 when left out. */
|
|
919
|
-
async write(path, data, writeOptions = {}) {
|
|
920
|
-
const { mode, ...options } = writeOptions;
|
|
921
|
-
const scope = requestScope(options);
|
|
922
|
-
scope.check();
|
|
923
|
-
const octal = mode === undefined ? undefined : (mode & 0o777).toString(8).padStart(3, "0");
|
|
924
|
-
const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
925
|
-
if (bytes.length <= CHUNK) {
|
|
926
|
-
// bytes(), not send(): the answer is read, so its connection is free
|
|
927
|
-
// for the next call rather than held until garbage collection.
|
|
928
|
-
await this.t.bytes({
|
|
929
|
-
method: "PUT",
|
|
930
|
-
path: this.#path("/files/content"),
|
|
931
|
-
query: { path, ...(octal ? { mode: octal } : {}) },
|
|
932
|
-
bytes,
|
|
933
|
-
...scope.request,
|
|
934
|
-
});
|
|
935
|
-
return { path, size: bytes.length };
|
|
936
|
-
}
|
|
937
|
-
const sha256 = await scope.wait(sha256Hex(bytes));
|
|
938
|
-
return this.#writeUpload(path, {
|
|
939
|
-
size: bytes.length,
|
|
940
|
-
sha256,
|
|
941
|
-
chunkAt: (offset, length) => bytes.subarray(offset, offset + length),
|
|
942
|
-
}, octal, scope);
|
|
943
|
-
}
|
|
944
|
-
/** Uploads byte streams with bounded memory on Node/Bun. Unknown-length
|
|
945
|
-
* inputs stage once in a private local temporary file; known local files
|
|
946
|
-
* and Blobs avoid that extra disk copy. Paths are local file paths. */
|
|
947
|
-
async writeStream(path, input, writeOptions = {}) {
|
|
948
|
-
const { mode, onProgress, ...options } = writeOptions;
|
|
949
|
-
if (input instanceof Uint8Array) {
|
|
950
|
-
const result = await this.write(path, input, {
|
|
951
|
-
...options,
|
|
952
|
-
...(mode === undefined ? {} : { mode }),
|
|
953
|
-
});
|
|
954
|
-
onProgress?.({ bytesSent: result.size });
|
|
955
|
-
return result;
|
|
956
|
-
}
|
|
957
|
-
const scope = requestScope(options);
|
|
958
|
-
scope.check();
|
|
959
|
-
if (!globalThis.process
|
|
960
|
-
?.versions?.node)
|
|
961
|
-
throw new RuntimeError({
|
|
962
|
-
message: "Streamed file uploads require Node or Bun for incremental hashing and private local staging. Use files.write with byte data in a browser.",
|
|
963
|
-
code: "unsupported_runtime",
|
|
964
|
-
status: 0,
|
|
965
|
-
});
|
|
966
|
-
const { prepareFileSource } = await import("./file-source.js");
|
|
967
|
-
const source = await prepareFileSource(input, { ...scope, signal: scope.request.signal });
|
|
968
|
-
let written;
|
|
969
|
-
try {
|
|
970
|
-
if (source.size <= CHUNK) {
|
|
971
|
-
written = await this.write(path, await scope.wait(source.chunkAt(0, source.size)), {
|
|
972
|
-
...scope.request,
|
|
973
|
-
...(mode === undefined ? {} : { mode }),
|
|
974
|
-
});
|
|
975
|
-
onProgress?.({ bytesSent: written.size });
|
|
976
|
-
}
|
|
977
|
-
else {
|
|
978
|
-
const octal = mode === undefined ? undefined : (mode & 0o777).toString(8).padStart(3, "0");
|
|
979
|
-
written = await this.#writeUpload(path, source, octal, scope, onProgress);
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
catch (primary) {
|
|
983
|
-
try {
|
|
984
|
-
await source.close();
|
|
985
|
-
}
|
|
986
|
-
catch (cleanupError) {
|
|
987
|
-
if (primary === undefined)
|
|
988
|
-
throw cleanupError;
|
|
989
|
-
if (primary instanceof Error && Object.isExtensible(primary)) {
|
|
990
|
-
try {
|
|
991
|
-
Object.defineProperty(primary, "cleanupError", {
|
|
992
|
-
value: cleanupError,
|
|
993
|
-
configurable: true,
|
|
994
|
-
});
|
|
995
|
-
}
|
|
996
|
-
catch {
|
|
997
|
-
/* Keep the original upload failure. */
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
throw primary;
|
|
1002
|
-
}
|
|
1003
|
-
// A failed close after a good upload is the call's failure.
|
|
1004
|
-
await source.close();
|
|
1005
|
-
return written;
|
|
1006
|
-
}
|
|
1007
|
-
/** One implementation of atomic, checked chunk uploads for bytes and streams. */
|
|
1008
|
-
async #writeUpload(path, source, octal, scope, onProgress) {
|
|
1009
|
-
const sha256 = source.sha256;
|
|
1010
|
-
// A guest journals mutations across operations, not per URL. One logical
|
|
1011
|
-
// write therefore owns separate stable keys for each mutation phase.
|
|
1012
|
-
const uploadKey = scope.request.idempotencyKey ?? crypto.randomUUID();
|
|
1013
|
-
const phaseKeys = new Map();
|
|
1014
|
-
for (const phase of ["begin", "legacy-begin", "commit", "chmod", "abort"])
|
|
1015
|
-
phaseKeys.set(phase, await sha256Hex(JSON.stringify(["files.write", uploadKey, phase])));
|
|
1016
|
-
const phaseOptions = (phase) => ({
|
|
1017
|
-
...scope.request,
|
|
1018
|
-
idempotencyKey: phaseKeys.get(phase),
|
|
1019
|
-
});
|
|
1020
|
-
let begin;
|
|
1021
|
-
scope.check();
|
|
1022
|
-
try {
|
|
1023
|
-
begin = await this.t.json({
|
|
1024
|
-
method: "POST",
|
|
1025
|
-
path: this.#path("/uploads"),
|
|
1026
|
-
body: { path, size: source.size, sha256, ...(octal ? { mode: octal } : {}) },
|
|
1027
|
-
...phaseOptions("begin"),
|
|
1028
|
-
});
|
|
1029
|
-
}
|
|
1030
|
-
catch (error) {
|
|
1031
|
-
if (!octal || !(error instanceof RuntimeError) || error.code !== "guest_upgrade_required")
|
|
1032
|
-
throw error;
|
|
1033
|
-
// The API aborted the unsupported transfer before accepting chunks.
|
|
1034
|
-
// A different body needs a different key; retain deterministic retries.
|
|
1035
|
-
scope.check();
|
|
1036
|
-
begin = await this.t.json({
|
|
1037
|
-
method: "POST",
|
|
1038
|
-
path: this.#path("/uploads"),
|
|
1039
|
-
body: { path, size: source.size, sha256 },
|
|
1040
|
-
...phaseOptions("legacy-begin"),
|
|
1041
|
-
});
|
|
1042
|
-
}
|
|
1043
|
-
// A malformed response does not prove ownership of any transfer to abort.
|
|
1044
|
-
if (typeof begin.uploadId !== "string" || begin.uploadId.length === 0)
|
|
1045
|
-
throw new ConnectionError({
|
|
1046
|
-
message: "The file upload returned no transfer identifier.",
|
|
1047
|
-
code: "connection_error",
|
|
1048
|
-
status: 0,
|
|
1049
|
-
});
|
|
1050
|
-
const commit = () => {
|
|
1051
|
-
scope.check();
|
|
1052
|
-
return this.t.json({
|
|
1053
|
-
method: "POST",
|
|
1054
|
-
path: this.#path(`/uploads/${enc(begin.uploadId)}:commit`),
|
|
1055
|
-
body: {},
|
|
1056
|
-
...phaseOptions("commit"),
|
|
1057
|
-
});
|
|
1058
|
-
};
|
|
1059
|
-
let committed = false;
|
|
1060
|
-
let nextOffset = 0;
|
|
1061
|
-
const stopChunks = new AbortController();
|
|
1062
|
-
const chunkSignal = scope.request.signal
|
|
1063
|
-
? AbortSignal.any([scope.request.signal, stopChunks.signal])
|
|
1064
|
-
: stopChunks.signal;
|
|
1065
|
-
const chunkScope = requestScope({ ...scope.request, signal: chunkSignal });
|
|
1066
|
-
let bytesSent = 0;
|
|
1067
|
-
let failed = false;
|
|
1068
|
-
let primaryFailure;
|
|
1069
|
-
const worker = async () => {
|
|
1070
|
-
try {
|
|
1071
|
-
while (nextOffset < source.size) {
|
|
1072
|
-
scope.check();
|
|
1073
|
-
if (stopChunks.signal.aborted)
|
|
1074
|
-
return;
|
|
1075
|
-
const offset = nextOffset;
|
|
1076
|
-
nextOffset += begin.chunkBytes;
|
|
1077
|
-
const offered = source.chunkAt(offset, Math.min(begin.chunkBytes, source.size - offset));
|
|
1078
|
-
const chunk = offered instanceof Promise ? await chunkScope.wait(offered) : offered;
|
|
1079
|
-
chunkScope.check();
|
|
1080
|
-
if (chunk.length !== Math.min(begin.chunkBytes, source.size - offset))
|
|
1081
|
-
throw new ConnectionError({
|
|
1082
|
-
message: "The local upload source returned an incomplete chunk.",
|
|
1083
|
-
code: "source_changed",
|
|
1084
|
-
status: 0,
|
|
1085
|
-
});
|
|
1086
|
-
const receipt = await this.t.json({
|
|
1087
|
-
method: "PUT",
|
|
1088
|
-
path: this.#path(`/uploads/${enc(begin.uploadId)}`),
|
|
1089
|
-
query: { offset },
|
|
1090
|
-
bytes: chunk,
|
|
1091
|
-
...scope.request,
|
|
1092
|
-
signal: chunkSignal,
|
|
1093
|
-
// Offsets and byte hashes make chunk replay safe without mutation keys.
|
|
1094
|
-
idempotencyKey: undefined,
|
|
1095
|
-
});
|
|
1096
|
-
// Parallel receipts report cumulative accepted bytes, not this offset.
|
|
1097
|
-
if (!Number.isSafeInteger(receipt.received) ||
|
|
1098
|
-
receipt.received < chunk.length ||
|
|
1099
|
-
receipt.received > source.size)
|
|
1100
|
-
throw new ConnectionError({
|
|
1101
|
-
message: "The file upload returned invalid byte progress.",
|
|
1102
|
-
code: "connection_error",
|
|
1103
|
-
status: 0,
|
|
1104
|
-
});
|
|
1105
|
-
bytesSent += chunk.length;
|
|
1106
|
-
onProgress?.({ bytesSent });
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
catch (error) {
|
|
1110
|
-
if (!failed) {
|
|
1111
|
-
failed = true;
|
|
1112
|
-
primaryFailure = error;
|
|
1113
|
-
stopChunks.abort(error);
|
|
1114
|
-
}
|
|
1115
|
-
throw error;
|
|
1116
|
-
}
|
|
1117
|
-
};
|
|
1118
|
-
try {
|
|
1119
|
-
if (!Number.isSafeInteger(begin.chunkBytes) ||
|
|
1120
|
-
begin.chunkBytes <= 0 ||
|
|
1121
|
-
begin.chunkBytes > CHUNK)
|
|
1122
|
-
throw new ConnectionError({
|
|
1123
|
-
message: "The file upload returned an invalid chunk size.",
|
|
1124
|
-
code: "connection_error",
|
|
1125
|
-
status: 0,
|
|
1126
|
-
});
|
|
1127
|
-
if (begin.replayed) {
|
|
1128
|
-
// A completed commit removed the transfer. Ask its journal before
|
|
1129
|
-
// resending chunks; an incomplete transfer alone is safe to continue.
|
|
1130
|
-
try {
|
|
1131
|
-
await commit();
|
|
1132
|
-
committed = true;
|
|
1133
|
-
onProgress?.({ bytesSent: source.size });
|
|
1134
|
-
}
|
|
1135
|
-
catch (error) {
|
|
1136
|
-
if (!(error instanceof RuntimeError) || error.code !== "upload_incomplete")
|
|
1137
|
-
throw error;
|
|
1138
|
-
}
|
|
1139
|
-
}
|
|
1140
|
-
if (!committed) {
|
|
1141
|
-
const workers = Array.from({ length: Math.min(PARALLEL, Math.ceil(source.size / begin.chunkBytes)) }, worker);
|
|
1142
|
-
// Drain every owned in-flight chunk before aborting its transfer.
|
|
1143
|
-
// Promise.all's early rejection could otherwise leave writes racing cleanup.
|
|
1144
|
-
await Promise.allSettled(workers);
|
|
1145
|
-
if (failed)
|
|
1146
|
-
throw primaryFailure;
|
|
1147
|
-
await commit();
|
|
1148
|
-
}
|
|
1149
|
-
// An older sandbox image ignores the mode in the upload; set it after.
|
|
1150
|
-
if (octal && begin.mode !== octal) {
|
|
1151
|
-
scope.check();
|
|
1152
|
-
await this.t.json({
|
|
1153
|
-
method: "POST",
|
|
1154
|
-
path: this.#path("/files:chmod"),
|
|
1155
|
-
body: { path, mode: octal },
|
|
1156
|
-
...phaseOptions("chmod"),
|
|
1157
|
-
});
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
catch (error) {
|
|
1161
|
-
try {
|
|
1162
|
-
await this.t.json({
|
|
1163
|
-
method: "POST",
|
|
1164
|
-
path: this.#path(`/uploads/${enc(begin.uploadId)}:abort`),
|
|
1165
|
-
body: {},
|
|
1166
|
-
idempotencyKey: phaseKeys.get("abort"),
|
|
1167
|
-
timeoutMs: 5000,
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1170
|
-
catch (cleanupError) {
|
|
1171
|
-
// Keep the original failure; retain cleanup evidence when possible.
|
|
1172
|
-
if (error instanceof Error && Object.isExtensible(error)) {
|
|
1173
|
-
try {
|
|
1174
|
-
Object.defineProperty(error, error.cause === undefined ? "cause" : "cleanupError", {
|
|
1175
|
-
value: cleanupError,
|
|
1176
|
-
configurable: true,
|
|
1177
|
-
});
|
|
1178
|
-
}
|
|
1179
|
-
catch {
|
|
1180
|
-
/* A frozen property cannot replace the primary failure. */
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
throw error;
|
|
1185
|
-
}
|
|
1186
|
-
return { path, size: source.size };
|
|
1187
|
-
}
|
|
1188
|
-
/** Directory entries; `depth` goes deeper, `glob` filters (e.g. "**\/*.py"). */
|
|
1189
|
-
async list(path = "/workspace", options = {}) {
|
|
1190
|
-
const { signal, timeoutMs, idempotencyKey, ...query } = options;
|
|
1191
|
-
return (await this.t.json({
|
|
1192
|
-
method: "GET",
|
|
1193
|
-
path: this.#path("/files/list"),
|
|
1194
|
-
query: { path, ...query },
|
|
1195
|
-
signal,
|
|
1196
|
-
timeoutMs,
|
|
1197
|
-
idempotencyKey,
|
|
1198
|
-
})).data;
|
|
1199
|
-
}
|
|
1200
|
-
async glob(pattern, root = "/workspace") {
|
|
1201
|
-
return this.list(root, { glob: pattern });
|
|
1202
|
-
}
|
|
1203
|
-
async stat(path, options = {}) {
|
|
1204
|
-
return this.t.json({
|
|
1205
|
-
method: "GET",
|
|
1206
|
-
path: this.#path("/files/stat"),
|
|
1207
|
-
query: { path },
|
|
1208
|
-
...options,
|
|
1209
|
-
});
|
|
1210
|
-
}
|
|
1211
|
-
async exists(path, options = {}) {
|
|
1212
|
-
return (await this.stat(path, options)).exists;
|
|
1213
|
-
}
|
|
1214
|
-
async mkdir(path, options = {}) {
|
|
1215
|
-
const { parents, ...request } = options;
|
|
1216
|
-
await this.t.json({
|
|
1217
|
-
method: "POST",
|
|
1218
|
-
path: this.#path("/files:mkdir"),
|
|
1219
|
-
body: { path, parents },
|
|
1220
|
-
...request,
|
|
1221
|
-
});
|
|
1222
|
-
}
|
|
1223
|
-
async remove(path, options = {}) {
|
|
1224
|
-
const { recursive, ...request } = options;
|
|
1225
|
-
return (await this.t.json({
|
|
1226
|
-
method: "POST",
|
|
1227
|
-
path: this.#path("/files:remove"),
|
|
1228
|
-
body: { path, recursive },
|
|
1229
|
-
...request,
|
|
1230
|
-
})).removed;
|
|
1231
|
-
}
|
|
1232
|
-
async rename(from, to, options = {}) {
|
|
1233
|
-
const { overwrite, ...request } = options;
|
|
1234
|
-
await this.t.json({
|
|
1235
|
-
method: "POST",
|
|
1236
|
-
path: this.#path("/files:rename"),
|
|
1237
|
-
body: {
|
|
1238
|
-
from,
|
|
1239
|
-
to,
|
|
1240
|
-
...(overwrite === undefined ? {} : { overwrite }),
|
|
1241
|
-
},
|
|
1242
|
-
...request,
|
|
1243
|
-
});
|
|
1244
|
-
}
|
|
1245
|
-
/** A link anyone can open with no API key to download this file, for a
|
|
1246
|
-
* browser or another service: Range works, so videos play and downloads
|
|
1247
|
-
* resume. One hour by default, at most 7 days (`expiresInSeconds`).
|
|
1248
|
-
* `filename` makes it a download with that name; `archive: true` links a
|
|
1249
|
-
* folder as a .tar.gz. Revoking the key that made it ends it, as does
|
|
1250
|
-
* `revokeLinks()`. */
|
|
1251
|
-
async downloadUrl(path, options = {}) {
|
|
1252
|
-
const { expiresInSeconds, filename, wake, archive, ...request } = options;
|
|
1253
|
-
return this.t.json({
|
|
1254
|
-
method: "POST",
|
|
1255
|
-
path: this.#path("/files:link"),
|
|
1256
|
-
body: { path, method: "GET", expiresInSeconds, filename, wake, archive },
|
|
1257
|
-
...request,
|
|
1258
|
-
});
|
|
1259
|
-
}
|
|
1260
|
-
/** A link anyone can PUT a file's bytes to, with no API key: the body
|
|
1261
|
-
* becomes the file at `path`, whole or not at all, up to `maxBytes` (5 GiB
|
|
1262
|
-
* at most; the body must arrive within 5 minutes). */
|
|
1263
|
-
async uploadUrl(path, options = {}) {
|
|
1264
|
-
const { expiresInSeconds, maxBytes, wake, ...request } = options;
|
|
1265
|
-
return this.t.json({
|
|
1266
|
-
method: "POST",
|
|
1267
|
-
path: this.#path("/files:link"),
|
|
1268
|
-
body: { path, method: "PUT", expiresInSeconds, maxBytes, wake },
|
|
1269
|
-
...request,
|
|
1270
|
-
});
|
|
1271
|
-
}
|
|
1272
|
-
/** Ends every link made for this sandbox so far; links made after work. */
|
|
1273
|
-
async revokeLinks(options = {}) {
|
|
1274
|
-
return this.t.json({ method: "POST", path: this.#path("/files:revoke-links"), ...options });
|
|
1275
|
-
}
|
|
1276
|
-
/** Packs a directory as archive bytes; `gzip: false` returns plain tar.
|
|
1277
|
-
* Exclusions are relative paths, not globs. `user: root` selects guest root. */
|
|
1278
|
-
async archive(path, options = {}) {
|
|
1279
|
-
const { gzip = true, exclude, user, ...request } = options;
|
|
1280
|
-
return this.t.fileBytes({
|
|
1281
|
-
method: "GET",
|
|
1282
|
-
path: this.#path("/files/archive"),
|
|
1283
|
-
query: { path, gzip, ...(exclude ? { exclude } : {}), ...(user ? { user } : {}) },
|
|
1284
|
-
accept: gzip ? "application/gzip" : "application/x-tar",
|
|
1285
|
-
...request,
|
|
1286
|
-
});
|
|
1287
|
-
}
|
|
1288
|
-
/** Unpacks archive bytes in a directory with the sandbox user's rights by
|
|
1289
|
-
* default; `user: root` explicitly selects root inside this guest. */
|
|
1290
|
-
async unarchive(path, bytes, options = {}) {
|
|
1291
|
-
const { gzip = bytes[0] === 0x1f && bytes[1] === 0x8b, user, ...request } = options;
|
|
1292
|
-
const scope = requestScope(request);
|
|
1293
|
-
scope.check();
|
|
1294
|
-
if (bytes.length <= CHUNK) {
|
|
1295
|
-
await this.t.bytes({
|
|
1296
|
-
method: "PUT",
|
|
1297
|
-
path: this.#path("/files/archive"),
|
|
1298
|
-
query: { path, ...(user ? { user } : {}) },
|
|
1299
|
-
bytes,
|
|
1300
|
-
...scope.request,
|
|
1301
|
-
});
|
|
1302
|
-
return;
|
|
1303
|
-
}
|
|
1304
|
-
const key = request.idempotencyKey ?? crypto.randomUUID();
|
|
1305
|
-
const phase = async (name) => ({
|
|
1306
|
-
...scope.request,
|
|
1307
|
-
idempotencyKey: await sha256Hex(JSON.stringify(["files.unarchive", key, name])),
|
|
1308
|
-
});
|
|
1309
|
-
const begin = await this.t.json({
|
|
1310
|
-
method: "POST",
|
|
1311
|
-
path: this.#path("/files/archive/uploads"),
|
|
1312
|
-
body: { path, gzip, ...(user ? { user } : {}) },
|
|
1313
|
-
...(await phase("begin")),
|
|
1314
|
-
});
|
|
1315
|
-
const upload = (suffix = "") => this.#path(`/files/archive/uploads/${enc(begin.uploadId)}${suffix}`);
|
|
1316
|
-
try {
|
|
1317
|
-
if (!Number.isSafeInteger(begin.chunkBytes) || begin.chunkBytes <= 0)
|
|
1318
|
-
throw new ConnectionError({
|
|
1319
|
-
message: "The archive upload returned an invalid chunk size.",
|
|
1320
|
-
code: "connection_error",
|
|
1321
|
-
status: 0,
|
|
1322
|
-
});
|
|
1323
|
-
for (let offset = 0; offset < bytes.length; offset += begin.chunkBytes) {
|
|
1324
|
-
scope.check();
|
|
1325
|
-
await this.t.bytes({
|
|
1326
|
-
method: "PUT",
|
|
1327
|
-
path: upload(),
|
|
1328
|
-
query: { offset },
|
|
1329
|
-
bytes: bytes.subarray(offset, offset + begin.chunkBytes),
|
|
1330
|
-
...(await phase(`chunk:${offset}`)),
|
|
1331
|
-
});
|
|
1332
|
-
}
|
|
1333
|
-
scope.check();
|
|
1334
|
-
await this.t.json({
|
|
1335
|
-
method: "POST",
|
|
1336
|
-
path: upload(":commit"),
|
|
1337
|
-
body: {},
|
|
1338
|
-
...(await phase("commit")),
|
|
1339
|
-
});
|
|
1340
|
-
}
|
|
1341
|
-
catch (error) {
|
|
1342
|
-
// Cleanup must still run when the caller's signal/deadline has expired.
|
|
1343
|
-
const idempotencyKey = await sha256Hex(JSON.stringify(["files.unarchive", key, "abort"]));
|
|
1344
|
-
await this.t
|
|
1345
|
-
.json({ method: "POST", path: upload(":abort"), body: {}, idempotencyKey })
|
|
1346
|
-
.catch(() => undefined);
|
|
1347
|
-
throw error;
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
|
-
/** Copies a local file or directory into the sandbox. A directory travels as
|
|
1351
|
-
* one gzipped tar to the API's folder routes, and the sandbox's own `tar`
|
|
1352
|
-
* unpacks it as it arrives, making the folder. */
|
|
1353
|
-
async upload(localPath, remotePath) {
|
|
1354
|
-
const { stat, readFile } = await import("node:fs/promises");
|
|
1355
|
-
const info = await stat(localPath);
|
|
1356
|
-
if (info.isFile()) {
|
|
1357
|
-
// Its permissions travel with it: an uploaded script stays runnable.
|
|
1358
|
-
const data = await readFile(localPath);
|
|
1359
|
-
const mode = info.mode & 0o777;
|
|
1360
|
-
await this.write(remotePath, data, { mode }).catch(async (error) => {
|
|
1361
|
-
// Make a missing parent, but keep errors about the sandbox or upload.
|
|
1362
|
-
const parent = remotePath.slice(0, remotePath.lastIndexOf("/"));
|
|
1363
|
-
if (!(error instanceof NotFoundError) ||
|
|
1364
|
-
(error.code !== "file_not_found" && error.code !== "path_not_found") ||
|
|
1365
|
-
!parent)
|
|
1366
|
-
throw error;
|
|
1367
|
-
await this.mkdir(parent, { parents: true });
|
|
1368
|
-
await this.write(remotePath, data, { mode });
|
|
1369
|
-
});
|
|
1370
|
-
return;
|
|
1371
|
-
}
|
|
1372
|
-
const { packDirectory } = await import("./tar.js");
|
|
1373
|
-
const archive = await packDirectory(localPath);
|
|
1374
|
-
if (archive.length <= CHUNK) {
|
|
1375
|
-
await this.t.bytes({
|
|
1376
|
-
method: "PUT",
|
|
1377
|
-
path: this.#path("/files/archive"),
|
|
1378
|
-
query: { path: remotePath },
|
|
1379
|
-
bytes: archive,
|
|
1380
|
-
});
|
|
1381
|
-
return;
|
|
1382
|
-
}
|
|
1383
|
-
// Larger: parts in order, each unpacked as it arrives; a part resent
|
|
1384
|
-
// after a lost answer is not written twice.
|
|
1385
|
-
const begin = await this.t.json({
|
|
1386
|
-
method: "POST",
|
|
1387
|
-
path: this.#path("/files/archive/uploads"),
|
|
1388
|
-
body: { path: remotePath, gzip: true },
|
|
1389
|
-
});
|
|
1390
|
-
const upload = (suffix = "") => this.#path(`/files/archive/uploads/${enc(begin.uploadId)}${suffix}`);
|
|
1391
|
-
try {
|
|
1392
|
-
for (let offset = 0; offset < archive.length; offset += begin.chunkBytes)
|
|
1393
|
-
await this.t.bytes({
|
|
1394
|
-
method: "PUT",
|
|
1395
|
-
path: upload(),
|
|
1396
|
-
query: { offset },
|
|
1397
|
-
bytes: archive.subarray(offset, offset + begin.chunkBytes),
|
|
1398
|
-
});
|
|
1399
|
-
await this.t.json({ method: "POST", path: upload(":commit"), body: {} });
|
|
1400
|
-
}
|
|
1401
|
-
catch (error) {
|
|
1402
|
-
await this.t
|
|
1403
|
-
.json({ method: "POST", path: upload(":abort"), body: {} })
|
|
1404
|
-
.catch(() => undefined);
|
|
1405
|
-
throw error;
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
/** Streams a file to disk through a partial file beside the target, renamed
|
|
1409
|
-
* into place only once every byte has arrived: a failed copy never leaves
|
|
1410
|
-
* a short file under the name asked for. A short stream is tried again,
|
|
1411
|
-
* twice, as a short `read` is. */
|
|
1412
|
-
async #streamTo(remotePath, localPath, options = {}) {
|
|
1413
|
-
const scope = requestScope(options);
|
|
1414
|
-
const fs = await import("node:fs/promises");
|
|
1415
|
-
const partial = `${localPath}.runtime-partial-${crypto.randomUUID().slice(0, 8)}`;
|
|
1416
|
-
for (let attempt = 0;; attempt++) {
|
|
1417
|
-
try {
|
|
1418
|
-
scope.check();
|
|
1419
|
-
const stream = await this.readStream(remotePath, scope.request);
|
|
1420
|
-
// The handle is closed before anything else touches the file, so a
|
|
1421
|
-
// failed copy's partial file is really gone when the error returns.
|
|
1422
|
-
try {
|
|
1423
|
-
const file = await fs.open(partial, "w");
|
|
1424
|
-
try {
|
|
1425
|
-
for await (const chunk of stream) {
|
|
1426
|
-
let written = 0;
|
|
1427
|
-
while (written < chunk.length) {
|
|
1428
|
-
scope.check();
|
|
1429
|
-
const result = await file.write(chunk.subarray(written));
|
|
1430
|
-
if (result.bytesWritten === 0)
|
|
1431
|
-
throw new Error("The local file accepted no bytes.");
|
|
1432
|
-
written += result.bytesWritten;
|
|
1433
|
-
}
|
|
1434
|
-
}
|
|
1435
|
-
}
|
|
1436
|
-
finally {
|
|
1437
|
-
await file.close();
|
|
1438
|
-
}
|
|
1439
|
-
}
|
|
1440
|
-
finally {
|
|
1441
|
-
// Opening or writing the local file can fail before consumption.
|
|
1442
|
-
await stream.cancel().catch(() => undefined);
|
|
1443
|
-
}
|
|
1444
|
-
scope.check();
|
|
1445
|
-
await fs.rename(partial, localPath);
|
|
1446
|
-
return;
|
|
1447
|
-
}
|
|
1448
|
-
catch (error) {
|
|
1449
|
-
await fs.rm(partial, { force: true });
|
|
1450
|
-
if (attempt >= 2 ||
|
|
1451
|
-
!(error instanceof RuntimeError) ||
|
|
1452
|
-
error.code !== "download_incomplete")
|
|
1453
|
-
throw error;
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
|
-
}
|
|
1457
|
-
/** Copies a file or directory out of the sandbox. A file streams to disk,
|
|
1458
|
-
* any size, checked against its length; a directory comes as one tar from
|
|
1459
|
-
* the API's folder route. */
|
|
1460
|
-
async download(remotePath, localPath, options = {}) {
|
|
1461
|
-
const scope = requestScope(options);
|
|
1462
|
-
scope.check();
|
|
1463
|
-
const fs = await import("node:fs/promises");
|
|
1464
|
-
const paths = await import("node:path");
|
|
1465
|
-
const entry = await this.stat(remotePath, scope.request);
|
|
1466
|
-
if (!entry.exists)
|
|
1467
|
-
throw new RuntimeError({
|
|
1468
|
-
message: `${remotePath} does not exist.`,
|
|
1469
|
-
code: "file_not_found",
|
|
1470
|
-
status: 404,
|
|
1471
|
-
});
|
|
1472
|
-
if (entry.type !== "directory") {
|
|
1473
|
-
await fs.mkdir(paths.dirname(localPath), { recursive: true });
|
|
1474
|
-
await this.#streamTo(remotePath, localPath, scope.request);
|
|
1475
|
-
return;
|
|
1476
|
-
}
|
|
1477
|
-
// The sandbox's own `tar` packs it as it streams, and it is unpacked as
|
|
1478
|
-
// it arrives; one cut short is refused and nothing is put in place.
|
|
1479
|
-
const archive = await this.t.fileStream({
|
|
1480
|
-
method: "GET",
|
|
1481
|
-
path: this.#path("/files/archive"),
|
|
1482
|
-
query: { path: remotePath, gzip: true },
|
|
1483
|
-
accept: "application/gzip",
|
|
1484
|
-
...scope.request,
|
|
1485
|
-
});
|
|
1486
|
-
const { unpackStream } = await import("./tar.js");
|
|
1487
|
-
try {
|
|
1488
|
-
await unpackStream(archive, localPath, {
|
|
1489
|
-
signal: scope.request.signal,
|
|
1490
|
-
});
|
|
1491
|
-
}
|
|
1492
|
-
finally {
|
|
1493
|
-
await archive.cancel().catch(() => undefined);
|
|
1494
|
-
}
|
|
1495
|
-
}
|
|
1496
|
-
}
|
|
1497
|
-
/** One page of `runtime.sandboxes.list()`, and the pages after it. */
|
|
1498
|
-
export function sandboxPage(t, body, query, options = {}) {
|
|
1499
|
-
return machinePage(SANDBOXES, t, (transport, info) => new Sandbox(transport, info), body, query, options);
|
|
1500
|
-
}
|