ai-sdk-sandbox-gce 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # ai-sdk-sandbox-gce
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ff30489: The commands of a sandbox no longer get `NODE_USE_ENV_PROXY=1` by default. It sent Node.js's own `fetch` and `http` to the egress proxy, where a test suite that mocks `fetch` with MSW 3 no longer saw its requests: they reached the proxy, which refused them (`fetch failed`, `Failed to establish tunnel … 403`). Package managers, git, curl and the harnesses still leave through the proxy, as they read `HTTPS_PROXY` themselves. The agent sets the variables: build the sandbox image again on this version for the change to take effect.
8
+
9
+ BREAKING: Node.js code in a sandbox that calls an outside host with its own `fetch` or `http`, rather than through a base URL, and has no proxy support of its own, can no longer reach it. Set the variable again with `nodeUseEnvProxy: true` on the sandbox (at its creation and at each resume), or `SANDBOX_NODE_USE_ENV_PROXY=true` on the service for every sandbox; for one command, `NODE_USE_ENV_PROXY=1 <command>` or `node --use-env-proxy`.
10
+
11
+ ## 0.4.2
12
+
13
+ ### Patch Changes
14
+
15
+ - 8341bb9: `deleteGceSandboxTemplate()` deletes the template that sandboxes created with a given `template`, `setup` and `image` boot from. A template made for a `setup` of its own, one per project say, used to outlive that setup when it changed or went, its image billed for its storage until deleted by hand. The sandboxes made from it keep their disk; the next sandbox created from the same template builds it again, without first meeting a 404 in the process that deleted it. A template that does not exist is no error.
16
+ - c89c8ef: Sessions implement `stat`, `listDirectory` and `deleteFile`, which `SandboxSession` requires since `@ai-sdk/provider-utils` 5.0.81. `stat` follows symbolic links and answers `null` for a path that does not exist; `listDirectory` reports a link as `symlink` without following it, answers `null` for a missing directory and rejects with `ENOTDIR` for a file; `deleteFile` deletes a link rather than its target, answers `false` for a missing file and rejects with `EISDIR` for a directory.
17
+
3
18
  ## 0.4.1
4
19
 
5
20
  ### Patch Changes
package/README.md CHANGED
@@ -135,7 +135,7 @@ gcloud compute instances create sandbox-proxy --zone=$ZONE --machine-type=e2-sma
135
135
  #!/bin/sh
136
136
  set -e
137
137
  # The version of the proxy: the one your application depends on.
138
- VERSION=0.4.1
138
+ VERSION=0.5.0
139
139
  # Writes $2 to the file $1 when it differs, and says whether it did.
