ai-sdk-sandbox-gce 0.3.3 → 0.3.5
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 +26 -0
- package/README.md +41 -24
- package/dist/client/gce-settings.d.ts +25 -1
- package/dist/client/lifecycle/create-session.d.ts +12 -9
- package/dist/client/lifecycle/create-session.js +17 -7
- package/dist/client/transport/sandbox-service-client.d.ts +9 -2
- package/dist/client/transport/sandbox-service-client.js +10 -3
- package/dist/in-vm/agent-config.js +45 -2
- package/dist/in-vm/agent-server.js +1 -1
- package/dist/in-vm/agent.d.ts +9 -0
- package/dist/in-vm/agent.js +12 -0
- package/dist/in-vm/idle-power-off.d.ts +28 -0
- package/dist/in-vm/idle-power-off.js +46 -0
- package/dist/in-vm/main.js +4 -0
- package/dist/in-vm/oom-policy.d.ts +23 -0
- package/dist/in-vm/oom-policy.js +50 -0
- package/dist/index.d.ts +1 -1
- package/dist/protocol/agent.d.ts +5 -0
- package/dist/protocol/agent.js +5 -0
- package/dist/server/http/routes.js +7 -2
- package/dist/server/sandboxes/sandboxes.d.ts +49 -6
- package/dist/server/sandboxes/sandboxes.js +154 -39
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# ai-sdk-sandbox-gce
|
|
2
2
|
|
|
3
|
+
## 0.3.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 7b6f2e5: The sandbox images carry the tools an agent most often reaches for: `make`, so it can run a project's Makefile, plus `jq`, `unzip` and `xz-utils`. The Compute Engine image script in the README also installs a C/C++ compiler (`build-essential`) for the native modules of a project's dependencies; the Cloud Run image leaves it out, some 300 MB, for an image built `FROM` it to add.
|
|
8
|
+
- 0fab5d6: A command that runs out of memory in a Compute Engine sandbox no longer kills every other command of the sandbox. The commands run in the agent's systemd service, and systemd stops a service whose process the kernel's OOM killer killed: the other commands, a harness bridge included, exited with 143 (`SIGTERM`), and the agent restarted. The agent now sets `OOMPolicy=continue` on its service as it starts, whatever unit the image has: only the command killed goes, with 137.
|
|
9
|
+
|
|
10
|
+
Rebuild the sandbox image with this version (`npm install --global ai-sdk-sandbox-gce@<version>`): the agent runs from the image, and the templates are made again on the new image. The README's unit has the line too.
|
|
11
|
+
|
|
12
|
+
## 0.3.4
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- fb3ec6d: `prepareGceSandboxService()` takes the sandbox's `template` (with its `setup` and `image`), and the service then boots a machine from it ahead of the sandbox, beside the egress proxy, with the `cost` profile too: the creation that follows takes it, in a few seconds rather than some 25 s for its own machine to boot. A person reading a summary before launching a sandbox gets it at once, for no fixed cost.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
void prepareGceSandboxService({
|
|
20
|
+
url,
|
|
21
|
+
auth: 'metadata',
|
|
22
|
+
template: await agent.getSandboxTemplate(),
|
|
23
|
+
}).catch(() => undefined);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
It never builds the template: until the first sandbox made from it, only the proxy boots. One machine at a time: a template whose pool holds one, running or booting, gets none more, however many calls. A prepared machine no creation took powers itself off 16 minutes after its boot: its agent does so, unless a sandbox took it, whether a call comes or not, and the service deletes it as the next creation or preparation meets it once it waited 15 minutes. Rebuild the sandbox image with this version for the agent's bound to apply: a machine of an older image keeps only the service's, and should no call come, `SANDBOX_MAX_RUN_HOURS` is what stops it, so set it when you prepare. The service no longer stops the egress proxy while a prepared machine waits for its sandbox, and a preparation starts a proxy the last sandbox was just stopping once it has stopped: the sandbox that takes the machine no longer waits for the proxy to boot again. A service of an earlier version ignores the template and boots the proxy only.
|
|
27
|
+
- 9c817f6: The condition of the proxy's unit in the README reads the installed version from the package's `package.json`, rather than with `npm ls --global`: npm took some 20 s to start on the proxy's machine as it booted, and the proxy waited for it, some 54 s for a stopped proxy rather than 35 s. Hand the new script to the proxy's machine (`gcloud compute instances add-metadata … --metadata-from-file=startup-script=proxy-startup.sh`).
|
|
28
|
+
|
|
3
29
|
## 0.3.3
|
|
4
30
|
|
|
5
31
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -135,7 +135,7 @@ gcloud compute instances create sandbox-proxy --zone=$ZONE --machine-type=e2-sma
|
|
|
135
135
|
#!/bin/sh
|
|
136
136
|
set -e
|
|
137
137
|
# The version of the proxy: the one your application depends on.
|
|
138
|
-
VERSION=0.3.
|
|
138
|
+
VERSION=0.3.5
|
|
139
139
|
# Writes $2 to the file $1 when it differs, and says whether it did.
|
|
140
140
|
changed() {
|
|
141
141
|
mkdir -p "$(dirname "$1")"
|
|
@@ -229,7 +229,11 @@ set -e
|
|
|
229
229
|
pinned=$(curl -fsS -H Metadata-Flavor:Google \
|
|
230
230
|
http://metadata.google.internal/computeMetadata/v1/instance/attributes/startup-script \
|
|
231
231
|
| sed -n 's/^VERSION=//p')
|
|
232
|
-
npm
|
|
232
|
+
# Read from its package.json, where Node.js from NodeSource installs it: npm itself takes some 20 s
|
|
233
|
+
# to start on a small machine as it boots.
|
|
234
|
+
installed=$(sed -n 's/^ *"version": *"\([^"]*\)".*/\1/p' \
|
|
235
|
+
/usr/lib/node_modules/ai-sdk-sandbox-gce/package.json | head -n 1)
|
|
236
|
+
[ -n "$pinned" ] && [ "$installed" = "$pinned" ]
|
|
233
237
|
SCRIPT
|
|
234
238
|
chmod 755 /usr/local/bin/ai-sdk-sandbox-proxy-pinned
|
|
235
239
|
# Started by systemd as the machine boots, seconds before this script runs, when its package is
|
|
@@ -250,7 +254,7 @@ gcloud compute instances add-metadata sandbox-proxy --zone=$ZONE \
|
|
|
250
254
|
gcloud compute instances reset sandbox-proxy --zone=$ZONE
|
|
251
255
|
```
|
|
252
256
|
|
|
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.
|
|
257
|
+
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 and no prepared machine waits for one. 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.
|
|
254
258
|
|
|
255
259
|
### 3. The sandbox image
|
|
256
260
|
|
|
@@ -261,6 +265,8 @@ Every sandbox boots from it: put the tools your agent needs in it, and never a s
|
|
|
261
265
|
set -e
|
|
262
266
|
apt-get update
|
|
263
267
|
apt-get install -y --no-install-recommends ca-certificates curl git gnupg procps python3 ripgrep sudo
|
|
268
|
+
# A project's Makefile and the native modules of its dependencies; the scripts and archives of the usual toolchains.
|
|
269
|
+
apt-get install -y --no-install-recommends build-essential jq unzip xz-utils
|
|
264
270
|
|
|
265
271
|
# Docker Engine and Compose.
|
|
266
272
|
install -m 0755 -d /etc/apt/keyrings
|
|
@@ -276,7 +282,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
|
|
|
276
282
|
> /etc/apt/sources.list.d/nodesource.list
|
|
277
283
|
apt-get update
|
|
278
284
|
apt-get install -y nodejs
|
|
279
|
-
npm install --global ai-sdk-sandbox-gce@0.3.
|
|
285
|
+
npm install --global ai-sdk-sandbox-gce@0.3.5 pnpm@10
|
|
280
286
|
|
|
281
287
|
# The sandbox's user: sudo without a password, and Docker.
|
|
282
288
|
useradd --create-home --shell /bin/bash agent
|
|
@@ -292,6 +298,7 @@ Wants=network-online.target
|
|
|
292
298
|
[Service]
|
|
293
299
|
ExecStart=/usr/bin/ai-sdk-sandbox-gce agent
|
|
294
300
|
Restart=always
|
|
301
|
+
OOMPolicy=continue
|
|
295
302
|
|
|
296
303
|
[Install]
|
|
297
304
|
WantedBy=multi-user.target
|
|
@@ -299,11 +306,11 @@ UNIT
|
|
|
299
306
|
systemctl enable ai-sdk-sandbox-agent
|
|
300
307
|
```
|
|
301
308
|
|
|
302
|
-
The agent runs as root and starts the commands as `agent
|
|
309
|
+
The agent runs as root and starts the commands as `agent`, in its own service: `OOMPolicy=continue` keeps it running when the kernel kills a command out of memory, which systemd's default, `stop`, answers by stopping the service, every other command of the sandbox killed with it (exit code 143). The agent sets it on its running service too, for an image whose unit lacks the line. It does not wait for Docker to boot, some 10 s on a small machine: its socket answers the first `docker` command once the daemon is up. It points Docker at the proxy itself, the daemon and the client: images are pulled through the proxy, and containers get its address in their proxy variables. Rebuild the image every week or so for the security updates: the templates made on the previous one are made again on the next sandbox.
|
|
303
310
|
|
|
304
311
|
### 4. The service
|
|
305
312
|
|
|
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.
|
|
313
|
+
The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.5 --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.
|
|
307
314
|
|
|
308
315
|
Its service account gets a role of its own, with what the service calls and nothing else, limited by a condition to the names it uses: the sandboxes' machines and disks (`sbx-`), the proxy's machine, the sandbox images and templates (`ai-sdk-`).
|
|
309
316
|
|
|
@@ -341,7 +348,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
|
|
|
341
348
|
--member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
|
|
342
349
|
done
|
|
343
350
|
|
|
344
|
-
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.
|
|
351
|
+
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.5 \
|
|
345
352
|
--service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
|
|
346
353
|
--network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
|
|
347
354
|
--no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
|
|
@@ -422,18 +429,21 @@ try {
|
|
|
422
429
|
|
|
423
430
|
`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`.
|
|
424
431
|
|
|
425
|
-
|
|
432
|
+
A sandbox made after a quiet spell waits for machines to boot: its own, some 25 s, and the egress proxy's when the service starts and stops it (`SANDBOX_PROXY_INSTANCE`). Ask the service to boot them as soon as a sandbox is likely to be asked for, a person reading what is about to run, say, and the sandbox finds them up, created in a few seconds:
|
|
426
433
|
|
|
427
434
|
```ts
|
|
428
435
|
import { prepareGceSandboxService } from 'ai-sdk-sandbox-gce';
|
|
429
436
|
|
|
430
|
-
//
|
|
431
|
-
void prepareGceSandboxService({
|
|
432
|
-
|
|
433
|
-
|
|
437
|
+
// A hint, not awaited: an error changes nothing for the sandboxes.
|
|
438
|
+
void prepareGceSandboxService({
|
|
439
|
+
url: process.env.GCE_SANDBOX_URL!,
|
|
440
|
+
auth: 'metadata',
|
|
441
|
+
// The sandbox's template, setup and image, as it will be created: a machine boots from it.
|
|
442
|
+
template: await agent.getSandboxTemplate(),
|
|
443
|
+
}).catch(() => undefined);
|
|
434
444
|
```
|
|
435
445
|
|
|
436
|
-
|
|
446
|
+
It never builds the template: until the first sandbox made from it, only the proxy boots. A proxy still stopping, the last sandbox just gone, is started once stopped. The service does not stop it while the prepared machine waits for its sandbox: it stops again with the next sandbox that stops once that machine is taken or gone, or by itself after 10 minutes when none comes (`SANDBOX_PROXY_IDLE_EXIT_MINUTES` in its unit); the machine, as [Speed or cost](#speed-or-cost) says. A service of an earlier version boots the proxy only, or nothing.
|
|
437
447
|
|
|
438
448
|
## Images and toolchains
|
|
439
449
|
|
|
@@ -494,6 +504,12 @@ await sandboxSession.destroy();
|
|
|
494
504
|
- With `SANDBOX_PROXY_INSTANCE`, the service starts the proxy with the first sandbox and leaves it running: leave the three lines of `SANDBOX_PROXY_IDLE_EXIT_MINUTES` out of its unit, or the proxy stops itself after 10 minutes with no sandbox. Without `SANDBOX_PROXY_INSTANCE`, the proxy is always on anyway.
|
|
495
505
|
- Back to `cost`, the next creation from a template takes what is left in its pool, and makes nothing more.
|
|
496
506
|
|
|
507
|
+
With `cost`, a person who reads before a sandbox is launched, a summary of what will run say, gets it in a few seconds too, for no fixed cost: call `prepareGceSandboxService()` with the sandbox's template as the summary opens (see [Usage](#usage)). The service boots one machine from the template, labelled `ai-sdk-sandbox-prepared=true`, and the creation that follows takes it like a machine of the pool. One at a time: a template whose pool holds a machine, running or booting, gets none more, however many people open a summary.
|
|
508
|
+
|
|
509
|
+
A prepared machine no creation takes costs while it runs, and two bounds stop it. Its agent powers it off itself 16 minutes after its boot unless a sandbox took it (`systemctl poweroff`, read from its metadata key `ai-sdk-sandbox-idle-poweroff-minutes`, which only prepared machines have), whether any call comes or not: it then costs its disk alone, until the next creation or preparation that meets it deletes it. And the service deletes it, running or not, as the next creation or preparation meets it once it waited 15 minutes, a minute before its agent would: a creation never takes a machine about to power off.
|
|
510
|
+
|
|
511
|
+
The agent's bound comes with the sandbox image: rebuild it with this version of the package (step 3) for it to apply. A machine of an older image keeps only the service's bound: should no call come, it runs until `SANDBOX_MAX_RUN_HOURS` stops it, or until the next call that meets it after 24 h without the limit; set `SANDBOX_MAX_RUN_HOURS` when you prepare. The proxy the preparation started stops by itself after `SANDBOX_PROXY_IDLE_EXIT_MINUTES`.
|
|
512
|
+
|
|
497
513
|
## Stopping and resuming
|
|
498
514
|
|
|
499
515
|
`stop()` suspends the sandbox: the processes this session started are stopped, the proxy forgets its credentials, then the machine is stopped, its disk kept. Resume it later, from this process or another one:
|
|
@@ -636,7 +652,7 @@ Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.
|
|
|
636
652
|
| `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 |
|
|
637
653
|
| `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 |
|
|
638
654
|
| `SANDBOX_RECONCILE_MINUTES` | `10` | How often, at most, the service makes the proxy forget the sandboxes whose machine no longer runs, in the background of a creation or a resume. A sandbox of another service sharing the proxy in the zone is left alone, under another `SANDBOX_INSTANCE_PREFIX`. `0` for never: a proxy shared with a service of another zone or project |
|
|
639
|
-
| `SANDBOX_PROXY_INSTANCE` | none | The egress proxy's machine, in the sandboxes' zone: started with the first sandbox that runs, stopped once none does. Always on without it
|
|
655
|
+
| `SANDBOX_PROXY_INSTANCE` | none | The egress proxy's machine, in the sandboxes' zone: started with the first sandbox that runs, stopped once none does and no prepared machine waits for one. Always on without it |
|
|
640
656
|
| `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
|
|
641
657
|
| `SANDBOX_WARM_POOL` | `0`, `1` with `fast` | How many machines are kept booted from each template used in the last 24 h, for the next creations from it to take at once. Each one is billed all the time |
|
|
642
658
|
| `SANDBOX_PROXY_ALWAYS_ON` | `false`, `true` with `fast` | `true`: the service starts the proxy's machine of `SANDBOX_PROXY_INSTANCE` with the first sandbox, and never stops it. No sandbox waits for it to boot, and it is billed all the time |
|
|
@@ -661,16 +677,17 @@ Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.
|
|
|
661
677
|
|
|
662
678
|
### The agent (`agent`)
|
|
663
679
|
|
|
664
|
-
| Variable | Default | Description
|
|
665
|
-
| -------------------------- | -------------------------------------------- |
|
|
666
|
-
| `SANDBOX_USER` | `agent` | The user the commands run as, when the agent is root
|
|
667
|
-
| `SANDBOX_HOME` | `/home/<user>` | Their `HOME`
|
|
668
|
-
| `SANDBOX_WORKDIR` | `/workspace` | Their working directory, made the user's
|
|
669
|
-
| `SANDBOX_PATH` | `/usr/local/sbin:/usr/local/bin:/usr/sbin:…` | Their `PATH`
|
|
670
|
-
| `SANDBOX_AGENT_PORT` | `8100` | Where the agent listens
|
|
671
|
-
| `SANDBOX_AGENT_TOKEN` | the instance's `ai-sdk-sandbox-agent-token` | Its token: the service puts it in the instance metadata
|
|
672
|
-
| `SANDBOX_STATE_DIR` | `/var/lib/ai-sdk-sandbox` | Where it keeps the network configuration, root's
|
|
673
|
-
| `SANDBOX_CONFIGURE_DOCKER` | `true` | `false` to leave Docker's proxy settings alone
|
|
680
|
+
| Variable | Default | Description |
|
|
681
|
+
| -------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
|
682
|
+
| `SANDBOX_USER` | `agent` | The user the commands run as, when the agent is root |
|
|
683
|
+
| `SANDBOX_HOME` | `/home/<user>` | Their `HOME` |
|
|
684
|
+
| `SANDBOX_WORKDIR` | `/workspace` | Their working directory, made the user's |
|
|
685
|
+
| `SANDBOX_PATH` | `/usr/local/sbin:/usr/local/bin:/usr/sbin:…` | Their `PATH` |
|
|
686
|
+
| `SANDBOX_AGENT_PORT` | `8100` | Where the agent listens |
|
|
687
|
+
| `SANDBOX_AGENT_TOKEN` | the instance's `ai-sdk-sandbox-agent-token` | Its token: the service puts it in the instance metadata |
|
|
688
|
+
| `SANDBOX_STATE_DIR` | `/var/lib/ai-sdk-sandbox` | Where it keeps the network configuration, root's |
|
|
689
|
+
| `SANDBOX_CONFIGURE_DOCKER` | `true` | `false` to leave Docker's proxy settings alone |
|
|
690
|
+
| `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 |
|
|
674
691
|
|
|
675
692
|
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.
|
|
676
693
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { HarnessV1SandboxSessionCreateOptions, HarnessV1SandboxSessionResumeOptions } from '@ai-sdk/harness';
|
|
1
|
+
import type { HarnessV1SandboxSessionCreateOptions, HarnessV1SandboxSessionResumeOptions, HarnessV1SandboxTemplate } from '@ai-sdk/harness';
|
|
2
2
|
/**
|
|
3
3
|
* How calls to the sandbox service are authenticated. The service runs on Cloud Run, deployed with
|
|
4
4
|
* `--no-allow-unauthenticated`: each call carries a Google identity token, granted
|
|
@@ -86,6 +86,30 @@ export interface GceCreationSettings extends GceConnectionSettings {
|
|
|
86
86
|
*/
|
|
87
87
|
setup?: readonly string[];
|
|
88
88
|
}
|
|
89
|
+
/** Options of `prepareGceSandboxService()`: the sandbox likely to be created next. */
|
|
90
|
+
export interface GcePrepareSettings extends GceConnectionSettings {
|
|
91
|
+
/**
|
|
92
|
+
* The template the sandbox will be created from, `await agent.getSandboxTemplate()`: the service
|
|
93
|
+
* boots a machine from it ahead of the sandbox, which the creation takes. Only once the template
|
|
94
|
+
* exists on the service: preparing never builds it. Without it, only the egress proxy is booted.
|
|
95
|
+
*/
|
|
96
|
+
template?: HarnessV1SandboxTemplate;
|
|
97
|
+
/**
|
|
98
|
+
* The `setup` the sandbox will be created with: with the template, what names the template's
|
|
99
|
+
* image.
|
|
100
|
+
*
|
|
101
|
+
* @defaultValue `[]`
|
|
102
|
+
*/
|
|
103
|
+
setup?: readonly string[];
|
|
104
|
+
/**
|
|
105
|
+
* The image the sandbox will be created on, by the name the service gives it in `SANDBOX_IMAGES`.
|
|
106
|
+
*
|
|
107
|
+
* @defaultValue the service's `SANDBOX_IMAGE`
|
|
108
|
+
*/
|
|
109
|
+
image?: string;
|
|
110
|
+
/** Aborts the call. */
|
|
111
|
+
abortSignal?: AbortSignal;
|
|
112
|
+
}
|
|
89
113
|
/** Options of `createGceNetworkSandboxSession()`. */
|
|
90
114
|
export type GceNetworkSandboxSessionCreateOptions = HarnessV1SandboxSessionCreateOptions<GceCreationSettings>;
|
|
91
115
|
/** Options of `resumeGceNetworkSandboxSession()`. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings } 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
|
|
@@ -16,15 +16,18 @@ import { GceNetworkSandboxSession } from '../session/gce-network-sandbox-session
|
|
|
16
16
|
*/
|
|
17
17
|
export declare function createGceNetworkSandboxSession(options: GceNetworkSandboxSessionCreateOptions): Promise<GceNetworkSandboxSession>;
|
|
18
18
|
/**
|
|
19
|
-
* Has the sandbox service at `url` boot what a sandbox needs,
|
|
20
|
-
* starts and stops it,
|
|
21
|
-
*
|
|
22
|
-
* the
|
|
23
|
-
*
|
|
19
|
+
* Has the sandbox service at `url` boot what a sandbox needs, without waiting for it: its egress
|
|
20
|
+
* proxy when the service starts and stops it, and, given the sandbox's `template` (with its `setup`
|
|
21
|
+
* and `image`), a machine booted from it. Call it as soon as a sandbox is likely to be asked for,
|
|
22
|
+
* the person who launches it still reading what will run, and the creation that follows finds them
|
|
23
|
+
* up. A hint: do not await it, and ignore its errors, which change nothing for the sandboxes.
|
|
24
|
+
*
|
|
25
|
+
* It never builds the template: before the first sandbox made from it, only the proxy is booted.
|
|
26
|
+
* Should no sandbox come, the proxy stops by itself, and the service deletes the machine as it
|
|
27
|
+
* meets it, once it waited 15 minutes. A service of an earlier version boots the proxy only, or
|
|
28
|
+
* nothing.
|
|
24
29
|
*/
|
|
25
|
-
export declare function prepareGceSandboxService(options:
|
|
26
|
-
abortSignal?: AbortSignal;
|
|
27
|
-
}): Promise<void>;
|
|
30
|
+
export declare function prepareGceSandboxService(options: GcePrepareSettings): Promise<void>;
|
|
28
31
|
/**
|
|
29
32
|
* Reattaches to a sandbox made by {@link createGceNetworkSandboxSession}, from this process or
|
|
30
33
|
* another one: a running sandbox as it is, a stopped one started again on its disk. Never creates
|
|
@@ -5,7 +5,7 @@ import { identityToken } from '../transport/identity-token.js';
|
|
|
5
5
|
import { SandboxServiceClient } from '../transport/sandbox-service-client.js';
|
|
6
6
|
import { abortReason } from '../utils/abort.js';
|
|
7
7
|
import { assertRequiredCommands, DEFAULT_REQUIRED_COMMANDS } from './required-commands.js';
|
|
8
|
-
import { ensureTemplate, runSetup } from './sandbox-template.js';
|
|
8
|
+
import { ensureTemplate, runSetup, templateId } from './sandbox-template.js';
|
|
9
9
|
/**
|
|
10
10
|
* What a Compute Engine instance name takes once the service's prefix is put before it, and a URL
|
|
11
11
|
* path as it is: the instance name is at most 63 characters and never ends with a dash.
|
|
@@ -80,14 +80,24 @@ export async function createGceNetworkSandboxSession(options) {
|
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
82
|
/**
|
|
83
|
-
* Has the sandbox service at `url` boot what a sandbox needs,
|
|
84
|
-
* starts and stops it,
|
|
85
|
-
*
|
|
86
|
-
* the
|
|
87
|
-
*
|
|
83
|
+
* Has the sandbox service at `url` boot what a sandbox needs, without waiting for it: its egress
|
|
84
|
+
* proxy when the service starts and stops it, and, given the sandbox's `template` (with its `setup`
|
|
85
|
+
* and `image`), a machine booted from it. Call it as soon as a sandbox is likely to be asked for,
|
|
86
|
+
* the person who launches it still reading what will run, and the creation that follows finds them
|
|
87
|
+
* up. A hint: do not await it, and ignore its errors, which change nothing for the sandboxes.
|
|
88
|
+
*
|
|
89
|
+
* It never builds the template: before the first sandbox made from it, only the proxy is booted.
|
|
90
|
+
* Should no sandbox come, the proxy stops by itself, and the service deletes the machine as it
|
|
91
|
+
* meets it, once it waited 15 minutes. A service of an earlier version boots the proxy only, or
|
|
92
|
+
* nothing.
|
|
88
93
|
*/
|
|
89
94
|
export async function prepareGceSandboxService(options) {
|
|
90
|
-
|
|
95
|
+
const { template, setup = [], image, abortSignal } = options;
|
|
96
|
+
await clientOf(options).prepare({
|
|
97
|
+
template: template === undefined ? undefined : templateId({ template, setup }),
|
|
98
|
+
image,
|
|
99
|
+
abortSignal,
|
|
100
|
+
});
|
|
91
101
|
}
|
|
92
102
|
/**
|
|
93
103
|
* Reattaches to a sandbox made by {@link createGceNetworkSandboxSession}, from this process or
|
|
@@ -75,8 +75,15 @@ 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
|
-
/**
|
|
79
|
-
|
|
78
|
+
/**
|
|
79
|
+
* Boots what a sandbox needs ahead of it: a machine from the template `template` of `image` too,
|
|
80
|
+
* when given. A service without the route answers 404: it is fine.
|
|
81
|
+
*/
|
|
82
|
+
prepare({ template, image, abortSignal, }?: {
|
|
83
|
+
template?: string;
|
|
84
|
+
image?: string;
|
|
85
|
+
abortSignal?: AbortSignal;
|
|
86
|
+
}): Promise<void>;
|
|
80
87
|
deleteTemplate(id: string, image?: string): Promise<void>;
|
|
81
88
|
/**
|
|
82
89
|
* Where a port of the sandbox is reached: a WebSocket through the service. The token is read
|
|
@@ -166,9 +166,16 @@ export class SandboxServiceClient {
|
|
|
166
166
|
});
|
|
167
167
|
return response.status !== 404;
|
|
168
168
|
}
|
|
169
|
-
/**
|
|
170
|
-
|
|
171
|
-
|
|
169
|
+
/**
|
|
170
|
+
* Boots what a sandbox needs ahead of it: a machine from the template `template` of `image` too,
|
|
171
|
+
* when given. A service without the route answers 404: it is fine.
|
|
172
|
+
*/
|
|
173
|
+
async prepare({ template, image, abortSignal, } = {}) {
|
|
174
|
+
await this.call('POST', 'v1/prepare', {
|
|
175
|
+
body: { template, image },
|
|
176
|
+
abortSignal,
|
|
177
|
+
accept: [404],
|
|
178
|
+
});
|
|
172
179
|
}
|
|
173
180
|
async deleteTemplate(id, image) {
|
|
174
181
|
await this.call('DELETE', templatePath(id, image));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
2
|
import { chownSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
3
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
|
-
import { AGENT_TOKEN_METADATA_KEY, DEFAULT_AGENT_PORT } from '../protocol/agent.js';
|
|
4
|
+
import { AGENT_TOKEN_METADATA_KEY, DEFAULT_AGENT_PORT, IDLE_POWER_OFF_METADATA_KEY, } from '../protocol/agent.js';
|
|
5
5
|
const METADATA = 'http://metadata.google.internal/computeMetadata/v1/instance/attributes/';
|
|
6
6
|
/** How long the agent tries to read its token from the metadata server, as the machine boots. */
|
|
7
7
|
const METADATA_ATTEMPTS = 30;
|
|
@@ -25,6 +25,49 @@ async function metadataToken(url) {
|
|
|
25
25
|
await sleep(1000);
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* The minutes after its boot the machine is powered off unless configured, from its instance
|
|
30
|
+
* metadata: read once, the metadata server having just answered the token. `undefined` when the
|
|
31
|
+
* key is missing, or cannot be read: the machine then runs on, as before the key was.
|
|
32
|
+
*/
|
|
33
|
+
async function metadataIdleMinutes(url, logger) {
|
|
34
|
+
try {
|
|
35
|
+
const response = await fetch(`${url}${IDLE_POWER_OFF_METADATA_KEY}`, {
|
|
36
|
+
headers: { 'metadata-flavor': 'Google' },
|
|
37
|
+
signal: AbortSignal.timeout(5000),
|
|
38
|
+
});
|
|
39
|
+
if (response.status === 404)
|
|
40
|
+
return undefined;
|
|
41
|
+
const text = (await response.text()).trim();
|
|
42
|
+
const minutes = Number(text);
|
|
43
|
+
if (response.ok && Number.isInteger(minutes) && minutes > 0)
|
|
44
|
+
return minutes;
|
|
45
|
+
logger.warn(`\`${IDLE_POWER_OFF_METADATA_KEY}\` is not a positive integer: \`${text}\`.`);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
logger.warn(`\`${IDLE_POWER_OFF_METADATA_KEY}\` could not be read: ${String(error)}`);
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The token, from the environment or else the instance metadata, and with the latter, as root, when
|
|
54
|
+
* to power the machine off unless configured.
|
|
55
|
+
*/
|
|
56
|
+
async function fromMetadata(env, logger) {
|
|
57
|
+
const given = env['SANDBOX_AGENT_TOKEN'];
|
|
58
|
+
if (given !== undefined)
|
|
59
|
+
return { token: given };
|
|
60
|
+
const url = env['METADATA_URL'] ?? METADATA;
|
|
61
|
+
const token = await metadataToken(url);
|
|
62
|
+
// Only root powers the machine off: an agent run by hand, or in tests, never does.
|
|
63
|
+
if (process.getuid?.() !== 0)
|
|
64
|
+
return { token };
|
|
65
|
+
const minutes = await metadataIdleMinutes(url, logger);
|
|
66
|
+
if (minutes === undefined)
|
|
67
|
+
return { token };
|
|
68
|
+
const runDirectory = env['SANDBOX_RUN_DIR'] ?? '/run/ai-sdk-sandbox';
|
|
69
|
+
return { token, idlePowerOff: { afterMs: minutes * 60_000, runDirectory } };
|
|
70
|
+
}
|
|
28
71
|
/** The ids of `user`, from `id`. */
|
|
29
72
|
function idsOf(user) {
|
|
30
73
|
const id = (flag) => Number(execFileSync('id', [flag, user], { encoding: 'utf8' }).trim());
|
|
@@ -61,7 +104,7 @@ export async function agentSettings(env, logger) {
|
|
|
61
104
|
chownSync(directory, commandUser.uid, commandUser.gid);
|
|
62
105
|
}
|
|
63
106
|
return {
|
|
64
|
-
|
|
107
|
+
...(await fromMetadata(env, logger)),
|
|
65
108
|
user,
|
|
66
109
|
home,
|
|
67
110
|
workingDirectory,
|
|
@@ -46,7 +46,7 @@ export function createAgentServer(settings) {
|
|
|
46
46
|
server,
|
|
47
47
|
processes: agent.processes,
|
|
48
48
|
close: async () => {
|
|
49
|
-
await agent.
|
|
49
|
+
await agent.close();
|
|
50
50
|
server.closeAllConnections();
|
|
51
51
|
await new Promise((resolve) => server.close(() => resolve()));
|
|
52
52
|
},
|
package/dist/in-vm/agent.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
|
2
2
|
import type { Reply } from '../common/http-reply.js';
|
|
3
3
|
import type { Logger } from '../common/logger.js';
|
|
4
4
|
import type { CommandSettings } from './environment.js';
|
|
5
|
+
import type { IdlePowerOffSettings } from './idle-power-off.js';
|
|
5
6
|
import type { CommandUser } from './processes.js';
|
|
6
7
|
import { Processes } from './processes.js';
|
|
7
8
|
/** What the agent is made with: its machine's to give. */
|
|
@@ -14,6 +15,11 @@ export interface AgentSettings extends CommandSettings {
|
|
|
14
15
|
commandUser?: CommandUser;
|
|
15
16
|
/** Whether to point Docker at the egress proxy: as root, on a machine that has it. */
|
|
16
17
|
configureDocker: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Powers the machine off when the agent is not configured soon enough after its boot: on a
|
|
20
|
+
* machine the service booted ahead of a sandbox. Never without it.
|
|
21
|
+
*/
|
|
22
|
+
idlePowerOff?: Omit<IdlePowerOffSettings, 'logger'>;
|
|
17
23
|
logger: Logger;
|
|
18
24
|
}
|
|
19
25
|
/**
|
|
@@ -25,7 +31,10 @@ export declare class Agent {
|
|
|
25
31
|
private readonly settings;
|
|
26
32
|
readonly processes: Processes;
|
|
27
33
|
private config?;
|
|
34
|
+
private readonly idle?;
|
|
28
35
|
constructor(settings: AgentSettings);
|
|
36
|
+
/** Stops the processes and the idle watch: the agent is closing. */
|
|
37
|
+
close(): Promise<void>;
|
|
29
38
|
private get configFile();
|
|
30
39
|
/** Answers a call, or streams its own answer and replies with nothing. */
|
|
31
40
|
handle(request: IncomingMessage, response: ServerResponse, path: string): Promise<Reply | undefined>;
|
package/dist/in-vm/agent.js
CHANGED
|
@@ -8,6 +8,7 @@ import { MAX_INPUT_WRITE_BYTES } from '../protocol/api.js';
|
|
|
8
8
|
import { encodeData, encodeFrame, FrameType, STDERR, STDOUT } from '../protocol/frames.js';
|
|
9
9
|
import { configureDocker } from './docker-proxy.js';
|
|
10
10
|
import { commandEnvironment } from './environment.js';
|
|
11
|
+
import { watchIdlePowerOff } from './idle-power-off.js';
|
|
11
12
|
import { Processes } from './processes.js';
|
|
12
13
|
/** How long `GET /v1/processes/:id` waits for an exit: less than any request timeout. */
|
|
13
14
|
const WAIT_MS = 5 * 60_000;
|
|
@@ -29,9 +30,13 @@ export class Agent {
|
|
|
29
30
|
settings;
|
|
30
31
|
processes;
|
|
31
32
|
config;
|
|
33
|
+
idle;
|
|
32
34
|
constructor(settings) {
|
|
33
35
|
this.settings = settings;
|
|
34
36
|
this.processes = new Processes(settings.commandUser);
|
|
37
|
+
if (settings.idlePowerOff !== undefined) {
|
|
38
|
+
this.idle = watchIdlePowerOff({ ...settings.idlePowerOff, logger: settings.logger });
|
|
39
|
+
}
|
|
35
40
|
try {
|
|
36
41
|
this.config = toConfig(parseObject(readFileSync(this.configFile, 'utf8')));
|
|
37
42
|
}
|
|
@@ -39,6 +44,11 @@ export class Agent {
|
|
|
39
44
|
// Not configured yet: the service does so before the first command.
|
|
40
45
|
}
|
|
41
46
|
}
|
|
47
|
+
/** Stops the processes and the idle watch: the agent is closing. */
|
|
48
|
+
async close() {
|
|
49
|
+
this.idle?.stop();
|
|
50
|
+
await this.processes.killAll();
|
|
51
|
+
}
|
|
42
52
|
get configFile() {
|
|
43
53
|
return join(this.settings.stateDirectory, 'config.json');
|
|
44
54
|
}
|
|
@@ -74,6 +84,8 @@ export class Agent {
|
|
|
74
84
|
}
|
|
75
85
|
async configure(config) {
|
|
76
86
|
const { settings } = this;
|
|
87
|
+
// A sandbox took the machine: it runs on, whatever the configuration below comes to.
|
|
88
|
+
this.idle?.configured();
|
|
77
89
|
if (settings.configureDocker) {
|
|
78
90
|
await configureDocker(config, { home: settings.home, user: settings.commandUser });
|
|
79
91
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Logger } from '../common/logger.js';
|
|
2
|
+
/** What the agent powers its machine off with, should no sandbox take it. */
|
|
3
|
+
export interface IdlePowerOffSettings {
|
|
4
|
+
/** How long after the machine's boot it waits to be configured. */
|
|
5
|
+
afterMs: number;
|
|
6
|
+
/**
|
|
7
|
+
* Where the agent marks that it was configured since the machine booted: a directory emptied at
|
|
8
|
+
* each boot, `/run`'s, so that an agent restarted by systemd after the sandbox took the machine
|
|
9
|
+
* never powers it off.
|
|
10
|
+
*/
|
|
11
|
+
runDirectory: string;
|
|
12
|
+
logger: Logger;
|
|
13
|
+
/** Powers the machine off: `systemctl poweroff` without it. Tests only. */
|
|
14
|
+
powerOff?: () => void;
|
|
15
|
+
/** How long the machine has been up: the system's uptime without it. Tests only. */
|
|
16
|
+
uptimeMs?: () => number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Powers the machine off once it ran `afterMs` since its boot without the agent being configured:
|
|
20
|
+
* a machine the service booted ahead of a sandbox that never came stops costing but its disk, and
|
|
21
|
+
* the service deletes it as it meets it. Being configured, what the service does for the sandbox
|
|
22
|
+
* that takes the machine, cancels it for the rest of the boot. Returns what marks it configured,
|
|
23
|
+
* and what stops the watch.
|
|
24
|
+
*/
|
|
25
|
+
export declare function watchIdlePowerOff({ afterMs, runDirectory, logger, powerOff, uptimeMs, }: IdlePowerOffSettings): {
|
|
26
|
+
configured(): void;
|
|
27
|
+
stop(): void;
|
|
28
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { uptime } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
/** Powers the machine off as root, through systemd: the guest halts, and Compute Engine stops it. */
|
|
6
|
+
function systemPowerOff(logger) {
|
|
7
|
+
execFile('systemctl', ['poweroff'], (error) => {
|
|
8
|
+
if (error !== null)
|
|
9
|
+
logger.error(`The machine could not be powered off: ${error.message}`);
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Powers the machine off once it ran `afterMs` since its boot without the agent being configured:
|
|
14
|
+
* a machine the service booted ahead of a sandbox that never came stops costing but its disk, and
|
|
15
|
+
* the service deletes it as it meets it. Being configured, what the service does for the sandbox
|
|
16
|
+
* that takes the machine, cancels it for the rest of the boot. Returns what marks it configured,
|
|
17
|
+
* and what stops the watch.
|
|
18
|
+
*/
|
|
19
|
+
export function watchIdlePowerOff({ afterMs, runDirectory, logger, powerOff = () => systemPowerOff(logger), uptimeMs = () => uptime() * 1000, }) {
|
|
20
|
+
const marker = join(runDirectory, 'configured');
|
|
21
|
+
let timer;
|
|
22
|
+
if (!existsSync(marker)) {
|
|
23
|
+
timer = setTimeout(() => {
|
|
24
|
+
logger.info(`Not configured ${afterMs / 60_000} min after boot: powering the machine off`);
|
|
25
|
+
powerOff();
|
|
26
|
+
}, Math.max(0, afterMs - uptimeMs()));
|
|
27
|
+
timer.unref();
|
|
28
|
+
}
|
|
29
|
+
const stop = () => {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
timer = undefined;
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
configured: () => {
|
|
35
|
+
stop();
|
|
36
|
+
try {
|
|
37
|
+
mkdirSync(runDirectory, { recursive: true, mode: 0o700 });
|
|
38
|
+
writeFileSync(marker, '', { mode: 0o600 });
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
logger.warn(`The configuration could not be marked in ${runDirectory}: ${String(error)}`);
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
stop,
|
|
45
|
+
};
|
|
46
|
+
}
|
package/dist/in-vm/main.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createLogger } from '../common/logger.js';
|
|
2
2
|
import { agentListenConfig, agentSettings } from './agent-config.js';
|
|
3
3
|
import { createAgentServer } from './agent-server.js';
|
|
4
|
+
import { keepRunningOnOomKill } from './oom-policy.js';
|
|
4
5
|
/**
|
|
5
6
|
* `ai-sdk-sandbox-gce agent`: serves the agent of a sandbox's machine until systemd stops it, the
|
|
6
7
|
* processes it started stopped with it.
|
|
@@ -8,6 +9,9 @@ import { createAgentServer } from './agent-server.js';
|
|
|
8
9
|
export async function main(env) {
|
|
9
10
|
const logger = createLogger({ json: env['LOG_FORMAT'] !== 'text' });
|
|
10
11
|
const config = agentListenConfig(env);
|
|
12
|
+
// As root, from the image's systemd unit: a command out of memory must not stop the others.
|
|
13
|
+
if (process.getuid?.() === 0)
|
|
14
|
+
await keepRunningOnOomKill({ logger });
|
|
11
15
|
const agent = createAgentServer(await agentSettings(env, logger));
|
|
12
16
|
agent.server.listen(config.port, config.host, () => logger.info(`Agent listening on ${config.host}:${config.port}`));
|
|
13
17
|
for (const signal of ['SIGTERM', 'SIGINT']) {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Logger } from '../common/logger.js';
|
|
2
|
+
/** Where the agent keeps its service running when one of its commands runs out of memory. */
|
|
3
|
+
export interface OomPolicySettings {
|
|
4
|
+
/** The agent's cgroup, which names its service: `/proc/self/cgroup` without it. Tests only. */
|
|
5
|
+
cgroupFile?: string;
|
|
6
|
+
/** Where runtime drop-ins go, emptied at each boot: `/run/systemd/system` without it. Tests only. */
|
|
7
|
+
dropInRoot?: string;
|
|
8
|
+
/** Has systemd read the drop-in: `systemctl daemon-reload` without it. Tests only. */
|
|
9
|
+
reload?: () => Promise<void>;
|
|
10
|
+
logger: Logger;
|
|
11
|
+
}
|
|
12
|
+
/** The systemd service of a process, from its `/proc/<pid>/cgroup`: `undefined` outside one. */
|
|
13
|
+
export declare function serviceOf(cgroup: string): string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Keeps the agent's systemd service running when the kernel's OOM killer kills one of its
|
|
16
|
+
* processes. The commands run in the service's cgroup, and systemd stops a service whose process
|
|
17
|
+
* the OOM killer killed (`OOMPolicy=stop`, its default): one command out of memory sent `SIGTERM`
|
|
18
|
+
* to every other command of the sandbox, which exited with 143, and to the agent, restarted by
|
|
19
|
+
* `Restart=always`. A runtime drop-in sets `OOMPolicy=continue` on the running service, whatever
|
|
20
|
+
* unit the image has: only the killed process goes, its command exiting with 137. Never fails: the
|
|
21
|
+
* agent runs without it, as before.
|
|
22
|
+
*/
|
|
23
|
+
export declare function keepRunningOnOomKill({ cgroupFile, dropInRoot, reload, logger, }: OomPolicySettings): Promise<void>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
const run = promisify(execFile);
|
|
6
|
+
/** What the drop-in holds: systemd leaves the service running when the OOM killer kills in it. */
|
|
7
|
+
const DROP_IN = '[Service]\nOOMPolicy=continue\n';
|
|
8
|
+
/** The drop-in's name, beside any of the image's own. */
|
|
9
|
+
const DROP_IN_FILE = '50-ai-sdk-sandbox-oom-policy.conf';
|
|
10
|
+
/** The systemd service of a process, from its `/proc/<pid>/cgroup`: `undefined` outside one. */
|
|
11
|
+
export function serviceOf(cgroup) {
|
|
12
|
+
for (const line of cgroup.split('\n')) {
|
|
13
|
+
// `<id>:<controllers>:<path>`, the path last: `0::/system.slice/<name>.service` on cgroup v2.
|
|
14
|
+
const unit = line.split(':').slice(2).join(':').split('/').at(-1);
|
|
15
|
+
if (unit !== undefined && /^[\w@.\\-]+\.service$/.test(unit))
|
|
16
|
+
return unit;
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Keeps the agent's systemd service running when the kernel's OOM killer kills one of its
|
|
22
|
+
* processes. The commands run in the service's cgroup, and systemd stops a service whose process
|
|
23
|
+
* the OOM killer killed (`OOMPolicy=stop`, its default): one command out of memory sent `SIGTERM`
|
|
24
|
+
* to every other command of the sandbox, which exited with 143, and to the agent, restarted by
|
|
25
|
+
* `Restart=always`. A runtime drop-in sets `OOMPolicy=continue` on the running service, whatever
|
|
26
|
+
* unit the image has: only the killed process goes, its command exiting with 137. Never fails: the
|
|
27
|
+
* agent runs without it, as before.
|
|
28
|
+
*/
|
|
29
|
+
export async function keepRunningOnOomKill({ cgroupFile = '/proc/self/cgroup', dropInRoot = '/run/systemd/system', reload = async () => void (await run('systemctl', ['daemon-reload'])), logger, }) {
|
|
30
|
+
let service;
|
|
31
|
+
try {
|
|
32
|
+
service = serviceOf(readFileSync(cgroupFile, 'utf8'));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// No cgroup to read: not on Linux.
|
|
36
|
+
}
|
|
37
|
+
if (service === undefined)
|
|
38
|
+
return;
|
|
39
|
+
const file = join(dropInRoot, `${service}.d`, DROP_IN_FILE);
|
|
40
|
+
try {
|
|
41
|
+
if (existsSync(file) && readFileSync(file, 'utf8') === DROP_IN)
|
|
42
|
+
return;
|
|
43
|
+
mkdirSync(join(dropInRoot, `${service}.d`), { recursive: true });
|
|
44
|
+
writeFileSync(file, DROP_IN);
|
|
45
|
+
await reload();
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
logger.warn(`${service} could not be kept running on an OOM kill: one command out of memory stops every command. ${String(error)}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/index.d.ts
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 type { GceAuth, GceConnectionSettings, GceCreationSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, } from './client/gce-settings.js';
|
|
4
|
+
export type { GceAuth, GceConnectionSettings, GceCreationSettings, GceNetworkSandboxSessionCreateOptions, GceNetworkSandboxSessionResumeOptions, GcePrepareSettings, } from './client/gce-settings.js';
|
|
5
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';
|
package/dist/protocol/agent.d.ts
CHANGED
|
@@ -17,6 +17,11 @@
|
|
|
17
17
|
export declare const AGENT_TOKEN_HEADER = "x-ai-sdk-sandbox-agent-token";
|
|
18
18
|
/** The instance metadata key the agent reads its token from, when its environment has none. */
|
|
19
19
|
export declare const AGENT_TOKEN_METADATA_KEY = "ai-sdk-sandbox-agent-token";
|
|
20
|
+
/**
|
|
21
|
+
* The instance metadata key of a machine booted ahead of a sandbox: the minutes after its boot its
|
|
22
|
+
* agent powers it off unless configured meanwhile. Never without it.
|
|
23
|
+
*/
|
|
24
|
+
export declare const IDLE_POWER_OFF_METADATA_KEY = "ai-sdk-sandbox-idle-poweroff-minutes";
|
|
20
25
|
/** The port the agent listens on, in its machine. */
|
|
21
26
|
export declare const DEFAULT_AGENT_PORT = 8100;
|
|
22
27
|
/** How a sandbox's commands reach the network: what the service tells its agent. */
|
package/dist/protocol/agent.js
CHANGED
|
@@ -17,5 +17,10 @@
|
|
|
17
17
|
export const AGENT_TOKEN_HEADER = 'x-ai-sdk-sandbox-agent-token';
|
|
18
18
|
/** The instance metadata key the agent reads its token from, when its environment has none. */
|
|
19
19
|
export const AGENT_TOKEN_METADATA_KEY = 'ai-sdk-sandbox-agent-token';
|
|
20
|
+
/**
|
|
21
|
+
* The instance metadata key of a machine booted ahead of a sandbox: the minutes after its boot its
|
|
22
|
+
* agent powers it off unless configured meanwhile. Never without it.
|
|
23
|
+
*/
|
|
24
|
+
export const IDLE_POWER_OFF_METADATA_KEY = 'ai-sdk-sandbox-idle-poweroff-minutes';
|
|
20
25
|
/** The port the agent listens on, in its machine. */
|
|
21
26
|
export const DEFAULT_AGENT_PORT = 8100;
|
|
@@ -29,8 +29,13 @@ export const ROUTES = [
|
|
|
29
29
|
body: { status: 'ok', protocol: PROTOCOL_VERSION, version: PACKAGE_VERSION },
|
|
30
30
|
})),
|
|
31
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
|
-
|
|
32
|
+
route('POST', /^\/v1\/prepare$/, async ({ sandboxes, request }) => {
|
|
33
|
+
// An earlier client sends no body: the proxy only.
|
|
34
|
+
const body = await readJson(request);
|
|
35
|
+
await sandboxes.prepare({
|
|
36
|
+
template: optionalString(body, 'template'),
|
|
37
|
+
image: optionalString(body, 'image'),
|
|
38
|
+
});
|
|
34
39
|
return NO_CONTENT;
|
|
35
40
|
}),
|
|
36
41
|
route('POST', /^\/v1\/sandboxes$/, async ({ sandboxes, request }) => {
|
|
@@ -160,11 +160,46 @@ export declare class Sandboxes {
|
|
|
160
160
|
templateExists(id: string, image?: string): Promise<boolean>;
|
|
161
161
|
deleteTemplate(id: string, image?: string): Promise<void>;
|
|
162
162
|
/**
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
163
|
+
* Boots what a sandbox likely to come soon will need, without waiting for it: the proxy's machine
|
|
164
|
+
* when the service drives it and it is stopped, and, given the `template` the sandbox will be made
|
|
165
|
+
* from, a machine of the warm pool booted from it when its pool holds none, whatever
|
|
166
|
+
* `SANDBOX_WARM_POOL`. The creation that follows takes it, rather than boot one. Nothing when the
|
|
167
|
+
* template does not exist yet: building it is the creation's. The proxy stops with the next
|
|
168
|
+
* sandbox that stops, or by itself when none comes; the machine is deleted by the next creation or
|
|
169
|
+
* preparation that meets it unused after {@link PREPARED_WAIT_MS}.
|
|
170
|
+
*/
|
|
171
|
+
prepare({ template, image, }?: {
|
|
172
|
+
template?: string;
|
|
173
|
+
image?: string;
|
|
174
|
+
}): Promise<void>;
|
|
175
|
+
/**
|
|
176
|
+
* Starts the proxy's machine when the service drives it and it is stopped, not waiting for it to
|
|
177
|
+
* boot. One on its way down, the last sandbox just gone, is let stop first, within
|
|
178
|
+
* `startTimeoutMs`: Compute Engine starts no machine that is stopping.
|
|
166
179
|
*/
|
|
167
|
-
|
|
180
|
+
private prepareProxy;
|
|
181
|
+
/**
|
|
182
|
+
* Boots a machine of the warm pool from the template `id` of `image` when it exists and its pool
|
|
183
|
+
* holds none usable, the machines no longer usable deleted meanwhile. One at a time: a
|
|
184
|
+
* preparation that finds another one made meanwhile deletes its own.
|
|
185
|
+
*/
|
|
186
|
+
private prepareMachine;
|
|
187
|
+
/**
|
|
188
|
+
* Creates a machine of the warm pool labelled prepared, without waiting for it, then deletes it
|
|
189
|
+
* when another usable one of the template shows up meanwhile: of two preparations at once, the
|
|
190
|
+
* one that sees the other's machine gives way, so that one at most is left, none at worst.
|
|
191
|
+
*/
|
|
192
|
+
private addPrepared;
|
|
193
|
+
/** Waits for every change of the pool, logging those that failed rather than failing. */
|
|
194
|
+
private settled;
|
|
195
|
+
/** The machines of the service's warm pool, taken or not. */
|
|
196
|
+
private poolMachines;
|
|
197
|
+
/**
|
|
198
|
+
* Whether the machine `machine` of the warm pool may be taken, of the template `templateLabel`
|
|
199
|
+
* when given: not retired, running or booting, and not waiting for too long, a prepared one
|
|
200
|
+
* {@link PREPARED_WAIT_MS}, any other {@link POOL_WAIT_MS}.
|
|
201
|
+
*/
|
|
202
|
+
private usable;
|
|
168
203
|
/**
|
|
169
204
|
* Takes for the sandbox `name` a machine of the warm pool of its template, `sourceImage`, and sees
|
|
170
205
|
* to the pool: the template's machines missing created, and any machine no longer running (a Spot
|
|
@@ -186,7 +221,10 @@ export declare class Sandboxes {
|
|
|
186
221
|
* before can no longer take it, nor this one take it from under a creation that did.
|
|
187
222
|
*/
|
|
188
223
|
private retire;
|
|
189
|
-
/**
|
|
224
|
+
/**
|
|
225
|
+
* Creates a machine of the warm pool booted from `template`, prepared for a sandbox likely to
|
|
226
|
+
* come when told so, without waiting for it. Answers its name.
|
|
227
|
+
*/
|
|
190
228
|
private addToPool;
|
|
191
229
|
/** What the machines of the warm pool are named after: the service's prefix, then `pool-`. */
|
|
192
230
|
private get poolPrefix();
|
|
@@ -200,7 +238,10 @@ export declare class Sandboxes {
|
|
|
200
238
|
private reconcileInBackground;
|
|
201
239
|
/**
|
|
202
240
|
* Stops the proxy's machine, when the service drives it and does not keep it running, once no
|
|
203
|
-
* sandbox runs
|
|
241
|
+
* sandbox runs, nor a prepared machine waits for one: a sandbox is about to take it, which would
|
|
242
|
+
* then wait for the proxy to boot again. The other machines of the warm pool need no proxy until
|
|
243
|
+
* taken; once the prepared one is taken or gone, the next stop applies the rule, and the proxy's
|
|
244
|
+
* own idle exit bounds it meanwhile.
|
|
204
245
|
*/
|
|
205
246
|
private proxyDownWhenIdle;
|
|
206
247
|
/** Refuses one more running sandbox beyond {@link SandboxesOptions.maxRunning}. */
|
|
@@ -297,4 +338,6 @@ export declare class Sandboxes {
|
|
|
297
338
|
*/
|
|
298
339
|
private namespace;
|
|
299
340
|
private instanceBody;
|
|
341
|
+
/** How a machine runs: Spot when the service's are, unless `standard`, its run limit either way. */
|
|
342
|
+
private scheduling;
|
|
300
343
|
}
|
|
@@ -2,7 +2,7 @@ import { createHash, randomBytes } from 'node:crypto';
|
|
|
2
2
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
3
|
import { HttpError } from '../../common/http-error.js';
|
|
4
4
|
import { PACKAGE_VERSION } from '../../common/package-version.js';
|
|
5
|
-
import { AGENT_TOKEN_METADATA_KEY } from '../../protocol/agent.js';
|
|
5
|
+
import { AGENT_TOKEN_METADATA_KEY, IDLE_POWER_OFF_METADATA_KEY } from '../../protocol/agent.js';
|
|
6
6
|
import { PROTOCOL_VERSION } from '../../protocol/version.js';
|
|
7
7
|
import { ComputeError } from '../compute/compute-error.js';
|
|
8
8
|
import { AgentClient, agentToken } from './agent-client.js';
|
|
@@ -19,6 +19,11 @@ const NAME_LABEL = 'ai-sdk-sandbox-name';
|
|
|
19
19
|
const POOL_TEMPLATE_LABEL = 'ai-sdk-sandbox-template';
|
|
20
20
|
/** The label of a machine of the warm pool on its way out: no creation takes it any more. */
|
|
21
21
|
const RETIRED_LABEL = 'ai-sdk-sandbox-retired';
|
|
22
|
+
/**
|
|
23
|
+
* The label of a machine of the warm pool booted by {@link Sandboxes.prepare} for a sandbox likely
|
|
24
|
+
* to come, rather than kept by `SANDBOX_WARM_POOL`.
|
|
25
|
+
*/
|
|
26
|
+
const PREPARED_LABEL = 'ai-sdk-sandbox-prepared';
|
|
22
27
|
/** A name of a sandbox or a template: what an instance or image name and a URL path all take. */
|
|
23
28
|
const NAME = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
24
29
|
/** Statuses of a machine that runs, or is about to: what {@link SandboxesOptions.maxRunning} counts. */
|
|
@@ -49,11 +54,26 @@ function createdAt(instance) {
|
|
|
49
54
|
const created = Date.parse(instance.creationTimestamp ?? '');
|
|
50
55
|
return Number.isNaN(created) ? Date.now() : created;
|
|
51
56
|
}
|
|
57
|
+
/** The name of an image from its path: what a label of the pool's machines holds. */
|
|
58
|
+
const labelOfImage = (path) => path.split('/').at(-1) ?? '';
|
|
52
59
|
/**
|
|
53
60
|
* How long a machine of the warm pool waits for a creation before the next creation that meets it
|
|
54
61
|
* deletes it, whatever its template: what a template no longer used costs, at most.
|
|
55
62
|
*/
|
|
56
63
|
const POOL_WAIT_MS = 24 * 3_600_000;
|
|
64
|
+
/**
|
|
65
|
+
* How long a machine booted by {@link Sandboxes.prepare} waits for its sandbox before the next
|
|
66
|
+
* creation or preparation that meets it deletes it: the sandbox comes within a minute or two, or
|
|
67
|
+
* not at all.
|
|
68
|
+
*/
|
|
69
|
+
const PREPARED_WAIT_MS = 15 * 60_000;
|
|
70
|
+
/**
|
|
71
|
+
* The minutes after its boot the agent of a prepared machine powers it off, unless a sandbox took
|
|
72
|
+
* it: a minute past {@link PREPARED_WAIT_MS}, which the service counts from the machine's creation,
|
|
73
|
+
* earlier, so that a creation never takes a machine about to power off. Applied by the agent
|
|
74
|
+
* itself, whether a creation comes or not, from images of this version on.
|
|
75
|
+
*/
|
|
76
|
+
const PREPARED_POWER_OFF_MINUTES = PREPARED_WAIT_MS / 60_000 + 1;
|
|
57
77
|
/** Why a creation is refused: the name is taken. */
|
|
58
78
|
const alreadyExists = (name) => new HttpError(409, `A sandbox named "${name}" already exists.`);
|
|
59
79
|
/** Compute Engine's names are 63 characters at most. */
|
|
@@ -284,20 +304,102 @@ export class Sandboxes {
|
|
|
284
304
|
await this.options.compute.deleteImage(name);
|
|
285
305
|
}
|
|
286
306
|
/**
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
307
|
+
* Boots what a sandbox likely to come soon will need, without waiting for it: the proxy's machine
|
|
308
|
+
* when the service drives it and it is stopped, and, given the `template` the sandbox will be made
|
|
309
|
+
* from, a machine of the warm pool booted from it when its pool holds none, whatever
|
|
310
|
+
* `SANDBOX_WARM_POOL`. The creation that follows takes it, rather than boot one. Nothing when the
|
|
311
|
+
* template does not exist yet: building it is the creation's. The proxy stops with the next
|
|
312
|
+
* sandbox that stops, or by itself when none comes; the machine is deleted by the next creation or
|
|
313
|
+
* preparation that meets it unused after {@link PREPARED_WAIT_MS}.
|
|
290
314
|
*/
|
|
291
|
-
async prepare() {
|
|
292
|
-
|
|
315
|
+
async prepare({ template, image = DEFAULT_IMAGE, } = {}) {
|
|
316
|
+
await Promise.all([
|
|
317
|
+
this.prepareProxy(),
|
|
318
|
+
template === undefined ? undefined : this.prepareMachine(template, image),
|
|
319
|
+
]);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Starts the proxy's machine when the service drives it and it is stopped, not waiting for it to
|
|
323
|
+
* boot. One on its way down, the last sandbox just gone, is let stop first, within
|
|
324
|
+
* `startTimeoutMs`: Compute Engine starts no machine that is stopping.
|
|
325
|
+
*/
|
|
326
|
+
async prepareProxy() {
|
|
327
|
+
const { proxyInstance, compute, logger, startTimeoutMs } = this.options;
|
|
293
328
|
if (proxyInstance === undefined)
|
|
294
329
|
return;
|
|
295
|
-
const
|
|
330
|
+
const deadline = Date.now() + startTimeoutMs;
|
|
331
|
+
let current = await compute.getInstance(proxyInstance);
|
|
332
|
+
while (current?.status === 'STOPPING' && Date.now() < deadline) {
|
|
333
|
+
await sleep(1000);
|
|
334
|
+
current = await compute.getInstance(proxyInstance);
|
|
335
|
+
}
|
|
296
336
|
if (current?.status !== 'TERMINATED')
|
|
297
337
|
return;
|
|
298
338
|
logger.info(`Preparing: starting the egress proxy ${proxyInstance}`);
|
|
299
339
|
await compute.startInstance(proxyInstance, { wait: false });
|
|
300
340
|
}
|
|
341
|
+
/**
|
|
342
|
+
* Boots a machine of the warm pool from the template `id` of `image` when it exists and its pool
|
|
343
|
+
* holds none usable, the machines no longer usable deleted meanwhile. One at a time: a
|
|
344
|
+
* preparation that finds another one made meanwhile deletes its own.
|
|
345
|
+
*/
|
|
346
|
+
async prepareMachine(id, image) {
|
|
347
|
+
if (!(await this.templateExists(id, image)))
|
|
348
|
+
return;
|
|
349
|
+
const sourceImage = this.options.compute.imagePath(await this.templateImageName(id, image));
|
|
350
|
+
const templateLabel = labelOfImage(sourceImage);
|
|
351
|
+
const machines = await this.poolMachines();
|
|
352
|
+
const changes = machines
|
|
353
|
+
.filter((machine) => !this.usable(machine))
|
|
354
|
+
.map((machine) => this.retire(machine));
|
|
355
|
+
if (!machines.some((machine) => this.usable(machine, templateLabel))) {
|
|
356
|
+
changes.push(this.addPrepared({ image, sourceImage }, templateLabel));
|
|
357
|
+
}
|
|
358
|
+
await this.settled(changes);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Creates a machine of the warm pool labelled prepared, without waiting for it, then deletes it
|
|
362
|
+
* when another usable one of the template shows up meanwhile: of two preparations at once, the
|
|
363
|
+
* one that sees the other's machine gives way, so that one at most is left, none at worst.
|
|
364
|
+
*/
|
|
365
|
+
async addPrepared(template, templateLabel) {
|
|
366
|
+
const instance = await this.addToPool(template, templateLabel, { prepared: true });
|
|
367
|
+
const pool = await this.poolMachines();
|
|
368
|
+
const others = pool.filter((machine) => machine.name !== instance && this.usable(machine, templateLabel));
|
|
369
|
+
if (others.length === 0)
|
|
370
|
+
return;
|
|
371
|
+
const own = pool.find((machine) => machine.name === instance);
|
|
372
|
+
if (own === undefined)
|
|
373
|
+
await this.options.compute.deleteInstance(instance, { wait: false });
|
|
374
|
+
else
|
|
375
|
+
await this.retire(own);
|
|
376
|
+
}
|
|
377
|
+
/** Waits for every change of the pool, logging those that failed rather than failing. */
|
|
378
|
+
async settled(changes) {
|
|
379
|
+
for (const result of await Promise.allSettled(changes)) {
|
|
380
|
+
if (result.status === 'rejected') {
|
|
381
|
+
this.options.logger.warn(`The warm pool could not be kept: ${String(result.reason)}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** The machines of the service's warm pool, taken or not. */
|
|
386
|
+
async poolMachines() {
|
|
387
|
+
const machines = await this.options.compute.listInstances(LABEL, 'pool');
|
|
388
|
+
return machines.filter(({ name, labels }) => labels?.[LABEL] === 'pool' && name.startsWith(this.poolPrefix));
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Whether the machine `machine` of the warm pool may be taken, of the template `templateLabel`
|
|
392
|
+
* when given: not retired, running or booting, and not waiting for too long, a prepared one
|
|
393
|
+
* {@link PREPARED_WAIT_MS}, any other {@link POOL_WAIT_MS}.
|
|
394
|
+
*/
|
|
395
|
+
usable(machine, templateLabel) {
|
|
396
|
+
const waited = Date.now() - createdAt(machine);
|
|
397
|
+
const labels = machine.labels ?? {};
|
|
398
|
+
return (labels[RETIRED_LABEL] === undefined &&
|
|
399
|
+
RUNNING.has(machine.status) &&
|
|
400
|
+
waited < (labels[PREPARED_LABEL] === undefined ? POOL_WAIT_MS : PREPARED_WAIT_MS) &&
|
|
401
|
+
(templateLabel === undefined || labels[POOL_TEMPLATE_LABEL] === templateLabel));
|
|
402
|
+
}
|
|
301
403
|
/**
|
|
302
404
|
* Takes for the sandbox `name` a machine of the warm pool of its template, `sourceImage`, and sees
|
|
303
405
|
* to the pool: the template's machines missing created, and any machine no longer running (a Spot
|
|
@@ -307,16 +409,13 @@ export class Sandboxes {
|
|
|
307
409
|
* template; once taken, it never goes back to the pool.
|
|
308
410
|
*/
|
|
309
411
|
async fromPool(name, template) {
|
|
310
|
-
const {
|
|
311
|
-
const templateLabel = template.sourceImage
|
|
312
|
-
const machines =
|
|
313
|
-
const
|
|
314
|
-
RUNNING.has(machine.status) &&
|
|
315
|
-
Date.now() - createdAt(machine) < POOL_WAIT_MS;
|
|
316
|
-
const dropped = machines.filter((machine) => !usable(machine));
|
|
412
|
+
const { logger, warmPool = 0 } = this.options;
|
|
413
|
+
const templateLabel = labelOfImage(template.sourceImage);
|
|
414
|
+
const machines = await this.poolMachines();
|
|
415
|
+
const dropped = machines.filter((machine) => !this.usable(machine));
|
|
317
416
|
// A running machine first, then the one booting longest: the soonest ready.
|
|
318
417
|
const kept = machines
|
|
319
|
-
.filter((machine) => usable(machine
|
|
418
|
+
.filter((machine) => this.usable(machine, templateLabel))
|
|
320
419
|
.sort((a, b) => Number(b.status === 'RUNNING') - Number(a.status === 'RUNNING') ||
|
|
321
420
|
createdAt(a) - createdAt(b));
|
|
322
421
|
let taken;
|
|
@@ -344,14 +443,7 @@ export class Sandboxes {
|
|
|
344
443
|
...dropped.map((machine) => this.retire(machine)),
|
|
345
444
|
...Array.from({ length: missing }, () => this.addToPool(template, templateLabel)),
|
|
346
445
|
];
|
|
347
|
-
|
|
348
|
-
for (const result of results) {
|
|
349
|
-
if (result.status === 'rejected') {
|
|
350
|
-
logger.warn(`The warm pool could not be kept: ${String(result.reason)}`);
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
});
|
|
354
|
-
return { taken, upkeep };
|
|
446
|
+
return { taken, upkeep: this.settled(changes) };
|
|
355
447
|
}
|
|
356
448
|
/**
|
|
357
449
|
* Takes the machine `machine` of the warm pool for the sandbox `name`, by its labels: of two
|
|
@@ -400,16 +492,25 @@ export class Sandboxes {
|
|
|
400
492
|
logger.info(`Deleting ${machine.name} of the warm pool (${machine.status})`);
|
|
401
493
|
await compute.deleteInstance(machine.name, { wait: false });
|
|
402
494
|
}
|
|
403
|
-
/**
|
|
404
|
-
|
|
495
|
+
/**
|
|
496
|
+
* Creates a machine of the warm pool booted from `template`, prepared for a sandbox likely to
|
|
497
|
+
* come when told so, without waiting for it. Answers its name.
|
|
498
|
+
*/
|
|
499
|
+
async addToPool(template, templateLabel, { prepared = false } = {}) {
|
|
405
500
|
const instance = `${this.poolPrefix}${randomBytes(4).toString('hex')}`;
|
|
406
|
-
|
|
501
|
+
const why = prepared ? 'prepared for a sandbox' : 'for the warm pool';
|
|
502
|
+
this.options.logger.info(`Creating ${instance} ${why}, from ${templateLabel}`);
|
|
407
503
|
const labels = {
|
|
408
504
|
[LABEL]: 'pool',
|
|
409
505
|
[IMAGE_LABEL]: template.image,
|
|
410
506
|
[POOL_TEMPLATE_LABEL]: templateLabel,
|
|
507
|
+
...(prepared ? { [PREPARED_LABEL]: 'true' } : {}),
|
|
411
508
|
};
|
|
412
|
-
|
|
509
|
+
const metadata = prepared
|
|
510
|
+
? [{ key: IDLE_POWER_OFF_METADATA_KEY, value: String(PREPARED_POWER_OFF_MINUTES) }]
|
|
511
|
+
: [];
|
|
512
|
+
await this.insert(instance, { ...template, labels, metadata }, { wait: false });
|
|
513
|
+
return instance;
|
|
413
514
|
}
|
|
414
515
|
/** What the machines of the warm pool are named after: the service's prefix, then `pool-`. */
|
|
415
516
|
get poolPrefix() {
|
|
@@ -456,7 +557,10 @@ export class Sandboxes {
|
|
|
456
557
|
}
|
|
457
558
|
/**
|
|
458
559
|
* Stops the proxy's machine, when the service drives it and does not keep it running, once no
|
|
459
|
-
* sandbox runs
|
|
560
|
+
* sandbox runs, nor a prepared machine waits for one: a sandbox is about to take it, which would
|
|
561
|
+
* then wait for the proxy to boot again. The other machines of the warm pool need no proxy until
|
|
562
|
+
* taken; once the prepared one is taken or gone, the next stop applies the rule, and the proxy's
|
|
563
|
+
* own idle exit bounds it meanwhile.
|
|
460
564
|
*/
|
|
461
565
|
async proxyDownWhenIdle() {
|
|
462
566
|
const { proxyInstance, proxyAlwaysOn, compute } = this.options;
|
|
@@ -465,6 +569,9 @@ export class Sandboxes {
|
|
|
465
569
|
const machines = await compute.listInstances(LABEL, 'sandbox');
|
|
466
570
|
if (machines.some(({ status }) => RUNNING.has(status)))
|
|
467
571
|
return;
|
|
572
|
+
const pool = await this.poolMachines();
|
|
573
|
+
if (pool.some((machine) => machine.labels?.[PREPARED_LABEL] !== undefined && this.usable(machine)))
|
|
574
|
+
return;
|
|
468
575
|
const current = await compute.getInstance(proxyInstance);
|
|
469
576
|
if (current?.status !== 'RUNNING')
|
|
470
577
|
return;
|
|
@@ -492,7 +599,10 @@ export class Sandboxes {
|
|
|
492
599
|
async drawRun(instance) {
|
|
493
600
|
if (instance === undefined || !STOPPED.has(instance.status))
|
|
494
601
|
return;
|
|
495
|
-
|
|
602
|
+
// Its power-off goes too: stopped, the machine is a sandbox's, which no longer waits for one.
|
|
603
|
+
const items = (instance.metadata?.items ?? []).filter(({ key }) => key !== AGENT_TOKEN_METADATA_KEY &&
|
|
604
|
+
key !== AGENT_RUN_METADATA_KEY &&
|
|
605
|
+
key !== IDLE_POWER_OFF_METADATA_KEY);
|
|
496
606
|
try {
|
|
497
607
|
await this.options.compute.setMetadata(instance.name, {
|
|
498
608
|
fingerprint: instance.metadata?.fingerprint,
|
|
@@ -836,7 +946,7 @@ export class Sandboxes {
|
|
|
836
946
|
this.bases.set(image, { namespace, until: Date.now() + IMAGE_KEPT_MS });
|
|
837
947
|
return namespace;
|
|
838
948
|
}
|
|
839
|
-
instanceBody(name, { sourceImage, image, labels = { [LABEL]: 'sandbox', [IMAGE_LABEL]: image }, standard = false, }) {
|
|
949
|
+
instanceBody(name, { sourceImage, image, labels = { [LABEL]: 'sandbox', [IMAGE_LABEL]: image }, metadata = [], standard = false, }) {
|
|
840
950
|
const { machine, zone } = this.options;
|
|
841
951
|
return {
|
|
842
952
|
name,
|
|
@@ -868,6 +978,7 @@ export class Sandboxes {
|
|
|
868
978
|
...this.agentItems(name),
|
|
869
979
|
{ key: 'block-project-ssh-keys', value: 'true' },
|
|
870
980
|
{ key: 'serial-port-enable', value: 'false' },
|
|
981
|
+
...metadata,
|
|
871
982
|
],
|
|
872
983
|
},
|
|
873
984
|
// No service account: nothing in the machine holds a Google credential.
|
|
@@ -877,15 +988,19 @@ export class Sandboxes {
|
|
|
877
988
|
enableVtpm: true,
|
|
878
989
|
enableIntegrityMonitoring: true,
|
|
879
990
|
},
|
|
880
|
-
scheduling:
|
|
881
|
-
? {
|
|
882
|
-
provisioningModel: 'SPOT',
|
|
883
|
-
instanceTerminationAction: 'STOP',
|
|
884
|
-
automaticRestart: false,
|
|
885
|
-
onHostMaintenance: 'TERMINATE',
|
|
886
|
-
...this.runLimit(),
|
|
887
|
-
}
|
|
888
|
-
: { ...STANDARD_SCHEDULING, ...this.runLimit() },
|
|
991
|
+
scheduling: this.scheduling(standard),
|
|
889
992
|
};
|
|
890
993
|
}
|
|
994
|
+
/** How a machine runs: Spot when the service's are, unless `standard`, its run limit either way. */
|
|
995
|
+
scheduling(standard) {
|
|
996
|
+
return this.options.machine.spot && !standard
|
|
997
|
+
? {
|
|
998
|
+
provisioningModel: 'SPOT',
|
|
999
|
+
instanceTerminationAction: 'STOP',
|
|
1000
|
+
automaticRestart: false,
|
|
1001
|
+
onHostMaintenance: 'TERMINATE',
|
|
1002
|
+
...this.runLimit(),
|
|
1003
|
+
}
|
|
1004
|
+
: { ...STANDARD_SCHEDULING, ...this.runLimit() };
|
|
1005
|
+
}
|
|
891
1006
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-sdk-sandbox-gce",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.5",
|
|
4
4
|
"description": "Compute Engine sandboxes for AI SDK harness agents: Claude Code, Codex and friends in a virtual machine of their own on Google Cloud, Docker included, stopped between turns.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -50,18 +50,18 @@
|
|
|
50
50
|
"@ai-sdk/provider-utils": "^5.0.0"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@ai-sdk/harness": "^1.0.
|
|
54
|
-
"@ai-sdk/provider-utils": "^5.0.
|
|
53
|
+
"@ai-sdk/harness": "^1.0.168",
|
|
54
|
+
"@ai-sdk/provider-utils": "^5.0.71",
|
|
55
55
|
"@types/node": "^24.19.2",
|
|
56
56
|
"@vitest/coverage-v8": "^5.0.5",
|
|
57
57
|
"typescript": "^6.0.3",
|
|
58
58
|
"vitest": "^5.0.5",
|
|
59
59
|
"zod": "^4.6.7",
|
|
60
60
|
"@repo/build": "0.0.0",
|
|
61
|
+
"@repo/prettier-config": "0.0.0",
|
|
61
62
|
"@repo/eslint-config": "0.0.0",
|
|
62
63
|
"@repo/vitest-config": "0.0.0",
|
|
63
|
-
"@repo/typescript-config": "0.0.0"
|
|
64
|
-
"@repo/prettier-config": "0.0.0"
|
|
64
|
+
"@repo/typescript-config": "0.0.0"
|
|
65
65
|
},
|
|
66
66
|
"author": {
|
|
67
67
|
"name": "Fabien Pasquet",
|