ai-sdk-sandbox-gce 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # ai-sdk-sandbox-gce
2
2
 
3
+ ## 0.5.1
4
+
5
+ ### Patch Changes
6
+
7
+ - bbd3d89: The egress proxy keeps an idle connection open for 120 seconds rather than Node.js's 5, longer than the runtimes' clients keep theirs: Codex's keeps an idle connection for 90 seconds, and Claude Code reused one after 34. A request a runtime sent on a connection just as the proxy closed it was reset (`ECONNRESET`).
8
+ - c2420ee: The egress proxy has a total limit of connections, for all its sandboxes: `SANDBOX_PROXY_TOTAL_CONNECTIONS`, by default what its file descriptors allow (two for each connection, 1024 kept apart: 32256 under `LimitNOFILE=65536`). Without it, once the descriptors ran out, the system reset every sandbox's new connections before the proxy saw them, and nothing was logged. Beyond the limit, a connection is now refused with a `503` that says the proxy is full, and a tenth of the total is kept for the base URL routes. The proxy logs when it reaches its limit, with the three sandboxes that hold the most connections, and when it goes back under.
9
+ - 9a9a524: The egress proxy keeps connections for the base URL routes: the runtime reaches its model provider while the commands of its sandbox hold every connection they may. `SANDBOX_PROXY_MAX_CONNECTIONS` (128) now bounds the commands' tunnels and plain HTTP requests, and `SANDBOX_PROXY_ROUTE_CONNECTIONS` (32) gives the routes that many more; no machine holds more than both together. A command refused at its limit gets a `503` that says why, rather than a reset connection. The proxy logs a warning when a sandbox reaches a limit, and a line when it goes back under, with how many connections it refused meanwhile. A tunnel whose client ends it before its TLS ClientHello now frees its connection at once, rather than after 10 seconds.
10
+
11
+ ## 0.5.0
12
+
13
+ ### Minor Changes
14
+
15
+ - 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.
16
+
17
+ 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`.
18
+
3
19
  ## 0.4.2
4
20
 
5
21
  ### 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.2
138
+ VERSION=0.5.1
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")"
@@ -210,7 +210,8 @@ Environment=SANDBOX_PROXY_IDLE_EXIT_MINUTES=10
210
210
  RestartPreventExitStatus=100
211
211
  ExecStopPost=+/bin/sh -c 'if [ "$$EXIT_STATUS" = 100 ]; then systemctl poweroff; fi'
212
212
  DynamicUser=yes
213
- # Every sandbox holds up to SANDBOX_PROXY_MAX_CONNECTIONS (128) connections at once.
213
+ # Every sandbox holds up to 160 connections at once: SANDBOX_PROXY_MAX_CONNECTIONS (128) for its
214
+ # commands, SANDBOX_PROXY_ROUTE_CONNECTIONS (32) more for its base URL routes.
214
215
  LimitNOFILE=65536
215
216
 
216
217
  [Install]
@@ -282,7 +283,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
282
283
  > /etc/apt/sources.list.d/nodesource.list
283
284
  apt-get update
284
285
  apt-get install -y nodejs
285
- npm install --global ai-sdk-sandbox-gce@0.4.2 pnpm@10
286
+ npm install --global ai-sdk-sandbox-gce@0.5.1 pnpm@10
286
287
 
287
288
  # The sandbox's user: sudo without a password, and Docker.
288
289
  useradd --create-home --shell /bin/bash agent
@@ -310,7 +311,7 @@ The agent runs as root and starts the commands as `agent`, in its own service: `
310
311
 
311
312
  ### 4. The service
312
313
 
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.2 --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
+ 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.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.
314
315
 
315
316
  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
317
 
@@ -348,7 +349,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
348
349
  --member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
349
350
  done
350
351
 
351
- gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.4.2 \
352
+ gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.5.1 \
352
353
  --service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
353
354
  --network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
354
355
  --no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
@@ -602,6 +603,33 @@ The machine has no external address, and the VPC firewall, applied outside the g
602
603
 
603
604
  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.
604
605
 
606
+ ### Connections
607
+
608
+ The proxy counts the connections each sandbox's machine holds open through it, so that no sandbox takes the sockets of the others:
609
+
610
+ - **Its commands** — the tunnels of `HTTPS_PROXY` and the plain requests of `HTTP_PROXY` — hold up to `SANDBOX_PROXY_MAX_CONNECTIONS` (128) at once: package managers, test suites and their keep-alive pools. One more is refused with `503 Service Unavailable`, and a message that says so.
611
+ - **Its base URL routes** — the runtime's way to its model provider — always find a connection: they may take `SANDBOX_PROXY_ROUTE_CONNECTIONS` (32) more, which the commands never do. A command that calls a base URL route itself counts there too.
612
+ - A connection counts from the moment it opens, before it says what it carries: no machine holds more than both together, 160. One more is cut.
613
+ - **The proxy as a whole** holds up to `SANDBOX_PROXY_TOTAL_CONNECTIONS` at once, for all its sandboxes: by default what its descriptors allow, two for each connection, with 1024 kept apart — 32256 under `LimitNOFILE=65536`. Beyond it, a connection is refused with a `503` that says the proxy is full. Without this limit the system would reset it before the proxy saw it, for every sandbox alike and with nothing logged. A tenth of the total is kept for the base URL routes: the commands of all sandboxes together never take it.
614
+
615
+ The proxy logs a warning when a sandbox reaches a limit, with what it holds, and a line when it goes back under three quarters of it, with how many connections it refused meanwhile: `box reached its limit: its commands hold 128 connections, …`, then `box is back under its limit: …; 412 refused meanwhile`. It does the same for its own limit, naming the three sandboxes that hold the most: `The proxy reached its limit: … Holding the most: box (160), …`. A turn that fails while the sandbox or the proxy is at its limit is told apart from an outage of the provider.
616
+
617
+ The proxy keeps an idle connection open for 120 seconds, longer than the runtimes' clients keep theirs (Codex's, 90 seconds): the client always closes it first, so that no request is sent on it just as the proxy closes it, and reset. An idle connection still counts against the limits until then.
618
+
619
+ To raise them, add `Environment=SANDBOX_PROXY_MAX_CONNECTIONS=256` (and `SANDBOX_PROXY_ROUTE_CONNECTIONS`) to the `[Service]` section of the proxy's unit, in its startup script, and restart the proxy. For more sandboxes on one proxy, raise its `LimitNOFILE` instead: the total follows it. Set `SANDBOX_PROXY_TOTAL_CONNECTIONS` only to hold the proxy below what its descriptors allow.
620
+
621
+ ### Node.js and the proxy
622
+
623
+ 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.
624
+
625
+ 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:
626
+
627
+ - for a sandbox: `nodeUseEnvProxy: true`, at its creation and at each resume;
628
+ - for every sandbox of the service: `SANDBOX_NODE_USE_ENV_PROXY=true`, which a sandbox's `nodeUseEnvProxy: false` turns off;
629
+ - 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.
630
+
631
+ 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.
632
+
605
633
  ## Ports
