ai-sdk-sandbox-gce 0.5.0 → 0.5.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 +8 -0
- package/README.md +31 -13
- package/dist/proxy/egress-proxy.d.ts +67 -9
- package/dist/proxy/egress-proxy.js +173 -23
- package/dist/proxy/main.d.ts +13 -2
- package/dist/proxy/main.js +49 -9
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# ai-sdk-sandbox-gce
|
|
2
2
|
|
|
3
|
+
## 0.5.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- bbd3d89: The egress proxy keeps an idle connection open for 120 seconds rather than Node.js's 5, longer than the runtimes' clients keep theirs: Codex's keeps an idle connection for 90 seconds, and Claude Code reused one after 34. A request a runtime sent on a connection just as the proxy closed it was reset (`ECONNRESET`).
|
|
8
|
+
- c2420ee: The egress proxy has a total limit of connections, for all its sandboxes: `SANDBOX_PROXY_TOTAL_CONNECTIONS`, by default what its file descriptors allow (two for each connection, 1024 kept apart: 32256 under `LimitNOFILE=65536`). Without it, once the descriptors ran out, the system reset every sandbox's new connections before the proxy saw them, and nothing was logged. Beyond the limit, a connection is now refused with a `503` that says the proxy is full, and a tenth of the total is kept for the base URL routes. The proxy logs when it reaches its limit, with the three sandboxes that hold the most connections, and when it goes back under.
|
|
9
|
+
- 9a9a524: The egress proxy keeps connections for the base URL routes: the runtime reaches its model provider while the commands of its sandbox hold every connection they may. `SANDBOX_PROXY_MAX_CONNECTIONS` (128) now bounds the commands' tunnels and plain HTTP requests, and `SANDBOX_PROXY_ROUTE_CONNECTIONS` (32) gives the routes that many more; no machine holds more than both together. A command refused at its limit gets a `503` that says why, rather than a reset connection. The proxy logs a warning when a sandbox reaches a limit, and a line when it goes back under, with how many connections it refused meanwhile. A tunnel whose client ends it before its TLS ClientHello now frees its connection at once, rather than after 10 seconds.
|
|
10
|
+
|
|
3
11
|
## 0.5.0
|
|
4
12
|
|
|
5
13
|
### Minor 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.5.
|
|
138
|
+
VERSION=0.5.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")"
|
|
@@ -210,7 +210,8 @@ Environment=SANDBOX_PROXY_IDLE_EXIT_MINUTES=10
|
|
|
210
210
|
RestartPreventExitStatus=100
|
|
211
211
|
ExecStopPost=+/bin/sh -c 'if [ "$$EXIT_STATUS" = 100 ]; then systemctl poweroff; fi'
|
|
212
212
|
DynamicUser=yes
|
|
213
|
-
# Every sandbox holds up to SANDBOX_PROXY_MAX_CONNECTIONS (128)
|
|
213
|
+
# Every sandbox holds up to 160 connections at once: SANDBOX_PROXY_MAX_CONNECTIONS (128) for its
|
|
214
|
+
# commands, SANDBOX_PROXY_ROUTE_CONNECTIONS (32) more for its base URL routes.
|
|
214
215
|
LimitNOFILE=65536
|
|
215
216
|
|
|
216
217
|
[Install]
|
|
@@ -282,7 +283,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
|
|
|
282
283
|
> /etc/apt/sources.list.d/nodesource.list
|
|
283
284
|
apt-get update
|
|
284
285
|
apt-get install -y nodejs
|
|
285
|
-
npm install --global ai-sdk-sandbox-gce@0.5.
|
|
286
|
+
npm install --global ai-sdk-sandbox-gce@0.5.1 pnpm@10
|
|
286
287
|
|
|
287
288
|
# The sandbox's user: sudo without a password, and Docker.
|
|
288
289
|
useradd --create-home --shell /bin/bash agent
|
|
@@ -310,7 +311,7 @@ The agent runs as root and starts the commands as `agent`, in its own service: `
|
|
|
310
311
|
|
|
311
312
|
### 4. The service
|
|
312
313
|
|
|
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.5.
|
|
314
|
+
The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.5.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
315
|
|
|
315
316
|
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
317
|
|
|
@@ -348,7 +349,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
|
|
|
348
349
|
--member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
|
|
349
350
|
done
|
|
350
351
|
|
|
351
|
-
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.5.
|
|
352
|
+
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.5.1 \
|
|
352
353
|
--service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
|
|
353
354
|
--network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
|
|
354
355
|
--no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
|
|
@@ -602,6 +603,21 @@ The machine has no external address, and the VPC firewall, applied outside the g
|
|
|
602
603
|
|
|
603
604
|
Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.io`, `auth.docker.io`, `production.cloudflare.docker.com` and `production.cloudfront.docker.com` (Docker Hub serves layers from either), or [`ai-sdk-harness-network`](https://ai-sdk-harness.pages.dev/docs/packages/harness-network)'s presets.
|
|
604
605
|
|
|
606
|
+
### Connections
|
|
607
|
+
|
|
608
|
+
The proxy counts the connections each sandbox's machine holds open through it, so that no sandbox takes the sockets of the others:
|
|
609
|
+
|
|
610
|
+
- **Its commands** — the tunnels of `HTTPS_PROXY` and the plain requests of `HTTP_PROXY` — hold up to `SANDBOX_PROXY_MAX_CONNECTIONS` (128) at once: package managers, test suites and their keep-alive pools. One more is refused with `503 Service Unavailable`, and a message that says so.
|
|
611
|
+
- **Its base URL routes** — the runtime's way to its model provider — always find a connection: they may take `SANDBOX_PROXY_ROUTE_CONNECTIONS` (32) more, which the commands never do. A command that calls a base URL route itself counts there too.
|
|
612
|
+
- A connection counts from the moment it opens, before it says what it carries: no machine holds more than both together, 160. One more is cut.
|
|
613
|
+
- **The proxy as a whole** holds up to `SANDBOX_PROXY_TOTAL_CONNECTIONS` at once, for all its sandboxes: by default what its descriptors allow, two for each connection, with 1024 kept apart — 32256 under `LimitNOFILE=65536`. Beyond it, a connection is refused with a `503` that says the proxy is full. Without this limit the system would reset it before the proxy saw it, for every sandbox alike and with nothing logged. A tenth of the total is kept for the base URL routes: the commands of all sandboxes together never take it.
|
|
614
|
+
|
|
615
|
+
The proxy logs a warning when a sandbox reaches a limit, with what it holds, and a line when it goes back under three quarters of it, with how many connections it refused meanwhile: `box reached its limit: its commands hold 128 connections, …`, then `box is back under its limit: …; 412 refused meanwhile`. It does the same for its own limit, naming the three sandboxes that hold the most: `The proxy reached its limit: … Holding the most: box (160), …`. A turn that fails while the sandbox or the proxy is at its limit is told apart from an outage of the provider.
|
|
616
|
+
|
|
617
|
+
The proxy keeps an idle connection open for 120 seconds, longer than the runtimes' clients keep theirs (Codex's, 90 seconds): the client always closes it first, so that no request is sent on it just as the proxy closes it, and reset. An idle connection still counts against the limits until then.
|
|
618
|
+
|
|
619
|
+
To raise them, add `Environment=SANDBOX_PROXY_MAX_CONNECTIONS=256` (and `SANDBOX_PROXY_ROUTE_CONNECTIONS`) to the `[Service]` section of the proxy's unit, in its startup script, and restart the proxy. For more sandboxes on one proxy, raise its `LimitNOFILE` instead: the total follows it. Set `SANDBOX_PROXY_TOTAL_CONNECTIONS` only to hold the proxy below what its descriptors allow.
|
|
620
|
+
|
|
605
621
|
### Node.js and the proxy
|
|
606
622
|
|
|
607
623
|
Package managers, git, curl and the harnesses (Claude Code, Codex) read `HTTPS_PROXY` themselves. Node.js's own `fetch` and `http` only do with `NODE_USE_ENV_PROXY=1`, which the sandbox does not set by default: with it, a test suite that mocks `fetch` with [MSW](https://mswjs.io) 3 sees its requests leave for the proxy, which refuses them (`fetch failed`, `Failed to establish tunnel … 403`), MSW's `onUnhandledRequest` saying nothing. MSW 3 catches a request at its socket, and Node.js then opens that socket to the proxy, with a `CONNECT`, rather than to the host the suite mocks.
|
|
@@ -694,14 +710,16 @@ The MCP servers that [`ai-sdk-harness-plugins`](https://ai-sdk-harness.pages.dev
|
|
|
694
710
|
|
|
695
711
|
### The proxy (`proxy`)
|
|
696
712
|
|
|
697
|
-
| Variable
|
|
698
|
-
|
|
|
699
|
-
| `SANDBOX_PROXY_TOKEN`
|
|
700
|
-
| `SANDBOX_PROXY_PORT`
|
|
701
|
-
| `SANDBOX_PROXY_ADMIN_PORT`
|
|
702
|
-
| `SANDBOX_ALLOW_PRIVATE_NETWORK`
|
|
703
|
-
| `SANDBOX_PROXY_MAX_CONNECTIONS`
|
|
704
|
-
| `
|
|
713
|
+
| Variable | Default | Description |
|
|
714
|
+
| --------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------- |
|
|
715
|
+
| `SANDBOX_PROXY_TOKEN` | required | The token the service proves itself with, 16 characters at least |
|
|
716
|
+
| `SANDBOX_PROXY_PORT` | `3128` | The port the sandboxes reach |
|
|
717
|
+
| `SANDBOX_PROXY_ADMIN_PORT` | `3129` | The port of the administration API |
|
|
718
|
+
| `SANDBOX_ALLOW_PRIVATE_NETWORK` | `false` | For tests only: lets the sandboxes reach private addresses and plain HTTP base URLs |
|
|
719
|
+
| `SANDBOX_PROXY_MAX_CONNECTIONS` | `128` | The most connections the commands of a sandbox hold open through the proxy at once: [Connections](#connections) |
|
|
720
|
+
| `SANDBOX_PROXY_ROUTE_CONNECTIONS` | `32` | The connections a sandbox holds beyond those, for its base URL routes alone: [Connections](#connections) |
|
|
721
|
+
| `SANDBOX_PROXY_TOTAL_CONNECTIONS` | from `LimitNOFILE` | The most connections the proxy holds for all its sandboxes, a tenth kept for the routes: [Connections](#connections) |
|
|
722
|
+
| `HOST`, `LOG_FORMAT` | `0.0.0.0` | Where it listens; `text` for plain logs |
|
|
705
723
|
|
|
706
724
|
### The agent (`agent`)
|
|
707
725
|
|
|
@@ -1,8 +1,28 @@
|
|
|
1
1
|
import type { Server } from 'node:http';
|
|
2
2
|
import type { Logger } from '../common/logger.js';
|
|
3
3
|
import type { EgressPolicy } from './egress-policy.js';
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* The most connections the commands of a sandbox hold open through the proxy at once, by default:
|
|
6
|
+
* its tunnels and plain HTTP requests.
|
|
7
|
+
*/
|
|
5
8
|
export declare const DEFAULT_MAX_CONNECTIONS = 128;
|
|
9
|
+
/**
|
|
10
|
+
* The connections a sandbox holds beyond {@link DEFAULT_MAX_CONNECTIONS}, by default, for its base
|
|
11
|
+
* URL routes alone: the runtime's way to its model provider stays open whatever the commands hold.
|
|
12
|
+
*/
|
|
13
|
+
export declare const DEFAULT_ROUTE_CONNECTIONS = 32;
|
|
14
|
+
/**
|
|
15
|
+
* How long the proxy keeps an idle connection of a base URL route open: longer than the runtimes'
|
|
16
|
+
* clients keep theirs, so that the client always closes first. Otherwise a request sent on it just
|
|
17
|
+
* as the proxy closes it is reset. Codex's client keeps an idle connection for 90 seconds; Claude
|
|
18
|
+
* Code's reused one after 34 seconds. Node's default, 5 seconds, is shorter than both.
|
|
19
|
+
*/
|
|
20
|
+
export declare const KEEP_ALIVE_MS = 120000;
|
|
21
|
+
/**
|
|
22
|
+
* The most connections the proxy holds open at once, for all its sandboxes, by default: what
|
|
23
|
+
* `LimitNOFILE=65536` allows, two descriptors for each connection, with a margin for the rest.
|
|
24
|
+
*/
|
|
25
|
+
export declare const DEFAULT_TOTAL_CONNECTIONS = 32256;
|
|
6
26
|
/**
|
|
7
27
|
* The way out of the sandboxes, on a machine of its own, outside their security boundary: the VPC
|
|
8
28
|
* firewall lets their machines reach nothing else. Every connection is the sandbox's whose machine
|
|
@@ -28,27 +48,65 @@ export declare class EgressProxy {
|
|
|
28
48
|
private readonly logger;
|
|
29
49
|
readonly server: Server;
|
|
30
50
|
/** The connections each machine holds open, by its address. */
|
|
31
|
-
private readonly
|
|
32
|
-
/** The
|
|
33
|
-
private readonly
|
|
51
|
+
private readonly machines;
|
|
52
|
+
/** The connections of every machine together. */
|
|
53
|
+
private readonly all;
|
|
54
|
+
/** What each connection carries, once its first request said. */
|
|
55
|
+
private readonly kinds;
|
|
34
56
|
private readonly maxConnections;
|
|
57
|
+
private readonly routeConnections;
|
|
58
|
+
private readonly totalConnections;
|
|
35
59
|
private readonly tunnelPort;
|
|
36
60
|
/**
|
|
37
|
-
* @param options.maxConnections The most connections a sandbox
|
|
38
|
-
* one more is
|
|
61
|
+
* @param options.maxConnections The most connections the commands of a sandbox hold open at
|
|
62
|
+
* once, its tunnels and plain HTTP requests: one more is refused, so that no sandbox takes the
|
|
63
|
+
* sockets of the others.
|
|
64
|
+
* @param options.routeConnections The connections a sandbox holds beyond `maxConnections` for
|
|
65
|
+
* its base URL routes alone, so that the runtime reaches its model provider whatever the
|
|
66
|
+
* commands hold. A machine never holds more than both together.
|
|
67
|
+
* @param options.totalConnections The most connections the proxy holds open at once, for all
|
|
68
|
+
* its sandboxes: below what its file descriptors allow, so that a connection beyond it is
|
|
69
|
+
* refused with a reason rather than reset by the system. A tenth of it is kept for the base
|
|
70
|
+
* URL routes, which the commands of all sandboxes together never take.
|
|
39
71
|
* @param options.tunnelPort The port a tunnel reaches on its host, whatever port its `CONNECT`
|
|
40
72
|
* names (443, the only one allowed). Tests only.
|
|
41
73
|
*/
|
|
42
|
-
constructor(policyFor: (address: string | undefined) => EgressPolicy | undefined, logger?: Logger, { maxConnections, tunnelPort, }?: {
|
|
74
|
+
constructor(policyFor: (address: string | undefined) => EgressPolicy | undefined, logger?: Logger, { maxConnections, routeConnections, totalConnections, tunnelPort, }?: {
|
|
43
75
|
maxConnections?: number;
|
|
76
|
+
routeConnections?: number;
|
|
77
|
+
totalConnections?: number;
|
|
44
78
|
tunnelPort?: number;
|
|
45
79
|
});
|
|
46
80
|
close(): void;
|
|
47
81
|
/**
|
|
48
|
-
* Counts the connections of a machine, and
|
|
49
|
-
*
|
|
82
|
+
* Counts the connections of a machine, and refuses one beyond the proxy's limit, or cuts one
|
|
83
|
+
* beyond both the machine's limits together: what it carries is not known yet.
|
|
50
84
|
*/
|
|
51
85
|
private count;
|
|
86
|
+
/**
|
|
87
|
+
* Why `socket` may not carry a command's traffic, `undefined` when it may: always once it does;
|
|
88
|
+
* otherwise while the machine's commands hold fewer than {@link maxConnections}, and those of
|
|
89
|
+
* all machines leave the routes their share of the proxy. It is then counted as a command's.
|
|
90
|
+
*/
|
|
91
|
+
private commandRefusal;
|
|
92
|
+
/** The most connections the commands of all sandboxes hold together: the routes keep the rest. */
|
|
93
|
+
private commandsOfAll;
|
|
94
|
+
/** A connection whose first request is a base URL route: never counted as a command's. */
|
|
95
|
+
private admitRoute;
|
|
96
|
+
/** Refuses a connection at a limit: the first refusal logged, until the machine goes under. */
|
|
97
|
+
private atLimit;
|
|
98
|
+
/**
|
|
99
|
+
* Logs that a machine at a limit went back well under it, three quarters of its commands' limit:
|
|
100
|
+
* one connection closed, and the next refused, would otherwise log twice each time.
|
|
101
|
+
*/
|
|
102
|
+
private underLimit;
|
|
103
|
+
/** Refuses a connection at the proxy's limit: the first refusal logged, with who holds the most. */
|
|
104
|
+
private proxyAtLimit;
|
|
105
|
+
/** Logs that the proxy went back under three quarters of its limits. */
|
|
106
|
+
private proxyUnderLimit;
|
|
107
|
+
/** The three sandboxes holding the most connections, with how many. */
|
|
108
|
+
private busiest;
|
|
109
|
+
private limits;
|
|
52
110
|
private tunnel;
|
|
53
111
|
/**
|
|
54
112
|
* A plain request: a base URL route, its credentials put in, or, through `HTTP_PROXY`, plain HTTP
|
|
@@ -32,8 +32,32 @@ function reachability(policy, host) {
|
|
|
32
32
|
return { lookup: publicOnlyLookup };
|
|
33
33
|
}
|
|
34
34
|
const UNKNOWN = 'This machine is no sandbox the proxy serves.';
|
|
35
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* The most connections the commands of a sandbox hold open through the proxy at once, by default:
|
|
37
|
+
* its tunnels and plain HTTP requests.
|
|
38
|
+
*/
|
|
36
39
|
export const DEFAULT_MAX_CONNECTIONS = 128;
|
|
40
|
+
/**
|
|
41
|
+
* The connections a sandbox holds beyond {@link DEFAULT_MAX_CONNECTIONS}, by default, for its base
|
|
42
|
+
* URL routes alone: the runtime's way to its model provider stays open whatever the commands hold.
|
|
43
|
+
*/
|
|
44
|
+
export const DEFAULT_ROUTE_CONNECTIONS = 32;
|
|
45
|
+
/**
|
|
46
|
+
* How long the proxy keeps an idle connection of a base URL route open: longer than the runtimes'
|
|
47
|
+
* clients keep theirs, so that the client always closes first. Otherwise a request sent on it just
|
|
48
|
+
* as the proxy closes it is reset. Codex's client keeps an idle connection for 90 seconds; Claude
|
|
49
|
+
* Code's reused one after 34 seconds. Node's default, 5 seconds, is shorter than both.
|
|
50
|
+
*/
|
|
51
|
+
export const KEEP_ALIVE_MS = 120_000;
|
|
52
|
+
/**
|
|
53
|
+
* The most connections the proxy holds open at once, for all its sandboxes, by default: what
|
|
54
|
+
* `LimitNOFILE=65536` allows, two descriptors for each connection, with a margin for the rest.
|
|
55
|
+
*/
|
|
56
|
+
export const DEFAULT_TOTAL_CONNECTIONS = 32_256;
|
|
57
|
+
/** The share of the proxy's connections its commands never take: the base URL routes keep it. */
|
|
58
|
+
const ROUTE_SHARE = 0.1;
|
|
59
|
+
/** What a command refused at the proxy's limit is told, and a connection cut at it. */
|
|
60
|
+
const PROXY_FULL = 'The proxy holds the most connections it may, for all its sandboxes. Try again in a moment.';
|
|
37
61
|
/** The most bytes a ClientHello is read from: well over any real one. */
|
|
38
62
|
const MAX_HELLO_BYTES = 64 * 1024;
|
|
39
63
|
/** How long a client has to send its ClientHello once its tunnel is open. */
|
|
@@ -50,6 +74,7 @@ function clientHello(socket, head) {
|
|
|
50
74
|
const done = (hello) => {
|
|
51
75
|
clearTimeout(timer);
|
|
52
76
|
socket.off('data', received);
|
|
77
|
+
socket.off('end', closed);
|
|
53
78
|
socket.off('close', closed);
|
|
54
79
|
socket.pause();
|
|
55
80
|
resolve({ bytes, hello });
|
|
@@ -68,6 +93,8 @@ function clientHello(socket, head) {
|
|
|
68
93
|
const closed = () => done();
|
|
69
94
|
const timer = setTimeout(done, HELLO_TIMEOUT_MS);
|
|
70
95
|
socket.on('data', received);
|
|
96
|
+
// The server keeps a socket half open once its client ended it: no `close` would come.
|
|
97
|
+
socket.once('end', closed);
|
|
71
98
|
socket.once('close', closed);
|
|
72
99
|
if (bytes.length > 0)
|
|
73
100
|
check();
|
|
@@ -93,6 +120,7 @@ function helloRefusal(host, hello) {
|
|
|
93
120
|
? `A tunnel to ${host} must name it in its TLS (SNI).`
|
|
94
121
|
: `A tunnel to ${host} may not name ${named} in its TLS.`;
|
|
95
122
|
}
|
|
123
|
+
const connections = (count) => `${count} connection${count === 1 ? '' : 's'}`;
|
|
96
124
|
const refuse = (res, message) => {
|
|
97
125
|
res.writeHead(403, { 'content-type': 'text/plain' }).end(`${message}\n`);
|
|
98
126
|
};
|
|
@@ -158,23 +186,40 @@ export class EgressProxy {
|
|
|
158
186
|
logger;
|
|
159
187
|
server;
|
|
160
188
|
/** The connections each machine holds open, by its address. */
|
|
161
|
-
|
|
162
|
-
/** The
|
|
163
|
-
|
|
189
|
+
machines = new Map();
|
|
190
|
+
/** The connections of every machine together. */
|
|
191
|
+
all = { open: 0, commands: 0 };
|
|
192
|
+
/** What each connection carries, once its first request said. */
|
|
193
|
+
kinds = new WeakMap();
|
|
164
194
|
maxConnections;
|
|
195
|
+
routeConnections;
|
|
196
|
+
totalConnections;
|
|
165
197
|
tunnelPort;
|
|
166
198
|
/**
|
|
167
|
-
* @param options.maxConnections The most connections a sandbox
|
|
168
|
-
* one more is
|
|
199
|
+
* @param options.maxConnections The most connections the commands of a sandbox hold open at
|
|
200
|
+
* once, its tunnels and plain HTTP requests: one more is refused, so that no sandbox takes the
|
|
201
|
+
* sockets of the others.
|
|
202
|
+
* @param options.routeConnections The connections a sandbox holds beyond `maxConnections` for
|
|
203
|
+
* its base URL routes alone, so that the runtime reaches its model provider whatever the
|
|
204
|
+
* commands hold. A machine never holds more than both together.
|
|
205
|
+
* @param options.totalConnections The most connections the proxy holds open at once, for all
|
|
206
|
+
* its sandboxes: below what its file descriptors allow, so that a connection beyond it is
|
|
207
|
+
* refused with a reason rather than reset by the system. A tenth of it is kept for the base
|
|
208
|
+
* URL routes, which the commands of all sandboxes together never take.
|
|
169
209
|
* @param options.tunnelPort The port a tunnel reaches on its host, whatever port its `CONNECT`
|
|
170
210
|
* names (443, the only one allowed). Tests only.
|
|
171
211
|
*/
|
|
172
|
-
constructor(policyFor, logger = silentLogger, { maxConnections = DEFAULT_MAX_CONNECTIONS, tunnelPort = 443, } = {}) {
|
|
212
|
+
constructor(policyFor, logger = silentLogger, { maxConnections = DEFAULT_MAX_CONNECTIONS, routeConnections = DEFAULT_ROUTE_CONNECTIONS, totalConnections = DEFAULT_TOTAL_CONNECTIONS, tunnelPort = 443, } = {}) {
|
|
173
213
|
this.policyFor = policyFor;
|
|
174
214
|
this.logger = logger;
|
|
175
215
|
this.maxConnections = maxConnections;
|
|
216
|
+
this.routeConnections = routeConnections;
|
|
217
|
+
this.totalConnections = totalConnections;
|
|
176
218
|
this.tunnelPort = tunnelPort;
|
|
177
219
|
this.server = createServer((req, res) => this.forward(req, res));
|
|
220
|
+
this.server.keepAliveTimeout = KEEP_ALIVE_MS;
|
|
221
|
+
// Above the keep-alive: an idle connection is closed by it, never by the wait for headers.
|
|
222
|
+
this.server.headersTimeout = KEEP_ALIVE_MS + 1_000;
|
|
178
223
|
this.server.on('connection', (socket) => this.count(socket));
|
|
179
224
|
this.server.on('connect', (req, socket, head) => this.tunnel(req, socket, head));
|
|
180
225
|
}
|
|
@@ -183,31 +228,124 @@ export class EgressProxy {
|
|
|
183
228
|
this.server.close();
|
|
184
229
|
}
|
|
185
230
|
/**
|
|
186
|
-
* Counts the connections of a machine, and
|
|
187
|
-
*
|
|
231
|
+
* Counts the connections of a machine, and refuses one beyond the proxy's limit, or cuts one
|
|
232
|
+
* beyond both the machine's limits together: what it carries is not known yet.
|
|
188
233
|
*/
|
|
189
234
|
count(socket) {
|
|
190
235
|
const address = socket.remoteAddress ?? '';
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
236
|
+
if (this.all.open >= this.totalConnections) {
|
|
237
|
+
this.proxyAtLimit(`${connections(this.all.open)} are open, base URL routes included`);
|
|
238
|
+
socket.end(`HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n${PROXY_FULL}\n`);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const machine = this.machines.get(address) ?? { open: 0, commands: 0 };
|
|
242
|
+
if (machine.open >= this.maxConnections + this.routeConnections) {
|
|
243
|
+
this.atLimit(address, machine, `${connections(machine.open)} are open, base URL routes included`);
|
|
198
244
|
socket.destroy();
|
|
199
245
|
return;
|
|
200
246
|
}
|
|
201
|
-
|
|
247
|
+
machine.open += 1;
|
|
248
|
+
this.all.open += 1;
|
|
249
|
+
this.machines.set(address, machine);
|
|
202
250
|
socket.once('close', () => {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
this.
|
|
208
|
-
|
|
251
|
+
machine.open -= 1;
|
|
252
|
+
this.all.open -= 1;
|
|
253
|
+
if (this.kinds.get(socket) === 'command') {
|
|
254
|
+
machine.commands -= 1;
|
|
255
|
+
this.all.commands -= 1;
|
|
256
|
+
}
|
|
257
|
+
if (machine.open === 0)
|
|
258
|
+
this.machines.delete(address);
|
|
259
|
+
this.underLimit(address, machine);
|
|
260
|
+
this.proxyUnderLimit();
|
|
209
261
|
});
|
|
210
262
|
}
|
|
263
|
+
/**
|
|
264
|
+
* Why `socket` may not carry a command's traffic, `undefined` when it may: always once it does;
|
|
265
|
+
* otherwise while the machine's commands hold fewer than {@link maxConnections}, and those of
|
|
266
|
+
* all machines leave the routes their share of the proxy. It is then counted as a command's.
|
|
267
|
+
*/
|
|
268
|
+
commandRefusal(socket) {
|
|
269
|
+
if (this.kinds.has(socket))
|
|
270
|
+
return undefined;
|
|
271
|
+
const address = socket.remoteAddress ?? '';
|
|
272
|
+
const machine = this.machines.get(address);
|
|
273
|
+
if (machine === undefined)
|
|
274
|
+
return undefined;
|
|
275
|
+
if (machine.commands >= this.maxConnections) {
|
|
276
|
+
this.atLimit(address, machine, `its commands hold ${connections(machine.commands)}`);
|
|
277
|
+
return `The sandbox holds the most connections its commands may: ${this.maxConnections}. Close some and try again.`;
|
|
278
|
+
}
|
|
279
|
+
if (this.all.commands >= this.commandsOfAll()) {
|
|
280
|
+
this.proxyAtLimit(`the commands of its sandboxes hold ${connections(this.all.commands)}`);
|
|
281
|
+
return PROXY_FULL;
|
|
282
|
+
}
|
|
283
|
+
machine.commands += 1;
|
|
284
|
+
this.all.commands += 1;
|
|
285
|
+
this.kinds.set(socket, 'command');
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
/** The most connections the commands of all sandboxes hold together: the routes keep the rest. */
|
|
289
|
+
commandsOfAll() {
|
|
290
|
+
return this.totalConnections - Math.ceil(this.totalConnections * ROUTE_SHARE);
|
|
291
|
+
}
|
|
292
|
+
/** A connection whose first request is a base URL route: never counted as a command's. */
|
|
293
|
+
admitRoute(socket) {
|
|
294
|
+
if (!this.kinds.has(socket))
|
|
295
|
+
this.kinds.set(socket, 'route');
|
|
296
|
+
}
|
|
297
|
+
/** Refuses a connection at a limit: the first refusal logged, until the machine goes under. */
|
|
298
|
+
atLimit(address, machine, state) {
|
|
299
|
+
if (machine.refused === undefined) {
|
|
300
|
+
const who = this.policyFor(address)?.name ?? address;
|
|
301
|
+
this.logger.warn(`${who} reached its limit: ${state}, the most it may. More are refused until some close: ${this.limits()}.`);
|
|
302
|
+
}
|
|
303
|
+
machine.refused = (machine.refused ?? 0) + 1;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Logs that a machine at a limit went back well under it, three quarters of its commands' limit:
|
|
307
|
+
* one connection closed, and the next refused, would otherwise log twice each time.
|
|
308
|
+
*/
|
|
309
|
+
underLimit(address, machine) {
|
|
310
|
+
if (machine.refused === undefined)
|
|
311
|
+
return;
|
|
312
|
+
if (machine.commands > (this.maxConnections * 3) / 4)
|
|
313
|
+
return;
|
|
314
|
+
if (machine.open > ((this.maxConnections + this.routeConnections) * 3) / 4)
|
|
315
|
+
return;
|
|
316
|
+
const who = this.policyFor(address)?.name ?? address;
|
|
317
|
+
this.logger.info(`${who} is back under its limit: ${connections(machine.open)} open, ${machine.commands} of its commands; ${machine.refused} refused meanwhile.`);
|
|
318
|
+
machine.refused = undefined;
|
|
319
|
+
}
|
|
320
|
+
/** Refuses a connection at the proxy's limit: the first refusal logged, with who holds the most. */
|
|
321
|
+
proxyAtLimit(state) {
|
|
322
|
+
if (this.all.refused === undefined) {
|
|
323
|
+
this.logger.warn(`The proxy reached its limit: ${state}, the most it may for all its sandboxes (${this.totalConnections}, ${this.commandsOfAll()} of them for the commands). More are refused until some close. Holding the most: ${this.busiest()}.`);
|
|
324
|
+
}
|
|
325
|
+
this.all.refused = (this.all.refused ?? 0) + 1;
|
|
326
|
+
}
|
|
327
|
+
/** Logs that the proxy went back under three quarters of its limits. */
|
|
328
|
+
proxyUnderLimit() {
|
|
329
|
+
if (this.all.refused === undefined)
|
|
330
|
+
return;
|
|
331
|
+
if (this.all.commands > (this.commandsOfAll() * 3) / 4)
|
|
332
|
+
return;
|
|
333
|
+
if (this.all.open > (this.totalConnections * 3) / 4)
|
|
334
|
+
return;
|
|
335
|
+
this.logger.info(`The proxy is back under its limit: ${connections(this.all.open)} open, ${this.all.commands} of commands; ${this.all.refused} refused meanwhile.`);
|
|
336
|
+
this.all.refused = undefined;
|
|
337
|
+
}
|
|
338
|
+
/** The three sandboxes holding the most connections, with how many. */
|
|
339
|
+
busiest() {
|
|
340
|
+
return [...this.machines]
|
|
341
|
+
.sort(([, a], [, b]) => b.open - a.open)
|
|
342
|
+
.slice(0, 3)
|
|
343
|
+
.map(([address, { open }]) => `${this.policyFor(address)?.name ?? address} (${open})`)
|
|
344
|
+
.join(', ');
|
|
345
|
+
}
|
|
346
|
+
limits() {
|
|
347
|
+
return `${this.maxConnections} for the commands, and ${this.routeConnections} more for the base URL routes`;
|
|
348
|
+
}
|
|
211
349
|
tunnel(req, socket, head) {
|
|
212
350
|
socket.on('error', () => socket.destroy());
|
|
213
351
|
const { hostname, port } = new URL(`http://${req.url ?? ''}`);
|
|
@@ -226,6 +364,11 @@ export class EgressProxy {
|
|
|
226
364
|
socket.end(`HTTP/1.1 403 Forbidden\r\n\r\n${refusal}\n`);
|
|
227
365
|
return;
|
|
228
366
|
}
|
|
367
|
+
const full = this.commandRefusal(socket);
|
|
368
|
+
if (full !== undefined) {
|
|
369
|
+
socket.end(`HTTP/1.1 503 Service Unavailable\r\n\r\n${full}\n`);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
229
372
|
const upstream = connect({ host: hostname, port: this.tunnelPort, lookup: reach.lookup }, () => {
|
|
230
373
|
socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
231
374
|
void clientHello(socket, head).then(({ bytes, hello }) => {
|
|
@@ -267,12 +410,19 @@ export class EgressProxy {
|
|
|
267
410
|
this.deny(res, { address, policy, target: route.host, why: refusal });
|
|
268
411
|
return;
|
|
269
412
|
}
|
|
413
|
+
this.admitRoute(req.socket);
|
|
270
414
|
this.send(req, res, { policy, target: route, transformations: policy.transformations });
|
|
271
415
|
}
|
|
272
416
|
/** A plain HTTP request through `HTTP_PROXY`: sent on to an allowed host, refused otherwise. */
|
|
273
417
|
forwardPlain(req, res, policy) {
|
|
274
418
|
const plain = plainTarget(req.url ?? '');
|
|
275
419
|
if (plain !== undefined && isListedHost(policy.allowedHosts, plain.hostname)) {
|
|
420
|
+
const full = this.commandRefusal(req.socket);
|
|
421
|
+
if (full !== undefined) {
|
|
422
|
+
res.writeHead(503, { 'content-type': 'text/plain', connection: 'close' });
|
|
423
|
+
res.end(`${full}\n`);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
276
426
|
this.send(req, res, { policy, target: plain, transformations: [] });
|
|
277
427
|
return;
|
|
278
428
|
}
|
package/dist/proxy/main.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
type Environment = Readonly<Record<string, string | undefined>>;
|
|
2
|
-
/**
|
|
3
|
-
|
|
2
|
+
/**
|
|
3
|
+
* The proxy's settings, from its environment, which the systemd unit of its machine sets.
|
|
4
|
+
* `limits` is the text of `/proc/self/limits`, for the total of connections by default.
|
|
5
|
+
*/
|
|
6
|
+
export declare function proxyConfig(env: Environment, limits?: string | undefined): {
|
|
4
7
|
adminPort: number;
|
|
5
8
|
allowPrivateNetwork: boolean;
|
|
6
9
|
host: string;
|
|
@@ -8,8 +11,16 @@ export declare function proxyConfig(env: Environment): {
|
|
|
8
11
|
idleExitMs?: number;
|
|
9
12
|
maxConnections: number;
|
|
10
13
|
port: number;
|
|
14
|
+
routeConnections: number;
|
|
11
15
|
token: string;
|
|
16
|
+
totalConnections: number;
|
|
12
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* The most connections the descriptors of the process allow, two for each, its soft `Max open
|
|
20
|
+
* files` in `limits` less {@link SPARE_DESCRIPTORS}: {@link DEFAULT_TOTAL_CONNECTIONS} when that
|
|
21
|
+
* limit is unknown or unlimited.
|
|
22
|
+
*/
|
|
23
|
+
export declare function totalConnectionsFor(limits: string | undefined): number;
|
|
13
24
|
/** `ai-sdk-sandbox-gce proxy`: serves the sandboxes and the administration API until stopped. */
|
|
14
25
|
export declare function main(env: Environment): void;
|
|
15
26
|
export {};
|
package/dist/proxy/main.js
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
1
2
|
import { createLogger } from '../common/logger.js';
|
|
2
3
|
import { DEFAULT_PROXY_ADMIN_PORT, DEFAULT_PROXY_PORT } from '../protocol/proxy.js';
|
|
3
4
|
import { createAdminServer } from './admin-server.js';
|
|
4
|
-
import { DEFAULT_MAX_CONNECTIONS, EgressProxy } from './egress-proxy.js';
|
|
5
|
+
import { DEFAULT_MAX_CONNECTIONS, DEFAULT_ROUTE_CONNECTIONS, DEFAULT_TOTAL_CONNECTIONS, EgressProxy, } from './egress-proxy.js';
|
|
5
6
|
import { IDLE_EXIT_CODE, watchIdle } from './idle-exit.js';
|
|
6
7
|
import { SandboxRegistry } from './registry.js';
|
|
7
|
-
/**
|
|
8
|
-
|
|
8
|
+
/**
|
|
9
|
+
* The proxy's settings, from its environment, which the systemd unit of its machine sets.
|
|
10
|
+
* `limits` is the text of `/proc/self/limits`, for the total of connections by default.
|
|
11
|
+
*/
|
|
12
|
+
export function proxyConfig(env, limits = readLimits()) {
|
|
9
13
|
const token = env['SANDBOX_PROXY_TOKEN'];
|
|
10
14
|
if (token === undefined || token.length < 16) {
|
|
11
15
|
throw new Error('SANDBOX_PROXY_TOKEN is required, 16 characters at least: the sandbox service proves itself with it.');
|
|
@@ -15,7 +19,18 @@ export function proxyConfig(env) {
|
|
|
15
19
|
adminPort: Number.parseInt(env['SANDBOX_PROXY_ADMIN_PORT'] ?? String(DEFAULT_PROXY_ADMIN_PORT), 10),
|
|
16
20
|
host: env['HOST'] ?? '0.0.0.0',
|
|
17
21
|
allowPrivateNetwork: env['SANDBOX_ALLOW_PRIVATE_NETWORK'] === 'true',
|
|
18
|
-
maxConnections:
|
|
22
|
+
maxConnections: connectionCount('SANDBOX_PROXY_MAX_CONNECTIONS', env, {
|
|
23
|
+
fallback: DEFAULT_MAX_CONNECTIONS,
|
|
24
|
+
min: 1,
|
|
25
|
+
}),
|
|
26
|
+
routeConnections: connectionCount('SANDBOX_PROXY_ROUTE_CONNECTIONS', env, {
|
|
27
|
+
fallback: DEFAULT_ROUTE_CONNECTIONS,
|
|
28
|
+
min: 0,
|
|
29
|
+
}),
|
|
30
|
+
totalConnections: connectionCount('SANDBOX_PROXY_TOTAL_CONNECTIONS', env, {
|
|
31
|
+
fallback: totalConnectionsFor(limits),
|
|
32
|
+
min: 1,
|
|
33
|
+
}),
|
|
19
34
|
idleExitMs: idleExitMs(env['SANDBOX_PROXY_IDLE_EXIT_MINUTES']),
|
|
20
35
|
token,
|
|
21
36
|
};
|
|
@@ -30,13 +45,36 @@ function idleExitMs(value) {
|
|
|
30
45
|
}
|
|
31
46
|
return parsed * 60_000;
|
|
32
47
|
}
|
|
33
|
-
/**
|
|
34
|
-
|
|
48
|
+
/** Descriptors kept apart from the connections: the proxy's own files, and upstream sockets kept alive. */
|
|
49
|
+
const SPARE_DESCRIPTORS = 1024;
|
|
50
|
+
/**
|
|
51
|
+
* The most connections the descriptors of the process allow, two for each, its soft `Max open
|
|
52
|
+
* files` in `limits` less {@link SPARE_DESCRIPTORS}: {@link DEFAULT_TOTAL_CONNECTIONS} when that
|
|
53
|
+
* limit is unknown or unlimited.
|
|
54
|
+
*/
|
|
55
|
+
export function totalConnectionsFor(limits) {
|
|
56
|
+
const soft = /^Max open files\s+(\d+)/m.exec(limits ?? '')?.[1];
|
|
57
|
+
if (soft === undefined)
|
|
58
|
+
return DEFAULT_TOTAL_CONNECTIONS;
|
|
59
|
+
return Math.max(1, Math.floor((Number(soft) - SPARE_DESCRIPTORS) / 2));
|
|
60
|
+
}
|
|
61
|
+
function readLimits() {
|
|
62
|
+
try {
|
|
63
|
+
return readFileSync('/proc/self/limits', 'utf8');
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** A number of connections the variable `name` sets, an integer from `min`: `fallback` when unset. */
|
|
70
|
+
function connectionCount(name, env, { fallback, min }) {
|
|
71
|
+
const value = env[name];
|
|
35
72
|
if (value === undefined || value === '')
|
|
36
|
-
return
|
|
73
|
+
return fallback;
|
|
37
74
|
const parsed = Number(value);
|
|
38
|
-
if (!Number.isInteger(parsed) || parsed <
|
|
39
|
-
|
|
75
|
+
if (!Number.isInteger(parsed) || parsed < min) {
|
|
76
|
+
const kind = min === 0 ? 'a non-negative integer' : 'a positive integer';
|
|
77
|
+
throw new Error(`${name}: \`${value}\` is not ${kind}.`);
|
|
40
78
|
}
|
|
41
79
|
return parsed;
|
|
42
80
|
}
|
|
@@ -50,6 +88,8 @@ export function main(env) {
|
|
|
50
88
|
const registry = new SandboxRegistry(config.allowPrivateNetwork);
|
|
51
89
|
const proxy = new EgressProxy((address) => registry.policyFor(address), logger, {
|
|
52
90
|
maxConnections: config.maxConnections,
|
|
91
|
+
routeConnections: config.routeConnections,
|
|
92
|
+
totalConnections: config.totalConnections,
|
|
53
93
|
});
|
|
54
94
|
const admin = createAdminServer({ registry, token: config.token, logger });
|
|
55
95
|
proxy.server.listen(config.port, config.host, () => logger.info(`Egress proxy listening on ${config.host}:${config.port}`));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-sdk-sandbox-gce",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.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",
|