ai-sdk-sandbox-gce 0.3.6 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +42 -43
- package/dist/client/lifecycle/create-session.js +5 -10
- package/dist/client/lifecycle/sandbox-template.d.ts +8 -0
- package/dist/client/lifecycle/sandbox-template.js +27 -1
- package/dist/in-vm/main.js +0 -4
- package/dist/protocol/proxy.d.ts +1 -15
- package/dist/protocol/proxy.js +1 -4
- package/dist/proxy/admin-server.js +3 -16
- package/dist/proxy/egress-policy.d.ts +0 -3
- package/dist/proxy/egress-proxy.js +0 -1
- package/dist/proxy/main.js +2 -2
- package/dist/proxy/registered-sandbox.d.ts +0 -5
- package/dist/proxy/registered-sandbox.js +0 -5
- package/dist/proxy/registry.d.ts +6 -13
- package/dist/proxy/registry.js +7 -25
- package/dist/server/config.js +0 -10
- package/dist/server/sandboxes/agent-client.d.ts +2 -3
- package/dist/server/sandboxes/agent-client.js +2 -3
- package/dist/server/sandboxes/proxy-admin.d.ts +4 -11
- package/dist/server/sandboxes/proxy-admin.js +5 -23
- package/dist/server/sandboxes/sandboxes.d.ts +6 -29
- package/dist/server/sandboxes/sandboxes.js +15 -74
- package/package.json +2 -2
- package/dist/in-vm/oom-policy.d.ts +0 -23
- package/dist/in-vm/oom-policy.js +0 -50
- package/dist/proxy/traffic.d.ts +0 -19
- package/dist/proxy/traffic.js +0 -39
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# ai-sdk-sandbox-gce
|
|
2
2
|
|
|
3
|
+
## 0.4.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- cb9b124: A process that outlives a template no longer fails every creation from it with a 404 until it restarts: the template is forgotten, built again, and the sandbox created. A template goes with a new version of the service, a new base image on Compute Engine, or a deletion.
|
|
8
|
+
|
|
9
|
+
## 0.4.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 2c49ce6: Four mechanisms go, whose cost outweighed what they protected against, the sandbox and the proxy being the boundary:
|
|
14
|
+
|
|
15
|
+
- The proxy no longer counts the bytes each sandbox moves: nothing but a log line read them. `GET /v1/sandboxes` goes with it, as does its `?serial=` on `DELETE`.
|
|
16
|
+
- The service no longer makes the proxy forget the sandboxes whose machine stopped without it, and `SANDBOX_RECONCILE_MINUTES` is gone: `stop()` and `destroy()` still do so at once, and a new machine on the same address takes the place of the old one in the proxy.
|
|
17
|
+
- An agent keeps its token for as long as its machine lives, rather than get a new one at each `stop()`. A machine made by 0.3.0 to 0.3.6 keeps the token it has.
|
|
18
|
+
- The agent no longer sets `OOMPolicy=continue` on its running service: the line belongs to the unit of the sandbox image, as the README has it. Keep it there, or a command out of memory stops every command of the sandbox.
|
|
19
|
+
|
|
3
20
|
## 0.3.6
|
|
4
21
|
|
|
5
22
|
### 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.
|
|
138
|
+
VERSION=0.4.1
|
|
139
139
|
# Writes $2 to the file $1 when it differs, and says whether it did.
|
|
140
140
|
changed() {
|
|
141
141
|
mkdir -p "$(dirname "$1")"
|
|
@@ -282,7 +282,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
|
|
|
282
282
|
> /etc/apt/sources.list.d/nodesource.list
|
|
283
283
|
apt-get update
|
|
284
284
|
apt-get install -y nodejs
|
|
285
|
-
npm install --global ai-sdk-sandbox-gce@0.
|
|
285
|
+
npm install --global ai-sdk-sandbox-gce@0.4.1 pnpm@10
|
|
286
286
|
|
|
287
287
|
# The sandbox's user: sudo without a password, and Docker.
|
|
288
288
|
useradd --create-home --shell /bin/bash agent
|
|
@@ -306,11 +306,11 @@ UNIT
|
|
|
306
306
|
systemctl enable ai-sdk-sandbox-agent
|
|
307
307
|
```
|
|
308
308
|
|
|
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).
|
|
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). Keep this line in your image's unit. 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.
|
|
310
310
|
|
|
311
311
|
### 4. The service
|
|
312
312
|
|
|
313
|
-
The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.
|
|
313
|
+
The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.4.1 --owner fpasquet` checks; its [`Dockerfile`](https://github.com/fpasquet/ai-sdk-harness/blob/main/packages/sandbox-gce/Dockerfile) builds the same image from your own registry.
|
|
314
314
|
|
|
315
315
|
Its service account gets a role of its own, with what the service calls and nothing else, limited by a condition to the names it uses: the sandboxes' machines and disks (`sbx-`), the proxy's machine, the sandbox images and templates (`ai-sdk-`).
|
|
316
316
|
|
|
@@ -348,7 +348,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
|
|
|
348
348
|
--member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
|
|
349
349
|
done
|
|
350
350
|
|
|
351
|
-
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.
|
|
351
|
+
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.4.1 \
|
|
352
352
|
--service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
|
|
353
353
|
--network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
|
|
354
354
|
--no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
|
|
@@ -381,7 +381,7 @@ gcloud run services add-iam-policy-binding sandboxes --region=$REGION \
|
|
|
381
381
|
--member=serviceAccount:my-app@$PROJECT.iam.gserviceaccount.com --role=roles/run.invoker
|
|
382
382
|
```
|
|
383
383
|
|
|
384
|
-
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
|
|
384
|
+
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. 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.
|
|
385
385
|
|
|
386
386
|
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`.
|
|
387
387
|
|
|
@@ -629,41 +629,40 @@ Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.
|
|
|
629
629
|
|
|
630
630
|
### The service (`serve`)
|
|
631
631
|
|
|
632
|
-
| Variable | Default | Description
|
|
633
|
-
| --------------------------- | ---------------------------------------------------------------------------------------- |
|
|
634
|
-
| `SANDBOX_ZONE` | required | The zone of the machines
|
|
635
|
-
| `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…`
|
|
636
|
-
| `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python`
|
|
637
|
-
| `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager
|
|
638
|
-
| `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128`
|
|
639
|
-
| `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129`
|
|
640
|
-
| `SANDBOX_PROXY_TOKEN` | required | The proxy's token
|
|
641
|
-
| `SANDBOX_PROJECT` | the service's project | The project of the machines
|
|
642
|
-
| `SANDBOX_NETWORK` | the default network | The machines' VPC network
|
|
643
|
-
| `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>`
|
|
644
|
-
| `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to
|
|
645
|
-
| `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192`
|
|
646
|
-
| `SANDBOX_DISK_GB` | `20` | The size of their disk
|
|
647
|
-
| `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type
|
|
648
|
-
| `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after
|
|
649
|
-
| `SANDBOX_SPOT_FALLBACK` | `true` | With Spot, a machine the zone has no Spot capacity for is created or started as a standard one, billed as such; `false` fails instead
|
|
650
|
-
| `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most
|
|
651
|
-
| `SANDBOX_AGENT_PORT` | `8100` | The port of the agents
|
|
652
|
-
| `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer
|
|
653
|
-
| `SANDBOX_MAX_RUNNING` | none | The most sandboxes running at once: a creation or a resume beyond it is answered with a 429. Counted at each call, so two at the same instant may both pass
|
|
654
|
-
| `SANDBOX_MAX_RUN_HOURS` | none | The longest a machine runs at a time: Compute Engine stops it then (`maxRunDuration`), disk kept, whatever the service or the application do. 30 s at least
|
|
655
|
-
| `
|
|
656
|
-
| `
|
|
657
|
-
| `
|
|
658
|
-
| `
|
|
659
|
-
| `
|
|
660
|
-
| `
|
|
661
|
-
| `
|
|
662
|
-
| `
|
|
663
|
-
| `
|
|
664
|
-
| `
|
|
665
|
-
| `
|
|
666
|
-
| `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text |
|
|
632
|
+
| Variable | Default | Description |
|
|
633
|
+
| --------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
634
|
+
| `SANDBOX_ZONE` | required | The zone of the machines |
|
|
635
|
+
| `SANDBOX_IMAGE` | required | The sandbox image: a name, `family/<family>`, or `projects/<project>/global/images/…` |
|
|
636
|
+
| `SANDBOX_IMAGES` | none | Other images callers may pick by name, as `NAME=image` pairs: `python=family/ai-sdk-sandbox-python` |
|
|
637
|
+
| `SANDBOX_AGENT_SECRET` | required | 32 characters at least: the agents' tokens are derived from it. Keep it in Secret Manager |
|
|
638
|
+
| `SANDBOX_PROXY_URL` | required | The proxy, as the machines reach it: `http://10.8.16.2:3128` |
|
|
639
|
+
| `SANDBOX_PROXY_ADMIN_URL` | required | Its administration API: `http://10.8.16.2:3129` |
|
|
640
|
+
| `SANDBOX_PROXY_TOKEN` | required | The proxy's token |
|
|
641
|
+
| `SANDBOX_PROJECT` | the service's project | The project of the machines |
|
|
642
|
+
| `SANDBOX_NETWORK` | the default network | The machines' VPC network |
|
|
643
|
+
| `SANDBOX_SUBNETWORK` | none | Their subnetwork: `regions/<region>/subnetworks/<name>` |
|
|
644
|
+
| `SANDBOX_NETWORK_TAGS` | `ai-sdk-sandbox` | Their network tags, which the firewall rules apply to |
|
|
645
|
+
| `SANDBOX_MACHINE_TYPE` | `e2-standard-4` | Their machine type, a custom one included: `e2-custom-4-8192` |
|
|
646
|
+
| `SANDBOX_DISK_GB` | `20` | The size of their disk |
|
|
647
|
+
| `SANDBOX_DISK_TYPE` | `pd-balanced` | Its type |
|
|
648
|
+
| `SANDBOX_SPOT` | `false` | `true` for Spot machines: cheaper, stopped when Compute Engine takes them back, resumable after |
|
|
649
|
+
| `SANDBOX_SPOT_FALLBACK` | `true` | With Spot, a machine the zone has no Spot capacity for is created or started as a standard one, billed as such; `false` fails instead |
|
|
650
|
+
| `SANDBOX_INSTANCE_PREFIX` | `sbx-` | Put before a sandbox's name to make its machine's, 8 characters at most |
|
|
651
|
+
| `SANDBOX_AGENT_PORT` | `8100` | The port of the agents |
|
|
652
|
+
| `SANDBOX_START_TIMEOUT` | `300` | Seconds a machine has to boot and its agent to answer |
|
|
653
|
+
| `SANDBOX_MAX_RUNNING` | none | The most sandboxes running at once: a creation or a resume beyond it is answered with a 429. Counted at each call, so two at the same instant may both pass |
|
|
654
|
+
| `SANDBOX_MAX_RUN_HOURS` | none | The longest a machine runs at a time: Compute Engine stops it then (`maxRunDuration`), disk kept, whatever the service or the application do. 30 s at least |
|
|
655
|
+
| `SANDBOX_PROXY_INSTANCE` | none | The egress proxy's machine, in the sandboxes' zone: started with the first sandbox that runs, stopped once none does and no prepared machine waits for one. Always on without it |
|
|
656
|
+
| `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
|
|
657
|
+
| `SANDBOX_WARM_POOL` | `0`, `1` with `fast` | How many machines are kept booted from each template used in the last 24 h, for the next creations from it to take at once. Each one is billed all the time |
|
|
658
|
+
| `SANDBOX_PROXY_ALWAYS_ON` | `false`, `true` with `fast` | `true`: the service starts the proxy's machine of `SANDBOX_PROXY_INSTANCE` with the first sandbox, and never stops it. No sandbox waits for it to boot, and it is billed all the time |
|
|
659
|
+
| `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup |
|
|
660
|
+
| `SANDBOX_BASE_URLS` | `ANTHROPIC_BASE_URL=https://api.anthropic.com,OPENAI_BASE_URL=https://api.openai.com/v1` | Base URL variables routed through the proxy, as `NAME=url` pairs |
|
|
661
|
+
| `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM |
|
|
662
|
+
| `SANDBOX_INSECURE_NO_TOKEN` | `false` | `true` to run on Cloud Run without `SANDBOX_SERVICE_TOKEN`, its IAM the only lock |
|
|
663
|
+
| `COMPUTE_AUTH` | `metadata` on Cloud Run, `gcloud` elsewhere | How the service gets its access tokens for the Compute Engine API |
|
|
664
|
+
| `PORT`, `HOST` | `8080`, `0.0.0.0` on Cloud Run and `127.0.0.1` elsewhere | Where the service listens |
|
|
665
|
+
| `LOG_FORMAT` | `json` on Cloud Run, `text` elsewhere | JSON lines for Cloud Logging, or plain text |
|
|
667
666
|
|
|
668
667
|
### The proxy (`proxy`)
|
|
669
668
|
|
|
@@ -714,11 +713,11 @@ To keep the bill down: stop idle sandboxes early, delete finished ones, delete o
|
|
|
714
713
|
- **The agents answer the service alone**: the firewall lets only the service's subnetwork reach their port, and every call carries a token derived from `SANDBOX_AGENT_SECRET` for that machine and its run, drawn anew when the machine is made and at each `stop()`: a token read once serves until the next stop. A machine only ever learns its own token, from its metadata, which whoever may read the project's machines reads too: see [Who may call it](#5-who-may-call-it).
|
|
715
714
|
- **Inside the VPC, traffic is plain HTTP**: the service's calls to the agents and to the proxy's administration API, real credentials included, and the sandboxes' requests to the base URL routes. Google Cloud encrypts traffic between its hosts and lets no machine listen to another's; nothing of the package adds TLS on top.
|
|
716
715
|
- **The sandbox's user has `sudo`, and Docker**: inside the machine, the agent's code can do anything. The machine is the boundary, not the user. What the agent changes on the disk, the machine's own `agent` service included, survives a stop: never hand a sandbox to another user, and never save one an agent worked in as a template.
|
|
717
|
-
- **An allowed host is a way out for data**: the allow list says where the sandbox's requests may go, not what they carry. An agent led astray by a prompt injection may push the sandbox's files to `github.com`, or publish them to a registry, with credentials of its own. Allow only the hosts a task needs; keep `*` and wildcards on shared domains (`*.googleapis.com`, `*.amazonaws.com`, `*.githubusercontent.com`, `*.cloudfront.net`) out of production, since anyone can own a bucket or a site under them. The service logs a warning when `SANDBOX_ALLOWED_HOSTS` holds `*`.
|
|
716
|
+
- **An allowed host is a way out for data**: the allow list says where the sandbox's requests may go, not what they carry. An agent led astray by a prompt injection may push the sandbox's files to `github.com`, or publish them to a registry, with credentials of its own. Allow only the hosts a task needs; keep `*` and wildcards on shared domains (`*.googleapis.com`, `*.amazonaws.com`, `*.githubusercontent.com`, `*.cloudfront.net`) out of production, since anyone can own a bucket or a site under them. The service logs a warning when `SANDBOX_ALLOWED_HOSTS` holds `*`.
|
|
718
717
|
- **A credential goes to every request its transformation matches**: the harnesses' own transformations match the placeholder the sandbox sends, so only a request carrying it gets the real value. A transformation of yours that names a host alone puts the credential in any request to that host. Cap the credential at the provider as well: a budget, the narrowest scope a token takes.
|
|
719
718
|
- **The proxy holds the credentials of every running sandbox**, in memory. Keep it a machine of its own, with nothing else on it, a service account that may only read its token and write logs, and its administration port open to the service alone.
|
|
720
719
|
- **The service trusts its callers**: anyone granted `roles/run.invoker` can run commands in any sandbox. It has no notion of a user: your application decides which sandbox a user reaches. Name sandboxes after a random id, kept beside the user's session on the server, never after anything a user can guess or send. Never deploy it with `--allow-unauthenticated`; `SANDBOX_SERVICE_TOKEN` is the second lock, required on Cloud Run.
|
|
721
|
-
- **A machine stopped outside the service keeps its credentials in the proxy for a while**: a Spot machine taken back, one stopped at `SANDBOX_MAX_RUN_HOURS` or from the console. The
|
|
720
|
+
- **A machine stopped outside the service keeps its credentials in the proxy for a while**: a Spot machine taken back, one stopped at `SANDBOX_MAX_RUN_HOURS` or from the console. The application stopping or deleting the sandbox makes the proxy forget them at once, and so does the proxy restarting. A new machine that gets the same address takes the place of the old one in the proxy, so it never reaches them. Stop idle sandboxes from the application even when their machine already stopped.
|
|
722
721
|
- **Disks and template images hold the sandbox's files**: the agent's work and its transcript. They stay in your project; delete them with the sandbox.
|
|
723
722
|
- **Metadata**: a machine reads its own metadata, project metadata included. Keep secrets out of the project's metadata, and SSH keys too (the service blocks project SSH keys on the machines).
|
|
724
723
|
|
|
@@ -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 {
|
|
8
|
+
import { runSetup, templateId, withTemplate } from './sandbox-template.js';
|
|
9
9
|
/**
|
|
10
10
|
* What a Compute Engine instance name takes once the service's prefix is put before it, and a URL
|
|
11
11
|
* path as it is: the instance name is at most 63 characters and never ends with a dash.
|
|
@@ -55,15 +55,10 @@ export async function createGceNetworkSandboxSession(options) {
|
|
|
55
55
|
assertSandboxName(name);
|
|
56
56
|
const client = clientOf(options);
|
|
57
57
|
const network = { allowedHosts, baseUrls };
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
...network,
|
|
63
|
-
image,
|
|
64
|
-
template: ready,
|
|
65
|
-
abortSignal,
|
|
66
|
-
});
|
|
58
|
+
const create = (ready) => createFrom(client, name, { ...network, image, template: ready, abortSignal });
|
|
59
|
+
const description = await (template
|
|
60
|
+
? withTemplate(client, { template, setup, network, image, requiredCommands, abortSignal }, create)
|
|
61
|
+
: create());
|
|
67
62
|
const session = sessionOf(client, description, options);
|
|
68
63
|
try {
|
|
69
64
|
// A template was checked and set up before it was saved.
|
|
@@ -41,4 +41,12 @@ export declare function runSetup(session: GceNetworkSandboxSession, setup: reado
|
|
|
41
41
|
* already installed.
|
|
42
42
|
*/
|
|
43
43
|
export declare function ensureTemplate(client: SandboxServiceClient, source: BuildSettings & TemplateSource, abortSignal?: AbortSignal): Promise<ReadyTemplate>;
|
|
44
|
+
/**
|
|
45
|
+
* Calls `create` with the template ready. This process remembers a template for as long as it runs,
|
|
46
|
+
* and the service can lose it meanwhile, to a new version or a new base image: on
|
|
47
|
+
* its 404, the template is forgotten, built again if need be, and `create` called once more.
|
|
48
|
+
*/
|
|
49
|
+
export declare function withTemplate<T>(client: SandboxServiceClient, { abortSignal, ...source }: BuildSettings & TemplateSource & {
|
|
50
|
+
abortSignal?: AbortSignal;
|
|
51
|
+
}, create: (template: ReadyTemplate) => Promise<T>): Promise<T>;
|
|
44
52
|
export {};
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { GceSandboxServiceError } from '../errors/gce-sandbox-service-error.js';
|
|
2
3
|
import { GceNetworkSandboxSession } from '../session/gce-network-sandbox-session.js';
|
|
3
4
|
import { assertRequiredCommands } from './required-commands.js';
|
|
4
5
|
/** The prefix of the templates' ids, and of the sandboxes that build them. */
|
|
5
6
|
export const TEMPLATE_PREFIX = 'ai-sdk-harness-template';
|
|
6
7
|
/** Templates being built by this process, by service and id: one build at a time. */
|
|
7
8
|
const building = new Map();
|
|
9
|
+
function keyOf(client, source) {
|
|
10
|
+
return `${client.baseUrl} ${source.image ?? ''} ${templateId(source)}`;
|
|
11
|
+
}
|
|
8
12
|
/**
|
|
9
13
|
* The template's id: `ai-sdk-harness-template-<digest>`, the digest covering the harness's recipe
|
|
10
14
|
* and the setup commands, so that a new harness version gets a template of its own.
|
|
@@ -33,7 +37,7 @@ export async function runSetup(session, setup, abortSignal) {
|
|
|
33
37
|
*/
|
|
34
38
|
export function ensureTemplate(client, source, abortSignal) {
|
|
35
39
|
const id = templateId(source);
|
|
36
|
-
const key =
|
|
40
|
+
const key = keyOf(client, source);
|
|
37
41
|
let ready = building.get(key);
|
|
38
42
|
if (ready === undefined) {
|
|
39
43
|
ready = client.templateExists(id, source.image, abortSignal).then(async (exists) => {
|
|
@@ -54,6 +58,28 @@ export function ensureTemplate(client, source, abortSignal) {
|
|
|
54
58
|
}
|
|
55
59
|
return ready;
|
|
56
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Calls `create` with the template ready. This process remembers a template for as long as it runs,
|
|
63
|
+
* and the service can lose it meanwhile, to a new version or a new base image: on
|
|
64
|
+
* its 404, the template is forgotten, built again if need be, and `create` called once more.
|
|
65
|
+
*/
|
|
66
|
+
export async function withTemplate(client, { abortSignal, ...source }, create) {
|
|
67
|
+
const remembered = ensureTemplate(client, source, abortSignal);
|
|
68
|
+
const template = await remembered;
|
|
69
|
+
try {
|
|
70
|
+
return await create(template);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (!(error instanceof GceSandboxServiceError) || error.status !== 404)
|
|
74
|
+
throw error;
|
|
75
|
+
// Sandboxes that failed alongside this one share the build that comes after.
|
|
76
|
+
const key = keyOf(client, source);
|
|
77
|
+
if (building.get(key) === remembered)
|
|
78
|
+
building.delete(key);
|
|
79
|
+
const rebuilt = await ensureTemplate(client, source, abortSignal);
|
|
80
|
+
return create(rebuilt);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
57
83
|
async function build(client, { template, setup, network, image, requiredCommands, id, }, abortSignal) {
|
|
58
84
|
const builder = `${TEMPLATE_PREFIX}-${id.slice(-8)}-${randomBytes(3).toString('hex')}`;
|
|
59
85
|
const { workingDirectory } = await client.create(builder, { ...network, image, abortSignal });
|
package/dist/in-vm/main.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
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';
|
|
5
4
|
/**
|
|
6
5
|
* `ai-sdk-sandbox-gce agent`: serves the agent of a sandbox's machine until systemd stops it, the
|
|
7
6
|
* processes it started stopped with it.
|
|
@@ -9,9 +8,6 @@ import { keepRunningOnOomKill } from './oom-policy.js';
|
|
|
9
8
|
export async function main(env) {
|
|
10
9
|
const logger = createLogger({ json: env['LOG_FORMAT'] !== 'text' });
|
|
11
10
|
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 });
|
|
15
11
|
const agent = createAgentServer(await agentSettings(env, logger));
|
|
16
12
|
agent.server.listen(config.port, config.host, () => logger.info(`Agent listening on ${config.host}:${config.port}`));
|
|
17
13
|
for (const signal of ['SIGTERM', 'SIGINT']) {
|
package/dist/protocol/proxy.d.ts
CHANGED
|
@@ -9,10 +9,7 @@
|
|
|
9
9
|
* - `POST` and `PUT /v1/sandboxes/:name/transformations`: `{ transformations }`, added or replaced;
|
|
10
10
|
* - `POST /v1/sandboxes/:name/screen`: `{ texts }`, answered `{ refused }`, whether one of them holds
|
|
11
11
|
* a credential the proxy keeps for the sandbox;
|
|
12
|
-
* - `
|
|
13
|
-
* the bytes each moved;
|
|
14
|
-
* - `DELETE /v1/sandboxes/:name`: forgets the sandbox and its credentials; with `?serial=`, only
|
|
15
|
-
* when that registration is still the sandbox's, not one made since.
|
|
12
|
+
* - `DELETE /v1/sandboxes/:name`: forgets the sandbox and its credentials.
|
|
16
13
|
*/
|
|
17
14
|
/** A sandbox, as the proxy knows it. */
|
|
18
15
|
export interface ProxyRegistration {
|
|
@@ -23,17 +20,6 @@ export interface ProxyRegistration {
|
|
|
23
20
|
/** Base URL variables and where they lead: their hosts are always reachable through a route. */
|
|
24
21
|
baseUrls: Readonly<Record<string, string>>;
|
|
25
22
|
}
|
|
26
|
-
/** A sandbox the proxy holds, as it lists them. */
|
|
27
|
-
export interface ProxySandbox {
|
|
28
|
-
name: string;
|
|
29
|
-
/** The address of its machine, normalized. */
|
|
30
|
-
address: string;
|
|
31
|
-
/** What tells its registration from the next one: another at each registration. */
|
|
32
|
-
serial: number;
|
|
33
|
-
/** The bytes it sent out through the proxy, and received back, since it was first registered. */
|
|
34
|
-
sent: number;
|
|
35
|
-
received: number;
|
|
36
|
-
}
|
|
37
23
|
/** The port the proxy serves the sandboxes on. */
|
|
38
24
|
export declare const DEFAULT_PROXY_PORT = 3128;
|
|
39
25
|
/** The port of its administration API. */
|
package/dist/protocol/proxy.js
CHANGED
|
@@ -9,10 +9,7 @@
|
|
|
9
9
|
* - `POST` and `PUT /v1/sandboxes/:name/transformations`: `{ transformations }`, added or replaced;
|
|
10
10
|
* - `POST /v1/sandboxes/:name/screen`: `{ texts }`, answered `{ refused }`, whether one of them holds
|
|
11
11
|
* a credential the proxy keeps for the sandbox;
|
|
12
|
-
* - `
|
|
13
|
-
* the bytes each moved;
|
|
14
|
-
* - `DELETE /v1/sandboxes/:name`: forgets the sandbox and its credentials; with `?serial=`, only
|
|
15
|
-
* when that registration is still the sandbox's, not one made since.
|
|
12
|
+
* - `DELETE /v1/sandboxes/:name`: forgets the sandbox and its credentials.
|
|
16
13
|
*/
|
|
17
14
|
/** The port the proxy serves the sandboxes on. */
|
|
18
15
|
export const DEFAULT_PROXY_PORT = 3128;
|
|
@@ -5,16 +5,6 @@ import { bearer, fail, NO_CONTENT, sameSecret, send } from '../common/http-reply
|
|
|
5
5
|
import { PACKAGE_VERSION } from '../common/package-version.js';
|
|
6
6
|
import { PROTOCOL_HEADER, PROTOCOL_VERSION } from '../protocol/version.js';
|
|
7
7
|
const SANDBOX = /^\/v1\/sandboxes\/([a-z0-9-]+)(\/[a-z]+)?$/;
|
|
8
|
-
/** `?serial=`, the registration a removal is meant for. */
|
|
9
|
-
function serialOf(query) {
|
|
10
|
-
const raw = query.get('serial');
|
|
11
|
-
if (raw === null)
|
|
12
|
-
return undefined;
|
|
13
|
-
const serial = Number(raw);
|
|
14
|
-
if (!Number.isSafeInteger(serial))
|
|
15
|
-
throw new HttpError(400, '`serial` must be an integer.');
|
|
16
|
-
return serial;
|
|
17
|
-
}
|
|
18
8
|
/** What each route does to the registry. */
|
|
19
9
|
const ROUTES = {
|
|
20
10
|
'PUT ': (registry, { name, body }) => {
|
|
@@ -25,8 +15,8 @@ const ROUTES = {
|
|
|
25
15
|
});
|
|
26
16
|
return NO_CONTENT;
|
|
27
17
|
},
|
|
28
|
-
'DELETE ': (registry, { name
|
|
29
|
-
registry.remove(name
|
|
18
|
+
'DELETE ': (registry, { name }) => {
|
|
19
|
+
registry.remove(name);
|
|
30
20
|
return NO_CONTENT;
|
|
31
21
|
},
|
|
32
22
|
'PUT /network': (registry, { name, body }) => {
|
|
@@ -48,15 +38,12 @@ const ROUTES = {
|
|
|
48
38
|
};
|
|
49
39
|
async function handle(registry, request, url) {
|
|
50
40
|
const path = url.pathname;
|
|
51
|
-
if (request.method === 'GET' && path === '/v1/sandboxes') {
|
|
52
|
-
return { status: 200, body: { sandboxes: registry.list() } };
|
|
53
|
-
}
|
|
54
41
|
const [, name, action = ''] = SANDBOX.exec(path) ?? [];
|
|
55
42
|
const route = ROUTES[`${request.method} ${action}`];
|
|
56
43
|
if (name === undefined || route === undefined) {
|
|
57
44
|
throw new HttpError(404, `No route for ${request.method} ${path}.`);
|
|
58
45
|
}
|
|
59
|
-
return route(registry, { name, body: await readJson(request)
|
|
46
|
+
return route(registry, { name, body: await readJson(request) });
|
|
60
47
|
}
|
|
61
48
|
/**
|
|
62
49
|
* The administration API of the egress proxy (`protocol/proxy.ts`): the sandbox service registers
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { HarnessV1RequestTransformation } from '@ai-sdk/harness';
|
|
2
2
|
import type { IncomingHttpHeaders } from 'node:http';
|
|
3
|
-
import type { Traffic } from './traffic.js';
|
|
4
3
|
/** What one sandbox may reach, and the credentials its requests leave with. */
|
|
5
4
|
export interface EgressPolicy {
|
|
6
5
|
/** The sandbox's name, which the proxy's log lines name it by. */
|
|
@@ -13,8 +12,6 @@ export interface EgressPolicy {
|
|
|
13
12
|
readonly transformations: readonly HarnessV1RequestTransformation[];
|
|
14
13
|
/** Let it reach private addresses and plain HTTP base URLs: tests and local runs only. */
|
|
15
14
|
readonly allowPrivateNetwork: boolean;
|
|
16
|
-
/** Where the bytes its connections move are counted. */
|
|
17
|
-
readonly traffic?: Traffic;
|
|
18
15
|
}
|
|
19
16
|
/** What the egress proxy knows of one request on its way out. */
|
|
20
17
|
export interface OutgoingRequest {
|
package/dist/proxy/main.js
CHANGED
|
@@ -47,7 +47,7 @@ export function main(env) {
|
|
|
47
47
|
if (config.allowPrivateNetwork) {
|
|
48
48
|
logger.warn('SANDBOX_ALLOW_PRIVATE_NETWORK=true: the sandboxes may reach the VPC and the metadata server. For tests only.');
|
|
49
49
|
}
|
|
50
|
-
const registry = new SandboxRegistry(config.allowPrivateNetwork
|
|
50
|
+
const registry = new SandboxRegistry(config.allowPrivateNetwork);
|
|
51
51
|
const proxy = new EgressProxy((address) => registry.policyFor(address), logger, {
|
|
52
52
|
maxConnections: config.maxConnections,
|
|
53
53
|
});
|
|
@@ -66,7 +66,7 @@ export function main(env) {
|
|
|
66
66
|
if (idleExitMs !== undefined) {
|
|
67
67
|
watchIdle({
|
|
68
68
|
idleMs: idleExitMs,
|
|
69
|
-
sandboxes: () => registry.
|
|
69
|
+
sandboxes: () => registry.size,
|
|
70
70
|
onIdle: () => {
|
|
71
71
|
logger.info(`No sandbox for ${idleExitMs / 60_000} min: exiting for the machine to stop`);
|
|
72
72
|
shutDown(IDLE_EXIT_CODE);
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { HarnessV1RequestTransformation } from '@ai-sdk/harness';
|
|
2
2
|
import type { ProxyRegistration } from '../protocol/proxy.js';
|
|
3
3
|
import type { EgressPolicy } from './egress-policy.js';
|
|
4
|
-
import { Traffic } from './traffic.js';
|
|
5
4
|
/** An IPv4 address as Node.js reports a connection's on a dual-stack socket: `::ffff:10.0.0.3`. */
|
|
6
5
|
export declare const normalizeAddress: (address: string) => string;
|
|
7
6
|
/** One sandbox, as the proxy knows it: its machine's address, what it may reach, its credentials. */
|
|
@@ -12,10 +11,6 @@ export declare class RegisteredSandbox implements EgressPolicy {
|
|
|
12
11
|
allowedHosts: readonly string[];
|
|
13
12
|
upstreamHosts: readonly string[];
|
|
14
13
|
transformations: HarnessV1RequestTransformation[];
|
|
15
|
-
/** What tells this registration from the next one of the same sandbox: the registry's to set. */
|
|
16
|
-
serial: number;
|
|
17
|
-
/** The bytes it moved, kept when it is registered again. */
|
|
18
|
-
traffic: Traffic;
|
|
19
14
|
constructor(name: string, registration: ProxyRegistration, allowPrivateNetwork: boolean);
|
|
20
15
|
/** The secrets the proxy holds for the sandbox: what its transformations put in requests. */
|
|
21
16
|
get secrets(): string[];
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { hostsOf } from '../protocol/proxy-routes.js';
|
|
2
|
-
import { Traffic } from './traffic.js';
|
|
3
2
|
/** The scheme a credential header value may start with, before the secret itself. */
|
|
4
3
|
const SCHEME = /^(Bearer|Basic|Token)\s+/i;
|
|
5
4
|
/** Shorter values are no secret worth guarding, and would match by chance. */
|
|
@@ -14,10 +13,6 @@ export class RegisteredSandbox {
|
|
|
14
13
|
allowedHosts;
|
|
15
14
|
upstreamHosts;
|
|
16
15
|
transformations = [];
|
|
17
|
-
/** What tells this registration from the next one of the same sandbox: the registry's to set. */
|
|
18
|
-
serial = 0;
|
|
19
|
-
/** The bytes it moved, kept when it is registered again. */
|
|
20
|
-
traffic = new Traffic();
|
|
21
16
|
constructor(name, registration, allowPrivateNetwork) {
|
|
22
17
|
this.name = name;
|
|
23
18
|
this.allowPrivateNetwork = allowPrivateNetwork;
|
package/dist/proxy/registry.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { HarnessV1RequestTransformation } from '@ai-sdk/harness';
|
|
2
|
-
import type {
|
|
3
|
-
import type { ProxyRegistration, ProxySandbox } from '../protocol/proxy.js';
|
|
2
|
+
import type { ProxyRegistration } from '../protocol/proxy.js';
|
|
4
3
|
import type { EgressPolicy } from './egress-policy.js';
|
|
5
4
|
/**
|
|
6
5
|
* The sandboxes the proxy serves, by name and by the address of their machine. Kept in memory
|
|
@@ -9,16 +8,13 @@ import type { EgressPolicy } from './egress-policy.js';
|
|
|
9
8
|
*/
|
|
10
9
|
export declare class SandboxRegistry {
|
|
11
10
|
private readonly allowPrivateNetwork;
|
|
12
|
-
private readonly logger;
|
|
13
11
|
private readonly byName;
|
|
14
12
|
private readonly byAddress;
|
|
15
|
-
private registrations;
|
|
16
13
|
/**
|
|
17
14
|
* @param allowPrivateNetwork Let the sandboxes reach private addresses and plain HTTP base URLs:
|
|
18
15
|
* tests and local runs only.
|
|
19
|
-
* @param logger Where the bytes a sandbox moved are told, once it is forgotten.
|
|
20
16
|
*/
|
|
21
|
-
constructor(allowPrivateNetwork?: boolean
|
|
17
|
+
constructor(allowPrivateNetwork?: boolean);
|
|
22
18
|
/**
|
|
23
19
|
* Registers the sandbox `name`, or registers it again after its machine started anew, perhaps
|
|
24
20
|
* on another address: what it may reach is replaced, its credentials kept.
|
|
@@ -30,13 +26,10 @@ export declare class SandboxRegistry {
|
|
|
30
26
|
setTransformations(name: string, transformations: HarnessV1RequestTransformation[]): void;
|
|
31
27
|
/** Whether one of `texts` holds a credential the proxy keeps for the sandbox `name`. */
|
|
32
28
|
holdsSecret(name: string, texts: readonly string[]): boolean;
|
|
33
|
-
/**
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
|
|
37
|
-
* {@link list} gave it: one made since, its machine started again meanwhile, is kept. Idempotent.
|
|
38
|
-
*/
|
|
39
|
-
remove(name: string, serial?: number): void;
|
|
29
|
+
/** How many sandboxes the proxy holds. */
|
|
30
|
+
get size(): number;
|
|
31
|
+
/** Forgets the sandbox `name` and its credentials. Idempotent. */
|
|
32
|
+
remove(name: string): void;
|
|
40
33
|
/** The policy of the sandbox whose machine has `address`, if one has. */
|
|
41
34
|
policyFor(address: string | undefined): EgressPolicy | undefined;
|
|
42
35
|
private get;
|
package/dist/proxy/registry.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { HttpError } from '../common/http-error.js';
|
|
2
|
-
import { silentLogger } from '../common/logger.js';
|
|
3
2
|
import { normalizeAddress, RegisteredSandbox } from './registered-sandbox.js';
|
|
4
|
-
import { formatBytes } from './traffic.js';
|
|
5
3
|
/**
|
|
6
4
|
* The sandboxes the proxy serves, by name and by the address of their machine. Kept in memory
|
|
7
5
|
* alone: the credentials never touch a disk. A connection from an address no sandbox holds is
|
|
@@ -9,18 +7,14 @@ import { formatBytes } from './traffic.js';
|
|
|
9
7
|
*/
|
|
10
8
|
export class SandboxRegistry {
|
|
11
9
|
allowPrivateNetwork;
|
|
12
|
-
logger;
|
|
13
10
|
byName = new Map();
|
|
14
11
|
byAddress = new Map();
|
|
15
|
-
registrations = 0;
|
|
16
12
|
/**
|
|
17
13
|
* @param allowPrivateNetwork Let the sandboxes reach private addresses and plain HTTP base URLs:
|
|
18
14
|
* tests and local runs only.
|
|
19
|
-
* @param logger Where the bytes a sandbox moved are told, once it is forgotten.
|
|
20
15
|
*/
|
|
21
|
-
constructor(allowPrivateNetwork = false
|
|
16
|
+
constructor(allowPrivateNetwork = false) {
|
|
22
17
|
this.allowPrivateNetwork = allowPrivateNetwork;
|
|
23
|
-
this.logger = logger;
|
|
24
18
|
}
|
|
25
19
|
/**
|
|
26
20
|
* Registers the sandbox `name`, or registers it again after its machine started anew, perhaps
|
|
@@ -28,11 +22,9 @@ export class SandboxRegistry {
|
|
|
28
22
|
*/
|
|
29
23
|
register(name, registration) {
|
|
30
24
|
const next = new RegisteredSandbox(name, registration, this.allowPrivateNetwork);
|
|
31
|
-
next.serial = ++this.registrations;
|
|
32
25
|
const previous = this.byName.get(name);
|
|
33
26
|
if (previous !== undefined) {
|
|
34
27
|
next.transformations = previous.transformations;
|
|
35
|
-
next.traffic = previous.traffic;
|
|
36
28
|
this.forgetAddress(name, previous.address);
|
|
37
29
|
}
|
|
38
30
|
this.byName.set(name, next);
|
|
@@ -53,27 +45,17 @@ export class SandboxRegistry {
|
|
|
53
45
|
const secrets = this.byName.get(name)?.secrets ?? [];
|
|
54
46
|
return secrets.some((secret) => texts.some((text) => text.includes(secret)));
|
|
55
47
|
}
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
return
|
|
59
|
-
name,
|
|
60
|
-
address,
|
|
61
|
-
serial,
|
|
62
|
-
...traffic.totals,
|
|
63
|
-
}));
|
|
48
|
+
/** How many sandboxes the proxy holds. */
|
|
49
|
+
get size() {
|
|
50
|
+
return this.byName.size;
|
|
64
51
|
}
|
|
65
|
-
/**
|
|
66
|
-
|
|
67
|
-
* {@link list} gave it: one made since, its machine started again meanwhile, is kept. Idempotent.
|
|
68
|
-
*/
|
|
69
|
-
remove(name, serial) {
|
|
52
|
+
/** Forgets the sandbox `name` and its credentials. Idempotent. */
|
|
53
|
+
remove(name) {
|
|
70
54
|
const sandbox = this.byName.get(name);
|
|
71
|
-
if (sandbox === undefined
|
|
55
|
+
if (sandbox === undefined)
|
|
72
56
|
return;
|
|
73
57
|
this.byName.delete(name);
|
|
74
58
|
this.forgetAddress(name, sandbox.address);
|
|
75
|
-
const { sent, received } = sandbox.traffic.totals;
|
|
76
|
-
this.logger.info(`${name} forgotten, having sent ${formatBytes(sent)} out and received ${formatBytes(received)}`);
|
|
77
59
|
}
|
|
78
60
|
/** The policy of the sandbox whose machine has `address`, if one has. */
|
|
79
61
|
policyFor(address) {
|
package/dist/server/config.js
CHANGED
|
@@ -110,15 +110,6 @@ function maxRunning(value) {
|
|
|
110
110
|
}
|
|
111
111
|
return parsed;
|
|
112
112
|
}
|
|
113
|
-
/** `SANDBOX_RECONCILE_MINUTES`: 10 when unset, `0` for never. */
|
|
114
|
-
function reconcileEveryMs(value) {
|
|
115
|
-
const text = nonEmpty(value) ?? '10';
|
|
116
|
-
const minutes = Number(text);
|
|
117
|
-
if (!Number.isFinite(minutes) || minutes < 0) {
|
|
118
|
-
throw new Error(`SANDBOX_RECONCILE_MINUTES: \`${text}\` is not a number of minutes.`);
|
|
119
|
-
}
|
|
120
|
-
return minutes === 0 ? undefined : minutes * 60_000;
|
|
121
|
-
}
|
|
122
113
|
/**
|
|
123
114
|
* What `SANDBOX_PROFILE` sets the defaults of: `cost`, nothing running but the sandboxes, each
|
|
124
115
|
* booted on demand; `fast`, a machine of the warm pool always booted and the proxy always on, for a
|
|
@@ -231,7 +222,6 @@ export async function sandboxesConfig(env, logger) {
|
|
|
231
222
|
},
|
|
232
223
|
startTimeoutMs: Number.parseInt(env['SANDBOX_START_TIMEOUT'] ?? '300', 10) * 1000,
|
|
233
224
|
maxRunning: maxRunning(env['SANDBOX_MAX_RUNNING']),
|
|
234
|
-
reconcileEveryMs: reconcileEveryMs(env['SANDBOX_RECONCILE_MINUTES']),
|
|
235
225
|
proxyInstance: nonEmpty(env['SANDBOX_PROXY_INSTANCE']),
|
|
236
226
|
...speedSettings(env, logger),
|
|
237
227
|
serviceToken: serviceToken(env, logger),
|
|
@@ -3,9 +3,8 @@ import type { AgentConfig, AgentDescription } from '../../protocol/agent.js';
|
|
|
3
3
|
/**
|
|
4
4
|
* The token of the agent of the machine `instance`: derived from the service's secret, so that
|
|
5
5
|
* any instance of the service finds it again without keeping it, and a machine only ever learns
|
|
6
|
-
* its own. `run
|
|
7
|
-
*
|
|
8
|
-
* machine made before runs were drawn.
|
|
6
|
+
* its own. `run` is what the token of a machine made by versions 0.3.0 to 0.3.6 also covers, read
|
|
7
|
+
* from its metadata: the agent of such a machine goes on reading the token it was given.
|
|
9
8
|
*/
|
|
10
9
|
export declare function agentToken(secret: string, instance: string, run?: string): string;
|
|
11
10
|
/** Where the agent of a running machine is reached, and what it is proven to with. */
|
|
@@ -6,9 +6,8 @@ import { PROTOCOL_HEADER, PROTOCOL_VERSION } from '../../protocol/version.js';
|
|
|
6
6
|
/**
|
|
7
7
|
* The token of the agent of the machine `instance`: derived from the service's secret, so that
|
|
8
8
|
* any instance of the service finds it again without keeping it, and a machine only ever learns
|
|
9
|
-
* its own. `run
|
|
10
|
-
*
|
|
11
|
-
* machine made before runs were drawn.
|
|
9
|
+
* its own. `run` is what the token of a machine made by versions 0.3.0 to 0.3.6 also covers, read
|
|
10
|
+
* from its metadata: the agent of such a machine goes on reading the token it was given.
|
|
12
11
|
*/
|
|
13
12
|
export function agentToken(secret, instance, run) {
|
|
14
13
|
const subject = run === undefined ? instance : `${instance}:${run}`;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { HarnessV1RequestTransformation } from '@ai-sdk/harness';
|
|
2
|
-
import type { ProxyRegistration
|
|
2
|
+
import type { ProxyRegistration } from '../../protocol/proxy.js';
|
|
3
3
|
/**
|
|
4
4
|
* The administration API of the egress proxy (`protocol/proxy.ts`), where the service registers the
|
|
5
5
|
* sandboxes, what they may reach and their credentials. The proxy alone holds the credentials: the
|
|
@@ -17,15 +17,8 @@ export declare class ProxyAdmin {
|
|
|
17
17
|
holdsSecret(name: string, texts: readonly string[]): Promise<boolean>;
|
|
18
18
|
/** Whether the proxy answers: its machine booted and its process listens. */
|
|
19
19
|
healthy(): Promise<boolean>;
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
list(): Promise<ProxySandbox[] | undefined>;
|
|
24
|
-
/**
|
|
25
|
-
* Forgets the sandbox `name` and its credentials, or with `serial` only the registration that
|
|
26
|
-
* {@link list} gave it. Idempotent.
|
|
27
|
-
*/
|
|
28
|
-
remove(name: string, serial?: number): Promise<void>;
|
|
29
|
-
/** Calls `/v1/sandboxes/<path>`, `/v1/sandboxes` itself for an empty `path`. */
|
|
20
|
+
/** Forgets the sandbox `name` and its credentials. Idempotent. */
|
|
21
|
+
remove(name: string): Promise<void>;
|
|
22
|
+
/** Calls `/v1/sandboxes/<path>`. */
|
|
30
23
|
private call;
|
|
31
24
|
}
|
|
@@ -41,33 +41,15 @@ export class ProxyAdmin {
|
|
|
41
41
|
return false;
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
/**
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
async list() {
|
|
48
|
-
try {
|
|
49
|
-
const response = await this.call('GET', '');
|
|
50
|
-
return (await response.json()).sandboxes;
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
if (error instanceof HttpError && error.status === 404)
|
|
54
|
-
return undefined;
|
|
55
|
-
throw error;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Forgets the sandbox `name` and its credentials, or with `serial` only the registration that
|
|
60
|
-
* {@link list} gave it. Idempotent.
|
|
61
|
-
*/
|
|
62
|
-
async remove(name, serial) {
|
|
63
|
-
await this.call('DELETE', serial === undefined ? name : `${name}?serial=${serial}`);
|
|
44
|
+
/** Forgets the sandbox `name` and its credentials. Idempotent. */
|
|
45
|
+
async remove(name) {
|
|
46
|
+
await this.call('DELETE', name);
|
|
64
47
|
}
|
|
65
|
-
/** Calls `/v1/sandboxes/<path
|
|
48
|
+
/** Calls `/v1/sandboxes/<path>`. */
|
|
66
49
|
async call(method, path, { body } = {}) {
|
|
67
50
|
let response;
|
|
68
51
|
try {
|
|
69
|
-
|
|
70
|
-
response = await fetch(new URL(resource, `${this.url.replace(/\/$/, '')}/`), {
|
|
52
|
+
response = await fetch(new URL(`v1/sandboxes/${path}`, `${this.url.replace(/\/$/, '')}/`), {
|
|
71
53
|
method,
|
|
72
54
|
headers: {
|
|
73
55
|
authorization: `Bearer ${this.token}`,
|
|
@@ -70,12 +70,6 @@ export interface SandboxesOptions {
|
|
|
70
70
|
* No limit without it.
|
|
71
71
|
*/
|
|
72
72
|
maxRunning?: number;
|
|
73
|
-
/**
|
|
74
|
-
* How often, at most, the service makes the proxy forget the sandboxes whose machine no longer
|
|
75
|
-
* runs, see {@link Sandboxes.reconcile}: in the background of a creation or a resume, the first
|
|
76
|
-
* one at once. Never without it.
|
|
77
|
-
*/
|
|
78
|
-
reconcileEveryMs?: number;
|
|
79
73
|
/**
|
|
80
74
|
* How many machines are kept booted from each template in use, for the next creations from it to
|
|
81
75
|
* take at once rather than boot one: billed while they run, all the time, and deleted once they
|
|
@@ -101,7 +95,6 @@ export declare class Sandboxes {
|
|
|
101
95
|
private readonly endpoints;
|
|
102
96
|
private readonly machines;
|
|
103
97
|
private readonly bases;
|
|
104
|
-
private nextReconcile;
|
|
105
98
|
constructor(options: SandboxesOptions);
|
|
106
99
|
/** The agent of the running sandbox `name`. */
|
|
107
100
|
agent(name: string): Promise<AgentClient>;
|
|
@@ -120,9 +113,8 @@ export declare class Sandboxes {
|
|
|
120
113
|
*/
|
|
121
114
|
resume(name: string, network: SandboxNetwork): Promise<SandboxDescription>;
|
|
122
115
|
/**
|
|
123
|
-
* Stops the sandbox's machine, its disk kept: the proxy forgets its credentials first
|
|
124
|
-
*
|
|
125
|
-
* resume. Returns once the machine left `RUNNING`, the guest off within seconds, not when Compute
|
|
116
|
+
* Stops the sandbox's machine, its disk kept: the proxy forgets its credentials first. Nothing
|
|
117
|
+
* runs, nothing is billed but the disk, until a resume. Returns once the machine left `RUNNING`, the guest off within seconds, not when Compute
|
|
126
118
|
* Engine is done some 50 s later: a resume meanwhile waits for it. Idempotent.
|
|
127
119
|
*/
|
|
128
120
|
suspend(name: string): Promise<void>;
|
|
@@ -132,15 +124,6 @@ export declare class Sandboxes {
|
|
|
132
124
|
* for it. Idempotent.
|
|
133
125
|
*/
|
|
134
126
|
delete(name: string): Promise<void>;
|
|
135
|
-
/**
|
|
136
|
-
* Makes the proxy forget the sandboxes whose machine no longer runs, and their credentials: a
|
|
137
|
-
* machine stopped or deleted outside the service (a Spot machine taken back, one stopped at its
|
|
138
|
-
* run limit or from the console) leaves them in the proxy until then. A sandbox is kept while a
|
|
139
|
-
* running machine of the zone holds its address, unless it is another sandbox of this service:
|
|
140
|
-
* the sandboxes of another service sharing the proxy in the zone are left alone. A sandbox
|
|
141
|
-
* registered again meanwhile is kept too. Answers the names forgotten.
|
|
142
|
-
*/
|
|
143
|
-
reconcile(): Promise<string[]>;
|
|
144
127
|
/** Replaces the hosts the running sandbox `name` may reach, the service's own aside. */
|
|
145
128
|
setAllowedHosts(name: string, allowedHosts: readonly string[]): Promise<void>;
|
|
146
129
|
addTransformations(name: string, transformations: readonly HarnessV1RequestTransformation[]): Promise<void>;
|
|
@@ -234,8 +217,6 @@ export declare class Sandboxes {
|
|
|
234
217
|
* that start register again.
|
|
235
218
|
*/
|
|
236
219
|
private proxyUp;
|
|
237
|
-
/** Starts a {@link reconcile} without waiting for it, once per period at most. */
|
|
238
|
-
private reconcileInBackground;
|
|
239
220
|
/**
|
|
240
221
|
* Stops the proxy's machine, when the service drives it and does not keep it running, once no
|
|
241
222
|
* sandbox runs, nor a prepared machine waits for one: a sandbox is about to take it, which would
|
|
@@ -247,15 +228,11 @@ export declare class Sandboxes {
|
|
|
247
228
|
/** Refuses one more running sandbox beyond {@link SandboxesOptions.maxRunning}. */
|
|
248
229
|
private assertRoom;
|
|
249
230
|
/**
|
|
250
|
-
*
|
|
251
|
-
* goes
|
|
252
|
-
*
|
|
253
|
-
* is. A stop racing this one that changed the metadata first has drawn one already. Failing, the
|
|
254
|
-
* machine keeps its token, as it did before runs were drawn: the stop goes on.
|
|
231
|
+
* Stopped, a machine prepared ahead of a sandbox is the sandbox's, which no longer waits for one:
|
|
232
|
+
* its power-off goes. A stop racing this one that changed the metadata first has done so already.
|
|
233
|
+
* Failing, the stop goes on.
|
|
255
234
|
*/
|
|
256
|
-
private
|
|
257
|
-
/** The metadata the agent of the machine `instance` reads its token from, for a new run. */
|
|
258
|
-
private agentItems;
|
|
235
|
+
private dropPowerOff;
|
|
259
236
|
/**
|
|
260
237
|
* Waits until the machine `instance`, told to stop or go, is no longer `RUNNING`: Compute Engine
|
|
261
238
|
* may still say so for a moment, and a resume would then take it for a machine that runs. The
|
|
@@ -28,8 +28,6 @@ const PREPARED_LABEL = 'ai-sdk-sandbox-prepared';
|
|
|
28
28
|
const NAME = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
29
29
|
/** Statuses of a machine that runs, or is about to: what {@link SandboxesOptions.maxRunning} counts. */
|
|
30
30
|
const RUNNING = new Set(['PROVISIONING', 'REPAIRING', 'RUNNING', 'STAGING']);
|
|
31
|
-
/** Statuses of a machine whose guest is off, or on its way: its agent will read its token anew. */
|
|
32
|
-
const STOPPED = new Set(['STOPPING', 'TERMINATED']);
|
|
33
31
|
/** Statuses a machine moves on from by itself. */
|
|
34
32
|
const TRANSIENT = new Set(['PROVISIONING', 'REPAIRING', 'STAGING', 'STOPPING', 'SUSPENDING']);
|
|
35
33
|
/** How long the address of a running machine is trusted before it is read again. */
|
|
@@ -45,9 +43,9 @@ const MACHINE_KEPT_MS = 10 * 60_000;
|
|
|
45
43
|
const IMAGE_KEPT_MS = 5 * 60_000;
|
|
46
44
|
/** The image a sandbox gets when its caller names none. */
|
|
47
45
|
export const DEFAULT_IMAGE = 'default';
|
|
48
|
-
/** The instance metadata key of the run
|
|
46
|
+
/** The instance metadata key of the run of a machine of an earlier version, see {@link agentToken}. */
|
|
49
47
|
const AGENT_RUN_METADATA_KEY = 'ai-sdk-sandbox-agent-run';
|
|
50
|
-
/** The run the machine's agent token
|
|
48
|
+
/** The run the machine's agent token covers: none but on a machine of an earlier version. */
|
|
51
49
|
const runOf = (instance) => instance.metadata?.items?.find(({ key }) => key === AGENT_RUN_METADATA_KEY)?.value;
|
|
52
50
|
/** When the machine `instance` was made, in milliseconds: now when Compute Engine does not say. */
|
|
53
51
|
function createdAt(instance) {
|
|
@@ -94,7 +92,6 @@ export class Sandboxes {
|
|
|
94
92
|
endpoints = new Map();
|
|
95
93
|
machines = new Map();
|
|
96
94
|
bases = new Map();
|
|
97
|
-
nextReconcile = 0;
|
|
98
95
|
constructor(options) {
|
|
99
96
|
this.options = options;
|
|
100
97
|
if (options.machine.images[DEFAULT_IMAGE] === undefined) {
|
|
@@ -182,9 +179,8 @@ export class Sandboxes {
|
|
|
182
179
|
return description;
|
|
183
180
|
}
|
|
184
181
|
/**
|
|
185
|
-
* Stops the sandbox's machine, its disk kept: the proxy forgets its credentials first
|
|
186
|
-
*
|
|
187
|
-
* resume. Returns once the machine left `RUNNING`, the guest off within seconds, not when Compute
|
|
182
|
+
* Stops the sandbox's machine, its disk kept: the proxy forgets its credentials first. Nothing
|
|
183
|
+
* runs, nothing is billed but the disk, until a resume. Returns once the machine left `RUNNING`, the guest off within seconds, not when Compute
|
|
188
184
|
* Engine is done some 50 s later: a resume meanwhile waits for it. Idempotent.
|
|
189
185
|
*/
|
|
190
186
|
async suspend(name) {
|
|
@@ -199,7 +195,7 @@ export class Sandboxes {
|
|
|
199
195
|
stopped = await this.leftRunning(instance.name);
|
|
200
196
|
this.options.logger.info(`${name} stopping`);
|
|
201
197
|
}
|
|
202
|
-
await this.
|
|
198
|
+
await this.dropPowerOff(stopped);
|
|
203
199
|
await this.proxyDownWhenIdle();
|
|
204
200
|
}
|
|
205
201
|
/**
|
|
@@ -211,37 +207,6 @@ export class Sandboxes {
|
|
|
211
207
|
this.assertSandboxName(name);
|
|
212
208
|
await this.removeMachine(name, (await this.instanceOf(name))?.name);
|
|
213
209
|
}
|
|
214
|
-
/**
|
|
215
|
-
* Makes the proxy forget the sandboxes whose machine no longer runs, and their credentials: a
|
|
216
|
-
* machine stopped or deleted outside the service (a Spot machine taken back, one stopped at its
|
|
217
|
-
* run limit or from the console) leaves them in the proxy until then. A sandbox is kept while a
|
|
218
|
-
* running machine of the zone holds its address, unless it is another sandbox of this service:
|
|
219
|
-
* the sandboxes of another service sharing the proxy in the zone are left alone. A sandbox
|
|
220
|
-
* registered again meanwhile is kept too. Answers the names forgotten.
|
|
221
|
-
*/
|
|
222
|
-
async reconcile() {
|
|
223
|
-
const { proxy, compute, logger } = this.options;
|
|
224
|
-
const registered = await proxy.list();
|
|
225
|
-
if (registered === undefined)
|
|
226
|
-
return [];
|
|
227
|
-
const machines = await compute.listInstances(LABEL, 'sandbox');
|
|
228
|
-
const holders = new Map(machines
|
|
229
|
-
.filter(({ status }) => RUNNING.has(status))
|
|
230
|
-
.map((machine) => [machine.networkInterfaces?.[0]?.networkIP, machine]));
|
|
231
|
-
const stale = registered.filter(({ name, address }) => {
|
|
232
|
-
const holder = holders.get(address);
|
|
233
|
-
if (holder === undefined)
|
|
234
|
-
return true;
|
|
235
|
-
return holder.name.startsWith(this.options.instancePrefix) && this.sandboxOf(holder) !== name;
|
|
236
|
-
});
|
|
237
|
-
await Promise.all(stale.map(({ name, serial }) => proxy.remove(name, serial)));
|
|
238
|
-
const names = stale.map(({ name }) => name);
|
|
239
|
-
if (names.length > 0) {
|
|
240
|
-
const runs = names.length === 1 ? 'its machine no longer runs' : 'their machines no longer run';
|
|
241
|
-
logger.info(`The proxy forgot ${names.join(', ')}: ${runs}`);
|
|
242
|
-
}
|
|
243
|
-
return names;
|
|
244
|
-
}
|
|
245
210
|
/** Replaces the hosts the running sandbox `name` may reach, the service's own aside. */
|
|
246
211
|
async setAllowedHosts(name, allowedHosts) {
|
|
247
212
|
this.assertSandboxName(name);
|
|
@@ -545,16 +510,6 @@ export class Sandboxes {
|
|
|
545
510
|
}
|
|
546
511
|
}
|
|
547
512
|
}
|
|
548
|
-
/** Starts a {@link reconcile} without waiting for it, once per period at most. */
|
|
549
|
-
reconcileInBackground() {
|
|
550
|
-
const { reconcileEveryMs, logger } = this.options;
|
|
551
|
-
if (reconcileEveryMs === undefined || Date.now() < this.nextReconcile)
|
|
552
|
-
return;
|
|
553
|
-
this.nextReconcile = Date.now() + reconcileEveryMs;
|
|
554
|
-
this.reconcile().catch((error) => {
|
|
555
|
-
logger.warn(`The proxy could not be reconciled with the machines: ${String(error)}`);
|
|
556
|
-
});
|
|
557
|
-
}
|
|
558
513
|
/**
|
|
559
514
|
* Stops the proxy's machine, when the service drives it and does not keep it running, once no
|
|
560
515
|
* sandbox runs, nor a prepared machine waits for one: a sandbox is about to take it, which would
|
|
@@ -590,39 +545,27 @@ export class Sandboxes {
|
|
|
590
545
|
}
|
|
591
546
|
}
|
|
592
547
|
/**
|
|
593
|
-
*
|
|
594
|
-
* goes
|
|
595
|
-
*
|
|
596
|
-
* is. A stop racing this one that changed the metadata first has drawn one already. Failing, the
|
|
597
|
-
* machine keeps its token, as it did before runs were drawn: the stop goes on.
|
|
548
|
+
* Stopped, a machine prepared ahead of a sandbox is the sandbox's, which no longer waits for one:
|
|
549
|
+
* its power-off goes. A stop racing this one that changed the metadata first has done so already.
|
|
550
|
+
* Failing, the stop goes on.
|
|
598
551
|
*/
|
|
599
|
-
async
|
|
600
|
-
|
|
552
|
+
async dropPowerOff(instance) {
|
|
553
|
+
const items = instance?.metadata?.items ?? [];
|
|
554
|
+
if (instance === undefined || !items.some(({ key }) => key === IDLE_POWER_OFF_METADATA_KEY)) {
|
|
601
555
|
return;
|
|
602
|
-
|
|
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);
|
|
556
|
+
}
|
|
606
557
|
try {
|
|
607
558
|
await this.options.compute.setMetadata(instance.name, {
|
|
608
559
|
fingerprint: instance.metadata?.fingerprint,
|
|
609
|
-
items:
|
|
560
|
+
items: items.filter(({ key }) => key !== IDLE_POWER_OFF_METADATA_KEY),
|
|
610
561
|
});
|
|
611
562
|
}
|
|
612
563
|
catch (error) {
|
|
613
564
|
if (error instanceof ComputeError && error.status === 412)
|
|
614
565
|
return;
|
|
615
|
-
this.options.logger.warn(`${instance.name} keeps its
|
|
566
|
+
this.options.logger.warn(`${instance.name} keeps its power-off: ${String(error)}`);
|
|
616
567
|
}
|
|
617
568
|
}
|
|
618
|
-
/** The metadata the agent of the machine `instance` reads its token from, for a new run. */
|
|
619
|
-
agentItems(instance) {
|
|
620
|
-
const run = randomBytes(8).toString('hex');
|
|
621
|
-
return [
|
|
622
|
-
{ key: AGENT_TOKEN_METADATA_KEY, value: agentToken(this.options.agentSecret, instance, run) },
|
|
623
|
-
{ key: AGENT_RUN_METADATA_KEY, value: run },
|
|
624
|
-
];
|
|
625
|
-
}
|
|
626
569
|
/**
|
|
627
570
|
* Waits until the machine `instance`, told to stop or go, is no longer `RUNNING`: Compute Engine
|
|
628
571
|
* may still say so for a moment, and a resume would then take it for a machine that runs. The
|
|
@@ -859,8 +802,6 @@ export class Sandboxes {
|
|
|
859
802
|
proxy: this.options.proxyUrl,
|
|
860
803
|
baseUrls,
|
|
861
804
|
});
|
|
862
|
-
// The proxy answers by now: a good time to make it forget the machines gone meanwhile.
|
|
863
|
-
this.reconcileInBackground();
|
|
864
805
|
return { name, home, workingDirectory };
|
|
865
806
|
}
|
|
866
807
|
async waitForAgent(name, agent) {
|
|
@@ -975,7 +916,7 @@ export class Sandboxes {
|
|
|
975
916
|
],
|
|
976
917
|
metadata: {
|
|
977
918
|
items: [
|
|
978
|
-
|
|
919
|
+
{ key: AGENT_TOKEN_METADATA_KEY, value: agentToken(this.options.agentSecret, name) },
|
|
979
920
|
{ key: 'block-project-ssh-keys', value: 'true' },
|
|
980
921
|
{ key: 'serial-port-enable', value: 'false' },
|
|
981
922
|
...metadata,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-sdk-sandbox-gce",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Compute Engine sandboxes for AI SDK harness agents: Claude Code, Codex and friends in a virtual machine of their own on Google Cloud, Docker included, stopped between turns.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -58,8 +58,8 @@
|
|
|
58
58
|
"vitest": "^5.0.5",
|
|
59
59
|
"zod": "^4.6.7",
|
|
60
60
|
"@repo/build": "0.0.0",
|
|
61
|
-
"@repo/eslint-config": "0.0.0",
|
|
62
61
|
"@repo/prettier-config": "0.0.0",
|
|
62
|
+
"@repo/eslint-config": "0.0.0",
|
|
63
63
|
"@repo/typescript-config": "0.0.0",
|
|
64
64
|
"@repo/vitest-config": "0.0.0"
|
|
65
65
|
},
|
|
@@ -1,23 +0,0 @@
|
|
|
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>;
|
package/dist/in-vm/oom-policy.js
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
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/proxy/traffic.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import type { Socket } from 'node:net';
|
|
2
|
-
/** `bytes` for a log line: `512 B`, `12.3 MB`. */
|
|
3
|
-
export declare function formatBytes(bytes: number): string;
|
|
4
|
-
/**
|
|
5
|
-
* The bytes one sandbox moved through the proxy, over every connection of its machine: those
|
|
6
|
-
* closed, and those still open as they stand. A tunnel's TLS and a request's headers included.
|
|
7
|
-
*/
|
|
8
|
-
export declare class Traffic {
|
|
9
|
-
private closedSent;
|
|
10
|
-
private closedReceived;
|
|
11
|
-
private readonly open;
|
|
12
|
-
/** Counts the connection `socket` of the sandbox's machine, from now on. */
|
|
13
|
-
track(socket: Socket): void;
|
|
14
|
-
/** `sent`: what left the sandbox; `received`: what came back into it. */
|
|
15
|
-
get totals(): {
|
|
16
|
-
received: number;
|
|
17
|
-
sent: number;
|
|
18
|
-
};
|
|
19
|
-
}
|
package/dist/proxy/traffic.js
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
const UNITS = ['kB', 'MB', 'GB', 'TB'];
|
|
2
|
-
/** `bytes` for a log line: `512 B`, `12.3 MB`. */
|
|
3
|
-
export function formatBytes(bytes) {
|
|
4
|
-
if (bytes < 1000)
|
|
5
|
-
return `${bytes} B`;
|
|
6
|
-
let value = bytes;
|
|
7
|
-
let unit = 0;
|
|
8
|
-
for (value /= 1000; value >= 1000 && unit < UNITS.length - 1; value /= 1000)
|
|
9
|
-
unit++;
|
|
10
|
-
return `${value.toFixed(1)} ${UNITS[unit] ?? ''}`;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* The bytes one sandbox moved through the proxy, over every connection of its machine: those
|
|
14
|
-
* closed, and those still open as they stand. A tunnel's TLS and a request's headers included.
|
|
15
|
-
*/
|
|
16
|
-
export class Traffic {
|
|
17
|
-
closedSent = 0;
|
|
18
|
-
closedReceived = 0;
|
|
19
|
-
open = new Set();
|
|
20
|
-
/** Counts the connection `socket` of the sandbox's machine, from now on. */
|
|
21
|
-
track(socket) {
|
|
22
|
-
this.open.add(socket);
|
|
23
|
-
socket.once('close', () => {
|
|
24
|
-
this.open.delete(socket);
|
|
25
|
-
this.closedSent += socket.bytesRead;
|
|
26
|
-
this.closedReceived += socket.bytesWritten;
|
|
27
|
-
});
|
|
28
|
-
}
|
|
29
|
-
/** `sent`: what left the sandbox; `received`: what came back into it. */
|
|
30
|
-
get totals() {
|
|
31
|
-
let sent = this.closedSent;
|
|
32
|
-
let received = this.closedReceived;
|
|
33
|
-
for (const socket of this.open) {
|
|
34
|
-
sent += socket.bytesRead;
|
|
35
|
-
received += socket.bytesWritten;
|
|
36
|
-
}
|
|
37
|
-
return { sent, received };
|
|
38
|
-
}
|
|
39
|
-
}
|