ai-sdk-sandbox-gce 0.3.0 → 0.3.2

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,23 @@
1
1
  # ai-sdk-sandbox-gce
2
2
 
3
+ ## 0.3.2
4
+
5
+ ### Patch Changes
6
+
7
+ - b40ea5d: `prepareGceSandboxService({ url, auth })` has the service boot its egress proxy ahead of a sandbox, when it starts and stops it (`SANDBOX_PROXY_INSTANCE`), without waiting for it: call it as soon as a sandbox is likely to be asked for, and the sandbox finds the proxy up rather than waiting some 40 s for its machine. The service answers it at `POST /v1/prepare`; a service of an earlier version answers 404, which the client takes as nothing to do.
8
+
9
+ Should no sandbox come, the proxy exits after `SANDBOX_PROXY_IDLE_EXIT_MINUTES` with no sandbox, with the exit code 100, on which the unit of the README stops its machine: set to 10 minutes there. The proxy never exits by itself without the variable: leave it out of the unit of a proxy always on.
10
+ - b40ea5d: The proxy's startup script in the README lets systemd start the proxy as its machine boots again, some 25 s before the startup script runs: a sandbox waited for the script since 0.3.0, about 60 s for a stopped proxy rather than 35 s. A condition of its unit (`ExecCondition`) only lets the proxy start at boot when it is the version the script pins, its new `VERSION` line: after a change of version, the script upgrades it and starts it, as 0.3.0 does. The script also restarts the network's resolver only when its settings change. Hand the new script to the proxy's machine (`gcloud compute instances add-metadata … --metadata-from-file=startup-script=proxy-startup.sh`).
11
+ - a9d2fe3: The sandbox service's image is published to Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`, with a provenance attestation: deploy it with `gcloud run deploy --image`, rather than writing a `Dockerfile` and having Cloud Build make it with an account of its own. The README deploys it so.
12
+ - b40ea5d: The client deletes a template's throwaway sandbox once the sandbox made from the template runs, rather than as soon as the template is saved. With `SANDBOX_PROXY_INSTANCE`, no sandbox ran in between: the service stopped the egress proxy, and the sandbox that followed waited a whole minute for it to boot again.
13
+
14
+ ## 0.3.1
15
+
16
+ ### Patch Changes
17
+
18
+ - f6225e5: The README pins `ai-sdk-sandbox-gce@0.3.0` in the service's Dockerfile, the proxy's startup script and the sandbox image, rather than `0.2.0`: the service of 0.3.0 makes the proxy forget the sandboxes whose machine no longer runs, which takes a proxy of the same version.
19
+ - a9476c5: The READMEs deploy the service with a build account of its own, `--build-service-account` granted `roles/run.builder`, rather than the Compute Engine default service account, which older projects grant `roles/editor`: whatever a build ran could then reach everything in the project, the agents' tokens included. The sandbox-gce README also has the roles inherited from the folder and the organization checked, since they read the machines' metadata as well.
20
+
3
21
  ## 0.3.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -134,15 +134,27 @@ gcloud compute instances create sandbox-proxy --zone=$ZONE --machine-type=e2-sma
