ai-sdk-sandbox-gce 0.5.2 → 0.7.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 +29 -0
- package/README.md +296 -79
- package/dist/client/errors/gce-sandbox-capacity-error.d.ts +20 -0
- package/dist/client/errors/gce-sandbox-capacity-error.js +22 -0
- package/dist/client/gce-settings.d.ts +39 -2
- package/dist/client/gce-usage.d.ts +37 -0
- package/dist/client/gce-usage.js +1 -0
- package/dist/client/lifecycle/create-session.d.ts +38 -2
- package/dist/client/lifecycle/create-session.js +78 -8
- package/dist/client/lifecycle/sandbox-template.d.ts +2 -0
- package/dist/client/lifecycle/sandbox-template.js +7 -2
- package/dist/client/session/gce-network-sandbox-session.d.ts +38 -0
- package/dist/client/session/gce-network-sandbox-session.js +56 -2
- package/dist/client/session/gce-sandbox-session.d.ts +5 -0
- package/dist/client/transport/sandbox-service-client.d.ts +28 -6
- package/dist/client/transport/sandbox-service-client.js +71 -8
- package/dist/common/http-error.d.ts +11 -1
- package/dist/common/http-error.js +3 -1
- package/dist/common/http-reply.d.ts +3 -6
- package/dist/common/http-reply.js +28 -6
- package/dist/common/logger.d.ts +17 -1
- package/dist/common/logger.js +8 -4
- package/dist/in-vm/agent-config.js +41 -5
- package/dist/in-vm/agent.d.ts +16 -0
- package/dist/in-vm/agent.js +24 -0
- package/dist/in-vm/metrics-sampler.d.ts +66 -0
- package/dist/in-vm/metrics-sampler.js +223 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -1
- package/dist/protocol/agent.d.ts +3 -1
- package/dist/protocol/agent.js +3 -1
- package/dist/protocol/api.d.ts +163 -0
- package/dist/protocol/api.js +5 -0
- package/dist/protocol/labels.d.ts +16 -0
- package/dist/protocol/labels.js +37 -0
- package/dist/protocol/proxy.d.ts +23 -1
- package/dist/protocol/proxy.js +3 -1
- package/dist/proxy/admin-server.js +3 -2
- package/dist/proxy/egress-meter.d.ts +18 -0
- package/dist/proxy/egress-meter.js +37 -0
- package/dist/proxy/egress-policy.d.ts +3 -0
- package/dist/proxy/egress-proxy.d.ts +27 -0
- package/dist/proxy/egress-proxy.js +111 -8
- package/dist/proxy/main.d.ts +6 -0
- package/dist/proxy/main.js +22 -0
- package/dist/proxy/registered-sandbox.d.ts +3 -0
- package/dist/proxy/registered-sandbox.js +3 -0
- package/dist/proxy/registry.d.ts +8 -3
- package/dist/proxy/registry.js +11 -2
- package/dist/server/compute/compute-api.d.ts +41 -0
- package/dist/server/compute/compute-api.js +68 -13
- package/dist/server/http/routes.js +36 -8
- package/dist/server/sandboxes/agent-client.d.ts +11 -0
- package/dist/server/sandboxes/agent-client.js +27 -3
- package/dist/server/sandboxes/proxy-admin.d.ts +10 -3
- package/dist/server/sandboxes/proxy-admin.js +18 -3
- package/dist/server/sandboxes/sandboxes.d.ts +75 -16
- package/dist/server/sandboxes/sandboxes.js +343 -69
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# ai-sdk-sandbox-gce
|
|
2
2
|
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 574c460: `gceSandboxTemplateExists({ template, setup, image })` says whether the template that sandboxes created with these options boot from is saved on the service. It is not after a new base image, a new version of the service or a new harness version, which each name another template: an application can build it ahead rather than have the next sandbox build it.
|
|
8
|
+
- 4b5f85a: The egress proxy can take the direct connections of programs that ignore `HTTPS_PROXY` and `HTTP_PROXY` (Node.js's own `fetch` without `NODE_USE_ENV_PROXY`, Go, Java…), once the sandboxes' DNS answers its address for every name: TLS on `SANDBOX_PROXY_TLS_PORT` (443), checked by the host its ClientHello names (SNI) and relayed without being decrypted, and plain HTTP on `SANDBOX_PROXY_HTTP_PORT` (80), sent on to its `Host`. Node.js then reaches its hosts without `NODE_USE_ENV_PROXY`, and test suites that mock `fetch` with MSW 3 pass. Nothing changes without these settings. HTTP/3, a TLS connection without SNI, and programs that pin addresses or resolve names elsewhere are not covered.
|
|
9
|
+
|
|
10
|
+
### Patch Changes
|
|
11
|
+
|
|
12
|
+
- 1e20913: The README closes the sandboxes' DNS with a private zone for the root, which answers every type of query in the network, rather than a response policy rule on `*.`, which answered only `A` queries and let the others (`AAAA`, `TXT`, `MX`…) leave it, a channel for a few bytes at a time. A peering zone keeps `googleapis.com` resolving for the service. A network set up with the earlier steps should move to the zones, as the README shows.
|
|
13
|
+
- 1e20913: A sandbox's `timings` count the registration with the egress proxy once: it runs alongside the boot, and `agentMs` now holds only what it took beyond the boot, so that `insertMs`, `bootMs` and `agentMs` follow one another within `totalMs`, as documented.
|
|
14
|
+
|
|
15
|
+
## 0.6.0
|
|
16
|
+
|
|
17
|
+
### Minor Changes
|
|
18
|
+
|
|
19
|
+
- be187a8: A creation or a resume refused for `SANDBOX_MAX_RUNNING` now throws `GceSandboxCapacityError`, carrying `running`, `max` and `retryAfterSeconds`, for the caller to queue the call rather than read the message. It extends `GceSandboxServiceError`, its `status` still 429. The service answers that 429 with `code: 'SANDBOX_MAX_RUNNING'`, `running`, `max` and `retryAfterSeconds` in its body, and a `Retry-After` header.
|
|
20
|
+
- be187a8: `describeGceSandbox({ url, sandboxId })`, and `describe()` of a session, read the sandbox's machine from Compute Engine without starting it (`GET /v1/sandboxes/:name` on the service): when it was made, last started and last stopped, whether it is billed as Spot or standard (`spotFallback` says when a service of Spot machines fell back to a standard one), its machine type, the size of its disk, its image, whether it came from the warm pool, and the caller's labels.
|
|
21
|
+
- be187a8: The egress proxy counts the bytes each sandbox's connections carry, outside its machine. `usage()` of a session, or `getGceSandboxUsage()`, reads the count while the sandbox runs (`GET /v1/sandboxes/:name/usage` on the service, `GET /v1/sandboxes/:name/usage` on the proxy's administration API). The proxy keeps it in memory and forgets it with the sandbox: a stop and a deletion now answer the last count in a report (`POST …/suspend` and `DELETE /v1/sandboxes/:name` answer 200 with it, no longer 204), which `onUsageReport` is handed (by `stop()`, `destroy()` and `deleteGceSandbox()`) and `lastReport` of the session holds. Upgrade the proxy with the service: one of an earlier version counts nothing.
|
|
22
|
+
- be187a8: `createGceNetworkSandboxSession()` takes `labels`, put on the sandbox's machine and on its disk beside the service's own, for a Cloud Billing export or a budget to group their cost by. Keys starting with `ai-sdk-` are refused, and so are labels Compute Engine would refuse. A machine taken from the warm pool gets them as it is taken, and so does its disk, now labelled `ai-sdk-sandbox=pool` until then and `ai-sdk-sandbox-name=<sandbox>` after.
|
|
23
|
+
- be187a8: The service logs each creation, resume, suspension and deletion as a structured JSON line, `{ event, sandbox, at, … }`, beside its message: the machine, the image, the template, the caller's labels and the timings of a creation; the timings of a resume; the proxy's last count of a suspension or a deletion. Cloud Logging reads them as structured entries, for log-based metrics. With `LOG_FORMAT=text`, the message alone is written, as before.
|
|
24
|
+
- be187a8: The agent of each machine samples it every 30 s from `/proc` (CPU busy and stolen shares, memory in use, CPU and memory pressure, OOM kills), keeping the last day of samples on the machine's disk, across stops. `metrics()` of a session, or `getGceSandboxMetrics({ since })`, reads them while the sandbox runs (`GET /v1/sandboxes/:name/metrics?since=` on the service, `GET /v1/metrics` on the agent), and a stop or a deletion reads the last ones before the machine goes, in the `metrics` of its report. Read in the machine, they are fit for sizing, never for billing. `SANDBOX_METRICS_INTERVAL` sets the interval on the agent. Build the sandbox image again with this version to get them: an earlier agent samples nothing.
|
|
25
|
+
- be187a8: `timings` of a session says how long its creation or its resume took on the service, step by step: the egress proxy, Compute Engine making or starting the machine (or the warm pool handing one over, `fromPool`), its boot until the agent answered, then the agent's configuration, and the whole call. The service answers it with the sandbox, in the create and resume responses.
|
|
26
|
+
|
|
27
|
+
### Patch Changes
|
|
28
|
+
|
|
29
|
+
- e1994c7: The service's Docker image is now based on Debian 13 (`node:24-trixie-slim`) and no longer contains npm, corepack or yarn: the service only runs Node.js. An image of your own built `FROM` it that calls npm must install it.
|
|
30
|
+
- be187a8: The sandbox service sends a Compute Engine call again, up to 3 times, when Compute Engine cannot be reached (a kept-alive connection closed while Cloud Run throttled the CPU), with a request id that makes a change safe to send twice; the last failure names the call and its cause instead of `fetch failed`. A sandbox created just after the last one stopped the egress proxy is registered again once the proxy is back, rather than failing with a 502 or a 500. Unexpected errors are logged with their cause.
|
|
31
|
+
|
|
3
32
|
## 0.5.2
|
|
4
33
|
|
|
5
34
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -95,14 +95,28 @@ gcloud compute firewall-rules create proxy-admin-from-service --network=sandboxe
|
|
|
95
95
|
--action=ALLOW --rules=tcp:3129 --source-ranges=10.8.17.0/26 --target-tags=ai-sdk-sandbox-proxy
|
|
96
96
|
```
|
|
97
97
|
|
|
98
|
-
A sandbox resolves names through the metadata server, which the firewall does not filter: a DNS query for any name leaves the VPC, a channel for a few bytes at a time. Close it with a
|
|
98
|
+
A sandbox resolves names through the metadata server, which the firewall does not filter: a DNS query for any name leaves the VPC, a channel for a few bytes at a time. Close it with a private zone for the root of the DNS on the network, which answers every name itself, for every type of query, so that no query leaves it. The service, on the same network, still reaches Google's APIs: a peering zone resolves `googleapis.com` in a network with no zone of its own, created for that alone and free without subnetworks.
|
|
99
99
|
|
|
100
100
|
```bash
|
|
101
101
|
gcloud services enable dns.googleapis.com
|
|
102
|
-
gcloud dns
|
|
102
|
+
gcloud dns managed-zones create sandboxes-root --dns-name=. --visibility=private --networks=sandboxes \
|
|
103
103
|
--description="Every name answered locally: DNS is no way out of a sandbox."
|
|
104
|
-
gcloud dns
|
|
105
|
-
|
|
104
|
+
gcloud dns record-sets create "*." --zone=sandboxes-root --type=A --ttl=300 --rrdatas=0.0.0.0
|
|
105
|
+
|
|
106
|
+
gcloud compute networks create sandboxes-dns --subnet-mode=custom
|
|
107
|
+
gcloud dns managed-zones create sandboxes-googleapis --dns-name=googleapis.com. --visibility=private \
|
|
108
|
+
--networks=sandboxes --target-network=sandboxes-dns --target-project=$PROJECT \
|
|
109
|
+
--description="Google's APIs for the service, through a network that answers them."
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
An `A` query then gets `0.0.0.0`, any other type (`AAAA`, `TXT`, `MX`…) an empty answer, and none of them leaves the network. The names of Google Cloud (`metadata.google.internal`, the machines' internal names) still resolve, and `googleapis.com` too: its queries reach only Google's servers. Should the service reach another domain by name, give it a peering zone of its own the same way.
|
|
113
|
+
|
|
114
|
+
A network closed earlier with a response policy rule on `*.` (an earlier version of these steps) is not closed: such a rule answers only `A` queries, and the others leave the network. Create the zones above, then delete the policy:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
gcloud dns response-policies rules delete every-name --response-policy=sandboxes-no-dns
|
|
118
|
+
gcloud dns response-policies update sandboxes-no-dns --networks=""
|
|
119
|
+
gcloud dns response-policies delete sandboxes-no-dns
|
|
106
120
|
```
|
|
107
121
|
|
|
108
122
|
Keep the `service` subnetwork for the service alone: whatever else runs in it, a Cloud Run job or a machine, reaches the agents and the proxy's administration API like the service does.
|
|
@@ -135,14 +149,14 @@ gcloud compute instances create sandbox-proxy --zone=$ZONE --machine-type=e2-sma
|
|
|
135
149
|
#!/bin/sh
|
|
136
150
|
set -e
|
|
137
151
|
# The version of the proxy: the one your application depends on.
|
|
138
|
-
VERSION=0.
|
|
152
|
+
VERSION=0.7.0
|
|
139
153
|
# Writes $2 to the file $1 when it differs, and says whether it did.
|
|
140
154
|
changed() {
|
|
141
155
|
mkdir -p "$(dirname "$1")"
|
|
142
156
|
if printf '%b' "$2" | cmp -s - "$1"; then return 1; fi
|
|
143
157
|
printf '%b' "$2" > "$1"
|
|
144
158
|
}
|
|
145
|
-
# Public resolvers, not the metadata server's, which the sandboxes'
|
|
159
|
+
# Public resolvers, not the metadata server's, which the sandboxes' root zone answers.
|
|
146
160
|
# After gce-resolved.conf, which adds the metadata server: the empty DNS= resets the list.
|
|
147
161
|
dns=false
|
|
148
162
|
if changed /etc/systemd/resolved.conf.d/public-dns.conf '[Resolve]\nDNS=\nDNS=8.8.8.8 1.1.1.1\nDomains=~.\n'; then
|
|
@@ -283,7 +297,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
|
|
|
283
297
|
> /etc/apt/sources.list.d/nodesource.list
|
|
284
298
|
apt-get update
|
|
285
299
|
apt-get install -y nodejs
|
|
286
|
-
npm install --global ai-sdk-sandbox-gce@0.
|
|
300
|
+
npm install --global ai-sdk-sandbox-gce@0.7.0 pnpm@10
|
|
287
301
|
|
|
288
302
|
# The sandbox's user: sudo without a password, and Docker.
|
|
289
303
|
useradd --create-home --shell /bin/bash agent
|
|
@@ -311,7 +325,7 @@ The agent runs as root and starts the commands as `agent`, in its own service: `
|
|
|
311
325
|
|
|
312
326
|
### 4. The service
|
|
313
327
|
|
|
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.
|
|
328
|
+
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.7.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.
|
|
315
329
|
|
|
316
330
|
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-`).
|
|
317
331
|
|
|
@@ -349,7 +363,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
|
|
|
349
363
|
--member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
|
|
350
364
|
done
|
|
351
365
|
|
|
352
|
-
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.
|
|
366
|
+
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.7.0 \
|
|
353
367
|
--service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
|
|
354
368
|
--network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
|
|
355
369
|
--no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
|
|
@@ -483,6 +497,18 @@ await deleteGceSandboxTemplate({
|
|
|
483
497
|
|
|
484
498
|
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.
|
|
485
499
|
|
|
500
|
+
A template can also be gone without your deleting it: a new base image, a new version of the service or a new harness version each name another template, and old ones get cleaned up. `gceSandboxTemplateExists()` says whether the template a sandbox would boot from is saved, with the same options: build it ahead when it is not, rather than have the next user wait for it.
|
|
501
|
+
|
|
502
|
+
```ts
|
|
503
|
+
import { gceSandboxTemplateExists } from 'ai-sdk-sandbox-gce';
|
|
504
|
+
|
|
505
|
+
const ready = await gceSandboxTemplateExists({
|
|
506
|
+
url: process.env.GCE_SANDBOX_URL!,
|
|
507
|
+
template: await agent.getSandboxTemplate(),
|
|
508
|
+
setup,
|
|
509
|
+
});
|
|
510
|
+
```
|
|
511
|
+
|
|
486
512
|
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.
|
|
487
513
|
|
|
488
514
|
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:
|
|
@@ -630,21 +656,68 @@ Without it, code that calls an outside host with Node.js's `fetch` and has no pr
|
|
|
630
656
|
|
|
631
657
|
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
658
|
|
|
659
|
+
To have both, Node.js's `fetch` reaching its hosts and MSW test suites passing, without `NODE_USE_ENV_PROXY`, let the sandboxes reach the proxy directly: see [Programs that ignore the proxy variables](#programs-that-ignore-the-proxy-variables).
|
|
660
|
+
|
|
661
|
+
### Programs that ignore the proxy variables
|
|
662
|
+
|
|
663
|
+
Optional. By default, only programs that read `HTTPS_PROXY` or `HTTP_PROXY` leave a sandbox: Node.js's own `fetch` without `NODE_USE_ENV_PROXY`, Go, Java, and any binary that ignores the variables connect directly, and the firewall refuses them. The proxy can take those direct connections too, on 443 for TLS and on 80 for plain HTTP, when every name resolves to its address in the sandboxes:
|
|
664
|
+
|
|
665
|
+
- **TLS, on 443**: the proxy reads the host the connection's ClientHello names (SNI), lets it through only to an allowed host and a public address, as it does a `CONNECT` tunnel, then relays the bytes to it on 443 without decrypting them;
|
|
666
|
+
- **plain HTTP, on 80**: the proxy reads `Host`, and sends the request on as one through `HTTP_PROXY`;
|
|
667
|
+
- the same connection limits, egress counters and refusal logs as through the proxy variables.
|
|
668
|
+
|
|
669
|
+
A program then connects to `host:443` as it would anywhere, and reaches the proxy. MSW 3 sees a request it can mock, with no `CONNECT`, and `NODE_USE_ENV_PROXY` is no longer needed for Node.js to reach its hosts. The programs that read the proxy variables go on using them.
|
|
670
|
+
|
|
671
|
+
To set it up:
|
|
672
|
+
|
|
673
|
+
1. Have the root zone answer every name with the proxy's address rather than `0.0.0.0`. No query leaves the network, as before:
|
|
674
|
+
|
|
675
|
+
```bash
|
|
676
|
+
gcloud dns record-sets update "*." --zone=sandboxes-root --type=A --ttl=300 --rrdatas=10.8.16.2
|
|
677
|
+
```
|
|
678
|
+
|
|
679
|
+
2. Let the sandboxes reach the proxy on 80 and 443 as well:
|
|
680
|
+
|
|
681
|
+
```bash
|
|
682
|
+
gcloud compute firewall-rules update sandboxes-to-proxy --rules=tcp:3128,tcp:80,tcp:443
|
|
683
|
+
gcloud compute firewall-rules update proxy-from-sandboxes --rules=tcp:3128,tcp:80,tcp:443
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
3. Add to the `[Service]` section of the proxy's unit, in its startup script, then restart the proxy with no sandbox running (it forgets its sandboxes as it restarts):
|
|
687
|
+
|
|
688
|
+
```ini
|
|
689
|
+
Environment=SANDBOX_PROXY_TLS_PORT=443
|
|
690
|
+
Environment=SANDBOX_PROXY_HTTP_PORT=80
|
|
691
|
+
# Ports below 1024, for a user that is not root.
|
|
692
|
+
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
Its limits:
|
|
696
|
+
|
|
697
|
+
- **HTTP/3** (QUIC, over UDP) does not go through: clients fall back to TCP;
|
|
698
|
+
- **a TLS connection that names no host** (no SNI), or that is no TLS, is cut: there is no HTTP to answer it with, and it shows in the proxy's refusals;
|
|
699
|
+
- **credentials** stay on the base URL routes: a direct connection is never decrypted, any more than a `CONNECT` tunnel is, so no request transformation applies to it;
|
|
700
|
+
- **a program that pins IP addresses, or resolves names elsewhere** (its own DNS over HTTPS, `/etc/hosts`), does not reach the proxy, and stays refused by the firewall;
|
|
701
|
+
- **ports other than 80 and 443**: refused by the firewall, as before.
|
|
702
|
+
|
|
633
703
|
## Ports
|
|
634
704
|
|
|
635
705
|
`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`.
|
|
636
706
|
|
|
637
707
|
## Lifecycle
|
|
638
708
|
|
|
639
|
-
| Method | What it does
|
|
640
|
-
| -------------------------- |
|
|
641
|
-
| `release()` | Stops the processes this session started and forgets its credentials, leaving the sandbox running
|
|
642
|
-
| `killAllProcesses()` | Stops every process the machine's agent started
|
|
643
|
-
| `stop()` | Stops the machine, its disk kept. Idempotent
|
|
644
|
-
| `destroy()` | Deletes the machine and its disk. Idempotent
|
|
645
|
-
| `setNetworkPolicy(policy)` | Replaces the hosts the sandbox may reach
|
|
646
|
-
| `restricted()` | The files-and-processes view of the same sandbox, to hand to tools
|
|
647
|
-
| `fork({ ports })` | Another view of the same sandbox, with ports, processes and credentials of its own
|
|
709
|
+
| Method | What it does |
|
|
710
|
+
| -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
711
|
+
| `release()` | Stops the processes this session started and forgets its credentials, leaving the sandbox running |
|
|
712
|
+
| `killAllProcesses()` | Stops every process the machine's agent started |
|
|
713
|
+
| `stop()` | Stops the machine, its disk kept. Idempotent |
|
|
714
|
+
| `destroy()` | Deletes the machine and its disk. Idempotent |
|
|
715
|
+
| `setNetworkPolicy(policy)` | Replaces the hosts the sandbox may reach |
|
|
716
|
+
| `restricted()` | The files-and-processes view of the same sandbox, to hand to tools |
|
|
717
|
+
| `fork({ ports })` | Another view of the same sandbox, with ports, processes and credentials of its own |
|
|
718
|
+
| `describe()` | The sandbox's machine, as Compute Engine describes it: see [Its machine](#its-machine) |
|
|
719
|
+
| `usage()` | What its connections carried through the proxy: see [What its connections carried](#what-its-connections-carried) |
|
|
720
|
+
| `lastReport` | The last measures the last `stop()` or `destroy()` of this view answered |
|
|
648
721
|
|
|
649
722
|
`fork()` lets several harness sessions run side by side in one machine, each with a bridge on its own port, as with `ai-sdk-sandbox-cloud-run`.
|
|
650
723
|
|
|
@@ -654,74 +727,77 @@ The MCP servers that [`ai-sdk-harness-plugins`](https://ai-sdk-harness.pages.dev
|
|
|
654
727
|
|
|
655
728
|
`createGceNetworkSandboxSession(options)` takes every option below; `resumeGceNetworkSandboxSession(options)` takes `sandboxId`, `abortSignal` and the connection settings.
|
|
656
729
|
|
|
657
|
-
| Option | Default | Description
|
|
658
|
-
| ------------------ | ----------------- |
|
|
659
|
-
| `url` | required | _Connection._ The URL of the sandbox service
|
|
660
|
-
| `auth` | `'gcloud'` | _Connection._ `'gcloud'`, `'metadata'`, `'none'`, or a function returning an identity token
|
|
661
|
-
| `ports` | `[]` | _Connection._ Ports the harness may reach, through the service
|
|
662
|
-
| `allowedHosts` | `[]` | _Connection._ Hosts the sandbox may reach over HTTPS, on top of the service's
|
|
663
|
-
| `baseUrls` | `{}` | _Connection._ Base URL variables routed through the proxy, on top of the service's
|
|
664
|
-
| `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)
|
|
665
|
-
| `serviceToken` | none | _Connection._ The service's `SANDBOX_SERVICE_TOKEN`, when it has one
|
|
666
|
-
| `sandboxId` | `ai-sdk-<hex>` | The sandbox's name: lowercase letters, digits and dashes, 55 at most. Creation fails if it is taken
|
|
667
|
-
| `template` | none | `await agent.getSandboxTemplate()`: prepare once, boot every later sandbox from it
|
|
668
|
-
| `image` | `default` | The image the machine boots from, by the name the service gives it in `SANDBOX_IMAGES`
|
|
669
|
-
| `
|
|
670
|
-
| `
|
|
671
|
-
| `
|
|
730
|
+
| Option | Default | Description |
|
|
731
|
+
| ------------------ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
732
|
+
| `url` | required | _Connection._ The URL of the sandbox service |
|
|
733
|
+
| `auth` | `'gcloud'` | _Connection._ `'gcloud'`, `'metadata'`, `'none'`, or a function returning an identity token |
|
|
734
|
+
| `ports` | `[]` | _Connection._ Ports the harness may reach, through the service |
|
|
735
|
+
| `allowedHosts` | `[]` | _Connection._ Hosts the sandbox may reach over HTTPS, on top of the service's |
|
|
736
|
+
| `baseUrls` | `{}` | _Connection._ Base URL variables routed through the proxy, on top of the service's |
|
|
737
|
+
| `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) |
|
|
738
|
+
| `serviceToken` | none | _Connection._ The service's `SANDBOX_SERVICE_TOKEN`, when it has one |
|
|
739
|
+
| `sandboxId` | `ai-sdk-<hex>` | The sandbox's name: lowercase letters, digits and dashes, 55 at most. Creation fails if it is taken |
|
|
740
|
+
| `template` | none | `await agent.getSandboxTemplate()`: prepare once, boot every later sandbox from it |
|
|
741
|
+
| `image` | `default` | The image the machine boots from, by the name the service gives it in `SANDBOX_IMAGES` |
|
|
742
|
+
| `labels` | `{}` | Labels put on the machine and its disk, for a billing export: see [Usage and cost of a sandbox](#usage-and-cost-of-a-sandbox) |
|
|
743
|
+
| `requiredCommands` | `['node', 'git']` | Commands the sandbox must have once `setup` ran |
|
|
744
|
+
| `setup` | `[]` | Commands run once after creation, as the sandbox's user (who has `sudo`), saved in the template |
|
|
745
|
+
| `abortSignal` | none | Aborts the creation or the resume |
|
|
672
746
|
|
|
673
747
|
## Configuration
|
|
674
748
|
|
|
675
749
|
### The service (`serve`)
|
|
676
750
|
|
|
677
|
-
| Variable | Default | Description
|
|
678
|
-
| ---------------------------- | ---------------------------------------------------------------------------------------- |
|
|
679
|
-
| `SANDBOX_ZONE` | required | The zone of the machines
|
|
680
|
-
| `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…`
|
|
681
|
-
| `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python`
|
|
682
|
-
| `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager
|
|
683
|
-
| `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128`
|
|
684
|
-
| `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129`
|
|
685
|
-
| `SANDBOX_PROXY_TOKEN` | required | The proxy's token
|
|
686
|
-
| `SANDBOX_PROJECT` | the service's project | The project of the machines
|
|
687
|
-
| `SANDBOX_NETWORK` | the default network | The machines' VPC network
|
|
688
|
-
| `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>`
|
|
689
|
-
| `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to
|
|
690
|
-
| `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192`
|
|
691
|
-
| `SANDBOX_DISK_GB` | `20` | The size of their disk
|
|
692
|
-
| `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type
|
|
693
|
-
| `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after
|
|
694
|
-
| `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
|
|
695
|
-
| `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most
|
|
696
|
-
| `SANDBOX_AGENT_PORT` | `8100` | The port of the agents
|
|
697
|
-
| `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer
|
|
698
|
-
| `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
|
|
699
|
-
| `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
|
|
700
|
-
| `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
|
|
701
|
-
| `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost)
|
|
702
|
-
| `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
|
|
703
|
-
| `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
|
|
704
|
-
| `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup
|
|
705
|
-
| `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
|
|
706
|
-
| `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)
|
|
707
|
-
| `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM
|
|
708
|
-
| `SANDBOX_INSECURE_NO_TOKEN` | `false` | `true` to run on Cloud Run without `SANDBOX_SERVICE_TOKEN`, its IAM the only lock
|
|
709
|
-
| `COMPUTE_AUTH` | `metadata` on Cloud Run, `gcloud` elsewhere | How the service gets its access tokens for the Compute Engine API
|
|
710
|
-
| `PORT`, `HOST` | `8080`, `0.0.0.0` on Cloud Run and `127.0.0.1` elsewhere | Where the service listens
|
|
711
|
-
| `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text
|
|
751
|
+
| Variable | Default | Description |
|
|
752
|
+
| ---------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
753
|
+
| `SANDBOX_ZONE` | required | The zone of the machines |
|
|
754
|
+
| `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…` |
|
|
755
|
+
| `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python` |
|
|
756
|
+
| `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager |
|
|
757
|
+
| `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128` |
|
|
758
|
+
| `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129` |
|
|
759
|
+
| `SANDBOX_PROXY_TOKEN` | required | The proxy's token |
|
|
760
|
+
| `SANDBOX_PROJECT` | the service's project | The project of the machines |
|
|
761
|
+
| `SANDBOX_NETWORK` | the default network | The machines' VPC network |
|
|
762
|
+
| `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>` |
|
|
763
|
+
| `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to |
|
|
764
|
+
| `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192` |
|
|
765
|
+
| `SANDBOX_DISK_GB` | `20` | The size of their disk |
|
|
766
|
+
| `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type |
|
|
767
|
+
| `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after |
|
|
768
|
+
| `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 |
|
|
769
|
+
| `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most |
|
|
770
|
+
| `SANDBOX_AGENT_PORT` | `8100` | The port of the agents |
|
|
771
|
+
| `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer |
|
|
772
|
+
| `SANDBOX_MAX_RUNNING` | none | The most sandboxes running at once: a creation or a resume beyond it is answered with a 429 (`GceSandboxCapacityError`, with `Retry-After`). Counted at each call, so two at the same instant may both pass |
|
|
773
|
+
| `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 |
|
|
774
|
+
| `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 |
|
|
775
|
+
| `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
|
|
776
|
+
| `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 |
|
|
777
|
+
| `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 |
|
|
778
|
+
| `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup |
|
|
779
|
+
| `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 |
|
|
780
|
+
| `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) |
|
|
781
|
+
| `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM |
|
|
782
|
+
| `SANDBOX_INSECURE_NO_TOKEN` | `false` | `true` to run on Cloud Run without `SANDBOX_SERVICE_TOKEN`, its IAM the only lock |
|
|
783
|
+
| `COMPUTE_AUTH` | `metadata` on Cloud Run, `gcloud` elsewhere | How the service gets its access tokens for the Compute Engine API |
|
|
784
|
+
| `PORT`, `HOST` | `8080`, `0.0.0.0` on Cloud Run and `127.0.0.1` elsewhere | Where the service listens |
|
|
785
|
+
| `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text |
|
|
712
786
|
|
|
713
787
|
### The proxy (`proxy`)
|
|
714
788
|
|
|
715
|
-
| Variable | Default | Description
|
|
716
|
-
| --------------------------------- | ------------------ |
|
|
717
|
-
| `SANDBOX_PROXY_TOKEN` | required | The token the service proves itself with, 16 characters at least
|
|
718
|
-
| `SANDBOX_PROXY_PORT` | `3128` | The port the sandboxes reach
|
|
719
|
-
| `SANDBOX_PROXY_ADMIN_PORT` | `3129` | The port of the administration API
|
|
720
|
-
| `
|
|
721
|
-
| `
|
|
722
|
-
| `
|
|
723
|
-
| `
|
|
724
|
-
| `
|
|
789
|
+
| Variable | Default | Description |
|
|
790
|
+
| --------------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
791
|
+
| `SANDBOX_PROXY_TOKEN` | required | The token the service proves itself with, 16 characters at least |
|
|
792
|
+
| `SANDBOX_PROXY_PORT` | `3128` | The port the sandboxes reach |
|
|
793
|
+
| `SANDBOX_PROXY_ADMIN_PORT` | `3129` | The port of the administration API |
|
|
794
|
+
| `SANDBOX_PROXY_TLS_PORT` | none | Where the proxy takes direct TLS connections, `443`: see [Programs that ignore the proxy variables](#programs-that-ignore-the-proxy-variables) |
|
|
795
|
+
| `SANDBOX_PROXY_HTTP_PORT` | none | Where it takes direct plain HTTP requests, `80`, likewise |
|
|
796
|
+
| `SANDBOX_ALLOW_PRIVATE_NETWORK` | `false` | For tests only: lets the sandboxes reach private addresses and plain HTTP base URLs |
|
|
797
|
+
| `SANDBOX_PROXY_MAX_CONNECTIONS` | `128` | The most connections the commands of a sandbox hold open through the proxy at once: [Connections](#connections) |
|
|
798
|
+
| `SANDBOX_PROXY_ROUTE_CONNECTIONS` | `32` | The connections a sandbox holds beyond those, for its base URL routes alone: [Connections](#connections) |
|
|
799
|
+
| `SANDBOX_PROXY_TOTAL_CONNECTIONS` | from `LimitNOFILE` | The most connections the proxy holds for all its sandboxes, a tenth kept for the routes: [Connections](#connections) |
|
|
800
|
+
| `HOST`, `LOG_FORMAT` | `0.0.0.0` | Where it listens; `text` for plain logs |
|
|
725
801
|
|
|
726
802
|
### The agent (`agent`)
|
|
727
803
|
|
|
@@ -733,8 +809,9 @@ The MCP servers that [`ai-sdk-harness-plugins`](https://ai-sdk-harness.pages.dev
|
|
|
733
809
|
| `SANDBOX_PATH` | `/usr/local/sbin:/usr/local/bin:/usr/sbin:…` | Their `PATH` |
|
|
734
810
|
| `SANDBOX_AGENT_PORT` | `8100` | Where the agent listens |
|
|
735
811
|
| `SANDBOX_AGENT_TOKEN` | the instance's `ai-sdk-sandbox-agent-token` | Its token: the service puts it in the instance metadata |
|
|
736
|
-
| `SANDBOX_STATE_DIR` | `/var/lib/ai-sdk-sandbox` | Where it keeps the network configuration, root's
|
|
812
|
+
| `SANDBOX_STATE_DIR` | `/var/lib/ai-sdk-sandbox` | Where it keeps the network configuration and the samples of the machine, root's |
|
|
737
813
|
| `SANDBOX_CONFIGURE_DOCKER` | `true` | `false` to leave Docker's proxy settings alone |
|
|
814
|
+
| `SANDBOX_METRICS_INTERVAL` | `30` | Seconds between two samples of the machine; `0` for none but those a stop or a deletion takes |
|
|
738
815
|
| `SANDBOX_RUN_DIR` | `/run/ai-sdk-sandbox` | Where it marks it was configured since the machine booted, emptied at each boot: an agent restarted then never powers a machine off |
|
|
739
816
|
|
|
740
817
|
A sandbox's commands run with nothing of the agent's environment: only their `PATH`, `HOME`, `USER`, the proxy and base URL variables, and the variables the command sets.
|
|
@@ -743,10 +820,150 @@ A sandbox's commands run with nothing of the agent's environment: only their `PA
|
|
|
743
820
|
|
|
744
821
|
- `GceSandboxImageError`: the image of a new sandbox lacks a command of `requiredCommands`. Carries `sandboxId` and `missing`.
|
|
745
822
|
- `GceSandboxNotFoundError`: `resumeGceNetworkSandboxSession()` found no sandbox of that name, running or stopped. Carries `sandboxId`.
|
|
823
|
+
- `GceSandboxCapacityError`: the service runs as many sandboxes as `SANDBOX_MAX_RUNNING` allows, and refused to create or resume one more. Carries `running`, `max` and `retryAfterSeconds` (also the answer's `Retry-After`): queue the call and try again after it, or stop a sandbox. A `GceSandboxServiceError` with `status` 429, so code that checks the status goes on working. The count is made at each call: two calls at the same instant may both pass, and run one sandbox more than the most.
|
|
746
824
|
- `GceSandboxServiceError`: the service answered with an error status: 409 for a name already taken, 400 for an image it does not offer or a command carrying a credential, 504 for a machine whose agent did not answer in time. Carries `request` and `status`.
|
|
747
825
|
- `HarnessSandboxAuthenticationError` (from `@ai-sdk/harness`): Cloud Run refused the call (401 or 403), or the service token is missing or wrong.
|
|
748
826
|
- `HarnessCapabilityUnsupportedError` (from `@ai-sdk/harness`): a port that is not exposed, or a network policy with CIDR rules.
|
|
749
827
|
|
|
828
|
+
## Usage and cost of a sandbox
|
|
829
|
+
|
|
830
|
+
The machine has no service account, and reaches nothing but the egress proxy: what a sandbox costs is read from outside, from the service, by the application.
|
|
831
|
+
|
|
832
|
+
### Labels
|
|
833
|
+
|
|
834
|
+
`labels` puts labels of yours on the sandbox's machine and on its disk, beside the service's own (`ai-sdk-sandbox`, `ai-sdk-sandbox-name`…): a [Cloud Billing export](https://cloud.google.com/billing/docs/how-to/export-data-bigquery) or a budget then groups their cost by them.
|
|
835
|
+
|
|
836
|
+
```ts
|
|
837
|
+
const sandbox = await createGceNetworkSandboxSession({
|
|
838
|
+
url,
|
|
839
|
+
template: await agent.getSandboxTemplate(),
|
|
840
|
+
labels: { app: 'studio', tenant: 'acme', session: 's-42' },
|
|
841
|
+
});
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
Keys start with a lowercase letter, then lowercase letters, digits, `_` or `-`; values take the same characters and may be empty; 63 characters at most each, 56 labels at most. Keys starting with `ai-sdk-` are the package's and are refused. A machine taken from the warm pool gets them as it is taken, and so does its disk, the pool's until then; a template's builder gets those of the creation that builds it. A resume keeps them as they are.
|
|
845
|
+
|
|
846
|
+
### Its machine
|
|
847
|
+
|
|
848
|
+
`describeGceSandbox({ url, sandboxId })`, or `describe()` of a session, reads the sandbox's machine from Compute Engine, running or stopped, without starting it:
|
|
849
|
+
|
|
850
|
+
```ts
|
|
851
|
+
import { describeGceSandbox } from 'ai-sdk-sandbox-gce';
|
|
852
|
+
|
|
853
|
+
const machine = await describeGceSandbox({ url, sandboxId: 'box' });
|
|
854
|
+
// {
|
|
855
|
+
// name: 'box', instance: 'sbx-box', zone: 'europe-west1-b', status: 'TERMINATED',
|
|
856
|
+
// creationTimestamp: '2026-11-25T10:00:00.000-08:00',
|
|
857
|
+
// lastStartTimestamp: '2026-11-25T10:00:20.000-08:00',
|
|
858
|
+
// lastStopTimestamp: '2026-11-25T11:00:00.000-08:00',
|
|
859
|
+
// provisioningModel: 'STANDARD', spotFallback: true,
|
|
860
|
+
// machineType: 'e2-standard-4', diskSizeGb: 20, image: 'default', fromPool: false,
|
|
861
|
+
// labels: { app: 'studio', tenant: 'acme', session: 's-42' },
|
|
862
|
+
// }
|
|
863
|
+
```
|
|
864
|
+
|
|
865
|
+
`provisioningModel` is what the machine is billed as: a service of Spot machines (`SANDBOX_SPOT`) creates or starts a standard one when the zone has no Spot capacity left (`SANDBOX_SPOT_FALLBACK`), and `spotFallback` says so. The machine of a sandbox taken from the warm pool (`fromPool`) was made before the sandbox took it: `creationTimestamp` is the pool's. `labels` leaves the package's own out. It throws `GceSandboxNotFoundError` once the sandbox is deleted: Compute Engine deletes the machine some 50 s after the deletion returns, and it is answered `STOPPING` meanwhile, as a stopped one is until it is `TERMINATED`, its `lastStopTimestamp` set then. A service of an earlier version answers 405.
|
|
866
|
+
|
|
867
|
+
### How long it took
|
|
868
|
+
|
|
869
|
+
`timings` of the session returned by `createGceNetworkSandboxSession()` or `resumeGceNetworkSandboxSession()` says how long the call took on the service, in milliseconds, step by step:
|
|
870
|
+
|
|
871
|
+
```ts
|
|
872
|
+
const sandbox = await createGceNetworkSandboxSession({ url, template });
|
|
873
|
+
console.log(sandbox.timings);
|
|
874
|
+
// { fromPool: true, proxyMs: 3, insertMs: 412, bootMs: 1210, agentMs: 95, totalMs: 1890 }
|
|
875
|
+
```
|
|
876
|
+
|
|
877
|
+
| Field | What it measures |
|
|
878
|
+
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
879
|
+
| `fromPool` | The creation took a machine of the warm pool, booted ahead of it. Always `false` on a resume |
|
|
880
|
+
| `proxyMs` | Waiting for the egress proxy, booting when the service had stopped it (`SANDBOX_PROXY_INSTANCE`). It overlaps the steps below |
|
|
881
|
+
| `insertMs` | Compute Engine creating the machine, or the warm pool handing one over; on a resume, starting the stopped machine, or waiting for one |
|
|
882
|
+
| `bootMs` | The machine running and its guest booting, until its agent answers, while the proxy is waited for |
|
|
883
|
+
| `agentMs` | Registering the sandbox with the proxy and configuring its agent, the waits for either left out |
|
|
884
|
+
| `totalMs` | The whole call on the service, its checks included |
|
|
885
|
+
|
|
886
|
+
A template built by the creation is not counted: the creation of its builder, its setup and the image take minutes, once. A service of an earlier version answers no `timings`.
|
|
887
|
+
|
|
888
|
+
### What its connections carried
|
|
889
|
+
|
|
890
|
+
The egress proxy counts the bytes each sandbox's connections carry, outside the machine, where nothing the sandbox runs changes them: `bytesRead`, what the proxy read from the sandbox (its requests, its uploads, the TLS it sent through its tunnels), and `bytesWritten`, what it wrote to it (answers, downloads). `usage()` of a session, or `getGceSandboxUsage({ url, sandboxId })`, reads them while the sandbox runs:
|
|
891
|
+
|
|
892
|
+
```ts
|
|
893
|
+
import { getGceSandboxUsage } from 'ai-sdk-sandbox-gce';
|
|
894
|
+
|
|
895
|
+
const usage = await getGceSandboxUsage({ url, sandboxId: 'box' });
|
|
896
|
+
// { bytesRead: 48211, bytesWritten: 9134877, connections: 12, openConnections: 2,
|
|
897
|
+
// since: '2026-11-25T18:00:21.120Z' }
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
The count starts when the proxy registers the sandbox, at its creation or its resume from a stop, and covers the connections still open as they stand. The proxy keeps it in memory only: it forgets it with the sandbox, at a stop or a deletion, and loses it when it restarts. So **a stop and a deletion answer the last count**, read just before the proxy forgets the sandbox, in a report:
|
|
901
|
+
|
|
902
|
+
```ts
|
|
903
|
+
const sandbox = await createGceNetworkSandboxSession({
|
|
904
|
+
url,
|
|
905
|
+
// Each time a view of the sandbox stops or destroys it, ai-sdk-harness-sessions included.
|
|
906
|
+
onUsageReport: async (report) => {
|
|
907
|
+
// { name: 'box', event: 'suspend', at: '2026-11-25T19:02:00.000Z', egress: { … } }
|
|
908
|
+
await saveUsage(report);
|
|
909
|
+
},
|
|
910
|
+
});
|
|
911
|
+
await sandbox.stop();
|
|
912
|
+
console.log(sandbox.lastReport);
|
|
913
|
+
|
|
914
|
+
// Deleting a sandbox by its id reports too.
|
|
915
|
+
await deleteGceSandbox({ url, sandboxId: 'box', onUsageReport: saveUsage });
|
|
916
|
+
```
|
|
917
|
+
|
|
918
|
+
`onUsageReport` is awaited, an error it throws ignored. `lastReport` holds the report of the last `stop()` or `destroy()` of that view. Reading the count of a stopped sandbox fails with `GceSandboxServiceError` (404): its stop answered it. A proxy of an earlier version counts nothing: its reports have no `egress`, and `usage()` fails with a 404.
|
|
919
|
+
|
|
920
|
+
### What its machine went through
|
|
921
|
+
|
|
922
|
+
The agent of each machine samples it every 30 s, from `/proc` alone: the share of the CPUs busy (`cpuPercent`) and stolen by the hypervisor (`cpuStealPercent`) since the sample before, the memory in use (`memoryUsedBytes` of `memoryTotalBytes`), the pressure on both when the kernel reports it (`cpuPressure`, `memoryPressure`, from `/proc/pressure`), and the processes the kernel killed for want of memory since the boot (`oomKills`). It keeps the last day of samples in its state directory (`/var/lib/ai-sdk-sandbox/metrics.jsonl`), on the machine's disk: they outlive a stop. A machine made from a template does not inherit the samples of the machine that built it: the agent keeps only those of its own machine, by the id of the instance. `metrics()` of a session, or `getGceSandboxMetrics({ url, sandboxId, since })`, reads them while the sandbox runs, those after `since` when given:
|
|
923
|
+
|
|
924
|
+
```ts
|
|
925
|
+
import { getGceSandboxMetrics } from 'ai-sdk-sandbox-gce';
|
|
926
|
+
|
|
927
|
+
let since: string | undefined;
|
|
928
|
+
const { intervalSeconds, samples } = await getGceSandboxMetrics({ url, sandboxId: 'box', since });
|
|
929
|
+
// samples: [{ at: '2026-11-25T18:01:00.000Z', cpuPercent: 37.5, cpuStealPercent: 0, cpuCount: 4,
|
|
930
|
+
// memoryUsedBytes: 2147483648, memoryTotalBytes: 16777216000,
|
|
931
|
+
// cpuPressure: { someAvg10: 2.1, someAvg60: 1.3, fullAvg10: 0, fullAvg60: 0 },
|
|
932
|
+
// memoryPressure: { someAvg10: 0, someAvg60: 0, fullAvg10: 0, fullAvg60: 0 }, oomKills: 0 }, …]
|
|
933
|
+
since = samples.at(-1)?.at ?? since;
|
|
934
|
+
```
|
|
935
|
+
|
|
936
|
+
A stop and a deletion read the last ones before the machine goes, a sample taken then, those since the machine last started: the report handed to `onUsageReport` holds them in `metrics`, beside `egress`. The agent runs in the machine, where the sandbox's user has `sudo`: what it reports is fit for sizing the machines and `SANDBOX_MAX_RUNNING`, never for billing, which [the labels](#labels) and the proxy's count are for. An image built with an earlier version of the package samples nothing: `metrics()` fails with a 501, and the reports have no `metrics`. Build the image again to get them.
|
|
937
|
+
|
|
938
|
+
### Its logs
|
|
939
|
+
|
|
940
|
+
The service logs each creation, resume, suspension and deletion as a JSON line (`LOG_FORMAT=json`, the default on Cloud Run), which Cloud Logging reads as a structured entry, for a log-based metric or a BigQuery sink:
|
|
941
|
+
|
|
942
|
+
```json
|
|
943
|
+
{
|
|
944
|
+
"event": "create",
|
|
945
|
+
"sandbox": "box",
|
|
946
|
+
"at": "2026-11-25T18:00:21.120Z",
|
|
947
|
+
"instance": "sbx-pool-1a2b3c4d",
|
|
948
|
+
"image": "default",
|
|
949
|
+
"template": "ai-sdk-harness-template-…",
|
|
950
|
+
"labels": { "app": "studio" },
|
|
951
|
+
"timings": {
|
|
952
|
+
"fromPool": true,
|
|
953
|
+
"proxyMs": 3,
|
|
954
|
+
"insertMs": 412,
|
|
955
|
+
"bootMs": 1210,
|
|
956
|
+
"agentMs": 95,
|
|
957
|
+
"totalMs": 1890
|
|
958
|
+
},
|
|
959
|
+
"severity": "INFO",
|
|
960
|
+
"message": "box created in 1890 ms on sbx-pool-1a2b3c4d of the warm pool",
|
|
961
|
+
"time": "2026-11-25T18:00:21.120Z"
|
|
962
|
+
}
|
|
963
|
+
```
|
|
964
|
+
|
|
965
|
+
`resume` carries `instance` and `timings`; `suspend` and `delete` carry `instance`, its `status`, `egress` (the proxy's last count) and `samples` (how many samples the report holds). With `LOG_FORMAT=text`, only the message is written. A Spot machine Compute Engine took back is in its audit logs (`compute.instances.preempted`), not in the service's.
|
|
966
|
+
|
|
750
967
|
## Cost
|
|
751
968
|
|
|
752
969
|
A machine is billed by the second while it runs, and only for its disk once stopped: in `europe-west1`, an `e2-standard-4` is in the order of $0.15 an hour, Spot much less, and a stopped 20 GB balanced disk about $2 a month. The proxy machine, an `e2-small`, is about $15 a month when always on, its external address a few dollars more; with `SANDBOX_PROXY_INSTANCE`, both are billed only while a sandbox runs. The service scales to zero. Check the current [Compute Engine pricing](https://cloud.google.com/compute/vm-instance-pricing).
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { GceSandboxServiceError } from './gce-sandbox-service-error.js';
|
|
2
|
+
/**
|
|
3
|
+
* The service runs as many sandboxes as its `SANDBOX_MAX_RUNNING` allows, and refused to create or
|
|
4
|
+
* resume one more: answered with a 429, its `status`. Wait `retryAfterSeconds`, or stop a sandbox,
|
|
5
|
+
* and try again: queue the call rather than fail it. The count is made at each call, so two calls
|
|
6
|
+
* at once may both pass, and run one sandbox more than the most.
|
|
7
|
+
*/
|
|
8
|
+
export declare class GceSandboxCapacityError extends GceSandboxServiceError {
|
|
9
|
+
/** The sandboxes running, or booting, when the call was refused. */
|
|
10
|
+
readonly running: number;
|
|
11
|
+
/** The most the service runs at once. */
|
|
12
|
+
readonly max: number;
|
|
13
|
+
/** How long the service says to wait before trying again, in seconds. */
|
|
14
|
+
readonly retryAfterSeconds: number;
|
|
15
|
+
constructor(request: string, message: string, { running, max, retryAfterSeconds, }: {
|
|
16
|
+
running: number;
|
|
17
|
+
max: number;
|
|
18
|
+
retryAfterSeconds: number;
|
|
19
|
+
});
|
|
20
|
+
}
|