606
634
 
607
635
  `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`.
@@ -624,70 +652,74 @@ Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.
624
652
 
625
653
  `createGceNetworkSandboxSession(options)` takes every option below; `resumeGceNetworkSandboxSession(options)` takes `sandboxId`, `abortSignal` and the connection settings.
626
654
 
627
- | Option | Default | Description |
628
- | ------------------ | ----------------- | --------------------------------------------------------------------------------------------------- |
629
- | `url` | required | _Connection._ The URL of the sandbox service |
630
- | `auth` | `'gcloud'` | _Connection._ `'gcloud'`, `'metadata'`, `'none'`, or a function returning an identity token |
631
- | `ports` | `[]` | _Connection._ Ports the harness may reach, through the service |
632
- | `allowedHosts` | `[]` | _Connection._ Hosts the sandbox may reach over HTTPS, on top of the service's |
633
- | `baseUrls` | `{}` | _Connection._ Base URL variables routed through the proxy, on top of the service's |
634
- | `serviceToken` | none | _Connection._ The service's `SANDBOX_SERVICE_TOKEN`, when it has one |
635
- | `sandboxId` | `ai-sdk-<hex>` | The sandbox's name: lowercase letters, digits and dashes, 55 at most. Creation fails if it is taken |
636
- | `template` | none | `await agent.getSandboxTemplate()`: prepare once, boot every later sandbox from it |
637
- | `image` | `default` | The image the machine boots from, by the name the service gives it in `SANDBOX_IMAGES` |
638
- | `requiredCommands` | `['node', 'git']` | Commands the sandbox must have once `setup` ran |
639
- | `setup` | `[]` | Commands run once after creation, as the sandbox's user (who has `sudo`), saved in the template |
640
- | `abortSignal` | none | Aborts the creation or the resume |
655
+ | Option | Default | Description |
656
+ | ------------------ | ----------------- | --------------------------------------------------------------------------------------------------------------------- |
657
+ | `url` | required | _Connection._ The URL of the sandbox service |
658
+ | `auth` | `'gcloud'` | _Connection._ `'gcloud'`, `'metadata'`, `'none'`, or a function returning an identity token |
659
+ | `ports` | `[]` | _Connection._ Ports the harness may reach, through the service |
660
+ | `allowedHosts` | `[]` | _Connection._ Hosts the sandbox may reach over HTTPS, on top of the service's |
661
+ | `baseUrls` | `{}` | _Connection._ Base URL variables routed through the proxy, on top of the service's |
662
+ | `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) |
663
+ | `serviceToken` | none | _Connection._ The service's `SANDBOX_SERVICE_TOKEN`, when it has one |
664
+ | `sandboxId` | `ai-sdk-<hex>` | The sandbox's name: lowercase letters, digits and dashes, 55 at most. Creation fails if it is taken |
665
+ | `template` | none | `await agent.getSandboxTemplate()`: prepare once, boot every later sandbox from it |
666
+ | `image` | `default` | The image the machine boots from, by the name the service gives it in `SANDBOX_IMAGES` |
667
+ | `requiredCommands` | `['node', 'git']` | Commands the sandbox must have once `setup` ran |
668
+ | `setup` | `[]` | Commands run once after creation, as the sandbox's user (who has `sudo`), saved in the template |
669
+ | `abortSignal` | none | Aborts the creation or the resume |
641
670
 
642
671
  ## Configuration
643
672
 
644
673
  ### The service (`serve`)
645
674
 
646
- | Variable | Default | Description |
647
- | --------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
648
- | `SANDBOX_ZONE` | required | The zone of the machines |
649
- | `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…` |
650
- | `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python` |
651
- | `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager |
652
- | `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128` |
653
- | `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129` |
654
- | `SANDBOX_PROXY_TOKEN` | required | The proxy's token |
655
- | `SANDBOX_PROJECT` | the service's project | The project of the machines |
656
- | `SANDBOX_NETWORK` | the default network | The machines' VPC network |
657
- | `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>` |
658
- | `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to |
659
- | `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192` |
660
- | `SANDBOX_DISK_GB` | `20` | The size of their disk |
661
- | `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type |
662
- | `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after |
663
- | `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 |
664
- | `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most |
665
- | `SANDBOX_AGENT_PORT` | `8100` | The port of the agents |
666
- | `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer |
667
- | `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 |
668
- | `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 |
669
- | `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 |
670
- | `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
671
- | `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 |
672
- | `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 |
673
- | `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup |
674
- | `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 |
675
- | `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM |
676
- | `SANDBOX_INSECURE_NO_TOKEN` | `false` | `true` to run on Cloud Run without `SANDBOX_SERVICE_TOKEN`, its IAM the only lock |
677
- | `COMPUTE_AUTH` | `metadata` on Cloud Run, `gcloud` elsewhere | How the service gets its access tokens for the Compute Engine API |
678
- | `PORT`, `HOST` | `8080`, `0.0.0.0` on Cloud Run and `127.0.0.1` elsewhere | Where the service listens |
679
- | `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text |
675
+ | Variable | Default | Description |
676
+ | ---------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
677
+ | `SANDBOX_ZONE` | required | The zone of the machines |
678
+ | `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…` |
679
+ | `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python` |
680
+ | `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager |
681
+ | `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128` |
682
+ | `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129` |
683
+ | `SANDBOX_PROXY_TOKEN` | required | The proxy's token |
684
+ | `SANDBOX_PROJECT` | the service's project | The project of the machines |
685
+ | `SANDBOX_NETWORK` | the default network | The machines' VPC network |
686
+ | `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>` |
687
+ | `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to |
688
+ | `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192` |
689
+ | `SANDBOX_DISK_GB` | `20` | The size of their disk |
690
+ | `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type |
691
+ | `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after |
692
+ | `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 |
693
+ | `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most |
694
+ | `SANDBOX_AGENT_PORT` | `8100` | The port of the agents |
695
+ | `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer |
696
+ | `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 |
697
+ | `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 |
698
+ | `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 |
699
+ | `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
700
+ | `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 |
701
+ | `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 |
702
+ | `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup |
703
+ | `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 |
704
+ | `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) |
705
+ | `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM |
706
+ | `SANDBOX_INSECURE_NO_TOKEN` | `false` | `true` to run on Cloud Run without `SANDBOX_SERVICE_TOKEN`, its IAM the only lock |
707
+ | `COMPUTE_AUTH` | `metadata` on Cloud Run, `gcloud` elsewhere | How the service gets its access tokens for the Compute Engine API |
708
+ | `PORT`, `HOST` | `8080`, `0.0.0.0` on Cloud Run and `127.0.0.1` elsewhere | Where the service listens |
709
+ | `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text |
680
710
 