134
134
  ```bash title="proxy-startup.sh"
135
135
  #!/bin/sh
136
136
  set -e
137
+ # The version of the proxy: the one your application depends on.
138
+ VERSION=0.3.2
139
+ # Writes $2 to the file $1 when it differs, and says whether it did.
140
+ changed() {
141
+ mkdir -p "$(dirname "$1")"
142
+ if printf '%b' "$2" | cmp -s - "$1"; then return 1; fi
143
+ printf '%b' "$2" > "$1"
144
+ }
137
145
  # Public resolvers, not the metadata server's, which the sandboxes' response policy answers.
138
- mkdir -p /etc/systemd/resolved.conf.d
139
146
  # After gce-resolved.conf, which adds the metadata server: the empty DNS= resets the list.
140
- printf '[Resolve]\nDNS=\nDNS=8.8.8.8 1.1.1.1\nDomains=~.\n' > /etc/systemd/resolved.conf.d/public-dns.conf
147
+ dns=false
148
+ if changed /etc/systemd/resolved.conf.d/public-dns.conf '[Resolve]\nDNS=\nDNS=8.8.8.8 1.1.1.1\nDomains=~.\n'; then
149
+ dns=true
150
+ fi
141
151
  for network in /run/systemd/network/*.network; do
142
- mkdir -p "/etc/systemd/network/$(basename "$network").d"
143
- printf '[DHCPv4]\nUseDNS=false\n' > "/etc/systemd/network/$(basename "$network").d/no-dhcp-dns.conf"
152
+ if changed "/etc/systemd/network/$(basename "$network").d/no-dhcp-dns.conf" '[DHCPv4]\nUseDNS=false\n'; then
153
+ dns=true
154
+ fi
144
155
  done
145
- systemctl restart systemd-networkd systemd-resolved
156
+ # Restarted on a change only: from the second boot on, the proxy already runs, resolving names.
157
+ if [ "$dns" = true ]; then systemctl restart systemd-networkd systemd-resolved; fi
146
158
  # Node.js and the Ops Agent from their signed apt repositories: no script piped into a shell.
147
159
  install -m 0755 -d /etc/apt/keyrings
148
160
  if ! command -v npm >/dev/null; then
@@ -154,8 +166,8 @@ if ! command -v npm >/dev/null; then
154
166
  fi
155
167
  # Installed again whenever the pinned version changes: the proxy then restarts on it, below.
156
168
  restart=false
157
- if ! npm ls --global ai-sdk-sandbox-gce@0.2.0 >/dev/null 2>&1; then
158
- npm install --global ai-sdk-sandbox-gce@0.2.0
169
+ if ! npm ls --global "ai-sdk-sandbox-gce@$VERSION" >/dev/null 2>&1; then
170
+ npm install --global "ai-sdk-sandbox-gce@$VERSION"
159
171
  restart=true
160
172
  fi
161
173
  # Its logs, the refusals among them, sent to Cloud Logging by the Ops Agent.
@@ -186,8 +198,17 @@ After=network-online.target
186
198
  Wants=network-online.target
187
199
 
188
200
  [Service]
201
+ # Started at boot only when it is the version this script pins: an earlier one would take the
202
+ # sandboxes the service registers meanwhile, and forget them as the script upgrades it.
203
+ ExecCondition=+/usr/local/bin/ai-sdk-sandbox-proxy-pinned
189
204
  ExecStart=/bin/sh -c 'SANDBOX_PROXY_TOKEN=$(/usr/local/bin/ai-sdk-sandbox-proxy-token) exec ai-sdk-sandbox-gce proxy'
190
205
  Restart=always
206
+ # With SANDBOX_PROXY_INSTANCE on the service: after 10 minutes with no sandbox, the proxy exits
207
+ # with 100 and its machine stops, should no sandbox come after prepareGceSandboxService(). Leave
208
+ # these three lines out for a proxy always on.
209
+ Environment=SANDBOX_PROXY_IDLE_EXIT_MINUTES=10
210
+ RestartPreventExitStatus=100
211
+ ExecStopPost=+/bin/sh -c 'if [ "$$EXIT_STATUS" = 100 ]; then systemctl poweroff; fi'
191
212
  DynamicUser=yes
192
213
  # Every sandbox holds up to SANDBOX_PROXY_MAX_CONNECTIONS (128) connections at once.
193
214
  LimitNOFILE=65536
@@ -200,9 +221,20 @@ if ! cmp -s /tmp/ai-sdk-sandbox-proxy.service /etc/systemd/system/ai-sdk-sandbox
200
221
  systemctl daemon-reload
201
222
  restart=true
202
223
  fi
203
- # Started here, once its package is the pinned one, and not by systemd at boot: the previous
204
- # version would take the sandboxes the service registers meanwhile, and forget them as it restarts.
205
- systemctl disable --quiet ai-sdk-sandbox-proxy
224
+ # Whether the installed proxy is the version the startup script in the metadata pins: read anew at
225
+ # each boot, before this script runs again.
226
+ cat > /usr/local/bin/ai-sdk-sandbox-proxy-pinned <<'SCRIPT'
227
+ #!/bin/sh
228
+ set -e
229
+ pinned=$(curl -fsS -H Metadata-Flavor:Google \
230
+ http://metadata.google.internal/computeMetadata/v1/instance/attributes/startup-script \
231
+ | sed -n 's/^VERSION=//p')
232
+ npm ls --global "ai-sdk-sandbox-gce@$pinned" >/dev/null 2>&1
233
+ SCRIPT
234
+ chmod 755 /usr/local/bin/ai-sdk-sandbox-proxy-pinned
235
+ # Started by systemd as the machine boots, seconds before this script runs, when its package is
236
+ # the pinned one; started here otherwise, once upgraded.
237
+ systemctl enable --quiet ai-sdk-sandbox-proxy
206
238
  if [ "$restart" = true ]; then
207
239
  systemctl restart ai-sdk-sandbox-proxy
208
240
  else
@@ -210,7 +242,7 @@ else
210
242
  fi
211
243
  ```
212
244
 