140
140
  changed() {
141
141
  mkdir -p "$(dirname "$1")"
@@ -282,7 +282,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
282
282
  > /etc/apt/sources.list.d/nodesource.list
283
283
  apt-get update
284
284
  apt-get install -y nodejs
285
- npm install --global ai-sdk-sandbox-gce@0.4.1 pnpm@10
285
+ npm install --global ai-sdk-sandbox-gce@0.5.0 pnpm@10
286
286
 
287
287
  # The sandbox's user: sudo without a password, and Docker.
288
288
  useradd --create-home --shell /bin/bash agent
@@ -310,7 +310,7 @@ The agent runs as root and starts the commands as `agent`, in its own service: `
310
310
 
311
311
  ### 4. The service
312
312
 
313
- The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.4.1 --owner fpasquet` checks; its [`Dockerfile`](https://github.com/fpasquet/ai-sdk-harness/blob/main/packages/sandbox-gce/Dockerfile) builds the same image from your own registry.
313
+ The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.5.0 --owner fpasquet` checks; its [`Dockerfile`](https://github.com/fpasquet/ai-sdk-harness/blob/main/packages/sandbox-gce/Dockerfile) builds the same image from your own registry.
314
314
 
315
315
  Its service account gets a role of its own, with what the service calls and nothing else, limited by a condition to the names it uses: the sandboxes' machines and disks (`sbx-`), the proxy's machine, the sandbox images and templates (`ai-sdk-`).
316
316
 
@@ -348,7 +348,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
348
348
  --member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
349
349
  done
350
350
 
351
- gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.4.1 \
351
+ gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.5.0 \
352
352
  --service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
353
353
  --network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
354
354
  --no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
@@ -468,6 +468,20 @@ A harness bootstraps itself in the sandbox before its first turn: Claude Code in
468
468
 
469
469
  The image is named after the template's id and a digest of this package's version and the base image, a family resolved to its latest image: `ai-sdk-harness-template-<digest>-<base>`. After a new sandbox image, or a new version of the package, the first sandbox makes the template again. Delete the old images (label `ai-sdk-sandbox=template`) now and then: each costs its storage.
470
470
 
471
+ A template whose sandboxes are made with a `setup` of their own, one per project say, outlives that setup when it changes or goes. Delete it then, with what the sandboxes were created with:
472
+
473
+ ```ts
474
+ import { deleteGceSandboxTemplate } from 'ai-sdk-sandbox-gce';
475
+
476
+ await deleteGceSandboxTemplate({
477
+ url: process.env.GCE_SANDBOX_URL!,
478
+ template: await agent.getSandboxTemplate(),
479
+ setup, // and `image`, when the sandboxes had one
480
+ });
481
+ ```
482
+
483
+ The sandboxes made from it keep their disk. The next sandbox created from the same template, setup and image builds it again. A template that does not exist is no error.
484
+
471
485
  A template is made from a sandbox no agent ever ran in: the client's throwaway one, where only `setup` and the harness's own installation run. Never save a sandbox an agent worked in as a template, through the API or otherwise: whatever the agent left on its disk, the `agent` service of the machine included, would start in every later sandbox.
472
486
 
473
487
  Making a template takes a few minutes: the machine boots, the harness installs, Compute Engine saves the disk, and the first sandbox on a new image waits a minute more while Compute Engine spreads it. Make it when you deploy, rather than in the first user's session, with a script that creates a sandbox from the agent's template and deletes it:
@@ -588,6 +602,18 @@ The machine has no external address, and the VPC firewall, applied outside the g
588
602
 
589
603
  Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.io`, `auth.docker.io`, `production.cloudflare.docker.com` and `production.cloudfront.docker.com` (Docker Hub serves layers from either), or [`ai-sdk-harness-network`](https://ai-sdk-harness.pages.dev/docs/packages/harness-network)'s presets.
590
604
 
605
+ ### Node.js and the proxy
606
+
607
+ Package managers, git, curl and the harnesses (Claude Code, Codex) read `HTTPS_PROXY` themselves. Node.js's own `fetch` and `http` only do with `NODE_USE_ENV_PROXY=1`, which the sandbox does not set by default: with it, a test suite that mocks `fetch` with [MSW](https://mswjs.io) 3 sees its requests leave for the proxy, which refuses them (`fetch failed`, `Failed to establish tunnel … 403`), MSW's `onUnhandledRequest` saying nothing. MSW 3 catches a request at its socket, and Node.js then opens that socket to the proxy, with a `CONNECT`, rather than to the host the suite mocks.
608
+
609
+ Without it, code that calls an outside host with Node.js's `fetch` and has no proxy support of its own cannot reach it. Turn it on where it is needed:
610
+
611
+ - for a sandbox: `nodeUseEnvProxy: true`, at its creation and at each resume;
612
+ - for every sandbox of the service: `SANDBOX_NODE_USE_ENV_PROXY=true`, which a sandbox's `nodeUseEnvProxy: false` turns off;
613
+ - for one command: `NODE_USE_ENV_PROXY=1 node script.mjs`, or `node --use-env-proxy script.mjs`. In a sandbox that sets it, `NODE_USE_ENV_PROXY= npm test` runs a test suite without it.
614
+
615
+ The MCP servers that [`ai-sdk-harness-plugins`](https://ai-sdk-harness.pages.dev/docs/packages/harness-plugins) runs in the sandbox get it on their own. The agent sets the variables: a sandbox image built on an earlier version of this package still gives every command `NODE_USE_ENV_PROXY=1`, until it is built again.
616
+
591
617
  ## Ports
592
618
 
593
619
  `ports` lists the ports inside the sandbox the harness may reach. `getPortEndpoint()` returns a WebSocket URL on the service, `wss://<service>/v1/sandboxes/<name>/ports/<port>`, with the identity token as a header, read anew at each connection. The service passes the connection on to the machine's agent, with the agent's token in place of the caller's, and the agent on to `127.0.0.1:<port>`. A port outside the list is refused with `HarnessCapabilityUnsupportedError`.
@@ -610,59 +636,61 @@ Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.
610
636
 
611
637
  `createGceNetworkSandboxSession(options)` takes every option below; `resumeGceNetworkSandboxSession(options)` takes `sandboxId`, `abortSignal` and the connection settings.
612
638
 
613
- | Option | Default | Description |
614
- | ------------------ | ----------------- | --------------------------------------------------------------------------------------------------- |
615
- | `url` | required | _Connection._ The URL of the sandbox service |
616
- | `auth` | `'gcloud'` | _Connection._ `'gcloud'`, `'metadata'`, `'none'`, or a function returning an identity token |
617
- | `ports` | `[]` | _Connection._ Ports the harness may reach, through the service |
618
- | `allowedHosts` | `[]` | _Connection._ Hosts the sandbox may reach over HTTPS, on top of the service's |
619
- | `baseUrls` | `{}` | _Connection._ Base URL variables routed through the proxy, on top of the service's |
620
- | `serviceToken` | none | _Connection._ The service's `SANDBOX_SERVICE_TOKEN`, when it has one |
621
- | `sandboxId` | `ai-sdk-<hex>` | The sandbox's name: lowercase letters, digits and dashes, 55 at most. Creation fails if it is taken |
622
- | `template` | none | `await agent.getSandboxTemplate()`: prepare once, boot every later sandbox from it |
623
- | `image` | `default` | The image the machine boots from, by the name the service gives it in `SANDBOX_IMAGES` |
624
- | `requiredCommands` | `['node', 'git']` | Commands the sandbox must have once `setup` ran |
625
- | `setup` | `[]` | Commands run once after creation, as the sandbox's user (who has `sudo`), saved in the template |
626
- | `abortSignal` | none | Aborts the creation or the resume |
639
+ | Option | Default | Description |
640
+ | ------------------ | ----------------- | --------------------------------------------------------------------------------------------------------------------- |
641
+ | `url` | required | _Connection._ The URL of the sandbox service |
642
+ | `auth` | `'gcloud'` | _Connection._ `'gcloud'`, `'metadata'`, `'none'`, or a function returning an identity token |
643
+ | `ports` | `[]` | _Connection._ Ports the harness may reach, through the service |
644
+ | `allowedHosts` | `[]` | _Connection._ Hosts the sandbox may reach over HTTPS, on top of the service's |
645
+ | `baseUrls` | `{}` | _Connection._ Base URL variables routed through the proxy, on top of the service's |
646
+ | `nodeUseEnvProxy` | the service's | _Connection._ `true` sets `NODE_USE_ENV_PROXY=1` for the commands: see [Node.js and the proxy](#nodejs-and-the-proxy) |
647
+ | `serviceToken` | none | _Connection._ The service's `SANDBOX_SERVICE_TOKEN`, when it has one |
648
+ | `sandboxId` | `ai-sdk-<hex>` | The sandbox's name: lowercase letters, digits and dashes, 55 at most. Creation fails if it is taken |
649
+ | `template` | none | `await agent.getSandboxTemplate()`: prepare once, boot every later sandbox from it |
650
+ | `image` | `default` | The image the machine boots from, by the name the service gives it in `SANDBOX_IMAGES` |
651
+ | `requiredCommands` | `['node', 'git']` | Commands the sandbox must have once `setup` ran |
652
+ | `setup` | `[]` | Commands run once after creation, as the sandbox's user (who has `sudo`), saved in the template |
653
+ | `abortSignal` | none | Aborts the creation or the resume |
627
654
 
628
655
  ## Configuration
629
656
 
630
657
  ### The service (`serve`)
631
658
 
632
- | Variable | Default | Description |
633
- | --------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
634
- | `SANDBOX_ZONE` | required | The zone of the machines |
635
- | `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…` |
636
- | `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python` |
637
- | `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager |
638
- | `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128` |
639
- | `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129` |
640
- | `SANDBOX_PROXY_TOKEN` | required | The proxy's token |
641
- | `SANDBOX_PROJECT` | the service's project | The project of the machines |
642
- | `SANDBOX_NETWORK` | the default network | The machines' VPC network |
643
- | `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>` |
644
- | `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to |
645
- | `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192` |
646
- | `SANDBOX_DISK_GB` | `20` | The size of their disk |
647
- | `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type |
648
- | `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after |
649
- | `SANDBOX_SPOT_FALLBACK` | `true` | With Spot, a machine the zone has no Spot capacity for is created or started as a standard one, billed as such; `false` fails instead |
650
- | `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most |
651
- | `SANDBOX_AGENT_PORT` | `8100` | The port of the agents |
652
- | `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer |
653
- | `SANDBOX_MAX_RUNNING` | none | The most sandboxes running at once: a creation or a resume beyond it is answered with a 429. Counted at each call, so two at the same instant may both pass |
654
- | `SANDBOX_MAX_RUN_HOURS` | none | The longest a machine runs at a time: Compute Engine stops it then (`maxRunDuration`), disk kept, whatever the service or the application do. 30 s at least |
655
- | `SANDBOX_PROXY_INSTANCE` | none | The egress proxy's machine, in the sandboxes' zone: started with the first sandbox that runs, stopped once none does and no prepared machine waits for one. Always on without it |
656
- | `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
657
- | `SANDBOX_WARM_POOL` | `0`, `1` with `fast` | How many machines are kept booted from each template used in the last 24 h, for the next creations from it to take at once. Each one is billed all the time |
658
- | `SANDBOX_PROXY_ALWAYS_ON` | `false`, `true` with `fast` | `true`: the service starts the proxy's machine of `SANDBOX_PROXY_INSTANCE` with the first sandbox, and never stops it. No sandbox waits for it to boot, and it is billed all the time |
659
- | `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup |
660
- | `SANDBOX_BASE_URLS` | `ANTHROPIC_BASE_URL=https://api.anthropic.com,OPENAI_BASE_URL=https://api.openai.com/v1` | Base URL variables routed through the proxy, as `NAME=url` pairs |
661
- | `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM |
662
- | `SANDBOX_INSECURE_NO_TOKEN` | `false` | `true` to run on Cloud Run without `SANDBOX_SERVICE_TOKEN`, its IAM the only lock |
663
- | `COMPUTE_AUTH` | `metadata` on Cloud Run, `gcloud` elsewhere | How the service gets its access tokens for the Compute Engine API |
664
- | `PORT`, `HOST` | `8080`, `0.0.0.0` on Cloud Run and `127.0.0.1` elsewhere | Where the service listens |
665
- | `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text |
659
+ | Variable | Default | Description |
660
+ | ---------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
661
+ | `SANDBOX_ZONE` | required | The zone of the machines |
662
+ | `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…` |
663
+ | `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python` |
664
+ | `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager |
665
+ | `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128` |
666
+ | `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129` |
667
+ | `SANDBOX_PROXY_TOKEN` | required | The proxy's token |
668
+ | `SANDBOX_PROJECT` | the service's project | The project of the machines |
669
+ | `SANDBOX_NETWORK` | the default network | The machines' VPC network |
670
+ | `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>` |
671
+ | `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to |
672
+ | `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192` |
673
+ | `SANDBOX_DISK_GB` | `20` | The size of their disk |
674
+ | `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type |
675
+ | `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after |
676
+ | `SANDBOX_SPOT_FALLBACK` | `true` | With Spot, a machine the zone has no Spot capacity for is created or started as a standard one, billed as such; `false` fails instead |
677
+ | `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most |
678
+ | `SANDBOX_AGENT_PORT` | `8100` | The port of the agents |
679
+ | `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer |
680
+ | `SANDBOX_MAX_RUNNING` | none | The most sandboxes running at once: a creation or a resume beyond it is answered with a 429. Counted at each call, so two at the same instant may both pass |
681
+ | `SANDBOX_MAX_RUN_HOURS` | none | The longest a machine runs at a time: Compute Engine stops it then (`maxRunDuration`), disk kept, whatever the service or the application do. 30 s at least |
682
+ | `SANDBOX_PROXY_INSTANCE` | none | The egress proxy's machine, in the sandboxes' zone: started with the first sandbox that runs, stopped once none does and no prepared machine waits for one. Always on without it |
683
+ | `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
684
+ | `SANDBOX_WARM_POOL` | `0`, `1` with `fast` | How many machines are kept booted from each template used in the last 24 h, for the next creations from it to take at once. Each one is billed all the time |
685
+ | `SANDBOX_PROXY_ALWAYS_ON` | `false`, `true` with `fast` | `true`: the service starts the proxy's machine of `SANDBOX_PROXY_INSTANCE` with the first sandbox, and never stops it. No sandbox waits for it to boot, and it is billed all the time |
686
+ | `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup |
687
+ | `SANDBOX_BASE_URLS` | `ANTHROPIC_BASE_URL=https://api.anthropic.com,OPENAI_BASE_URL=https://api.openai.com/v1` | Base URL variables routed through the proxy, as `NAME=url` pairs |
688
+ | `SANDBOX_NODE_USE_ENV_PROXY` | `false` | `true` sets `NODE_USE_ENV_PROXY=1` for the commands of every sandbox that does not say otherwise: see [Node.js and the proxy](#nodejs-and-the-proxy) |
689
+ | `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM |
690
+ | `SANDBOX_INSECURE_NO_TOKEN` | `false` | `true` to run on Cloud Run without `SANDBOX_SERVICE_TOKEN`, its IAM the only lock |
691
+ | `COMPUTE_AUTH` | `metadata` on Cloud Run, `gcloud` elsewhere | How the service gets its access tokens for the Compute Engine API |
692
+ | `PORT`, `HOST` | `8080`, `0.0.0.0` on Cloud Run and `127.0.0.1` elsewhere | Where the service listens |
693
+ | `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text |
666
694
 
667
695
  ### The proxy (`proxy`)
668
696
 
@@ -714,7 +742,7 @@ To keep the bill down: stop idle sandboxes early, delete finished ones, delete o
714
742
  - **Inside the VPC, traffic is plain HTTP**: the service's calls to the agents and to the proxy's administration API, real credentials included, and the sandboxes' requests to the base URL routes. Google Cloud encrypts traffic between its hosts and lets no machine listen to another's; nothing of the package adds TLS on top.
715
743
  - **The sandbox's user has `sudo`, and Docker**: inside the machine, the agent's code can do anything. The machine is the boundary, not the user. What the agent changes on the disk, the machine's own `agent` service included, survives a stop: never hand a sandbox to another user, and never save one an agent worked in as a template.
716
744
  - **An allowed host is a way out for data**: the allow list says where the sandbox's requests may go, not what they carry. An agent led astray by a prompt injection may push the sandbox's files to `github.com`, or publish them to a registry, with credentials of its own. Allow only the hosts a task needs; keep `*` and wildcards on shared domains (`*.googleapis.com`, `*.amazonaws.com`, `*.githubusercontent.com`, `*.cloudfront.net`) out of production, since anyone can own a bucket or a site under them. The service logs a warning when `SANDBOX_ALLOWED_HOSTS` holds `*`.
717
- - **A credential goes to every request its transformation matches**: the harnesses' own transformations match the placeholder the sandbox sends, so only a request carrying it gets the real value. A transformation of yours that names a host alone puts the credential in any request to that host. Cap the credential at the provider as well: a budget, the narrowest scope a token takes.
745
+ - **A credential goes to every request its transformation matches**: the harnesses' own transformations match the placeholder the sandbox sends, so only a request carrying it gets the real value. A transformation of yours that names a host alone puts the credential in any request to that host. An agent led astray can still use a credential, without ever reading it: cap it at the provider, a budget and the narrowest scope a token takes, as [Limiting what a credential can do](https://ai-sdk-harness.pages.dev/docs/securing-credentials#limiting-what-a-credential-can-do) shows.
718
746
  - **The proxy holds the credentials of every running sandbox**, in memory. Keep it a machine of its own, with nothing else on it, a service account that may only read its token and write logs, and its administration port open to the service alone.
719
747
  - **The service trusts its callers**: anyone granted `roles/run.invoker` can run commands in any sandbox. It has no notion of a user: your application decides which sandbox a user reaches. Name sandboxes after a random id, kept beside the user's session on the server, never after anything a user can guess or send. Never deploy it with `--allow-unauthenticated`; `SANDBOX_SERVICE_TOKEN` is the second lock, required on Cloud Run.
720
748
  - **A machine stopped outside the service keeps its credentials in the proxy for a while**: a Spot machine taken back, one stopped at `SANDBOX_MAX_RUN_HOURS` or from the console. The application stopping or deleting the sandbox makes the proxy forget them at once, and so does the proxy restarting. A new machine that gets the same address takes the place of the old one in the proxy, so it never reaches them. Stop idle sandboxes from the application even when their machine already stopped.
@@ -59,6 +59,16 @@ export interface GceConnectionSettings {
59
59
  * @defaultValue `{}`
60
60
  */
61
61
  baseUrls?: Readonly<Record<string, string>>;
62
+ /**
63
+ * Sets `NODE_USE_ENV_PROXY=1` for the sandbox's commands: Node.js's own `fetch` and `http` then
64
+ * leave through the egress proxy, as package managers, git and the harnesses already do. Off by
65
+ * default: it breaks the test suites that mock `fetch` by its sockets, such as MSW 3, whose
66
+ * requests then reach the proxy instead of their mocks. Turn it on for code that calls an outside
67
+ * API with Node.js's `fetch` and no proxy support of its own. A command can still set it itself.
68
+ *
69
+ * @defaultValue the service's `SANDBOX_NODE_USE_ENV_PROXY`, `false` by default
70
+ */
71
+ nodeUseEnvProxy?: boolean;
62
72
  }
63
73
  /** What a new sandbox is made of. */
64
74
  export interface GceCreationSettings extends GceConnectionSettings {
@@ -110,6 +120,26 @@ export interface GcePrepareSettings extends GceConnectionSettings {
110
120
  /** Aborts the call. */
111
121
  abortSignal?: AbortSignal;
112
122
  }
123
+ /** Options of `deleteGceSandboxTemplate()`: the template, as the sandboxes made from it were. */
124
+ export interface GceTemplateDeletionSettings extends GceConnectionSettings {
125
+ /** The template the sandboxes were created from, `await agent.getSandboxTemplate()`. */
126
+ template: HarnessV1SandboxTemplate;
127
+ /**
128
+ * The `setup` the sandboxes were created with: with the template, what names the template's
129
+ * image.
130
+ *
131
+ * @defaultValue `[]`
132
+ */
133
+ setup?: readonly string[];
134
+ /**
135
+ * The image the sandboxes were created on, by the name the service gives it in `SANDBOX_IMAGES`.
136
+ *
137
+ * @defaultValue the service's `SANDBOX_IMAGE`
138
+ */
139
+ image?: string;
140
+ /** Aborts the call. */
141
+ abortSignal?: AbortSignal;
142
+ }
113
143
  /** Options of `createGceNetworkSandboxSession()`. */
114
144
  export type GceNetworkSandboxSessionCreateOptions = HarnessV1SandboxSessionCreateOptions<GceCreationSettings>;
115
145
  /** Options of `resumeGceNetworkSandboxSession()`. */
@@ -1,4 +1,4 @@
1
- import type { GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings } from '../gce-settings.js';
1
+ import type { GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, GceTemplateDeletionSettings } from '../gce-settings.js';
2
2
  import { GceNetworkSandboxSession } from '../session/gce-network-sandbox-session.js';
3
3
  /**
4
4
  * Creates a sandbox, a [Compute Engine](https://cloud.google.com/compute) virtual machine of its
@@ -28,12 +28,22 @@ export declare function createGceNetworkSandboxSession(options: GceNetworkSandbo
28
28
  * nothing.
29
29
  */
30
30
  export declare function prepareGceSandboxService(options: GcePrepareSettings): Promise<void>;
31
+ /**
32
+ * Deletes the template that sandboxes created with `template`, `setup` and `image` boot from: the
33
+ * image the service saved of a prepared sandbox, billed for its storage until it goes. Call it once
34
+ * no sandbox is to be made from it any more, say when the setup it was made with changes.
35
+ *
36
+ * The sandboxes made from it keep their disk, and run, stop and resume as before. A sandbox created
37
+ * from the same template afterwards, by this process or another one, builds it again. Deleting a
38
+ * template that does not exist, or no longer does, is no error.
39
+ */
40
+ export declare function deleteGceSandboxTemplate(options: GceTemplateDeletionSettings): Promise<void>;
31
41
  /**
32
42
  * Reattaches to a sandbox made by {@link createGceNetworkSandboxSession}, from this process or
33
43
  * another one: a running sandbox as it is, a stopped one started again on its disk. Never creates
34
44
  * one: throws `GceSandboxNotFoundError` when no sandbox is named `sandboxId`.
35
45
  *
36
46
  * The service does not keep what a sandbox may reach across a suspension: pass the same `ports`,
37
- * `allowedHosts` and `baseUrls` the sandbox was created with.
47
+ * `allowedHosts`, `baseUrls` and `nodeUseEnvProxy` the sandbox was created with.
38
48
  */
39
49
  export declare function resumeGceNetworkSandboxSession(options: GceNetworkSandboxSessionResumeOptions): Promise<GceNetworkSandboxSession>;
@@ -5,7 +5,7 @@ import { identityToken } from '../transport/identity-token.js';
5
5
  import { SandboxServiceClient } from '../transport/sandbox-service-client.js';
6
6
  import { abortReason } from '../utils/abort.js';
7
7
  import { assertRequiredCommands, DEFAULT_REQUIRED_COMMANDS } from './required-commands.js';
8
- import { runSetup, templateId, withTemplate } from './sandbox-template.js';
8
+ import { forgetTemplate, runSetup, templateId, withTemplate, } from './sandbox-template.js';
9
9
  /**
10
10
  * What a Compute Engine instance name takes once the service's prefix is put before it, and a URL
11
11
  * path as it is: the instance name is at most 63 characters and never ends with a dash.
@@ -47,14 +47,14 @@ async function createFrom(client, name, { template, ...options }) {
47
47
  * both.
48
48
  */
49
49
  export async function createGceNetworkSandboxSession(options) {
50
- const { abortSignal, template, setup = [], allowedHosts, baseUrls, image } = options;
50
+ const { abortSignal, template, setup = [], allowedHosts, baseUrls, nodeUseEnvProxy, image, } = options;
51
51
  const requiredCommands = options.requiredCommands ?? DEFAULT_REQUIRED_COMMANDS;
52
52
  if (abortSignal?.aborted)
53
53
  throw abortReason(abortSignal);
54
54
  const name = options.sandboxId ?? `ai-sdk-${randomBytes(4).toString('hex')}`;
55
55
  assertSandboxName(name);
56
56
  const client = clientOf(options);
57
- const network = { allowedHosts, baseUrls };
57
+ const network = { allowedHosts, baseUrls, nodeUseEnvProxy };
58
58
  const create = (ready) => createFrom(client, name, { ...network, image, template: ready, abortSignal });
59
59
  const description = await (template
60
60
  ? withTemplate(client, { template, setup, network, image, requiredCommands, abortSignal }, create)
@@ -94,21 +94,44 @@ export async function prepareGceSandboxService(options) {
94
94
  abortSignal,
95
95
  });
96
96
  }
97
+ /**
98
+ * Deletes the template that sandboxes created with `template`, `setup` and `image` boot from: the
99
+ * image the service saved of a prepared sandbox, billed for its storage until it goes. Call it once
100
+ * no sandbox is to be made from it any more, say when the setup it was made with changes.
101
+ *
102
+ * The sandboxes made from it keep their disk, and run, stop and resume as before. A sandbox created
103
+ * from the same template afterwards, by this process or another one, builds it again. Deleting a
104
+ * template that does not exist, or no longer does, is no error.
105
+ */
106
+ export async function deleteGceSandboxTemplate(options) {
107
+ const { template, setup = [], image, abortSignal } = options;
108
+ if (abortSignal?.aborted)
109
+ throw abortReason(abortSignal);
110
+ const client = clientOf(options);
111
+ const source = { template, setup, image };
112
+ forgetTemplate(client, source);
113
+ await client.deleteTemplate(templateId(source), image, abortSignal);
114
+ }
97
115
  /**
98
116
  * Reattaches to a sandbox made by {@link createGceNetworkSandboxSession}, from this process or
99
117
  * another one: a running sandbox as it is, a stopped one started again on its disk. Never creates
100
118
  * one: throws `GceSandboxNotFoundError` when no sandbox is named `sandboxId`.
101
119
  *
102
120
  * The service does not keep what a sandbox may reach across a suspension: pass the same `ports`,
103
- * `allowedHosts` and `baseUrls` the sandbox was created with.
121
+ * `allowedHosts`, `baseUrls` and `nodeUseEnvProxy` the sandbox was created with.
104
122
  */
105
123
  export async function resumeGceNetworkSandboxSession(options) {
106
- const { abortSignal, sandboxId, allowedHosts, baseUrls } = options;
124
+ const { abortSignal, sandboxId, allowedHosts, baseUrls, nodeUseEnvProxy } = options;
107
125
  if (abortSignal?.aborted)
108
126
  throw abortReason(abortSignal);
109
127
  assertSandboxName(sandboxId);
110
128
  const client = clientOf(options);
111
- const description = await client.resume(sandboxId, { allowedHosts, baseUrls, abortSignal });
129
+ const description = await client.resume(sandboxId, {
130
+ allowedHosts,
131
+ baseUrls,
132
+ nodeUseEnvProxy,
133
+ abortSignal,
134
+ });
112
135
  if (description === undefined)
113
136
  throw new GceSandboxNotFoundError(sandboxId);
114
137
  return sessionOf(client, description, options);
@@ -41,6 +41,13 @@ export declare function runSetup(session: GceNetworkSandboxSession, setup: reado
41
41
  * already installed.
42
42
  */
43
43
  export declare function ensureTemplate(client: SandboxServiceClient, source: BuildSettings & TemplateSource, abortSignal?: AbortSignal): Promise<ReadyTemplate>;
44
+ /**
45
+ * Forgets the template of `source` on this service, built or being built: the next sandbox from it
46
+ * asks the service whether it exists, rather than create from it and meet a 404 first.
47
+ */
48
+ export declare function forgetTemplate(client: SandboxServiceClient, source: TemplateSource & {
49
+ image?: string;
50
+ }): void;
44
51
  /**
45
52
  * Calls `create` with the template ready. This process remembers a template for as long as it runs,
46
53
  * and the service can lose it meanwhile, to a new version or a new base image: on
@@ -58,6 +58,13 @@ export function ensureTemplate(client, source, abortSignal) {
58
58
  }
59
59
  return ready;
60
60
  }
61
+ /**
62
+ * Forgets the template of `source` on this service, built or being built: the next sandbox from it
63
+ * asks the service whether it exists, rather than create from it and meet a 404 first.
64
+ */
65
+ export function forgetTemplate(client, source) {
66
+ building.delete(keyOf(client, source));
67
+ }
61
68
  /**
62
69
  * Calls `create` with the template ready. This process remembers a template for as long as it runs,
63
70
  * and the service can lose it meanwhile, to a new version or a new base image: on
@@ -0,0 +1,23 @@
1
+ /** Information about a path, symbolic links followed: what `stat` of a session resolves to. */
2
+ export interface FileStat {
3
+ type: 'directory' | 'file' | 'other';
4
+ /** Size in bytes; for a directory, what the sandbox's filesystem says. */
5
+ size: number;
6
+ }
7
+ /** One entry of a directory: what `listDirectory` of a session resolves to. */
8
+ export interface DirectoryEntry {
9
+ name: string;
10
+ /** A symbolic link is reported as such, not followed. */
11
+ type: 'directory' | 'file' | 'other' | 'symlink';
12
+ }
13
+ /** The output of the `STAT` script, `<type> <size>`, as a {@link FileStat}. */
14
+ export declare function parseStat(stdout: Uint8Array): FileStat;
15
+ /** The output of the `LIST` script, `<type> <name>` records each ended by a NUL, as entries. */
16
+ export declare function parseEntries(stdout: Uint8Array): DirectoryEntry[];
17
+ declare const MESSAGES: {
18
+ EISDIR: string;
19
+ ENOTDIR: string;
20
+ };
21
+ /** The error Node.js's `fs` throws for `code`, on the operation `syscall` of `path`. */
22
+ export declare function fileError(code: keyof typeof MESSAGES, syscall: string, path: string): Error;
23
+ export {};
@@ -0,0 +1,24 @@
1
+ /** The output of the `STAT` script, `<type> <size>`, as a {@link FileStat}. */
2
+ export function parseStat(stdout) {
3
+ const [type = 'other', size = '0'] = Buffer.from(stdout).toString().trim().split(/\s+/);
4
+ return { type: type, size: Number(size) || 0 };
5
+ }
6
+ /** The output of the `LIST` script, `<type> <name>` records each ended by a NUL, as entries. */
7
+ export function parseEntries(stdout) {
8
+ return Buffer.from(stdout)
9
+ .toString()
10
+ .split('\0')
11
+ .filter((record) => record !== '')
12
+ .map((record) => {
13
+ const space = record.indexOf(' ');
14
+ return {
15
+ type: record.slice(0, space),
16
+ name: record.slice(space + 1),
17
+ };
18
+ });
19
+ }
20
+ const MESSAGES = { EISDIR: 'illegal operation on a directory', ENOTDIR: 'not a directory' };
21
+ /** The error Node.js's `fs` throws for `code`, on the operation `syscall` of `path`. */
22
+ export function fileError(code, syscall, path) {
23
+ return Object.assign(new Error(`${code}: ${MESSAGES[code]}, ${syscall} '${path}'`), { code });
24
+ }
@@ -1,5 +1,6 @@
1
1
  import type { Experimental_SandboxSession as SandboxSession, Experimental_SandboxSpawnOptions as SpawnOptions } from '@ai-sdk/provider-utils';
2
2
  import type { SandboxServiceClient } from '../transport/sandbox-service-client.js';
3
+ import type { DirectoryEntry, FileStat } from './file-info.js';
3
4
  type ReadOptions = Parameters<SandboxSession['readFile']>[0];
4
5
  type ReadTextOptions = Parameters<SandboxSession['readTextFile']>[0];
5
6
  type WriteOptions = Parameters<SandboxSession['writeFile']>[0];
@@ -36,6 +37,9 @@ export declare class GceSandboxSession implements SandboxSession {
36
37
  writeBinaryFile: ({ path, content, abortSignal }: WriteBinaryOptions) => Promise<void>;
37
38
  writeFile: ({ content, ...options }: WriteOptions) => Promise<void>;
38
39
  writeTextFile: ({ content, encoding, ...options }: WriteTextOptions) => Promise<void>;
40
+ stat: ({ path, abortSignal }: ReadOptions) => Promise<FileStat | null>;
41
+ listDirectory: ({ path, abortSignal }: ReadOptions) => Promise<DirectoryEntry[] | null>;
42
+ deleteFile: ({ path, abortSignal }: ReadOptions) => Promise<boolean>;
39
43
  /** Stops every process this session started and that may still run. */
40
44
  protected killAll(): Promise<void>;
41
45
  /** The process `id`, its output read from `response` as it comes. */
@@ -1,6 +1,7 @@
1
1
  import { posix } from 'node:path';
2
2
  import { FrameType, readFrames, STDERR, STDOUT } from '../../protocol/frames.js';
3
3
  import { abortReason } from '../utils/abort.js';
4
+ import { fileError, parseEntries, parseStat } from './file-info.js';
4
5
  import { processInput } from './process-input.js';
5
6
  const READ_MISSING = 44;
6
7
  const READ_DIRECTORY = 45;
@@ -8,6 +9,31 @@ const READ_DIRECTORY = 45;
8
9
  const READ = `[ -d "$0" ] && exit ${READ_DIRECTORY}; [ -e "$0" ] || exit ${READ_MISSING}; exec cat -- "$0"`;
9
10
  /** Writes stdin to the file `$0`, creating its parent directories. */
10
11
  const WRITE = 'mkdir -p "$(dirname "$0")" && cat > "$0"';
12
+ /** Exit status of {@link LIST} for a path that is not a directory. */
13
+ const NOT_DIRECTORY = 46;
14
+ /**
15
+ * The type of the path `$0`, symbolic links followed, then its size in bytes: `file 12`. Exits
16
+ * {@link READ_MISSING} for a path that does not exist.
17
+ */
18
+ const STAT = `[ -e "$0" ] || exit ${READ_MISSING}; ` +
19
+ 'if [ -d "$0" ]; then t=directory; elif [ -f "$0" ]; then t=file; else t=other; fi; ' +
20
+ 's=$(stat -L -c %s -- "$0" 2>/dev/null || wc -c < "$0" 2>/dev/null || echo 0); echo "$t" $s';
21
+ /**
22
+ * Every entry of the directory `$0` as `<type> <name>`, each ended by a NUL: a name may hold any
23
+ * other byte. Symbolic links are reported as such, not followed. Exits {@link READ_MISSING} for a
24
+ * path that does not exist and {@link NOT_DIRECTORY} for one that is not a directory.
25
+ */
26
+ const LIST = `[ -d "$0" ] || { [ -e "$0" ] && exit ${NOT_DIRECTORY}; exit ${READ_MISSING}; }; cd -- "$0" || exit 1; ` +
27
+ 'for f in * .[!.]* ..?*; do ' +
28
+ 'if [ -L "$f" ]; then t=symlink; elif [ -d "$f" ]; then t=directory; elif [ -f "$f" ]; then t=file; ' +
29
+ 'elif [ -e "$f" ]; then t=other; else continue; fi; ' +
30
+ 'printf \'%s %s\\0\' "$t" "$f"; done';
31
+ /**
32
+ * Deletes the file `$0`, a symbolic link itself rather than its target. Exits {@link READ_MISSING}
33
+ * for a path that does not exist and {@link READ_DIRECTORY} for a directory.
34
+ */
35
+ const DELETE = `if [ -L "$0" ]; then :; elif [ -d "$0" ]; then exit ${READ_DIRECTORY}; elif [ ! -e "$0" ]; then exit ${READ_MISSING}; fi; ` +
36
+ 'exec rm -f -- "$0"';
11
37
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
12
38
  /** `sh -c BODY ARG`, the argument quoted, never spliced into the body. */
13
39
  const script = (body, arg) => `sh -c '${body.replace(/'/g, `'\\''`)}' '${arg.replace(/'/g, `'\\''`)}'`;
@@ -104,11 +130,8 @@ export class GceSandboxSession {
104
130
  const { exitCode, stdout, stderr } = await this.exec(script(READ, target), { abortSignal });
105
131
  if (exitCode === READ_MISSING)
106
132
  return null;
107
- if (exitCode === READ_DIRECTORY) {
108
- throw Object.assign(new Error(`EISDIR: illegal operation on a directory, read '${target}'`), {
109
- code: 'EISDIR',
110
- });
111
- }
133
+ if (exitCode === READ_DIRECTORY)
134
+ throw fileError('EISDIR', 'read', target);
112
135
  if (exitCode !== 0)
113
136
  throw new Error(`Could not read ${target} in the sandbox: ${stderr.trim()}`);
114
137
  return stdout;
@@ -146,6 +169,37 @@ export class GceSandboxSession {
146
169
  ...options,
147
170
  content: new Uint8Array(Buffer.from(content, encoding)),
148
171
  });
172
+ stat = async ({ path, abortSignal }) => {
173
+ const target = this.resolve(path);
174
+ const { exitCode, stdout, stderr } = await this.exec(script(STAT, target), { abortSignal });
175
+ if (exitCode === READ_MISSING)
176
+ return null;
177
+ if (exitCode !== 0)
178
+ throw new Error(`Could not stat ${target} in the sandbox: ${stderr.trim()}`);
179
+ return parseStat(stdout);
180
+ };
181
+ listDirectory = async ({ path, abortSignal }) => {
182
+ const target = this.resolve(path);
183
+ const { exitCode, stdout, stderr } = await this.exec(script(LIST, target), { abortSignal });
184
+ if (exitCode === READ_MISSING)
185
+ return null;
186
+ if (exitCode === NOT_DIRECTORY)
187
+ throw fileError('ENOTDIR', 'scandir', target);
188
+ if (exitCode !== 0)
189
+ throw new Error(`Could not list ${target} in the sandbox: ${stderr.trim()}`);
190
+ return parseEntries(stdout);
191
+ };
192
+ deleteFile = async ({ path, abortSignal }) => {
193
+ const target = this.resolve(path);
194
+ const { exitCode, stderr } = await this.exec(script(DELETE, target), { abortSignal });
195
+ if (exitCode === READ_MISSING)
196
+ return false;
197
+ if (exitCode === READ_DIRECTORY)
198
+ throw fileError('EISDIR', 'unlink', target);
199
+ if (exitCode !== 0)
200
+ throw new Error(`Could not delete ${target} in the sandbox: ${stderr.trim()}`);
201
+ return true;
202
+ };
149
203
  /** Stops every process this session started and that may still run. */
150
204
  async killAll() {
151
205
  const { client, name, processes } = this.handle;
@@ -84,7 +84,8 @@ export declare class SandboxServiceClient {
84
84
  image?: string;
85
85
  abortSignal?: AbortSignal;
86
86
  }): Promise<void>;
87
- deleteTemplate(id: string, image?: string): Promise<void>;
87
+ /** Deletes the template `id` made on `image`: no error when there is none. */
88
+ deleteTemplate(id: string, image?: string, abortSignal?: AbortSignal): Promise<void>;
88
89
  /**
89
90
  * Where a port of the sandbox is reached: a WebSocket through the service. The token is read
90
91
  * anew each time the harness connects: a bridge connection outlives a token.
@@ -177,8 +177,9 @@ export class SandboxServiceClient {
177
177
  accept: [404],
178
178
  });
179
179
  }
180
- async deleteTemplate(id, image) {
181
- await this.call('DELETE', templatePath(id, image));
180
+ /** Deletes the template `id` made on `image`: no error when there is none. */
181
+ async deleteTemplate(id, image, abortSignal) {
182
+ await this.call('DELETE', templatePath(id, image), { abortSignal });
182
183
  }
183
184
  /**
184
185
  * Where a port of the sandbox is reached: a WebSocket through the service. The token is read
@@ -1,7 +1,7 @@
1
1
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { readCommandLine } from '../common/command-line.js';
4
- import { offsetOf, parseObject, readBytes, readJson, requiredString, stringRecord, } from '../common/http-body.js';
4
+ import { offsetOf, optionalBoolean, parseObject, readBytes, readJson, requiredString, stringRecord, } from '../common/http-body.js';
5
5
  import { HttpError } from '../common/http-error.js';
6
6
  import { NO_CONTENT, waitForExit } from '../common/http-reply.js';
7
7
  import { MAX_INPUT_WRITE_BYTES } from '../protocol/api.js';
@@ -19,7 +19,12 @@ function toConfig(body) {
19
19
  const proxy = requiredString(body, 'proxy');
20
20
  if (!URL.canParse(proxy))
21
21
  throw new HttpError(400, '`proxy` must be a URL.');
22
- return { proxy, baseUrls: stringRecord(body, 'baseUrls') ?? {} };
22
+ const nodeUseEnvProxy = optionalBoolean(body, 'nodeUseEnvProxy');
23
+ return {
24
+ proxy,
25
+ baseUrls: stringRecord(body, 'baseUrls') ?? {},
26
+ ...(nodeUseEnvProxy !== undefined && { nodeUseEnvProxy }),
27
+ };
23
28
  }
24
29
  /**
25
30
  * What the agent does for the service (`protocol/agent.ts`): run commands as the sandbox's user,
@@ -17,5 +17,9 @@ export declare function noProxy(config: AgentConfig): string;
17
17
  * base URL variable is routed too: a harness that points its client at the real API still goes
18
18
  * through the proxy. Before the service configured the agent, commands get no proxy: the firewall
19
19
  * leaves them no way out.
20
+ *
21
+ * `NODE_USE_ENV_PROXY` only when the sandbox asks for it: it sends Node.js's own `fetch` and `http`
22
+ * to the proxy, where a test suite that mocks them by their sockets (MSW 3) no longer sees its
23
+ * requests.
20
24
  */
21
25
  export declare function commandEnvironment(settings: CommandSettings, config: AgentConfig | undefined, env?: Readonly<Record<string, string>>): Record<string, string>;
@@ -18,6 +18,10 @@ export function noProxy(config) {
18
18
  * base URL variable is routed too: a harness that points its client at the real API still goes
19
19
  * through the proxy. Before the service configured the agent, commands get no proxy: the firewall
20
20
  * leaves them no way out.
21
+ *
22
+ * `NODE_USE_ENV_PROXY` only when the sandbox asks for it: it sends Node.js's own `fetch` and `http`
23
+ * to the proxy, where a test suite that mocks them by their sockets (MSW 3) no longer sees its
24
+ * requests.
21
25
  */
22
26
  export function commandEnvironment(settings, config, env = {}) {
23
27
  const variables = {
@@ -33,15 +37,16 @@ export function commandEnvironment(settings, config, env = {}) {
33
37
  const route = (url) => proxyRoute(url, origin) ?? url;
34
38
  const excluded = noProxy(config);
35
39
  Object.assign(variables, {
36
- // Everything else leaves through the proxy: package managers, git and Node.js read these.
40
+ // Everything else leaves through the proxy: package managers, git and the harnesses read these.
37
41
  HTTPS_PROXY: origin,
38
42
  HTTP_PROXY: origin,
39
43
  https_proxy: origin,
40
44
  http_proxy: origin,
41
45
  NO_PROXY: excluded,
42
46
  no_proxy: excluded,
43
- NODE_USE_ENV_PROXY: '1',
44
47
  });
48
+ if (config.nodeUseEnvProxy === true)
49
+ variables['NODE_USE_ENV_PROXY'] = '1';
45
50
  for (const [name, url] of Object.entries(config.baseUrls))
46
51
  variables[name] = route(url);
47
52
  for (const [name, value] of Object.entries(env)) {
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  export { GceSandboxImageError } from './client/errors/gce-sandbox-image-error.js';
2
2
  export { GceSandboxNotFoundError } from './client/errors/gce-sandbox-not-found-error.js';
3
3
  export { GceSandboxServiceError } from './client/errors/gce-sandbox-service-error.js';
4
- export type { GceAuth, GceConnectionSettings, GceCreationSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, } from './client/gce-settings.js';
5
- export { createGceNetworkSandboxSession, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
4
+ export type { GceAuth, GceConnectionSettings, GceCreationSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, GceTemplateDeletionSettings, } from './client/gce-settings.js';
5
+ export { createGceNetworkSandboxSession, deleteGceSandboxTemplate, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
6
6
  export { GCE_SANDBOX_PROVIDER_ID } from './client/provider-id.js';
7
7
  export { GceNetworkSandboxSession } from './client/session/gce-network-sandbox-session.js';
8
8
  export { GceSandboxSession } from './client/session/gce-sandbox-session.js';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { GceSandboxImageError } from './client/errors/gce-sandbox-image-error.js';
2
2
  export { GceSandboxNotFoundError } from './client/errors/gce-sandbox-not-found-error.js';
3
3
  export { GceSandboxServiceError } from './client/errors/gce-sandbox-service-error.js';
4
- export { createGceNetworkSandboxSession, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
4
+ export { createGceNetworkSandboxSession, deleteGceSandboxTemplate, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
5
5
  export { GCE_SANDBOX_PROVIDER_ID } from './client/provider-id.js';
6
6
  export { GceNetworkSandboxSession } from './client/session/gce-network-sandbox-session.js';
7
7
  export { GceSandboxSession } from './client/session/gce-sandbox-session.js';
@@ -30,6 +30,11 @@ export interface AgentConfig {
30
30
  proxy: string;
31
31
  /** Base URL variables, routed through the proxy, and where each really leads. */
32
32
  baseUrls: Readonly<Record<string, string>>;
33
+ /**
34
+ * Whether the commands get `NODE_USE_ENV_PROXY=1`, which sends Node.js's own `fetch` and `http`
35
+ * through the proxy. Off without it.
36
+ */
37
+ nodeUseEnvProxy?: boolean;
33
38
  }
34
39
  /** Where a sandbox's commands run: the agent's answer to its configuration. */
35
40
  export interface AgentDescription {
@@ -12,6 +12,8 @@ export interface SandboxDescription {
12
12
  export interface SandboxNetwork {
13
13
  allowedHosts?: readonly string[];
14
14
  baseUrls?: Readonly<Record<string, string>>;
15
+ /** Sets `NODE_USE_ENV_PROXY=1` for the sandbox's commands: the service's setting without it. */
16
+ nodeUseEnvProxy?: boolean;
15
17
  }
16
18
  /** One command to run in a sandbox. */
17
19
  export interface SandboxCommand {
@@ -219,6 +219,7 @@ export async function sandboxesConfig(env, logger) {
219
219
  network: {
220
220
  allowedHosts: allowedHosts(env, logger),
221
221
  baseUrls: baseUrls(env['SANDBOX_BASE_URLS']),
222
+ nodeUseEnvProxy: flag('SANDBOX_NODE_USE_ENV_PROXY', env['SANDBOX_NODE_USE_ENV_PROXY'], false),
222
223
  },
223
224
  startTimeoutMs: Number.parseInt(env['SANDBOX_START_TIMEOUT'] ?? '300', 10) * 1000,
224
225
  maxRunning: maxRunning(env['SANDBOX_MAX_RUNNING']),
@@ -1,4 +1,4 @@
1
- import { offsetOf, optionalString, readBytes, readJson, requiredString, stringList, stringRecord, transformationList, } from '../../common/http-body.js';
1
+ import { offsetOf, optionalBoolean, optionalString, readBytes, readJson, requiredString, stringList, stringRecord, transformationList, } from '../../common/http-body.js';
2
2
  import { NO_CONTENT } from '../../common/http-reply.js';
3
3
  import { PACKAGE_VERSION } from '../../common/package-version.js';
4
4
  import { MAX_INPUT_WRITE_BYTES } from '../../protocol/api.js';
@@ -9,6 +9,7 @@ const network = async (request) => {
9
9
  return {
10
10
  allowedHosts: stringList(body, 'allowedHosts'),
11
11
  baseUrls: stringRecord(body, 'baseUrls'),
12
+ nodeUseEnvProxy: optionalBoolean(body, 'nodeUseEnvProxy'),
12
13
  template: optionalString(body, 'template'),
13
14
  image: optionalString(body, 'image'),
14
15
  name: optionalString(body, 'name'),
@@ -55,8 +55,11 @@ export interface SandboxesOptions {
55
55
  };
56
56
  /** The egress proxy, as the machines reach it: `http://10.0.0.2:3128`. */
57
57
  proxyUrl: string;
58
- /** What every sandbox may reach, before what the caller adds. */
59
- network: Required<SandboxNetwork>;
58
+ /**
59
+ * What every sandbox may reach, before what the caller adds; whether its commands get
60
+ * `NODE_USE_ENV_PROXY`, when the caller does not say.
61
+ */
62
+ network: Pick<SandboxNetwork, 'nodeUseEnvProxy'> & Required<Omit<SandboxNetwork, 'nodeUseEnvProxy'>>;
60
63
  /** How long a machine has to boot and its agent to answer. */
61
64
  startTimeoutMs: number;
62
65
  /**
@@ -801,6 +801,7 @@ export class Sandboxes {
801
801
  const { home, workingDirectory } = await agent.configure({
802
802
  proxy: this.options.proxyUrl,
803
803
  baseUrls,
804
+ nodeUseEnvProxy: network.nodeUseEnvProxy ?? this.options.network.nodeUseEnvProxy,
804
805
  });
805
806
  return { name, home, workingDirectory };
806
807
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-sdk-sandbox-gce",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Compute Engine sandboxes for AI SDK harness agents: Claude Code, Codex and friends in a virtual machine of their own on Google Cloud, Docker included, stopped between turns.",
5
5
  "keywords": [
6
6
  "ai",
@@ -50,16 +50,16 @@
50
50
  "@ai-sdk/provider-utils": "^5.0.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@ai-sdk/harness": "^1.0.168",
54
- "@ai-sdk/provider-utils": "^5.0.71",
53
+ "@ai-sdk/harness": "^1.0.183",
54
+ "@ai-sdk/provider-utils": "^5.0.81",
55
55
  "@types/node": "^24.19.2",
56
- "@vitest/coverage-v8": "^5.0.5",
56
+ "@vitest/coverage-v8": "^5.1.0",
57
57
  "typescript": "^6.0.3",
58
- "vitest": "^5.0.5",
58
+ "vitest": "^5.1.0",
59
59
  "zod": "^4.6.7",
60
60
  "@repo/build": "0.0.0",
61
- "@repo/prettier-config": "0.0.0",
62
61
  "@repo/eslint-config": "0.0.0",
62
+ "@repo/prettier-config": "0.0.0",
63
63
  "@repo/typescript-config": "0.0.0",
64
64
  "@repo/vitest-config": "0.0.0"
65
65
  },