681
711
  ### The proxy (`proxy`)
682
712
 
683
- | Variable | Default | Description |
684
- | ------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------ |
685
- | `SANDBOX_PROXY_TOKEN` | required | The token the service proves itself with, 16 characters at least |
686
- | `SANDBOX_PROXY_PORT` | `3128` | The port the sandboxes reach |
687
- | `SANDBOX_PROXY_ADMIN_PORT` | `3129` | The port of the administration API |
688
- | `SANDBOX_ALLOW_PRIVATE_NETWORK` | `false` | For tests only: lets the sandboxes reach private addresses and plain HTTP base URLs |
689
- | `SANDBOX_PROXY_MAX_CONNECTIONS` | `128` | The most connections a sandbox holds open through the proxy at once: one more is cut, and the first one cut logged |
690
- | `HOST`, `LOG_FORMAT` | `0.0.0.0` | Where it listens; `text` for plain logs |
713
+ | Variable | Default | Description |
714
+ | --------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- |
715
+ | `SANDBOX_PROXY_TOKEN` | required | The token the service proves itself with, 16 characters at least |
716
+ | `SANDBOX_PROXY_PORT` | `3128` | The port the sandboxes reach |
717
+ | `SANDBOX_PROXY_ADMIN_PORT` | `3129` | The port of the administration API |
718
+ | `SANDBOX_ALLOW_PRIVATE_NETWORK` | `false` | For tests only: lets the sandboxes reach private addresses and plain HTTP base URLs |
719
+ | `SANDBOX_PROXY_MAX_CONNECTIONS` | `128` | The most connections the commands of a sandbox hold open through the proxy at once: [Connections](#connections) |
720
+ | `SANDBOX_PROXY_ROUTE_CONNECTIONS` | `32` | The connections a sandbox holds beyond those, for its base URL routes alone: [Connections](#connections) |
721
+ | `SANDBOX_PROXY_TOTAL_CONNECTIONS` | from `LimitNOFILE` | The most connections the proxy holds for all its sandboxes, a tenth kept for the routes: [Connections](#connections) |
722
+ | `HOST`, `LOG_FORMAT` | `0.0.0.0` | Where it listens; `text` for plain logs |
691
723
 
692
724
  ### The agent (`agent`)
693
725
 
@@ -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 {
@@ -44,6 +44,6 @@ export declare function deleteGceSandboxTemplate(options: GceTemplateDeletionSet
44
44
  * one: throws `GceSandboxNotFoundError` when no sandbox is named `sandboxId`.
45
45
  *
46
46
  * The service does not keep what a sandbox may reach across a suspension: pass the same `ports`,
47
- * `allowedHosts` and `baseUrls` the sandbox was created with.
47
+ * `allowedHosts`, `baseUrls` and `nodeUseEnvProxy` the sandbox was created with.
48
48
  */
49
49
  export declare function resumeGceNetworkSandboxSession(options: GceNetworkSandboxSessionResumeOptions): Promise<GceNetworkSandboxSession>;
@@ -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)
@@ -118,15 +118,20 @@ export async function deleteGceSandboxTemplate(options) {
118
118
  * one: throws `GceSandboxNotFoundError` when no sandbox is named `sandboxId`.
119
119
  *
120
120
  * The service does not keep what a sandbox may reach across a suspension: pass the same `ports`,
121
- * `allowedHosts` and `baseUrls` the sandbox was created with.
121
+ * `allowedHosts`, `baseUrls` and `nodeUseEnvProxy` the sandbox was created with.
122
122
  */
123
123
  export async function resumeGceNetworkSandboxSession(options) {
124
- const { abortSignal, sandboxId, allowedHosts, baseUrls } = options;
124
+ const { abortSignal, sandboxId, allowedHosts, baseUrls, nodeUseEnvProxy } = options;
125
125
  if (abortSignal?.aborted)
126
126
  throw abortReason(abortSignal);
127
127
  assertSandboxName(sandboxId);
128
128
  const client = clientOf(options);
129
- 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
+ });
130
135
  if (description === undefined)
131
136
  throw new GceSandboxNotFoundError(sandboxId);
132
137
  return sessionOf(client, description, options);
@@ -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)) {
@@ -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 {
@@ -1,8 +1,28 @@
1
1
  import type { Server } from 'node:http';
2
2
  import type { Logger } from '../common/logger.js';
3
3
  import type { EgressPolicy } from './egress-policy.js';
4
- /** The most connections a sandbox's machine holds open through the proxy at once, by default. */
4
+ /**
5
+ * The most connections the commands of a sandbox hold open through the proxy at once, by default:
6
+ * its tunnels and plain HTTP requests.
7
+ */
5
8
  export declare const DEFAULT_MAX_CONNECTIONS = 128;
9
+ /**
10
+ * The connections a sandbox holds beyond {@link DEFAULT_MAX_CONNECTIONS}, by default, for its base
11
+ * URL routes alone: the runtime's way to its model provider stays open whatever the commands hold.
12
+ */
13
+ export declare const DEFAULT_ROUTE_CONNECTIONS = 32;
14
+ /**
15
+ * How long the proxy keeps an idle connection of a base URL route open: longer than the runtimes'
16
+ * clients keep theirs, so that the client always closes first. Otherwise a request sent on it just
17
+ * as the proxy closes it is reset. Codex's client keeps an idle connection for 90 seconds; Claude
18
+ * Code's reused one after 34 seconds. Node's default, 5 seconds, is shorter than both.
19
+ */
20
+ export declare const KEEP_ALIVE_MS = 120000;
21
+ /**
22
+ * The most connections the proxy holds open at once, for all its sandboxes, by default: what
23
+ * `LimitNOFILE=65536` allows, two descriptors for each connection, with a margin for the rest.
24
+ */
25
+ export declare const DEFAULT_TOTAL_CONNECTIONS = 32256;
6
26
  /**
7
27
  * The way out of the sandboxes, on a machine of its own, outside their security boundary: the VPC
8
28
  * firewall lets their machines reach nothing else. Every connection is the sandbox's whose machine
@@ -28,27 +48,65 @@ export declare class EgressProxy {
28
48
  private readonly logger;
29
49
  readonly server: Server;
30
50
  /** The connections each machine holds open, by its address. */
31
- private readonly open;
32
- /** The machines cut at their limit since they last went under it: logged once. */
33
- private readonly capped;
51
+ private readonly machines;
52
+ /** The connections of every machine together. */
53
+ private readonly all;
54
+ /** What each connection carries, once its first request said. */
55
+ private readonly kinds;
34
56
  private readonly maxConnections;
57
+ private readonly routeConnections;
58
+ private readonly totalConnections;
35
59
  private readonly tunnelPort;
36
60
  /**
37
- * @param options.maxConnections The most connections a sandbox's machine holds open at once:
38
- * one more is cut at once, so that no sandbox takes the sockets of the others.
61
+ * @param options.maxConnections The most connections the commands of a sandbox hold open at
62
+ * once, its tunnels and plain HTTP requests: one more is refused, so that no sandbox takes the
63
+ * sockets of the others.
64
+ * @param options.routeConnections The connections a sandbox holds beyond `maxConnections` for
65
+ * its base URL routes alone, so that the runtime reaches its model provider whatever the
66
+ * commands hold. A machine never holds more than both together.
67
+ * @param options.totalConnections The most connections the proxy holds open at once, for all
68
+ * its sandboxes: below what its file descriptors allow, so that a connection beyond it is
69
+ * refused with a reason rather than reset by the system. A tenth of it is kept for the base
70
+ * URL routes, which the commands of all sandboxes together never take.
39
71
  * @param options.tunnelPort The port a tunnel reaches on its host, whatever port its `CONNECT`
40
72
  * names (443, the only one allowed). Tests only.
41
73
  */
42
- constructor(policyFor: (address: string | undefined) => EgressPolicy | undefined, logger?: Logger, { maxConnections, tunnelPort, }?: {
74
+ constructor(policyFor: (address: string | undefined) => EgressPolicy | undefined, logger?: Logger, { maxConnections, routeConnections, totalConnections, tunnelPort, }?: {
43
75
  maxConnections?: number;
76
+ routeConnections?: number;
77
+ totalConnections?: number;
44
78
  tunnelPort?: number;
45
79
  });
46
80
  close(): void;
47
81
  /**
48
- * Counts the connections of a machine, and cuts the one beyond {@link maxConnections}: logged the
49
- * first time only, until the machine goes under its limit again.
82
+ * Counts the connections of a machine, and refuses one beyond the proxy's limit, or cuts one
83
+ * beyond both the machine's limits together: what it carries is not known yet.
50
84
  */
51
85
  private count;
86
+ /**
87
+ * Why `socket` may not carry a command's traffic, `undefined` when it may: always once it does;
88
+ * otherwise while the machine's commands hold fewer than {@link maxConnections}, and those of
89
+ * all machines leave the routes their share of the proxy. It is then counted as a command's.
90
+ */
91
+ private commandRefusal;
92
+ /** The most connections the commands of all sandboxes hold together: the routes keep the rest. */
93
+ private commandsOfAll;
94
+ /** A connection whose first request is a base URL route: never counted as a command's. */
95
+ private admitRoute;
96
+ /** Refuses a connection at a limit: the first refusal logged, until the machine goes under. */
97
+ private atLimit;
98
+ /**
99
+ * Logs that a machine at a limit went back well under it, three quarters of its commands' limit:
100
+ * one connection closed, and the next refused, would otherwise log twice each time.
101
+ */
102
+ private underLimit;
103
+ /** Refuses a connection at the proxy's limit: the first refusal logged, with who holds the most. */
104
+ private proxyAtLimit;
105
+ /** Logs that the proxy went back under three quarters of its limits. */
106
+ private proxyUnderLimit;
107
+ /** The three sandboxes holding the most connections, with how many. */
108
+ private busiest;
109
+ private limits;
52
110
  private tunnel;
53
111
  /**
54
112
  * A plain request: a base URL route, its credentials put in, or, through `HTTP_PROXY`, plain HTTP
@@ -32,8 +32,32 @@ function reachability(policy, host) {
32
32
  return { lookup: publicOnlyLookup };
33
33
  }
34
34
  const UNKNOWN = 'This machine is no sandbox the proxy serves.';
35
- /** The most connections a sandbox's machine holds open through the proxy at once, by default. */
35
+ /**
36
+ * The most connections the commands of a sandbox hold open through the proxy at once, by default:
37
+ * its tunnels and plain HTTP requests.
38
+ */
36
39
  export const DEFAULT_MAX_CONNECTIONS = 128;
40
+ /**
41
+ * The connections a sandbox holds beyond {@link DEFAULT_MAX_CONNECTIONS}, by default, for its base
42
+ * URL routes alone: the runtime's way to its model provider stays open whatever the commands hold.
43
+ */
44
+ export const DEFAULT_ROUTE_CONNECTIONS = 32;
45
+ /**
46
+ * How long the proxy keeps an idle connection of a base URL route open: longer than the runtimes'
47
+ * clients keep theirs, so that the client always closes first. Otherwise a request sent on it just
48
+ * as the proxy closes it is reset. Codex's client keeps an idle connection for 90 seconds; Claude
49
+ * Code's reused one after 34 seconds. Node's default, 5 seconds, is shorter than both.
50
+ */
51
+ export const KEEP_ALIVE_MS = 120_000;
52
+ /**
53
+ * The most connections the proxy holds open at once, for all its sandboxes, by default: what
54
+ * `LimitNOFILE=65536` allows, two descriptors for each connection, with a margin for the rest.
55
+ */
56
+ export const DEFAULT_TOTAL_CONNECTIONS = 32_256;
57
+ /** The share of the proxy's connections its commands never take: the base URL routes keep it. */
58
+ const ROUTE_SHARE = 0.1;
59
+ /** What a command refused at the proxy's limit is told, and a connection cut at it. */
60
+ const PROXY_FULL = 'The proxy holds the most connections it may, for all its sandboxes. Try again in a moment.';
37
61
  /** The most bytes a ClientHello is read from: well over any real one. */
38
62
  const MAX_HELLO_BYTES = 64 * 1024;
39
63
  /** How long a client has to send its ClientHello once its tunnel is open. */
@@ -50,6 +74,7 @@ function clientHello(socket, head) {
50
74
  const done = (hello) => {
51
75
  clearTimeout(timer);
52
76
  socket.off('data', received);
77
+ socket.off('end', closed);
53
78
  socket.off('close', closed);
54
79
  socket.pause();
55
80
  resolve({ bytes, hello });
@@ -68,6 +93,8 @@ function clientHello(socket, head) {
68
93
  const closed = () => done();
69
94
  const timer = setTimeout(done, HELLO_TIMEOUT_MS);
70
95
  socket.on('data', received);
96
+ // The server keeps a socket half open once its client ended it: no `close` would come.
97
+ socket.once('end', closed);
71
98
  socket.once('close', closed);
72
99
  if (bytes.length > 0)
73
100
  check();
@@ -93,6 +120,7 @@ function helloRefusal(host, hello) {
93
120
  ? `A tunnel to ${host} must name it in its TLS (SNI).`
94
121
  : `A tunnel to ${host} may not name ${named} in its TLS.`;
95
122
  }
123
+ const connections = (count) => `${count} connection${count === 1 ? '' : 's'}`;
96
124
  const refuse = (res, message) => {
97
125
  res.writeHead(403, { 'content-type': 'text/plain' }).end(`${message}\n`);
98
126
  };
@@ -158,23 +186,40 @@ export class EgressProxy {
158
186
  logger;
159
187
  server;
160
188
  /** The connections each machine holds open, by its address. */
161
- open = new Map();
162
- /** The machines cut at their limit since they last went under it: logged once. */
163
- capped = new Set();
189
+ machines = new Map();
190
+ /** The connections of every machine together. */
191
+ all = { open: 0, commands: 0 };
192
+ /** What each connection carries, once its first request said. */
193
+ kinds = new WeakMap();
164
194
  maxConnections;
195
+ routeConnections;
196
+ totalConnections;
165
197
  tunnelPort;
166
198
  /**
167
- * @param options.maxConnections The most connections a sandbox's machine holds open at once:
168
- * one more is cut at once, so that no sandbox takes the sockets of the others.
199
+ * @param options.maxConnections The most connections the commands of a sandbox hold open at
200
+ * once, its tunnels and plain HTTP requests: one more is refused, so that no sandbox takes the
201
+ * sockets of the others.
202
+ * @param options.routeConnections The connections a sandbox holds beyond `maxConnections` for
203
+ * its base URL routes alone, so that the runtime reaches its model provider whatever the
204
+ * commands hold. A machine never holds more than both together.
205
+ * @param options.totalConnections The most connections the proxy holds open at once, for all
206
+ * its sandboxes: below what its file descriptors allow, so that a connection beyond it is
207
+ * refused with a reason rather than reset by the system. A tenth of it is kept for the base
208
+ * URL routes, which the commands of all sandboxes together never take.
169
209
  * @param options.tunnelPort The port a tunnel reaches on its host, whatever port its `CONNECT`
170
210
  * names (443, the only one allowed). Tests only.
171
211
  */
172
- constructor(policyFor, logger = silentLogger, { maxConnections = DEFAULT_MAX_CONNECTIONS, tunnelPort = 443, } = {}) {
212
+ constructor(policyFor, logger = silentLogger, { maxConnections = DEFAULT_MAX_CONNECTIONS, routeConnections = DEFAULT_ROUTE_CONNECTIONS, totalConnections = DEFAULT_TOTAL_CONNECTIONS, tunnelPort = 443, } = {}) {
173
213
  this.policyFor = policyFor;
174
214
  this.logger = logger;
175
215
  this.maxConnections = maxConnections;
216
+ this.routeConnections = routeConnections;
217
+ this.totalConnections = totalConnections;
176
218
  this.tunnelPort = tunnelPort;
177
219
  this.server = createServer((req, res) => this.forward(req, res));
220
+ this.server.keepAliveTimeout = KEEP_ALIVE_MS;
221
+ // Above the keep-alive: an idle connection is closed by it, never by the wait for headers.
222
+ this.server.headersTimeout = KEEP_ALIVE_MS + 1_000;
178
223
  this.server.on('connection', (socket) => this.count(socket));
179
224
  this.server.on('connect', (req, socket, head) => this.tunnel(req, socket, head));
180
225
  }
@@ -183,31 +228,124 @@ export class EgressProxy {
183
228
  this.server.close();
184
229
  }
185
230
  /**
186
- * Counts the connections of a machine, and cuts the one beyond {@link maxConnections}: logged the
187
- * first time only, until the machine goes under its limit again.
231
+ * Counts the connections of a machine, and refuses one beyond the proxy's limit, or cuts one
232
+ * beyond both the machine's limits together: what it carries is not known yet.
188
233
  */
189
234
  count(socket) {
190
235
  const address = socket.remoteAddress ?? '';
191
- const open = this.open.get(address) ?? 0;
192
- if (open >= this.maxConnections) {
193
- if (!this.capped.has(address)) {
194
- this.capped.add(address);
195
- const why = `${open} connections are open already, the most a sandbox holds at once.`;
196
- this.refused({ address, policy: this.policyFor(address), why });
197
- }
236
+ if (this.all.open >= this.totalConnections) {
237
+ this.proxyAtLimit(`${connections(this.all.open)} are open, base URL routes included`);
238
+ socket.end(`HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n${PROXY_FULL}\n`);
239
+ return;
240
+ }
241
+ const machine = this.machines.get(address) ?? { open: 0, commands: 0 };
242
+ if (machine.open >= this.maxConnections + this.routeConnections) {
243
+ this.atLimit(address, machine, `${connections(machine.open)} are open, base URL routes included`);
198
244
  socket.destroy();
199
245
  return;
200
246
  }
201
- this.open.set(address, open + 1);
247
+ machine.open += 1;
248
+ this.all.open += 1;
249
+ this.machines.set(address, machine);
202
250
  socket.once('close', () => {
203
- const left = (this.open.get(address) ?? 1) - 1;
204
- if (left === 0)
205
- this.open.delete(address);
206
- else
207
- this.open.set(address, left);
208
- this.capped.delete(address);
251
+ machine.open -= 1;
252
+ this.all.open -= 1;
253
+ if (this.kinds.get(socket) === 'command') {
254
+ machine.commands -= 1;
255
+ this.all.commands -= 1;
256
+ }
257
+ if (machine.open === 0)
258
+ this.machines.delete(address);
259
+ this.underLimit(address, machine);
260
+ this.proxyUnderLimit();
209
261
  });
210
262
  }
263
+ /**
264
+ * Why `socket` may not carry a command's traffic, `undefined` when it may: always once it does;
265
+ * otherwise while the machine's commands hold fewer than {@link maxConnections}, and those of
266
+ * all machines leave the routes their share of the proxy. It is then counted as a command's.
267
+ */
268
+ commandRefusal(socket) {
269
+ if (this.kinds.has(socket))
270
+ return undefined;
271
+ const address = socket.remoteAddress ?? '';
272
+ const machine = this.machines.get(address);
273
+ if (machine === undefined)
274
+ return undefined;
275
+ if (machine.commands >= this.maxConnections) {
276
+ this.atLimit(address, machine, `its commands hold ${connections(machine.commands)}`);
277
+ return `The sandbox holds the most connections its commands may: ${this.maxConnections}. Close some and try again.`;
278
+ }
279
+ if (this.all.commands >= this.commandsOfAll()) {
280
+ this.proxyAtLimit(`the commands of its sandboxes hold ${connections(this.all.commands)}`);
281
+ return PROXY_FULL;
282
+ }
283
+ machine.commands += 1;
284
+ this.all.commands += 1;
285
+ this.kinds.set(socket, 'command');
286
+ return undefined;
287
+ }
288
+ /** The most connections the commands of all sandboxes hold together: the routes keep the rest. */
289
+ commandsOfAll() {
290
+ return this.totalConnections - Math.ceil(this.totalConnections * ROUTE_SHARE);
291
+ }
292
+ /** A connection whose first request is a base URL route: never counted as a command's. */
293
+ admitRoute(socket) {
294
+ if (!this.kinds.has(socket))
295
+ this.kinds.set(socket, 'route');
296
+ }
297
+ /** Refuses a connection at a limit: the first refusal logged, until the machine goes under. */
298
+ atLimit(address, machine, state) {
299
+ if (machine.refused === undefined) {
300
+ const who = this.policyFor(address)?.name ?? address;
301
+ this.logger.warn(`${who} reached its limit: ${state}, the most it may. More are refused until some close: ${this.limits()}.`);
302
+ }
303
+ machine.refused = (machine.refused ?? 0) + 1;
304
+ }
305
+ /**
306
+ * Logs that a machine at a limit went back well under it, three quarters of its commands' limit:
307
+ * one connection closed, and the next refused, would otherwise log twice each time.
308
+ */
309
+ underLimit(address, machine) {
310
+ if (machine.refused === undefined)
311
+ return;
312
+ if (machine.commands > (this.maxConnections * 3) / 4)
313
+ return;
314
+ if (machine.open > ((this.maxConnections + this.routeConnections) * 3) / 4)
315
+ return;
316
+ const who = this.policyFor(address)?.name ?? address;
317
+ this.logger.info(`${who} is back under its limit: ${connections(machine.open)} open, ${machine.commands} of its commands; ${machine.refused} refused meanwhile.`);
318
+ machine.refused = undefined;
319
+ }
320
+ /** Refuses a connection at the proxy's limit: the first refusal logged, with who holds the most. */
321
+ proxyAtLimit(state) {
322
+ if (this.all.refused === undefined) {
323
+ this.logger.warn(`The proxy reached its limit: ${state}, the most it may for all its sandboxes (${this.totalConnections}, ${this.commandsOfAll()} of them for the commands). More are refused until some close. Holding the most: ${this.busiest()}.`);
324
+ }
325
+ this.all.refused = (this.all.refused ?? 0) + 1;
326
+ }
327
+ /** Logs that the proxy went back under three quarters of its limits. */
328
+ proxyUnderLimit() {
329
+ if (this.all.refused === undefined)
330
+ return;
331
+ if (this.all.commands > (this.commandsOfAll() * 3) / 4)
332
+ return;
333
+ if (this.all.open > (this.totalConnections * 3) / 4)
334
+ return;
335
+ this.logger.info(`The proxy is back under its limit: ${connections(this.all.open)} open, ${this.all.commands} of commands; ${this.all.refused} refused meanwhile.`);
336
+ this.all.refused = undefined;
337
+ }
338
+ /** The three sandboxes holding the most connections, with how many. */
339
+ busiest() {
340
+ return [...this.machines]
341
+ .sort(([, a], [, b]) => b.open - a.open)
342
+ .slice(0, 3)
343
+ .map(([address, { open }]) => `${this.policyFor(address)?.name ?? address} (${open})`)
344
+ .join(', ');
345
+ }
346
+ limits() {
347
+ return `${this.maxConnections} for the commands, and ${this.routeConnections} more for the base URL routes`;
348
+ }
211
349
  tunnel(req, socket, head) {
212
350
  socket.on('error', () => socket.destroy());
213
351
  const { hostname, port } = new URL(`http://${req.url ?? ''}`);
@@ -226,6 +364,11 @@ export class EgressProxy {
226
364
  socket.end(`HTTP/1.1 403 Forbidden\r\n\r\n${refusal}\n`);
227
365
  return;
228
366
  }
367
+ const full = this.commandRefusal(socket);
368
+ if (full !== undefined) {
369
+ socket.end(`HTTP/1.1 503 Service Unavailable\r\n\r\n${full}\n`);
370
+ return;
371
+ }
229
372
  const upstream = connect({ host: hostname, port: this.tunnelPort, lookup: reach.lookup }, () => {
230
373
  socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
231
374
  void clientHello(socket, head).then(({ bytes, hello }) => {
@@ -267,12 +410,19 @@ export class EgressProxy {
267
410
  this.deny(res, { address, policy, target: route.host, why: refusal });
268
411
  return;
269
412
  }
413
+ this.admitRoute(req.socket);
270
414
  this.send(req, res, { policy, target: route, transformations: policy.transformations });
271
415
  }
272
416
  /** A plain HTTP request through `HTTP_PROXY`: sent on to an allowed host, refused otherwise. */
273
417
  forwardPlain(req, res, policy) {
274
418
  const plain = plainTarget(req.url ?? '');
275
419
  if (plain !== undefined && isListedHost(policy.allowedHosts, plain.hostname)) {
420
+ const full = this.commandRefusal(req.socket);
421
+ if (full !== undefined) {
422
+ res.writeHead(503, { 'content-type': 'text/plain', connection: 'close' });
423
+ res.end(`${full}\n`);
424
+ return;
425
+ }
276
426
  this.send(req, res, { policy, target: plain, transformations: [] });
277
427
  return;
278
428
  }
@@ -1,6 +1,9 @@
1
1
  type Environment = Readonly<Record<string, string | undefined>>;
2
- /** The proxy's settings, from its environment, which the systemd unit of its machine sets. */
3
- export declare function proxyConfig(env: Environment): {
2
+ /**
3
+ * The proxy's settings, from its environment, which the systemd unit of its machine sets.
4
+ * `limits` is the text of `/proc/self/limits`, for the total of connections by default.
5
+ */
6
+ export declare function proxyConfig(env: Environment, limits?: string | undefined): {
4
7
  adminPort: number;
5
8
  allowPrivateNetwork: boolean;
6
9
  host: string;
@@ -8,8 +11,16 @@ export declare function proxyConfig(env: Environment): {
8
11
  idleExitMs?: number;
9
12
  maxConnections: number;
10
13
  port: number;
14
+ routeConnections: number;
11
15
  token: string;
16
+ totalConnections: number;
12
17
  };
18
+ /**
19
+ * The most connections the descriptors of the process allow, two for each, its soft `Max open
20
+ * files` in `limits` less {@link SPARE_DESCRIPTORS}: {@link DEFAULT_TOTAL_CONNECTIONS} when that
21
+ * limit is unknown or unlimited.
22
+ */
23
+ export declare function totalConnectionsFor(limits: string | undefined): number;
13
24
  /** `ai-sdk-sandbox-gce proxy`: serves the sandboxes and the administration API until stopped. */
14
25
  export declare function main(env: Environment): void;
15
26
  export {};
@@ -1,11 +1,15 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { createLogger } from '../common/logger.js';
2
3
  import { DEFAULT_PROXY_ADMIN_PORT, DEFAULT_PROXY_PORT } from '../protocol/proxy.js';
3
4
  import { createAdminServer } from './admin-server.js';
4
- import { DEFAULT_MAX_CONNECTIONS, EgressProxy } from './egress-proxy.js';
5
+ import { DEFAULT_MAX_CONNECTIONS, DEFAULT_ROUTE_CONNECTIONS, DEFAULT_TOTAL_CONNECTIONS, EgressProxy, } from './egress-proxy.js';
5
6
  import { IDLE_EXIT_CODE, watchIdle } from './idle-exit.js';
6
7
  import { SandboxRegistry } from './registry.js';
7
- /** The proxy's settings, from its environment, which the systemd unit of its machine sets. */
8
- export function proxyConfig(env) {
8
+ /**
9
+ * The proxy's settings, from its environment, which the systemd unit of its machine sets.
10
+ * `limits` is the text of `/proc/self/limits`, for the total of connections by default.
11
+ */
12
+ export function proxyConfig(env, limits = readLimits()) {
9
13
  const token = env['SANDBOX_PROXY_TOKEN'];
10
14
  if (token === undefined || token.length < 16) {
11
15
  throw new Error('SANDBOX_PROXY_TOKEN is required, 16 characters at least: the sandbox service proves itself with it.');
@@ -15,7 +19,18 @@ export function proxyConfig(env) {
15
19
  adminPort: Number.parseInt(env['SANDBOX_PROXY_ADMIN_PORT'] ?? String(DEFAULT_PROXY_ADMIN_PORT), 10),
16
20
  host: env['HOST'] ?? '0.0.0.0',
17
21
  allowPrivateNetwork: env['SANDBOX_ALLOW_PRIVATE_NETWORK'] === 'true',
18
- maxConnections: maxConnections(env['SANDBOX_PROXY_MAX_CONNECTIONS']),
22
+ maxConnections: connectionCount('SANDBOX_PROXY_MAX_CONNECTIONS', env, {
23
+ fallback: DEFAULT_MAX_CONNECTIONS,
24
+ min: 1,
25
+ }),
26
+ routeConnections: connectionCount('SANDBOX_PROXY_ROUTE_CONNECTIONS', env, {
27
+ fallback: DEFAULT_ROUTE_CONNECTIONS,
28
+ min: 0,
29
+ }),
30
+ totalConnections: connectionCount('SANDBOX_PROXY_TOTAL_CONNECTIONS', env, {
31
+ fallback: totalConnectionsFor(limits),
32
+ min: 1,
33
+ }),
19
34
  idleExitMs: idleExitMs(env['SANDBOX_PROXY_IDLE_EXIT_MINUTES']),
20
35
  token,
21
36
  };
@@ -30,13 +45,36 @@ function idleExitMs(value) {
30
45
  }
31
46
  return parsed * 60_000;
32
47
  }
33
- /** `SANDBOX_PROXY_MAX_CONNECTIONS`, a positive integer: {@link DEFAULT_MAX_CONNECTIONS} when unset. */
34
- function maxConnections(value) {
48
+ /** Descriptors kept apart from the connections: the proxy's own files, and upstream sockets kept alive. */
49
+ const SPARE_DESCRIPTORS = 1024;
50
+ /**
51
+ * The most connections the descriptors of the process allow, two for each, its soft `Max open
52
+ * files` in `limits` less {@link SPARE_DESCRIPTORS}: {@link DEFAULT_TOTAL_CONNECTIONS} when that
53
+ * limit is unknown or unlimited.
54
+ */
55
+ export function totalConnectionsFor(limits) {
56
+ const soft = /^Max open files\s+(\d+)/m.exec(limits ?? '')?.[1];
57
+ if (soft === undefined)
58
+ return DEFAULT_TOTAL_CONNECTIONS;
59
+ return Math.max(1, Math.floor((Number(soft) - SPARE_DESCRIPTORS) / 2));
60
+ }
61
+ function readLimits() {
62
+ try {
63
+ return readFileSync('/proc/self/limits', 'utf8');
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ /** A number of connections the variable `name` sets, an integer from `min`: `fallback` when unset. */
70
+ function connectionCount(name, env, { fallback, min }) {
71
+ const value = env[name];
35
72
  if (value === undefined || value === '')
36
- return DEFAULT_MAX_CONNECTIONS;
73
+ return fallback;
37
74
  const parsed = Number(value);
38
- if (!Number.isInteger(parsed) || parsed < 1) {
39
- throw new Error(`SANDBOX_PROXY_MAX_CONNECTIONS: \`${value}\` is not a positive integer.`);
75
+ if (!Number.isInteger(parsed) || parsed < min) {
76
+ const kind = min === 0 ? 'a non-negative integer' : 'a positive integer';
77
+ throw new Error(`${name}: \`${value}\` is not ${kind}.`);
40
78
  }
41
79
  return parsed;
42
80
  }
@@ -50,6 +88,8 @@ export function main(env) {
50
88
  const registry = new SandboxRegistry(config.allowPrivateNetwork);
51
89
  const proxy = new EgressProxy((address) => registry.policyFor(address), logger, {
52
90
  maxConnections: config.maxConnections,
91
+ routeConnections: config.routeConnections,
92
+ totalConnections: config.totalConnections,
53
93
  });
54
94
  const admin = createAdminServer({ registry, token: config.token, logger });
55
95
  proxy.server.listen(config.port, config.host, () => logger.info(`Egress proxy listening on ${config.host}:${config.port}`));
@@ -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.2",
3
+ "version": "0.5.1",
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",