213
- Pin `ai-sdk-sandbox-gce` to the version your application depends on, here and in the two images below: every side checks that the others speak its protocol. Every version published by the release workflow carries a [provenance attestation](https://docs.npmjs.com/generating-provenance-statements): `npm audit signatures` checks it, in a project that depends on the package. To upgrade the proxy, change the version in the script, hand it to the machine again, and reboot it, or let the service start it with the next sandbox if it is stopped:
245
+ Pin `ai-sdk-sandbox-gce` to the version your application depends on, here and in the two images below: every side checks that the others speak its protocol. Every version published by the release workflow carries a [provenance attestation](https://docs.npmjs.com/generating-provenance-statements): `npm audit signatures` checks it, in a project that depends on the package. To upgrade the proxy, change `VERSION` in the script, hand it to the machine again, and reboot it, or let the service start it with the next sandbox if it is stopped:
214
246
 
215
247
  ```bash
216
248
  gcloud compute instances add-metadata sandbox-proxy --zone=$ZONE \
@@ -218,7 +250,7 @@ gcloud compute instances add-metadata sandbox-proxy --zone=$ZONE \
218
250
  gcloud compute instances reset sandbox-proxy --zone=$ZONE
219
251
  ```
220
252
 
221
- The proxy need not run when no sandbox does: set `SANDBOX_PROXY_INSTANCE=sandbox-proxy` on the service (step 4), which then starts it with the first sandbox, booting alongside it, and stops it once none runs. Its startup script runs again at each boot, and its registrations, held in memory, are made again by the sandboxes that start.
253
+ The proxy need not run when no sandbox does: set `SANDBOX_PROXY_INSTANCE=sandbox-proxy` on the service (step 4), which then starts it with the first sandbox, booting alongside it, and stops it once none runs. A sandbox then waits some 40 s for the proxy to boot: call `prepareGceSandboxService()` (see [Usage](#usage)) as soon as one is likely to be asked for, and it finds the proxy up. Its startup script runs again at each boot, and its registrations, held in memory, are made again by the sandboxes that start.
222
254
 
223
255
  ### 3. The sandbox image
224
256
 
@@ -244,7 +276,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
244
276
  > /etc/apt/sources.list.d/nodesource.list
245
277
  apt-get update
246
278
  apt-get install -y nodejs
247
- npm install --global ai-sdk-sandbox-gce@0.2.0 pnpm@10
279
+ npm install --global ai-sdk-sandbox-gce@0.3.2 pnpm@10
248
280
 
249
281
  # The sandbox's user: sudo without a password, and Docker.
250
282
  useradd --create-home --shell /bin/bash agent
@@ -271,13 +303,7 @@ The agent runs as root and starts the commands as `agent`. It does not wait for
271
303
 
272
304
  ### 4. The service
273
305
 
274
- The service's image is the package and Node.js:
275
-
276
- ```dockerfile title="Dockerfile"
277
- FROM node:24-bookworm-slim
278
- RUN npm install --global --silent ai-sdk-sandbox-gce@0.2.0 && npm cache clean --force
279
- CMD ["ai-sdk-sandbox-gce", "serve"]
280
- ```
306
+ 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.3.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.
281
307
 
282
308
  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-`).
283
309
 
@@ -315,7 +341,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
315
341
  --member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
316
342
  done
317
343
 
318
- gcloud run deploy sandboxes --region=$REGION --source=. \
344
+ gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.2 \
319
345
  --service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
320
346
  --network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
321
347
  --no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
@@ -331,6 +357,7 @@ gcloud run deploy sandboxes --region=$REGION --source=. \
331
357
  What these settings are for:
332
358
 
333
359
  - `--network`, `--subnet`, `--vpc-egress`: Direct VPC egress, so that the service reaches the agents and the proxy on their internal addresses.
360
+ - `--image`: Cloud Run resolves the tag to its digest when it deploys a revision, which runs that image whatever is pushed under the tag later. Nothing is built in your project: no Cloud Build, and no build account to keep away from the agents' tokens.
334
361
  - `sandboxService`: create, stop, start and delete the machines, save a template as an image, start and stop the proxy; nothing outside the names of the condition. A missing permission shows in `pnpm test:e2e`.
335
362
  - `SANDBOX_PROXY_INSTANCE`: the proxy only runs while a sandbox does. `SANDBOX_MAX_RUNNING`: the machines running at once, a cap on the bill. `SANDBOX_MAX_RUN_HOURS`: Compute Engine stops a machine after so long, whatever happens.
336
363
  - `SANDBOX_SERVICE_TOKEN`: a second lock beside Cloud Run's IAM, should the service ever be deployed open; the client hands it over as `serviceToken`. The service refuses to start on Cloud Run without it, unless `SANDBOX_INSECURE_NO_TOKEN=true`.
@@ -347,7 +374,7 @@ gcloud run services add-iam-policy-binding sandboxes --region=$REGION \
347
374
  --member=serviceAccount:my-app@$PROJECT.iam.gserviceaccount.com --role=roles/run.invoker
348
375
  ```
349
376
 
350
- Anyone with that role and the service token can run commands in every sandbox of the service: grant it to your application, not to people who only need to read logs, and hand the token to the client as `serviceToken` (`gcloud secrets versions access latest --secret=sandbox-service-token`). Each agent's token sits in its machine's metadata, which anyone allowed `compute.instances.get` on the project reads (`roles/viewer`, `roles/compute.viewer`): with a foothold in the `service` subnetwork as well, they run commands in that sandbox as root, until the sandbox is next stopped, which draws it a new token. Grant those roles sparingly, and keep the subnetwork to the service alone.
377
+ Anyone with that role and the service token can run commands in every sandbox of the service: grant it to your application, not to people who only need to read logs, and hand the token to the client as `serviceToken` (`gcloud secrets versions access latest --secret=sandbox-service-token`). Each agent's token sits in its machine's metadata, which anyone allowed `compute.instances.get` on the project reads (`roles/viewer`, `roles/compute.viewer`): with a foothold in the `service` subnetwork as well, they run commands in that sandbox as root, until the sandbox is next stopped, which draws it a new token. Grant those roles sparingly, and keep the subnetwork to the service alone. Roles granted on the project's folder or organization count as well: `gcloud projects get-ancestors-iam-policy $PROJECT` lists them.
351
378
 
352
379
  Read the service's URL with `gcloud run services describe sandboxes --region=$REGION --format='value(status.url)'`; the examples below read it from `GCE_SANDBOX_URL`.
353
380
 
@@ -395,6 +422,19 @@ try {
395
422
 
396
423
  `auth` takes `'gcloud'` (the default: `gcloud auth print-identity-token`), `'metadata'` (the workload's service account on Google Cloud), `'none'`, or a function returning an identity token for the service's URL, such as one from `google-auth-library`.
397
424
 
425
+ When the service starts and stops the egress proxy (`SANDBOX_PROXY_INSTANCE`), the first sandbox after a quiet spell waits for the proxy's machine to boot. Ask the service to boot it as soon as a sandbox is likely to be asked for, a person reading what is about to run, say, and the sandbox finds it up:
426
+
427
+ ```ts
428
+ import { prepareGceSandboxService } from 'ai-sdk-sandbox-gce';
429
+
430
+ // Not awaited: it only starts the proxy's machine, and an error changes nothing for the sandboxes.
431
+ void prepareGceSandboxService({ url: process.env.GCE_SANDBOX_URL!, auth: 'metadata' }).catch(
432
+ () => undefined,
433
+ );
434
+ ```
435
+
436
+ The proxy stops again with the next sandbox that stops, or by itself after 10 minutes when none comes (`SANDBOX_PROXY_IDLE_EXIT_MINUTES` in its unit). A service that keeps its proxy always on, or of an earlier version, does nothing.
437
+
398
438
  ## Images and toolchains
399
439
 
400
440
  Every sandbox boots from an image the service offers: `SANDBOX_IMAGE`, its default, and those `SANDBOX_IMAGES` names, one per toolchain say. A caller picks one by its name, never by its path:
@@ -676,7 +716,7 @@ The steps above set up the network, the proxy and the service as they ran on Goo
676
716
  - [ ] **Set a budget alert** on the project, and keep the region's vCPU quota low: unlike an alert, a quota stops the spending.
677
717
  - [ ] **Restrict the service's ingress** when your application runs on Google Cloud: `gcloud run services update sandboxes --region=$REGION --ingress=internal`, the application then reaching it through the VPC (Direct VPC egress with `--vpc-egress=all-traffic`). Called from outside Google Cloud, the service stays public, guarded by IAM and its token.
678
718
  - [ ] **Review the allowed hosts**: no `*`, no wildcard on a shared domain, a package registry only where the agent installs packages. Each is a way out for the sandbox's files.
679
- - [ ] **Grant `roles/viewer` and `roles/compute.viewer` sparingly**: they read the agents' tokens in the machines' metadata.
719
+ - [ ] **Grant `roles/viewer` and `roles/compute.viewer` sparingly**: they read the agents' tokens in the machines' metadata. Check the roles inherited from the folder and the organization too (`gcloud projects get-ancestors-iam-policy $PROJECT`), and that no service account, the Compute Engine default one first, holds `roles/editor`.
680
720
  - [ ] **Authenticate your users** before anything reaches the service: whoever can call your application runs commands in its sandboxes. With Google accounts, a sign-in limited to your domain (Google OAuth, the `hd` claim checked on the server); on Google Cloud, [Identity-Aware Proxy](https://cloud.google.com/iap/docs/enabling-cloud-run) in front of the application. Either way, `roles/run.invoker` on the service goes to the application's service account alone, and the application checks on the server, at every call, that the sandbox belongs to the user.
681
721
 
682
722
  ## Limitations
@@ -1,4 +1,4 @@
1
- import type { GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions } from '../gce-settings.js';
1
+ import type { GceConnectionSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions } from '../gce-settings.js';
2
2
  import { GceNetworkSandboxSession } from '../session/gce-network-sandbox-session.js';
3
3
  /**
4
4
  * Creates a sandbox, a [Compute Engine](https://cloud.google.com/compute) virtual machine of its
@@ -15,6 +15,16 @@ import { GceNetworkSandboxSession } from '../session/gce-network-sandbox-session
15
15
  * both.
16
16
  */
17
17
  export declare function createGceNetworkSandboxSession(options: GceNetworkSandboxSessionCreateOptions): Promise<GceNetworkSandboxSession>;
18
+ /**
19
+ * Has the sandbox service at `url` boot what a sandbox needs, its egress proxy when the service
20
+ * starts and stops it, without waiting for it: call it as soon as a sandbox is likely to be asked
21
+ * for, the person who launches it still reading what will run, and the creation that follows finds
22
+ * the proxy up. The proxy stops again with the next sandbox that stops, or by itself when none is
23
+ * made. A service that does not drive its proxy, or of an earlier version, does nothing.
24
+ */
25
+ export declare function prepareGceSandboxService(options: GceConnectionSettings & {
26
+ abortSignal?: AbortSignal;
27
+ }): Promise<void>;
18
28
  /**
19
29
  * Reattaches to a sandbox made by {@link createGceNetworkSandboxSession}, from this process or
20
30
  * another one: a running sandbox as it is, a stopped one started again on its disk. Never creates
@@ -22,6 +22,16 @@ function clientOf({ url, auth = 'gcloud', serviceToken, }) {
22
22
  function sessionOf(client, { name, workingDirectory }, settings) {
23
23
  return new GceNetworkSandboxSession({ client, name, workingDirectory, processes: new Set() }, settings.ports ?? []);
24
24
  }
25
+ /** Creates the sandbox `name`, from `template` when given, its builder removed once it runs. */
26
+ async function createFrom(client, name, { template, ...options }) {
27
+ try {
28
+ return await client.create(name, { ...options, template: template?.id });
29
+ }
30
+ finally {
31
+ // Not before: with no sandbox running in between, the service would stop the egress proxy.
32
+ await template?.releaseBuilder();
33
+ }
34
+ }
25
35
  /**
26
36
  * Creates a sandbox, a [Compute Engine](https://cloud.google.com/compute) virtual machine of its
27
37
  * own, through the sandbox service at `url`, and returns a network sandbox session on it, to hand
@@ -45,13 +55,13 @@ export async function createGceNetworkSandboxSession(options) {
45
55
  assertSandboxName(name);
46
56
  const client = clientOf(options);
47
57
  const network = { allowedHosts, baseUrls };
48
- const templateId = template
58
+ const ready = template
49
59
  ? await ensureTemplate(client, { template, setup, network, image, requiredCommands }, abortSignal)
50
60
  : undefined;
51
- const description = await client.create(name, {
61
+ const description = await createFrom(client, name, {
52
62
  ...network,
53
63
  image,
54
- template: templateId,
64
+ template: ready,
55
65
  abortSignal,
56
66
  });
57
67
  const session = sessionOf(client, description, options);
@@ -69,6 +79,16 @@ export async function createGceNetworkSandboxSession(options) {
69
79
  throw error;
70
80
  }
71
81
  }
82
+ /**
83
+ * Has the sandbox service at `url` boot what a sandbox needs, its egress proxy when the service
84
+ * starts and stops it, without waiting for it: call it as soon as a sandbox is likely to be asked
85
+ * for, the person who launches it still reading what will run, and the creation that follows finds
86
+ * the proxy up. The proxy stops again with the next sandbox that stops, or by itself when none is
87
+ * made. A service that does not drive its proxy, or of an earlier version, does nothing.
88
+ */
89
+ export async function prepareGceSandboxService(options) {
90
+ await clientOf(options).prepare(options.abortSignal);
91
+ }
72
92
  /**
73
93
  * Reattaches to a sandbox made by {@link createGceNetworkSandboxSession}, from this process or
74
94
  * another one: a running sandbox as it is, a stopped one started again on its disk. Never creates
@@ -17,6 +17,16 @@ interface BuildSettings {
17
17
  /** Commands the image must have, checked before the setup. */
18
18
  requiredCommands: readonly string[];
19
19
  }
20
+ /** A template ready to boot from, and the builder it was made with, if this process made it. */
21
+ export interface ReadyTemplate {
22
+ id: string;
23
+ /**
24
+ * Removes the builder, once for all the sandboxes waiting for the template: after the first of
25
+ * them is created, so that a sandbox always runs meanwhile and the service keeps its egress proxy
26
+ * up. Never fails.
27
+ */
28
+ releaseBuilder(): Promise<void>;
29
+ }
20
30
  /**
21
31
  * The template's id: `ai-sdk-harness-template-<digest>`, the digest covering the harness's recipe
22
32
  * and the setup commands, so that a new harness version gets a template of its own.
@@ -25,9 +35,10 @@ export declare function templateId({ template, setup }: TemplateSource): string;
25
35
  /** Runs each of `setup` in the sandbox, in order, stopping at the first failure. */
26
36
  export declare function runSetup(session: GceNetworkSandboxSession, setup: readonly string[], abortSignal?: AbortSignal): Promise<void>;
27
37
  /**
28
- * The id of a template prepared by `source.template`, built the first time and reused afterwards:
29
- * one sandbox is created, set up, prepared and its disk saved as an image by the service, then
30
- * deleted. Every later sandbox boots from that image, the harness already installed.
38
+ * The template prepared by `source.template`, built the first time and reused afterwards: one
39
+ * sandbox is created, set up, prepared and its disk saved as an image by the service, then deleted
40
+ * by {@link ReadyTemplate.releaseBuilder}. Every later sandbox boots from that image, the harness
41
+ * already installed.
31
42
  */
32
- export declare function ensureTemplate(client: SandboxServiceClient, source: BuildSettings & TemplateSource, abortSignal?: AbortSignal): Promise<string>;
43
+ export declare function ensureTemplate(client: SandboxServiceClient, source: BuildSettings & TemplateSource, abortSignal?: AbortSignal): Promise<ReadyTemplate>;
33
44
  export {};
@@ -26,18 +26,28 @@ export async function runSetup(session, setup, abortSignal) {
26
26
  }
27
27
  }
28
28
  /**
29
- * The id of a template prepared by `source.template`, built the first time and reused afterwards:
30
- * one sandbox is created, set up, prepared and its disk saved as an image by the service, then
31
- * deleted. Every later sandbox boots from that image, the harness already installed.
29
+ * The template prepared by `source.template`, built the first time and reused afterwards: one
30
+ * sandbox is created, set up, prepared and its disk saved as an image by the service, then deleted
31
+ * by {@link ReadyTemplate.releaseBuilder}. Every later sandbox boots from that image, the harness
32
+ * already installed.
32
33
  */
33
34
  export function ensureTemplate(client, source, abortSignal) {
34
35
  const id = templateId(source);
35
36
  const key = `${client.baseUrl} ${source.image ?? ''} ${id}`;
36
37
  let ready = building.get(key);
37
38
  if (ready === undefined) {
38
- ready = client
39
- .templateExists(id, source.image, abortSignal)
40
- .then((exists) => (exists ? id : build(client, { ...source, id }, abortSignal)));
39
+ ready = client.templateExists(id, source.image, abortSignal).then(async (exists) => {
40
+ let builder = exists ? undefined : await build(client, { ...source, id }, abortSignal);
41
+ return {
42
+ id,
43
+ releaseBuilder: async () => {
44
+ const name = builder;
45
+ builder = undefined;
46
+ if (name !== undefined)
47
+ await client.remove(name).catch(() => undefined);
48
+ },
49
+ };
50
+ });
41
51
  building.set(key, ready);
42
52
  // A failed build is not remembered: the next sandbox tries again.
43
53
  ready.catch(() => building.delete(key));
@@ -47,16 +57,17 @@ export function ensureTemplate(client, source, abortSignal) {
47
57
  async function build(client, { template, setup, network, image, requiredCommands, id, }, abortSignal) {
48
58
  const builder = `${TEMPLATE_PREFIX}-${id.slice(-8)}-${randomBytes(3).toString('hex')}`;
49
59
  const { workingDirectory } = await client.create(builder, { ...network, image, abortSignal });
60
+ // Answered once saved, for the caller to remove it; removed here when anything fails.
50
61
  try {
51
62
  const session = new GceNetworkSandboxSession({ client, name: builder, workingDirectory, processes: new Set() }, []);
52
63
  await runSetup(session, setup, abortSignal);
53
64
  await assertRequiredCommands(session, requiredCommands, abortSignal);
54
65
  await template.prepare({ session: session.restricted(), abortSignal });
55
- // Removed below only once saved: its disk is what the template's image is made of.
56
66
  await client.saveTemplate(builder, id, { image, abortSignal });
57
- return id;
67
+ return builder;
58
68
  }
59
- finally {
69
+ catch (error) {
60
70
  await client.remove(builder).catch(() => undefined);
71
+ throw error;
61
72
  }
62
73
  }
@@ -75,6 +75,8 @@ export declare class SandboxServiceClient {
75
75
  }): Promise<void>;
76
76
  /** Whether the template `id` exists, made on the image `image` (the service's default without). */
77
77
  templateExists(id: string, image?: string, abortSignal?: AbortSignal): Promise<boolean>;
78
+ /** Boots what a sandbox needs ahead of it. A service without the route answers 404: it is fine. */
79
+ prepare(abortSignal?: AbortSignal): Promise<void>;
78
80
  deleteTemplate(id: string, image?: string): Promise<void>;
79
81
  /**
80
82
  * Where a port of the sandbox is reached: a WebSocket through the service. The token is read
@@ -166,6 +166,10 @@ export class SandboxServiceClient {
166
166
  });
167
167
  return response.status !== 404;
168
168
  }
169
+ /** Boots what a sandbox needs ahead of it. A service without the route answers 404: it is fine. */
170
+ async prepare(abortSignal) {
171
+ await this.call('POST', 'v1/prepare', { abortSignal, accept: [404] });
172
+ }
169
173
  async deleteTemplate(id, image) {
170
174
  await this.call('DELETE', templatePath(id, image));
171
175
  }
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { GceSandboxImageError } from './client/errors/gce-sandbox-image-error.js
2
2
  export { GceSandboxNotFoundError } from './client/errors/gce-sandbox-not-found-error.js';
3
3
  export { GceSandboxServiceError } from './client/errors/gce-sandbox-service-error.js';
4
4
  export type { GceAuth, GceConnectionSettings, GceCreationSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, } from './client/gce-settings.js';
5
- export { createGceNetworkSandboxSession, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
5
+ export { createGceNetworkSandboxSession, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
6
6
  export { GCE_SANDBOX_PROVIDER_ID } from './client/provider-id.js';
7
7
  export { GceNetworkSandboxSession } from './client/session/gce-network-sandbox-session.js';
8
8
  export { GceSandboxSession } from './client/session/gce-sandbox-session.js';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { GceSandboxImageError } from './client/errors/gce-sandbox-image-error.js';
2
2
  export { GceSandboxNotFoundError } from './client/errors/gce-sandbox-not-found-error.js';
3
3
  export { GceSandboxServiceError } from './client/errors/gce-sandbox-service-error.js';
4
- export { createGceNetworkSandboxSession, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
4
+ export { createGceNetworkSandboxSession, prepareGceSandboxService, resumeGceNetworkSandboxSession, } from './client/lifecycle/create-session.js';
5
5
  export { GCE_SANDBOX_PROVIDER_ID } from './client/provider-id.js';
6
6
  export { GceNetworkSandboxSession } from './client/session/gce-network-sandbox-session.js';
7
7
  export { GceSandboxSession } from './client/session/gce-sandbox-session.js';
@@ -0,0 +1,14 @@
1
+ /** The proxy's exit code once idle: its systemd unit powers the machine off on it, and only on it. */
2
+ export declare const IDLE_EXIT_CODE = 100;
3
+ /**
4
+ * Calls `onIdle` once no sandbox was registered for `idleMs`, counted from now: a proxy the service
5
+ * started ahead of a sandbox that never came, or one the service could not stop, powers its machine
6
+ * off rather than run unused. Returns what stops the watch.
7
+ */
8
+ export declare function watchIdle({ idleMs, sandboxes, onIdle, now, }: {
9
+ idleMs: number;
10
+ /** How many sandboxes the proxy serves. */
11
+ sandboxes: () => number;
12
+ onIdle: () => void;
13
+ now?: () => number;
14
+ }): () => void;
@@ -0,0 +1,22 @@
1
+ /** The proxy's exit code once idle: its systemd unit powers the machine off on it, and only on it. */
2
+ export const IDLE_EXIT_CODE = 100;
3
+ /** How often the proxy checks whether it serves a sandbox. */
4
+ const CHECK_EVERY_MS = 30_000;
5
+ /**
6
+ * Calls `onIdle` once no sandbox was registered for `idleMs`, counted from now: a proxy the service
7
+ * started ahead of a sandbox that never came, or one the service could not stop, powers its machine
8
+ * off rather than run unused. Returns what stops the watch.
9
+ */
10
+ export function watchIdle({ idleMs, sandboxes, onIdle, now = Date.now, }) {
11
+ let busyAt = now();
12
+ const timer = setInterval(() => {
13
+ if (sandboxes() > 0)
14
+ busyAt = now();
15
+ else if (now() - busyAt >= idleMs) {
16
+ clearInterval(timer);
17
+ onIdle();
18
+ }
19
+ }, Math.min(CHECK_EVERY_MS, idleMs));
20
+ timer.unref();
21
+ return () => clearInterval(timer);
22
+ }
@@ -4,6 +4,8 @@ export declare function proxyConfig(env: Environment): {
4
4
  adminPort: number;
5
5
  allowPrivateNetwork: boolean;
6
6
  host: string;
7
+ /** How long the proxy runs with no sandbox before it exits for its machine to power off. */
8
+ idleExitMs?: number;
7
9
  maxConnections: number;
8
10
  port: number;
9
11
  token: string;
@@ -2,6 +2,7 @@ import { createLogger } from '../common/logger.js';
2
2
  import { DEFAULT_PROXY_ADMIN_PORT, DEFAULT_PROXY_PORT } from '../protocol/proxy.js';
3
3
  import { createAdminServer } from './admin-server.js';
4
4
  import { DEFAULT_MAX_CONNECTIONS, EgressProxy } from './egress-proxy.js';
5
+ import { IDLE_EXIT_CODE, watchIdle } from './idle-exit.js';
5
6
  import { SandboxRegistry } from './registry.js';
6
7
  /** The proxy's settings, from its environment, which the systemd unit of its machine sets. */
7
8
  export function proxyConfig(env) {
@@ -15,9 +16,20 @@ export function proxyConfig(env) {
15
16
  host: env['HOST'] ?? '0.0.0.0',
16
17
  allowPrivateNetwork: env['SANDBOX_ALLOW_PRIVATE_NETWORK'] === 'true',
17
18
  maxConnections: maxConnections(env['SANDBOX_PROXY_MAX_CONNECTIONS']),
19
+ idleExitMs: idleExitMs(env['SANDBOX_PROXY_IDLE_EXIT_MINUTES']),
18
20
  token,
19
21
  };
20
22
  }
23
+ /** `SANDBOX_PROXY_IDLE_EXIT_MINUTES`, a positive integer: never exits when unset. */
24
+ function idleExitMs(value) {
25
+ if (value === undefined || value === '')
26
+ return undefined;
27
+ const parsed = Number(value);
28
+ if (!Number.isInteger(parsed) || parsed < 1) {
29
+ throw new Error(`SANDBOX_PROXY_IDLE_EXIT_MINUTES: \`${value}\` is not a positive integer.`);
30
+ }
31
+ return parsed * 60_000;
32
+ }
21
33
  /** `SANDBOX_PROXY_MAX_CONNECTIONS`, a positive integer: {@link DEFAULT_MAX_CONNECTIONS} when unset. */
22
34
  function maxConnections(value) {
23
35
  if (value === undefined || value === '')
@@ -42,11 +54,23 @@ export function main(env) {
42
54
  const admin = createAdminServer({ registry, token: config.token, logger });
43
55
  proxy.server.listen(config.port, config.host, () => logger.info(`Egress proxy listening on ${config.host}:${config.port}`));
44
56
  admin.listen(config.adminPort, config.host, () => logger.info(`Administration API listening on ${config.host}:${config.adminPort}`));
57
+ const shutDown = (code) => {
58
+ proxy.close();
59
+ admin.closeAllConnections();
60
+ admin.close(() => process.exit(code));
61
+ };
45
62
  for (const signal of ['SIGTERM', 'SIGINT']) {
46
- process.once(signal, () => {
47
- proxy.close();
48
- admin.closeAllConnections();
49
- admin.close(() => process.exit(0));
63
+ process.once(signal, () => shutDown(0));
64
+ }
65
+ const { idleExitMs } = config;
66
+ if (idleExitMs !== undefined) {
67
+ watchIdle({
68
+ idleMs: idleExitMs,
69
+ sandboxes: () => registry.list().length,
70
+ onIdle: () => {
71
+ logger.info(`No sandbox for ${idleExitMs / 60_000} min: exiting for the machine to stop`);
72
+ shutDown(IDLE_EXIT_CODE);
73
+ },
50
74
  });
51
75
  }
52
76
  }
@@ -53,7 +53,7 @@ export declare class ComputeApi {
53
53
  /** The instances of the zone whose label `key` is `value`, every page of them. */
54
54
  listInstances(key: string, value: string): Promise<Instance[]>;
55
55
  insertInstance(body: Record<string, unknown>): Promise<void>;
56
- startInstance(name: string): Promise<void>;
56
+ startInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
57
57
  resumeInstance(name: string): Promise<void>;
58
58
  stopInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
59
59
  /** Changes how the stopped instance `name` is provisioned: from Spot to standard, say. */
@@ -36,8 +36,8 @@ export class ComputeApi {
36
36
  async insertInstance(body) {
37
37
  await this.change('POST', this.zonal('instances'), { body });
38
38
  }
39
- async startInstance(name) {
40
- await this.change('POST', this.zonal(`instances/${name}/start`));
39
+ async startInstance(name, { wait = true } = {}) {
40
+ await this.change('POST', this.zonal(`instances/${name}/start`), { wait });
41
41
  }
42
42
  async resumeInstance(name) {
43
43
  await this.change('POST', this.zonal(`instances/${name}/resume`));
@@ -28,6 +28,11 @@ export const ROUTES = [
28
28
  status: 200,
29
29
  body: { status: 'ok', protocol: PROTOCOL_VERSION, version: PACKAGE_VERSION },
30
30
  })),
31
+ // Beyond `ai-sdk-sandbox-cloud-run`'s API: boots what a sandbox will need, ahead of it.
32
+ route('POST', /^\/v1\/prepare$/, async ({ sandboxes }) => {
33
+ await sandboxes.prepare();
34
+ return NO_CONTENT;
35
+ }),
31
36
  route('POST', /^\/v1\/sandboxes$/, async ({ sandboxes, request }) => {
32
37
  const { name, ...options } = await network(request);
33
38
  return { status: 201, body: await sandboxes.create(name ?? '', options) };
@@ -146,6 +146,12 @@ export declare class Sandboxes {
146
146
  /** Whether the template `id` exists, made on the image `image`. */
147
147
  templateExists(id: string, image?: string): Promise<boolean>;
148
148
  deleteTemplate(id: string, image?: string): Promise<void>;
149
+ /**
150
+ * Starts the proxy's machine when the service drives it and it is stopped, without waiting for it
151
+ * to boot: a sandbox created soon after finds it up, rather than waiting for it. Nothing else:
152
+ * the proxy stops with the next sandbox that stops, or by itself when none comes.
153
+ */
154
+ prepare(): Promise<void>;
149
155
  /**
150
156
  * Starts the proxy's machine when the service drives it and it is stopped, and waits until the
151
157
  * proxy answers. Stopping, it is first let stop: its registrations go with it, and the sandboxes
@@ -268,6 +268,21 @@ export class Sandboxes {
268
268
  const name = await this.templateImageName(id, image);
269
269
  await this.options.compute.deleteImage(name);
270
270
  }
271
+ /**
272
+ * Starts the proxy's machine when the service drives it and it is stopped, without waiting for it
273
+ * to boot: a sandbox created soon after finds it up, rather than waiting for it. Nothing else:
274
+ * the proxy stops with the next sandbox that stops, or by itself when none comes.
275
+ */
276
+ async prepare() {
277
+ const { proxyInstance, compute, logger } = this.options;
278
+ if (proxyInstance === undefined)
279
+ return;
280
+ const current = await compute.getInstance(proxyInstance);
281
+ if (current?.status !== 'TERMINATED')
282
+ return;
283
+ logger.info(`Preparing: starting the egress proxy ${proxyInstance}`);
284
+ await compute.startInstance(proxyInstance, { wait: false });
285
+ }
271
286
  /**
272
287
  * Starts the proxy's machine when the service drives it and it is stopped, and waits until the
273
288
  * proxy answers. Stopping, it is first let stop: its registrations go with it, and the sandboxes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-sdk-sandbox-gce",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
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",