ai-sdk-sandbox-gce 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # ai-sdk-sandbox-gce
2
2
 
3
+ ## 0.3.6
4
+
5
+ ### Patch Changes
6
+
7
+ - af7195c: A command whose machine's agent stops before it exits (the agent restarted or killed, the machine stopping) no longer leaves the caller waiting until its own timeout: the service cuts its streamed answer at once, and the session, its exit code never coming, asks for the process by id, then reports it as killed (exit code 137). The service's answer used to stay open, a `run` or a `wait()` blocked for as long as the request could last.
8
+
9
+ ## 0.3.5
10
+
11
+ ### Patch Changes
12
+
13
+ - 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.
14
+ - 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.
15
+
16
+ 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.
17
+
3
18
  ## 0.3.4
4
19
 
5
20
  ### 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.4
138
+ VERSION=0.3.6
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")"
@@ -265,6 +265,8 @@ Every sandbox boots from it: put the tools your agent needs in it, and never a s
265
265
  set -e
266
266
  apt-get update
267
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
268
270
 
269
271
  # Docker Engine and Compose.
270
272
  install -m 0755 -d /etc/apt/keyrings
@@ -280,7 +282,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
280
282
  > /etc/apt/sources.list.d/nodesource.list
281
283
  apt-get update
282
284
  apt-get install -y nodejs
283
- npm install --global ai-sdk-sandbox-gce@0.3.4 pnpm@10
285
+ npm install --global ai-sdk-sandbox-gce@0.3.6 pnpm@10
284
286
 
285
287
  # The sandbox's user: sudo without a password, and Docker.
286
288
  useradd --create-home --shell /bin/bash agent
@@ -296,6 +298,7 @@ Wants=network-online.target
296
298
  [Service]
297
299
  ExecStart=/usr/bin/ai-sdk-sandbox-gce agent
298
300
  Restart=always
301
+ OOMPolicy=continue
299
302
 
300
303
  [Install]
301
304
  WantedBy=multi-user.target
@@ -303,11 +306,11 @@ UNIT
303
306
  systemctl enable ai-sdk-sandbox-agent
304
307
  ```
305
308
 
306
- The agent runs as root and starts the commands as `agent`. 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.
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.
307
310
 
308
311
  ### 4. The service
309
312
 
310
- 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.4 --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.
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.6 --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.
311
314
 
312
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-`).
313
316
 
@@ -345,7 +348,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
345
348
  --member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
346
349
  done
347
350
 
348
- gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.4 \
351
+ gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.6 \
349
352
  --service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
350
353
  --network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
351
354
  --no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
@@ -578,6 +581,7 @@ The machine has no external address, and the VPC firewall, applied outside the g
578
581
  - The base URLs go to the proxy too, as above.
579
582
  - `HTTP_PROXY` points at the proxy as well: plain HTTP to an allowed host, as Debian's package mirrors serve, is passed on as it is, no credential put in. Anything else in plain HTTP is refused.
580
583
  - `NO_PROXY` covers the machine itself, the proxy and the private ranges Docker puts its containers in. A container reached by its Compose service name is not covered: add the names to `NO_PROXY` in the Compose file.
584
+ - Docker gives the containers these variables too. busybox `wget`, the one of Alpine images, ignores `NO_PROXY`: a healthcheck that probes its own container with it, `wget -qO- http://127.0.0.1:3000/health`, reaches the proxy, which refuses a private address, and the container never becomes healthy (`docker compose up --wait` fails). Probe without the proxy: `wget -Y off -qO- …`, or `curl --noproxy '*' …`.
581
585
  - The proxy never connects to a private address, however it is named or allowed: loopback, link-local (its own metadata server), the private ranges of the VPC. It checks the address a name resolves to, at the moment it connects. In IPv6, it only reaches global unicast addresses (`2000::/3`), never one carrying a private IPv4 address (NAT64, 6to4, IPv4-mapped) nor a Teredo one.
582
586
 
583
587
  `allowedHosts` adds hosts for one sandbox, on top of the service's `SANDBOX_ALLOWED_HOSTS`. `*.example.com` covers the subdomains of `example.com`. `setNetworkPolicy` replaces the sandbox's own hosts: `allow-all` lets it reach any host over HTTPS, `deny-all` none but the service's and the base URLs'. CIDR rules are not supported.
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import { pipeline } from 'node:stream/promises';
1
2
  import { readCommandLine } from '../../common/command-line.js';
2
3
  import { HttpError } from '../../common/http-error.js';
3
4
  /** The agent's error, as its JSON says it. */
@@ -44,8 +45,8 @@ export async function execRelay(sandboxes, name, { request, response }) {
44
45
  });
45
46
  // At once: the caller waits for the process's id, and a quiet command writes nothing for long.
46
47
  response.flushHeaders();
47
- answer.pipe(response);
48
- // The caller gone, the agent's stream is let go: the process runs on, its exit kept by id.
49
- response.once('close', () => answer.destroy());
50
- await new Promise((resolve) => answer.once('close', resolve));
48
+ // Either side gone, the other is let go. The agent stopping mid-command (restarted, its machine
49
+ // stopping), the answer is cut rather than ended: the caller, its exit frame never coming, then
50
+ // waits for the process by id. The caller gone, the process runs on, its exit kept by id.
51
+ await pipeline(answer, response).catch(() => undefined);
51
52
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-sdk-sandbox-gce",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
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,8 +50,8 @@
50
50
  "@ai-sdk/provider-utils": "^5.0.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@ai-sdk/harness": "^1.0.153",
54
- "@ai-sdk/provider-utils": "^5.0.70",
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",