ai-sdk-sandbox-gce 0.3.2 → 0.3.3
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 +10 -0
- package/README.md +29 -4
- package/dist/server/compute/compute-api.d.ts +10 -1
- package/dist/server/compute/compute-api.js +11 -2
- package/dist/server/config.js +51 -0
- package/dist/server/sandboxes/sandboxes.d.ts +93 -13
- package/dist/server/sandboxes/sandboxes.js +331 -62
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# ai-sdk-sandbox-gce
|
|
2
2
|
|
|
3
|
+
## 0.3.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 7afcb0c: The sandbox service takes `SANDBOX_PROFILE=cost|fast`, to trade how fast a sandbox starts against what the service costs at rest. `cost`, the default, is the service as it was: nothing runs but the sandboxes, and a sandbox from a template starts in some 35 to 40 s. `fast` starts one in a few seconds, for one machine of `SANDBOX_MACHINE_TYPE` per template used in the last 24 h and the egress proxy running all the time: the service keeps a machine booted from each template in use, which the next creation from that template takes as it is, booted or still booting, and makes the next one meanwhile. A machine that waited 24 h without a creation is deleted without a replacement: a template no longer used costs a day of its machine at most. See "Speed or cost" in the README.
|
|
8
|
+
|
|
9
|
+
The profile only sets the defaults of two settings, each its own variable: `SANDBOX_WARM_POOL`, how many machines are kept booted per template (`0`, `1` with `fast`), and `SANDBOX_PROXY_ALWAYS_ON`, which never stops the proxy's machine of `SANDBOX_PROXY_INSTANCE` once no sandbox runs (`false`, `true` with `fast`). With `fast` and `SANDBOX_PROXY_INSTANCE`, leave the lines of `SANDBOX_PROXY_IDLE_EXIT_MINUTES` out of the proxy's unit.
|
|
10
|
+
|
|
11
|
+
A sandbox taken from the pool keeps its machine's name, `sbx-pool-<hex>`, since Compute Engine cannot rename a running machine: its sandbox's name is on its label `ai-sdk-sandbox-name`. The service's role needs no new permission: it already has `compute.instances.setLabels`.
|
|
12
|
+
|
|
3
13
|
## 0.3.2
|
|
4
14
|
|
|
5
15
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -135,7 +135,7 @@ gcloud compute instances create sandbox-proxy --zone=$ZONE --machine-type=e2-sma
|
|
|
135
135
|
#!/bin/sh
|
|
136
136
|
set -e
|
|
137
137
|
# The version of the proxy: the one your application depends on.
|
|
138
|
-
VERSION=0.3.
|
|
138
|
+
VERSION=0.3.3
|
|
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")"
|
|
@@ -276,7 +276,7 @@ echo "deb [signed-by=/etc/apt/keyrings/nodesource.asc] https://deb.nodesource.co
|
|
|
276
276
|
> /etc/apt/sources.list.d/nodesource.list
|
|
277
277
|
apt-get update
|
|
278
278
|
apt-get install -y nodejs
|
|
279
|
-
npm install --global ai-sdk-sandbox-gce@0.3.
|
|
279
|
+
npm install --global ai-sdk-sandbox-gce@0.3.3 pnpm@10
|
|
280
280
|
|
|
281
281
|
# The sandbox's user: sudo without a password, and Docker.
|
|
282
282
|
useradd --create-home --shell /bin/bash agent
|
|
@@ -303,7 +303,7 @@ The agent runs as root and starts the commands as `agent`. It does not wait for
|
|
|
303
303
|
|
|
304
304
|
### 4. The service
|
|
305
305
|
|
|
306
|
-
The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.
|
|
306
|
+
The service's image is published on Docker Hub with each release, `docker.io/fpasquet/ai-sdk-sandbox-gce:<version>`: Node.js and the package, built by the release workflow from the version on npm. Deploy the version your application depends on. Each image carries a provenance attestation, which `gh attestation verify oci://docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.3 --owner fpasquet` checks; its [`Dockerfile`](https://github.com/fpasquet/ai-sdk-harness/blob/main/packages/sandbox-gce/Dockerfile) builds the same image from your own registry.
|
|
307
307
|
|
|
308
308
|
Its service account gets a role of its own, with what the service calls and nothing else, limited by a condition to the names it uses: the sandboxes' machines and disks (`sbx-`), the proxy's machine, the sandbox images and templates (`ai-sdk-`).
|
|
309
309
|
|
|
@@ -341,7 +341,7 @@ for secret in sandbox-agent-secret sandbox-proxy-token sandbox-service-token; do
|
|
|
341
341
|
--member=serviceAccount:sandboxes@$PROJECT.iam.gserviceaccount.com --role=roles/secretmanager.secretAccessor
|
|
342
342
|
done
|
|
343
343
|
|
|
344
|
-
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.
|
|
344
|
+
gcloud run deploy sandboxes --region=$REGION --image=docker.io/fpasquet/ai-sdk-sandbox-gce:0.3.3 \
|
|
345
345
|
--service-account=sandboxes@$PROJECT.iam.gserviceaccount.com \
|
|
346
346
|
--network=sandboxes --subnet=service --vpc-egress=private-ranges-only \
|
|
347
347
|
--no-allow-unauthenticated --min-instances=0 --timeout=3600 --concurrency=1000 \
|
|
@@ -472,6 +472,28 @@ const sandboxSession = await createGceNetworkSandboxSession({
|
|
|
472
472
|
await sandboxSession.destroy();
|
|
473
473
|
```
|
|
474
474
|
|
|
475
|
+
## Speed or cost
|
|
476
|
+
|
|
477
|
+
`SANDBOX_PROFILE` on the service trades how fast a sandbox starts against what the service costs at rest. It only sets defaults: each setting below can be set on its own.
|
|
478
|
+
|
|
479
|
+
| Profile | At rest | A sandbox from a template |
|
|
480
|
+
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
|
|
481
|
+
| `cost` (default) | Nothing runs: the disks of stopped sandboxes and the templates' images only. With `SANDBOX_PROXY_INSTANCE`, the proxy runs while a sandbox does | Some 35 to 40 s: a machine boots for it |
|
|
482
|
+
| `fast` | One machine of `SANDBOX_MACHINE_TYPE` and its disk for each template used in the last 24 h, all the time, at its Spot price with `SANDBOX_SPOT=true`; and the proxy's machine, always on | A few seconds when the pool's machine has booted, less than a cold start while it boots |
|
|
483
|
+
|
|
484
|
+
`fast` keeps a machine booted from each template in use, the warm pool (`SANDBOX_WARM_POOL=1`, machines per template), and never stops the proxy (`SANDBOX_PROXY_ALWAYS_ON=true`). A creation from a template takes one of its machines as it is, and the service creates the next one in the same request, without waiting for it to boot: Cloud Run throttles the service's CPU once it has answered, so nothing is left to run after. Each machine runs some 730 hours a month: see [Compute Engine's prices](https://cloud.google.com/compute/vm-instance-pricing) for your machine type and region.
|
|
485
|
+
|
|
486
|
+
- Only a creation from a template takes from the pool: `template: await agent.getSandboxTemplate()`. A creation without one, or a resume, boots its machine as before.
|
|
487
|
+
- A machine of the pool never ran an agent: it boots from the template, as a new sandbox does. Once taken it is the sandbox's, and never goes back to the pool.
|
|
488
|
+
- Each template has its pool: two harnesses, Claude Code and Codex say, keep a machine each. A new template (a new version of the package or of the sandbox image) gets its own on its first creation.
|
|
489
|
+
- A machine that waited 24 h without a creation is deleted, without a replacement, by the next creation that meets it, whatever its template: a template no longer used costs a day of its machine at most.
|
|
490
|
+
- A creation takes a running machine of its template first, or else one still booting, the one booting longest: it is ready sooner than a machine booted for the creation. Two creations in a row: the second takes the machine the first one started.
|
|
491
|
+
- A machine taken from the pool keeps its name, `sbx-pool-<hex>`: Compute Engine cannot rename a running machine. The sandbox's name is on its label `ai-sdk-sandbox-name`, by which the service finds it.
|
|
492
|
+
- `SANDBOX_MAX_RUNNING` does not count the pool's machines, and they do not keep the proxy up.
|
|
493
|
+
- `SANDBOX_MAX_RUN_HOURS` applies to the pool's machines as to every other, the bill's guard: for a sandbox taken from the pool, Compute Engine counts it from the machine's boot in the pool, 24 h ago at most. How long a session lasts is the application's to decide, not the limit's. With `SANDBOX_SPOT=true`, Compute Engine may take a machine back. A machine stopped either way is deleted by the next creation that meets it, and the pool fills again.
|
|
494
|
+
- With `SANDBOX_PROXY_INSTANCE`, the service starts the proxy with the first sandbox and leaves it running: leave the three lines of `SANDBOX_PROXY_IDLE_EXIT_MINUTES` out of its unit, or the proxy stops itself after 10 minutes with no sandbox. Without `SANDBOX_PROXY_INSTANCE`, the proxy is always on anyway.
|
|
495
|
+
- Back to `cost`, the next creation from a template takes what is left in its pool, and makes nothing more.
|
|
496
|
+
|
|
475
497
|
## Stopping and resuming
|
|
476
498
|
|
|
477
499
|
`stop()` suspends the sandbox: the processes this session started are stopped, the proxy forgets its credentials, then the machine is stopped, its disk kept. Resume it later, from this process or another one:
|
|
@@ -615,6 +637,9 @@ Docker pulls images from Docker Hub through the proxy: allow `registry-1.docker.
|
|
|
615
637
|
| `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 |
|
|
616
638
|
| `SANDBOX_RECONCILE_MINUTES` | `10` | How often, at most, the service makes the proxy forget the sandboxes whose machine no longer runs, in the background of a creation or a resume. A sandbox of another service sharing the proxy in the zone is left alone, under another `SANDBOX_INSTANCE_PREFIX`. `0` for never: a proxy shared with a service of another zone or project |
|
|
617
639
|
| `SANDBOX_PROXY_INSTANCE` | none | The egress proxy's machine, in the sandboxes' zone: started with the first sandbox that runs, stopped once none does. Always on without it |
|
|
640
|
+
| `SANDBOX_PROFILE` | `cost` | `cost` or `fast`: the defaults of the two settings below, see [Speed or cost](#speed-or-cost) |
|
|
641
|
+
| `SANDBOX_WARM_POOL` | `0`, `1` with `fast` | How many machines are kept booted from each template used in the last 24 h, for the next creations from it to take at once. Each one is billed all the time |
|
|
642
|
+
| `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 |
|
|
618
643
|
| `SANDBOX_ALLOWED_HOSTS` | none | Hosts every sandbox may reach over HTTPS, comma-separated; `*.domain` allowed. `*`, any host, is logged as a warning at startup |
|
|
619
644
|
| `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 |
|
|
620
645
|
| `SANDBOX_SERVICE_TOKEN` | required on Cloud Run | A secret every call must carry, beside Cloud Run's IAM |
|
|
@@ -5,10 +5,14 @@ export interface Instance {
|
|
|
5
5
|
/** `PROVISIONING`, `STAGING`, `RUNNING`, `STOPPING`, `TERMINATED`, `SUSPENDING`, `SUSPENDED`… */
|
|
6
6
|
status: string;
|
|
7
7
|
labels?: Record<string, string>;
|
|
8
|
+
/** What the labels are changed with: Compute Engine refuses a change made on older ones. */
|
|
9
|
+
labelFingerprint?: string;
|
|
8
10
|
networkInterfaces?: {
|
|
9
11
|
networkIP?: string;
|
|
10
12
|
}[];
|
|
11
13
|
metadata?: InstanceMetadata;
|
|
14
|
+
/** When the instance was made: an RFC 3339 timestamp. */
|
|
15
|
+
creationTimestamp?: string;
|
|
12
16
|
}
|
|
13
17
|
/** The metadata of an instance: its `fingerprint` must be given back to change it. */
|
|
14
18
|
export interface InstanceMetadata {
|
|
@@ -52,7 +56,7 @@ export declare class ComputeApi {
|
|
|
52
56
|
getInstance(name: string): Promise<Instance | undefined>;
|
|
53
57
|
/** The instances of the zone whose label `key` is `value`, every page of them. */
|
|
54
58
|
listInstances(key: string, value: string): Promise<Instance[]>;
|
|
55
|
-
insertInstance(body: Record<string, unknown
|
|
59
|
+
insertInstance(body: Record<string, unknown>, { wait }?: ChangeOptions): Promise<void>;
|
|
56
60
|
startInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
|
|
57
61
|
resumeInstance(name: string): Promise<void>;
|
|
58
62
|
stopInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
|
|
@@ -63,6 +67,11 @@ export declare class ComputeApi {
|
|
|
63
67
|
* read with `fingerprint`.
|
|
64
68
|
*/
|
|
65
69
|
setMetadata(name: string, metadata: InstanceMetadata): Promise<void>;
|
|
70
|
+
/**
|
|
71
|
+
* Replaces the labels of the instance `name`. Refused with a 412 when they changed since they were
|
|
72
|
+
* read with `fingerprint`: of two changes made on the same labels, one only goes through.
|
|
73
|
+
*/
|
|
74
|
+
setLabels(name: string, labels: Record<string, string>, fingerprint: string | undefined): Promise<void>;
|
|
66
75
|
/** Deletes the instance `name` and its disks set to go with it. Nothing when there is none. */
|
|
67
76
|
deleteInstance(name: string, { wait }?: ChangeOptions): Promise<void>;
|
|
68
77
|
/**
|
|
@@ -33,8 +33,8 @@ export class ComputeApi {
|
|
|
33
33
|
} while (pageToken !== undefined);
|
|
34
34
|
return instances;
|
|
35
35
|
}
|
|
36
|
-
async insertInstance(body) {
|
|
37
|
-
await this.change('POST', this.zonal('instances'), { body });
|
|
36
|
+
async insertInstance(body, { wait = true } = {}) {
|
|
37
|
+
await this.change('POST', this.zonal('instances'), { body, wait });
|
|
38
38
|
}
|
|
39
39
|
async startInstance(name, { wait = true } = {}) {
|
|
40
40
|
await this.change('POST', this.zonal(`instances/${name}/start`), { wait });
|
|
@@ -56,6 +56,15 @@ export class ComputeApi {
|
|
|
56
56
|
async setMetadata(name, metadata) {
|
|
57
57
|
await this.change('POST', this.zonal(`instances/${name}/setMetadata`), { body: metadata });
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Replaces the labels of the instance `name`. Refused with a 412 when they changed since they were
|
|
61
|
+
* read with `fingerprint`: of two changes made on the same labels, one only goes through.
|
|
62
|
+
*/
|
|
63
|
+
async setLabels(name, labels, fingerprint) {
|
|
64
|
+
await this.change('POST', this.zonal(`instances/${name}/setLabels`), {
|
|
65
|
+
body: { labels, labelFingerprint: fingerprint },
|
|
66
|
+
});
|
|
67
|
+
}
|
|
59
68
|
/** Deletes the instance `name` and its disks set to go with it. Nothing when there is none. */
|
|
60
69
|
async deleteInstance(name, { wait = true } = {}) {
|
|
61
70
|
await this.change('DELETE', this.zonal(`instances/${name}`), { ignore: [404], wait });
|
package/dist/server/config.js
CHANGED
|
@@ -119,6 +119,56 @@ function reconcileEveryMs(value) {
|
|
|
119
119
|
}
|
|
120
120
|
return minutes === 0 ? undefined : minutes * 60_000;
|
|
121
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* What `SANDBOX_PROFILE` sets the defaults of: `cost`, nothing running but the sandboxes, each
|
|
124
|
+
* booted on demand; `fast`, a machine of the warm pool always booted and the proxy always on, for a
|
|
125
|
+
* sandbox in seconds at a fixed cost.
|
|
126
|
+
*/
|
|
127
|
+
const PROFILES = {
|
|
128
|
+
cost: { warmPool: 0, proxyAlwaysOn: false },
|
|
129
|
+
fast: { warmPool: 1, proxyAlwaysOn: true },
|
|
130
|
+
};
|
|
131
|
+
/** `SANDBOX_PROFILE`, `cost` or `fast`: `cost` when unset. */
|
|
132
|
+
function profile(value) {
|
|
133
|
+
const text = nonEmpty(value) ?? 'cost';
|
|
134
|
+
if (text !== 'cost' && text !== 'fast') {
|
|
135
|
+
throw new Error(`SANDBOX_PROFILE: \`${text}\` is neither \`cost\` nor \`fast\`.`);
|
|
136
|
+
}
|
|
137
|
+
return PROFILES[text];
|
|
138
|
+
}
|
|
139
|
+
/** `SANDBOX_WARM_POOL`, a whole number of machines: `fallback` when unset. */
|
|
140
|
+
function warmPool(value, fallback) {
|
|
141
|
+
const text = nonEmpty(value);
|
|
142
|
+
if (text === undefined)
|
|
143
|
+
return fallback;
|
|
144
|
+
const parsed = Number(text);
|
|
145
|
+
if (!Number.isInteger(parsed) || parsed < 0) {
|
|
146
|
+
throw new Error(`SANDBOX_WARM_POOL: \`${text}\` is not a whole number of machines.`);
|
|
147
|
+
}
|
|
148
|
+
return parsed;
|
|
149
|
+
}
|
|
150
|
+
/** A variable that is `true` or `false`: `fallback` when unset. */
|
|
151
|
+
function flag(name, value, fallback) {
|
|
152
|
+
const text = nonEmpty(value);
|
|
153
|
+
if (text === undefined)
|
|
154
|
+
return fallback;
|
|
155
|
+
if (text !== 'true' && text !== 'false') {
|
|
156
|
+
throw new Error(`${name}: \`${text}\` is neither \`true\` nor \`false\`.`);
|
|
157
|
+
}
|
|
158
|
+
return text === 'true';
|
|
159
|
+
}
|
|
160
|
+
/** The settings `SANDBOX_PROFILE` gives the defaults of, with a word on the cost of a warm pool. */
|
|
161
|
+
function speedSettings(env, logger) {
|
|
162
|
+
const defaults = profile(env['SANDBOX_PROFILE']);
|
|
163
|
+
const pool = warmPool(env['SANDBOX_WARM_POOL'], defaults.warmPool);
|
|
164
|
+
if (pool > 0) {
|
|
165
|
+
logger.info(`SANDBOX_WARM_POOL=${pool}: ${pool === 1 ? 'a machine is' : `${pool} machines are`} kept booted from each template in use, billed all the time.`);
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
warmPool: pool,
|
|
169
|
+
proxyAlwaysOn: flag('SANDBOX_PROXY_ALWAYS_ON', env['SANDBOX_PROXY_ALWAYS_ON'], defaults.proxyAlwaysOn),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
122
172
|
/** The secret the agents' tokens are derived from. */
|
|
123
173
|
function agentSecret(env) {
|
|
124
174
|
const secret = required(env, 'SANDBOX_AGENT_SECRET', 'the secret the tokens of the sandboxes’ agents are derived from, 32 characters at least');
|
|
@@ -183,6 +233,7 @@ export async function sandboxesConfig(env, logger) {
|
|
|
183
233
|
maxRunning: maxRunning(env['SANDBOX_MAX_RUNNING']),
|
|
184
234
|
reconcileEveryMs: reconcileEveryMs(env['SANDBOX_RECONCILE_MINUTES']),
|
|
185
235
|
proxyInstance: nonEmpty(env['SANDBOX_PROXY_INSTANCE']),
|
|
236
|
+
...speedSettings(env, logger),
|
|
186
237
|
serviceToken: serviceToken(env, logger),
|
|
187
238
|
};
|
|
188
239
|
}
|
|
@@ -76,26 +76,39 @@ export interface SandboxesOptions {
|
|
|
76
76
|
* one at once. Never without it.
|
|
77
77
|
*/
|
|
78
78
|
reconcileEveryMs?: number;
|
|
79
|
+
/**
|
|
80
|
+
* How many machines are kept booted from each template in use, for the next creations from it to
|
|
81
|
+
* take at once rather than boot one: billed while they run, all the time, and deleted once they
|
|
82
|
+
* waited a day. Created in the request of a creation, never waited for. None without it.
|
|
83
|
+
*/
|
|
84
|
+
warmPool?: number;
|
|
85
|
+
/**
|
|
86
|
+
* Never stops the proxy's machine of {@link proxyInstance} once no sandbox runs: a sandbox never
|
|
87
|
+
* waits for it to boot, and it is billed all the time. Stopped when idle without it.
|
|
88
|
+
*/
|
|
89
|
+
proxyAlwaysOn?: boolean;
|
|
79
90
|
}
|
|
80
91
|
/** The image a sandbox gets when its caller names none. */
|
|
81
92
|
export declare const DEFAULT_IMAGE = "default";
|
|
82
93
|
/**
|
|
83
|
-
* The sandboxes, each a Compute Engine machine of its own, named after it
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* serves any sandbox.
|
|
94
|
+
* The sandboxes, each a Compute Engine machine of its own, named after it, or labelled with its
|
|
95
|
+
* name when taken from the warm pool. The service keeps nothing of them: what a machine is, Compute
|
|
96
|
+
* Engine says; what it may reach and its credentials, the egress proxy holds; its processes, its
|
|
97
|
+
* agent runs. Any instance of the service, on any Cloud Run instance, serves any sandbox.
|
|
87
98
|
*/
|
|
88
99
|
export declare class Sandboxes {
|
|
89
100
|
private readonly options;
|
|
90
101
|
private readonly endpoints;
|
|
102
|
+
private readonly machines;
|
|
91
103
|
private readonly bases;
|
|
92
104
|
private nextReconcile;
|
|
93
105
|
constructor(options: SandboxesOptions);
|
|
94
106
|
/** The agent of the running sandbox `name`. */
|
|
95
107
|
agent(name: string): Promise<AgentClient>;
|
|
96
108
|
/**
|
|
97
|
-
* Creates the sandbox `name` on the image `image`, from its template `template` when given
|
|
98
|
-
*
|
|
109
|
+
* Creates the sandbox `name` on the image `image`, from its template `template` when given: on a
|
|
110
|
+
* machine of the warm pool booted from it when one runs, a new machine otherwise. Never resumes
|
|
111
|
+
* one.
|
|
99
112
|
*/
|
|
100
113
|
create(name: string, { template, image, ...network }: SandboxNetwork & {
|
|
101
114
|
image?: string;
|
|
@@ -152,6 +165,31 @@ export declare class Sandboxes {
|
|
|
152
165
|
* the proxy stops with the next sandbox that stops, or by itself when none comes.
|
|
153
166
|
*/
|
|
154
167
|
prepare(): Promise<void>;
|
|
168
|
+
/**
|
|
169
|
+
* Takes for the sandbox `name` a machine of the warm pool of its template, `sourceImage`, and sees
|
|
170
|
+
* to the pool: the template's machines missing created, and any machine no longer running (a Spot
|
|
171
|
+
* machine taken back, one at its run limit) or waiting for more than a day deleted, whatever its
|
|
172
|
+
* template. `upkeep` does so without waiting for Compute Engine, never failing: the caller awaits
|
|
173
|
+
* it before answering. A machine of the pool never ran an agent, as fresh as one made from the
|
|
174
|
+
* template; once taken, it never goes back to the pool.
|
|
175
|
+
*/
|
|
176
|
+
private fromPool;
|
|
177
|
+
/**
|
|
178
|
+
* Takes the machine `machine` of the warm pool for the sandbox `name`, by its labels: of two
|
|
179
|
+
* creations taking it at once, Compute Engine lets one change them only. The machine as it is
|
|
180
|
+
* then, running or still booting, `undefined` when another creation took it, or it no longer
|
|
181
|
+
* runs. Fails when Compute Engine refuses the change for another reason.
|
|
182
|
+
*/
|
|
183
|
+
private take;
|
|
184
|
+
/**
|
|
185
|
+
* Deletes the machine `machine` of the warm pool, once labelled retired: a creation that read it
|
|
186
|
+
* before can no longer take it, nor this one take it from under a creation that did.
|
|
187
|
+
*/
|
|
188
|
+
private retire;
|
|
189
|
+
/** Creates a machine of the warm pool booted from `template`, without waiting for it. */
|
|
190
|
+
private addToPool;
|
|
191
|
+
/** What the machines of the warm pool are named after: the service's prefix, then `pool-`. */
|
|
192
|
+
private get poolPrefix();
|
|
155
193
|
/**
|
|
156
194
|
* Starts the proxy's machine when the service drives it and it is stopped, and waits until the
|
|
157
195
|
* proxy answers. Stopping, it is first let stop: its registrations go with it, and the sandboxes
|
|
@@ -160,7 +198,10 @@ export declare class Sandboxes {
|
|
|
160
198
|
private proxyUp;
|
|
161
199
|
/** Starts a {@link reconcile} without waiting for it, once per period at most. */
|
|
162
200
|
private reconcileInBackground;
|
|
163
|
-
/**
|
|
201
|
+
/**
|
|
202
|
+
* Stops the proxy's machine, when the service drives it and does not keep it running, once no
|
|
203
|
+
* sandbox runs: the machines of the warm pool are none, and need no proxy until taken.
|
|
204
|
+
*/
|
|
164
205
|
private proxyDownWhenIdle;
|
|
165
206
|
/** Refuses one more running sandbox beyond {@link SandboxesOptions.maxRunning}. */
|
|
166
207
|
private assertRoom;
|
|
@@ -181,22 +222,61 @@ export declare class Sandboxes {
|
|
|
181
222
|
*/
|
|
182
223
|
private leftRunning;
|
|
183
224
|
/**
|
|
184
|
-
*
|
|
185
|
-
*
|
|
225
|
+
* The machine `instance` once it runs: a machine of the warm pool taken while it boots, which
|
|
226
|
+
* Compute Engine says is `RUNNING` some seconds later. As it is when it is not on its way.
|
|
227
|
+
*/
|
|
228
|
+
private booted;
|
|
229
|
+
/**
|
|
230
|
+
* Whether no instance is named after the sandbox `name`, nor holds it under its label, once those
|
|
231
|
+
* going away are gone: a machine stopping may be on its way to deletion, which takes some 50 s
|
|
232
|
+
* after the sandbox's own.
|
|
186
233
|
*/
|
|
187
234
|
private nameIsFree;
|
|
188
|
-
/** Creates the machine
|
|
235
|
+
/** Creates the machine named after the sandbox `name`, and answers its name. */
|
|
236
|
+
private insertSandbox;
|
|
237
|
+
/**
|
|
238
|
+
* Makes the new machine `made` the sandbox `name`'s, and ready: taken from the warm pool as it
|
|
239
|
+
* is, or created under its name and read. Deleted when another machine holds the name too, or
|
|
240
|
+
* anything fails: half-made, it would block a retry under the same name, and cost.
|
|
241
|
+
*/
|
|
242
|
+
private settle;
|
|
243
|
+
/**
|
|
244
|
+
* Whether the machine `instance` is the only one holding the sandbox `name`: two creations of the
|
|
245
|
+
* same name, one on a machine of the warm pool, are not stopped by Compute Engine as two machines
|
|
246
|
+
* of the same name are. The one that finds the other's loses; both may.
|
|
247
|
+
*/
|
|
248
|
+
private soleHolder;
|
|
249
|
+
/** The machines holding the sandbox `name` under its label: taken from the warm pool. */
|
|
250
|
+
private labelled;
|
|
251
|
+
/**
|
|
252
|
+
* Creates the machine `instance`, a standard one when the zone has no Spot capacity left: of the
|
|
253
|
+
* sandbox it is named after, or of the warm pool with its `labels`. Not waited for with `wait`
|
|
254
|
+
* false: a missing capacity then goes unseen, and the machine is not made.
|
|
255
|
+
*/
|
|
189
256
|
private insert;
|
|
190
257
|
/** Starts the stopped machine `instance`, as a standard one when the zone has no Spot capacity. */
|
|
191
258
|
private start;
|
|
192
259
|
/** The run limit of the machines, which Compute Engine enforces by stopping them. */
|
|
193
260
|
private runLimit;
|
|
194
261
|
private mayFallBack;
|
|
195
|
-
/**
|
|
262
|
+
/**
|
|
263
|
+
* The instance of the sandbox `name`: `undefined` when there is none, or one not the service's.
|
|
264
|
+
* The one named after it, or else the one holding it under its label, taken from the warm pool;
|
|
265
|
+
* the one found last tried first.
|
|
266
|
+
*/
|
|
196
267
|
private instanceOf;
|
|
268
|
+
/** The sandbox the machine `instance` holds: its label's, or the one it is named after. */
|
|
269
|
+
private sandboxOf;
|
|
270
|
+
/** Whether `instance` is a sandbox's machine of the service, holding `name`. */
|
|
271
|
+
private holds;
|
|
272
|
+
/**
|
|
273
|
+
* Deletes the machine `instance` of the sandbox `name`, the proxy made to forget it first, and
|
|
274
|
+
* returns once it left `RUNNING`. Only the proxy's registration without `instance`.
|
|
275
|
+
*/
|
|
276
|
+
private removeMachine;
|
|
197
277
|
/**
|
|
198
|
-
* Makes the running machine of `name` ready for commands: registered with the egress
|
|
199
|
-
* under its address, its agent answering and configured.
|
|
278
|
+
* Makes the running machine `instance` of `name` ready for commands: registered with the egress
|
|
279
|
+
* proxy under its address, its agent answering and configured.
|
|
200
280
|
*/
|
|
201
281
|
private ready;
|
|
202
282
|
private waitForAgent;
|
|
@@ -10,6 +10,15 @@ import { AgentClient, agentToken } from './agent-client.js';
|
|
|
10
10
|
const LABEL = 'ai-sdk-sandbox';
|
|
11
11
|
/** The label naming the image a machine or a template was made on. */
|
|
12
12
|
const IMAGE_LABEL = 'ai-sdk-sandbox-image';
|
|
13
|
+
/**
|
|
14
|
+
* The label naming the sandbox a machine holds when its instance is not named after it: a machine
|
|
15
|
+
* of the warm pool, which Compute Engine cannot rename once taken.
|
|
16
|
+
*/
|
|
17
|
+
const NAME_LABEL = 'ai-sdk-sandbox-name';
|
|
18
|
+
/** The label of a machine of the warm pool naming the template image it booted from. */
|
|
19
|
+
const POOL_TEMPLATE_LABEL = 'ai-sdk-sandbox-template';
|
|
20
|
+
/** The label of a machine of the warm pool on its way out: no creation takes it any more. */
|
|
21
|
+
const RETIRED_LABEL = 'ai-sdk-sandbox-retired';
|
|
13
22
|
/** A name of a sandbox or a template: what an instance or image name and a URL path all take. */
|
|
14
23
|
const NAME = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
15
24
|
/** Statuses of a machine that runs, or is about to: what {@link SandboxesOptions.maxRunning} counts. */
|
|
@@ -22,6 +31,11 @@ const TRANSIENT = new Set(['PROVISIONING', 'REPAIRING', 'STAGING', 'STOPPING', '
|
|
|
22
31
|
const ADDRESS_KEPT_MS = 5000;
|
|
23
32
|
/** How a machine runs when it is not Spot. */
|
|
24
33
|
const STANDARD_SCHEDULING = { automaticRestart: true, onHostMaintenance: 'MIGRATE' };
|
|
34
|
+
/**
|
|
35
|
+
* How long the instance found holding a sandbox is remembered, checked at each use: the machine of
|
|
36
|
+
* a sandbox taken from the warm pool is only found by its label otherwise.
|
|
37
|
+
*/
|
|
38
|
+
const MACHINE_KEPT_MS = 10 * 60_000;
|
|
25
39
|
/** How long a resolved base image is trusted: a family moves on when a new image is built. */
|
|
26
40
|
const IMAGE_KEPT_MS = 5 * 60_000;
|
|
27
41
|
/** The image a sandbox gets when its caller names none. */
|
|
@@ -30,6 +44,18 @@ export const DEFAULT_IMAGE = 'default';
|
|
|
30
44
|
const AGENT_RUN_METADATA_KEY = 'ai-sdk-sandbox-agent-run';
|
|
31
45
|
/** The run the machine's agent token was drawn for: none on a machine made before runs were. */
|
|
32
46
|
const runOf = (instance) => instance.metadata?.items?.find(({ key }) => key === AGENT_RUN_METADATA_KEY)?.value;
|
|
47
|
+
/** When the machine `instance` was made, in milliseconds: now when Compute Engine does not say. */
|
|
48
|
+
function createdAt(instance) {
|
|
49
|
+
const created = Date.parse(instance.creationTimestamp ?? '');
|
|
50
|
+
return Number.isNaN(created) ? Date.now() : created;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* How long a machine of the warm pool waits for a creation before the next creation that meets it
|
|
54
|
+
* deletes it, whatever its template: what a template no longer used costs, at most.
|
|
55
|
+
*/
|
|
56
|
+
const POOL_WAIT_MS = 24 * 3_600_000;
|
|
57
|
+
/** Why a creation is refused: the name is taken. */
|
|
58
|
+
const alreadyExists = (name) => new HttpError(409, `A sandbox named "${name}" already exists.`);
|
|
33
59
|
/** Compute Engine's names are 63 characters at most. */
|
|
34
60
|
const MAX_NAME = 63;
|
|
35
61
|
function assertName(name, what, room) {
|
|
@@ -38,14 +64,15 @@ function assertName(name, what, room) {
|
|
|
38
64
|
}
|
|
39
65
|
}
|
|
40
66
|
/**
|
|
41
|
-
* The sandboxes, each a Compute Engine machine of its own, named after it
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* serves any sandbox.
|
|
67
|
+
* The sandboxes, each a Compute Engine machine of its own, named after it, or labelled with its
|
|
68
|
+
* name when taken from the warm pool. The service keeps nothing of them: what a machine is, Compute
|
|
69
|
+
* Engine says; what it may reach and its credentials, the egress proxy holds; its processes, its
|
|
70
|
+
* agent runs. Any instance of the service, on any Cloud Run instance, serves any sandbox.
|
|
45
71
|
*/
|
|
46
72
|
export class Sandboxes {
|
|
47
73
|
options;
|
|
48
74
|
endpoints = new Map();
|
|
75
|
+
machines = new Map();
|
|
49
76
|
bases = new Map();
|
|
50
77
|
nextReconcile = 0;
|
|
51
78
|
constructor(options) {
|
|
@@ -70,40 +97,33 @@ export class Sandboxes {
|
|
|
70
97
|
return new AgentClient(this.remember(name, instance));
|
|
71
98
|
}
|
|
72
99
|
/**
|
|
73
|
-
* Creates the sandbox `name` on the image `image`, from its template `template` when given
|
|
74
|
-
*
|
|
100
|
+
* Creates the sandbox `name` on the image `image`, from its template `template` when given: on a
|
|
101
|
+
* machine of the warm pool booted from it when one runs, a new machine otherwise. Never resumes
|
|
102
|
+
* one.
|
|
75
103
|
*/
|
|
76
104
|
async create(name, { template, image = DEFAULT_IMAGE, ...network }) {
|
|
77
105
|
this.assertSandboxName(name);
|
|
78
106
|
const base = this.imagePathOf(image);
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
throw new HttpError(409, `A sandbox named "${name}" already exists.`);
|
|
82
|
-
}
|
|
107
|
+
if (!(await this.nameIsFree(name)))
|
|
108
|
+
throw alreadyExists(name);
|
|
83
109
|
const sourceImage = template === undefined ? base : await this.templateImage(template, image);
|
|
84
110
|
await this.assertRoom();
|
|
85
111
|
const startedAt = Date.now();
|
|
86
112
|
// The proxy boots meanwhile, when it was stopped: ready() waits for it.
|
|
87
113
|
const proxyUp = this.proxyUp();
|
|
88
114
|
proxyUp.catch(() => undefined);
|
|
115
|
+
const source = { sourceImage, image };
|
|
116
|
+
const pool = template === undefined ? undefined : await this.fromPool(name, source);
|
|
89
117
|
try {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
throw new HttpError(409, `A sandbox named "${name}" already exists.`);
|
|
95
|
-
}
|
|
96
|
-
throw error;
|
|
97
|
-
}
|
|
98
|
-
try {
|
|
99
|
-
const description = await this.ready(name, network);
|
|
100
|
-
this.options.logger.info(`${name} created in ${Date.now() - startedAt} ms`);
|
|
118
|
+
const taken = pool?.taken;
|
|
119
|
+
const description = await this.settle(name, network, taken ?? (await this.insertSandbox(name, source)));
|
|
120
|
+
const from = taken === undefined ? '' : ` on ${taken.name} of the warm pool`;
|
|
121
|
+
this.options.logger.info(`${name} created in ${Date.now() - startedAt} ms${from}`);
|
|
101
122
|
return description;
|
|
102
123
|
}
|
|
103
|
-
|
|
104
|
-
//
|
|
105
|
-
await
|
|
106
|
-
throw error;
|
|
124
|
+
finally {
|
|
125
|
+
// Before answering: Cloud Run throttles the instance's CPU once it has answered.
|
|
126
|
+
await pool?.upkeep;
|
|
107
127
|
}
|
|
108
128
|
}
|
|
109
129
|
/**
|
|
@@ -112,11 +132,11 @@ export class Sandboxes {
|
|
|
112
132
|
*/
|
|
113
133
|
async resume(name, network) {
|
|
114
134
|
this.assertSandboxName(name);
|
|
115
|
-
const instance = this.instanceName(name);
|
|
116
135
|
const deadline = Date.now() + this.options.startTimeoutMs;
|
|
117
136
|
const startedAt = Date.now();
|
|
137
|
+
let current;
|
|
118
138
|
for (;;) {
|
|
119
|
-
|
|
139
|
+
current = await this.instanceOf(name);
|
|
120
140
|
if (current === undefined) {
|
|
121
141
|
throw new HttpError(404, `No sandbox "${name}": it was never created, or it was deleted.`);
|
|
122
142
|
}
|
|
@@ -124,11 +144,11 @@ export class Sandboxes {
|
|
|
124
144
|
break;
|
|
125
145
|
if (current.status === 'TERMINATED') {
|
|
126
146
|
await this.assertRoom();
|
|
127
|
-
await Promise.all([this.start(
|
|
147
|
+
await Promise.all([this.start(current.name), this.proxyUp()]);
|
|
128
148
|
}
|
|
129
149
|
else if (current.status === 'SUSPENDED') {
|
|
130
150
|
await this.assertRoom();
|
|
131
|
-
await Promise.all([this.options.compute.resumeInstance(
|
|
151
|
+
await Promise.all([this.options.compute.resumeInstance(current.name), this.proxyUp()]);
|
|
132
152
|
}
|
|
133
153
|
else if (TRANSIENT.has(current.status) && Date.now() < deadline) {
|
|
134
154
|
await sleep(2000);
|
|
@@ -137,7 +157,7 @@ export class Sandboxes {
|
|
|
137
157
|
throw new HttpError(503, `The machine of "${name}" is ${current.status}: try again later.`);
|
|
138
158
|
}
|
|
139
159
|
}
|
|
140
|
-
const description = await this.ready(name, network);
|
|
160
|
+
const description = await this.ready(name, network, current);
|
|
141
161
|
this.options.logger.info(`${name} resumed in ${Date.now() - startedAt} ms`);
|
|
142
162
|
return description;
|
|
143
163
|
}
|
|
@@ -169,12 +189,7 @@ export class Sandboxes {
|
|
|
169
189
|
*/
|
|
170
190
|
async delete(name) {
|
|
171
191
|
this.assertSandboxName(name);
|
|
172
|
-
await this.
|
|
173
|
-
const instance = this.instanceName(name);
|
|
174
|
-
await this.options.compute.deleteInstance(instance, { wait: false });
|
|
175
|
-
await this.leftRunning(instance);
|
|
176
|
-
this.options.logger.info(`${name} deleting`);
|
|
177
|
-
await this.proxyDownWhenIdle();
|
|
192
|
+
await this.removeMachine(name, (await this.instanceOf(name))?.name);
|
|
178
193
|
}
|
|
179
194
|
/**
|
|
180
195
|
* Makes the proxy forget the sandboxes whose machine no longer runs, and their credentials: a
|
|
@@ -192,12 +207,12 @@ export class Sandboxes {
|
|
|
192
207
|
const machines = await compute.listInstances(LABEL, 'sandbox');
|
|
193
208
|
const holders = new Map(machines
|
|
194
209
|
.filter(({ status }) => RUNNING.has(status))
|
|
195
|
-
.map((
|
|
210
|
+
.map((machine) => [machine.networkInterfaces?.[0]?.networkIP, machine]));
|
|
196
211
|
const stale = registered.filter(({ name, address }) => {
|
|
197
212
|
const holder = holders.get(address);
|
|
198
213
|
if (holder === undefined)
|
|
199
214
|
return true;
|
|
200
|
-
return holder
|
|
215
|
+
return holder.name.startsWith(this.options.instancePrefix) && this.sandboxOf(holder) !== name;
|
|
201
216
|
});
|
|
202
217
|
await Promise.all(stale.map(({ name, serial }) => proxy.remove(name, serial)));
|
|
203
218
|
const names = stale.map(({ name }) => name);
|
|
@@ -283,6 +298,123 @@ export class Sandboxes {
|
|
|
283
298
|
logger.info(`Preparing: starting the egress proxy ${proxyInstance}`);
|
|
284
299
|
await compute.startInstance(proxyInstance, { wait: false });
|
|
285
300
|
}
|
|
301
|
+
/**
|
|
302
|
+
* Takes for the sandbox `name` a machine of the warm pool of its template, `sourceImage`, and sees
|
|
303
|
+
* to the pool: the template's machines missing created, and any machine no longer running (a Spot
|
|
304
|
+
* machine taken back, one at its run limit) or waiting for more than a day deleted, whatever its
|
|
305
|
+
* template. `upkeep` does so without waiting for Compute Engine, never failing: the caller awaits
|
|
306
|
+
* it before answering. A machine of the pool never ran an agent, as fresh as one made from the
|
|
307
|
+
* template; once taken, it never goes back to the pool.
|
|
308
|
+
*/
|
|
309
|
+
async fromPool(name, template) {
|
|
310
|
+
const { compute, logger, warmPool = 0 } = this.options;
|
|
311
|
+
const templateLabel = template.sourceImage.split('/').at(-1) ?? '';
|
|
312
|
+
const machines = (await compute.listInstances(LABEL, 'pool')).filter(({ name: instance, labels }) => labels?.[LABEL] === 'pool' && instance.startsWith(this.poolPrefix));
|
|
313
|
+
const usable = (machine) => machine.labels?.[RETIRED_LABEL] === undefined &&
|
|
314
|
+
RUNNING.has(machine.status) &&
|
|
315
|
+
Date.now() - createdAt(machine) < POOL_WAIT_MS;
|
|
316
|
+
const dropped = machines.filter((machine) => !usable(machine));
|
|
317
|
+
// A running machine first, then the one booting longest: the soonest ready.
|
|
318
|
+
const kept = machines
|
|
319
|
+
.filter((machine) => usable(machine) && machine.labels?.[POOL_TEMPLATE_LABEL] === templateLabel)
|
|
320
|
+
.sort((a, b) => Number(b.status === 'RUNNING') - Number(a.status === 'RUNNING') ||
|
|
321
|
+
createdAt(a) - createdAt(b));
|
|
322
|
+
let taken;
|
|
323
|
+
const tried = new Set();
|
|
324
|
+
try {
|
|
325
|
+
for (const machine of kept) {
|
|
326
|
+
tried.add(machine.name);
|
|
327
|
+
taken = await this.take(machine, name);
|
|
328
|
+
if (taken !== undefined)
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
catch (error) {
|
|
333
|
+
// Left alone rather than grown: a pool whose machines cannot be taken would only cost.
|
|
334
|
+
logger.warn(`The warm pool is left alone: ${String(error)}`);
|
|
335
|
+
return { upkeep: Promise.resolve() };
|
|
336
|
+
}
|
|
337
|
+
const left = kept.filter((machine) => !tried.has(machine.name));
|
|
338
|
+
dropped.push(...left.slice(warmPool));
|
|
339
|
+
// A machine lost to another creation is refilled by that creation: both refilling it, the
|
|
340
|
+
// pool would grow past its size until the next creation.
|
|
341
|
+
const lostRace = taken === undefined && tried.size > 0;
|
|
342
|
+
const missing = lostRace ? 0 : Math.max(0, warmPool - left.length);
|
|
343
|
+
const changes = [
|
|
344
|
+
...dropped.map((machine) => this.retire(machine)),
|
|
345
|
+
...Array.from({ length: missing }, () => this.addToPool(template, templateLabel)),
|
|
346
|
+
];
|
|
347
|
+
const upkeep = Promise.allSettled(changes).then((results) => {
|
|
348
|
+
for (const result of results) {
|
|
349
|
+
if (result.status === 'rejected') {
|
|
350
|
+
logger.warn(`The warm pool could not be kept: ${String(result.reason)}`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
return { taken, upkeep };
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Takes the machine `machine` of the warm pool for the sandbox `name`, by its labels: of two
|
|
358
|
+
* creations taking it at once, Compute Engine lets one change them only. The machine as it is
|
|
359
|
+
* then, running or still booting, `undefined` when another creation took it, or it no longer
|
|
360
|
+
* runs. Fails when Compute Engine refuses the change for another reason.
|
|
361
|
+
*/
|
|
362
|
+
async take(machine, name) {
|
|
363
|
+
const { compute, logger } = this.options;
|
|
364
|
+
try {
|
|
365
|
+
await compute.setLabels(machine.name, { ...machine.labels, [LABEL]: 'sandbox', [NAME_LABEL]: name }, machine.labelFingerprint);
|
|
366
|
+
}
|
|
367
|
+
catch (error) {
|
|
368
|
+
if (error instanceof ComputeError && (error.status === 412 || error.status === 404)) {
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
const taken = await compute.getInstance(machine.name);
|
|
374
|
+
if (taken === undefined || !this.holds(taken, name))
|
|
375
|
+
return undefined;
|
|
376
|
+
if (!RUNNING.has(taken.status)) {
|
|
377
|
+
// Stopped meanwhile, and the sandbox's now: deleted rather than left to block its name.
|
|
378
|
+
await compute.deleteInstance(taken.name, { wait: false });
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
logger.info(`${name} takes ${taken.name} from the warm pool`);
|
|
382
|
+
return taken;
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Deletes the machine `machine` of the warm pool, once labelled retired: a creation that read it
|
|
386
|
+
* before can no longer take it, nor this one take it from under a creation that did.
|
|
387
|
+
*/
|
|
388
|
+
async retire(machine) {
|
|
389
|
+
const { compute, logger } = this.options;
|
|
390
|
+
if (machine.labels?.[RETIRED_LABEL] === undefined) {
|
|
391
|
+
try {
|
|
392
|
+
await compute.setLabels(machine.name, { ...machine.labels, [RETIRED_LABEL]: 'true' }, machine.labelFingerprint);
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
if (error instanceof ComputeError && (error.status === 412 || error.status === 404))
|
|
396
|
+
return;
|
|
397
|
+
throw error;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
logger.info(`Deleting ${machine.name} of the warm pool (${machine.status})`);
|
|
401
|
+
await compute.deleteInstance(machine.name, { wait: false });
|
|
402
|
+
}
|
|
403
|
+
/** Creates a machine of the warm pool booted from `template`, without waiting for it. */
|
|
404
|
+
async addToPool(template, templateLabel) {
|
|
405
|
+
const instance = `${this.poolPrefix}${randomBytes(4).toString('hex')}`;
|
|
406
|
+
this.options.logger.info(`Creating ${instance} for the warm pool, from ${templateLabel}`);
|
|
407
|
+
const labels = {
|
|
408
|
+
[LABEL]: 'pool',
|
|
409
|
+
[IMAGE_LABEL]: template.image,
|
|
410
|
+
[POOL_TEMPLATE_LABEL]: templateLabel,
|
|
411
|
+
};
|
|
412
|
+
await this.insert(instance, { ...template, labels }, { wait: false });
|
|
413
|
+
}
|
|
414
|
+
/** What the machines of the warm pool are named after: the service's prefix, then `pool-`. */
|
|
415
|
+
get poolPrefix() {
|
|
416
|
+
return `${this.options.instancePrefix}pool-`;
|
|
417
|
+
}
|
|
286
418
|
/**
|
|
287
419
|
* Starts the proxy's machine when the service drives it and it is stopped, and waits until the
|
|
288
420
|
* proxy answers. Stopping, it is first let stop: its registrations go with it, and the sandboxes
|
|
@@ -322,10 +454,13 @@ export class Sandboxes {
|
|
|
322
454
|
logger.warn(`The proxy could not be reconciled with the machines: ${String(error)}`);
|
|
323
455
|
});
|
|
324
456
|
}
|
|
325
|
-
/**
|
|
457
|
+
/**
|
|
458
|
+
* Stops the proxy's machine, when the service drives it and does not keep it running, once no
|
|
459
|
+
* sandbox runs: the machines of the warm pool are none, and need no proxy until taken.
|
|
460
|
+
*/
|
|
326
461
|
async proxyDownWhenIdle() {
|
|
327
|
-
const { proxyInstance, compute } = this.options;
|
|
328
|
-
if (proxyInstance === undefined)
|
|
462
|
+
const { proxyInstance, proxyAlwaysOn, compute } = this.options;
|
|
463
|
+
if (proxyInstance === undefined || proxyAlwaysOn === true)
|
|
329
464
|
return;
|
|
330
465
|
const machines = await compute.listInstances(LABEL, 'sandbox');
|
|
331
466
|
if (machines.some(({ status }) => RUNNING.has(status)))
|
|
@@ -396,30 +531,113 @@ export class Sandboxes {
|
|
|
396
531
|
}
|
|
397
532
|
}
|
|
398
533
|
/**
|
|
399
|
-
*
|
|
400
|
-
*
|
|
534
|
+
* The machine `instance` once it runs: a machine of the warm pool taken while it boots, which
|
|
535
|
+
* Compute Engine says is `RUNNING` some seconds later. As it is when it is not on its way.
|
|
401
536
|
*/
|
|
402
|
-
async
|
|
537
|
+
async booted(instance) {
|
|
403
538
|
const deadline = Date.now() + this.options.startTimeoutMs;
|
|
539
|
+
let current = instance;
|
|
540
|
+
while (current !== undefined &&
|
|
541
|
+
current.status !== 'RUNNING' &&
|
|
542
|
+
RUNNING.has(current.status) &&
|
|
543
|
+
Date.now() < deadline) {
|
|
544
|
+
await sleep(1000);
|
|
545
|
+
current = await this.options.compute.getInstance(current.name);
|
|
546
|
+
}
|
|
547
|
+
return current;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Whether no instance is named after the sandbox `name`, nor holds it under its label, once those
|
|
551
|
+
* going away are gone: a machine stopping may be on its way to deletion, which takes some 50 s
|
|
552
|
+
* after the sandbox's own.
|
|
553
|
+
*/
|
|
554
|
+
async nameIsFree(name) {
|
|
555
|
+
const { compute, startTimeoutMs } = this.options;
|
|
556
|
+
const deadline = Date.now() + startTimeoutMs;
|
|
404
557
|
for (;;) {
|
|
405
|
-
const
|
|
406
|
-
|
|
558
|
+
const named = await compute.getInstance(this.instanceName(name));
|
|
559
|
+
const holders = named === undefined ? await this.labelled(name) : [named];
|
|
560
|
+
if (holders.length === 0)
|
|
407
561
|
return true;
|
|
408
|
-
if (
|
|
562
|
+
if (holders.some(({ status }) => status !== 'STOPPING') || Date.now() > deadline) {
|
|
409
563
|
return false;
|
|
564
|
+
}
|
|
410
565
|
await sleep(2000);
|
|
411
566
|
}
|
|
412
567
|
}
|
|
413
|
-
/** Creates the machine
|
|
414
|
-
async
|
|
568
|
+
/** Creates the machine named after the sandbox `name`, and answers its name. */
|
|
569
|
+
async insertSandbox(name, source) {
|
|
570
|
+
const instance = this.instanceName(name);
|
|
571
|
+
try {
|
|
572
|
+
await this.insert(instance, source);
|
|
573
|
+
}
|
|
574
|
+
catch (error) {
|
|
575
|
+
if (error instanceof ComputeError && error.status === 409)
|
|
576
|
+
throw alreadyExists(name);
|
|
577
|
+
throw error;
|
|
578
|
+
}
|
|
579
|
+
return instance;
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Makes the new machine `made` the sandbox `name`'s, and ready: taken from the warm pool as it
|
|
583
|
+
* is, or created under its name and read. Deleted when another machine holds the name too, or
|
|
584
|
+
* anything fails: half-made, it would block a retry under the same name, and cost.
|
|
585
|
+
*/
|
|
586
|
+
async settle(name, network, made) {
|
|
587
|
+
const machine = typeof made === 'string' ? made : made.name;
|
|
588
|
+
if (!(await this.soleHolder(name, machine))) {
|
|
589
|
+
// Another creation of the same name took a machine meanwhile: the name is its.
|
|
590
|
+
await this.options.compute.deleteInstance(machine, { wait: false });
|
|
591
|
+
throw alreadyExists(name);
|
|
592
|
+
}
|
|
415
593
|
try {
|
|
416
|
-
await this.options.compute.
|
|
594
|
+
const instance = typeof made === 'string' ? await this.options.compute.getInstance(made) : made;
|
|
595
|
+
return await this.ready(name, network, await this.booted(instance));
|
|
596
|
+
}
|
|
597
|
+
catch (error) {
|
|
598
|
+
await this.removeMachine(name, machine).catch(() => undefined);
|
|
599
|
+
throw error;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Whether the machine `instance` is the only one holding the sandbox `name`: two creations of the
|
|
604
|
+
* same name, one on a machine of the warm pool, are not stopped by Compute Engine as two machines
|
|
605
|
+
* of the same name are. The one that finds the other's loses; both may.
|
|
606
|
+
*/
|
|
607
|
+
async soleHolder(name, instance) {
|
|
608
|
+
const named = this.instanceName(name);
|
|
609
|
+
const [direct, labelled] = await Promise.all([
|
|
610
|
+
named === instance ? undefined : this.options.compute.getInstance(named),
|
|
611
|
+
this.labelled(name),
|
|
612
|
+
]);
|
|
613
|
+
const holders = [
|
|
614
|
+
...(direct !== undefined && this.holds(direct, name) ? [direct] : []),
|
|
615
|
+
...labelled,
|
|
616
|
+
];
|
|
617
|
+
return holders.every((holder) => holder.name === instance);
|
|
618
|
+
}
|
|
619
|
+
/** The machines holding the sandbox `name` under its label: taken from the warm pool. */
|
|
620
|
+
async labelled(name) {
|
|
621
|
+
const found = await this.options.compute.listInstances(NAME_LABEL, name);
|
|
622
|
+
return found.filter(({ labels }) => labels?.[LABEL] === 'sandbox' && labels[NAME_LABEL] === name);
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Creates the machine `instance`, a standard one when the zone has no Spot capacity left: of the
|
|
626
|
+
* sandbox it is named after, or of the warm pool with its `labels`. Not waited for with `wait`
|
|
627
|
+
* false: a missing capacity then goes unseen, and the machine is not made.
|
|
628
|
+
*/
|
|
629
|
+
async insert(instance, source, { wait = true } = {}) {
|
|
630
|
+
const { compute, logger, zone } = this.options;
|
|
631
|
+
try {
|
|
632
|
+
await compute.insertInstance(this.instanceBody(instance, source), { wait });
|
|
417
633
|
}
|
|
418
634
|
catch (error) {
|
|
419
635
|
if (!this.mayFallBack(error))
|
|
420
636
|
throw error;
|
|
421
|
-
|
|
422
|
-
await
|
|
637
|
+
logger.warn(`No Spot capacity in ${zone}: ${instance} is created as a standard machine.`);
|
|
638
|
+
await compute.insertInstance(this.instanceBody(instance, { ...source, standard: true }), {
|
|
639
|
+
wait,
|
|
640
|
+
});
|
|
423
641
|
}
|
|
424
642
|
}
|
|
425
643
|
/** Starts the stopped machine `instance`, as a standard one when the zone has no Spot capacity. */
|
|
@@ -453,19 +671,67 @@ export class Sandboxes {
|
|
|
453
671
|
const { spot, spotFallback } = this.options.machine;
|
|
454
672
|
return spot && spotFallback !== false && error instanceof ComputeError && error.outOfCapacity;
|
|
455
673
|
}
|
|
456
|
-
/**
|
|
674
|
+
/**
|
|
675
|
+
* The instance of the sandbox `name`: `undefined` when there is none, or one not the service's.
|
|
676
|
+
* The one named after it, or else the one holding it under its label, taken from the warm pool;
|
|
677
|
+
* the one found last tried first.
|
|
678
|
+
*/
|
|
457
679
|
async instanceOf(name) {
|
|
458
|
-
const
|
|
459
|
-
|
|
680
|
+
const { compute } = this.options;
|
|
681
|
+
const named = this.instanceName(name);
|
|
682
|
+
const cached = this.machines.get(name);
|
|
683
|
+
if (cached !== undefined && Date.now() < cached.until && cached.instance !== named) {
|
|
684
|
+
const instance = await compute.getInstance(cached.instance);
|
|
685
|
+
if (instance !== undefined && this.holds(instance, name))
|
|
686
|
+
return instance;
|
|
687
|
+
}
|
|
688
|
+
const instance = await compute.getInstance(named);
|
|
689
|
+
if (instance !== undefined && this.holds(instance, name))
|
|
690
|
+
return instance;
|
|
691
|
+
const [labelled] = await this.labelled(name);
|
|
692
|
+
if (labelled !== undefined) {
|
|
693
|
+
this.machines.set(name, { instance: labelled.name, until: Date.now() + MACHINE_KEPT_MS });
|
|
694
|
+
}
|
|
695
|
+
return labelled;
|
|
696
|
+
}
|
|
697
|
+
/** The sandbox the machine `instance` holds: its label's, or the one it is named after. */
|
|
698
|
+
sandboxOf(instance) {
|
|
699
|
+
const labelled = instance.labels?.[NAME_LABEL];
|
|
700
|
+
if (labelled !== undefined)
|
|
701
|
+
return labelled;
|
|
702
|
+
const { instancePrefix } = this.options;
|
|
703
|
+
return instance.name.startsWith(instancePrefix)
|
|
704
|
+
? instance.name.slice(instancePrefix.length)
|
|
705
|
+
: undefined;
|
|
706
|
+
}
|
|
707
|
+
/** Whether `instance` is a sandbox's machine of the service, holding `name`. */
|
|
708
|
+
holds(instance, name) {
|
|
709
|
+
return instance.labels?.[LABEL] === 'sandbox' && this.sandboxOf(instance) === name;
|
|
460
710
|
}
|
|
461
711
|
/**
|
|
462
|
-
*
|
|
463
|
-
*
|
|
712
|
+
* Deletes the machine `instance` of the sandbox `name`, the proxy made to forget it first, and
|
|
713
|
+
* returns once it left `RUNNING`. Only the proxy's registration without `instance`.
|
|
464
714
|
*/
|
|
465
|
-
async
|
|
466
|
-
|
|
715
|
+
async removeMachine(name, instance) {
|
|
716
|
+
this.machines.delete(name);
|
|
717
|
+
await this.forget(name);
|
|
718
|
+
if (instance !== undefined) {
|
|
719
|
+
await this.options.compute.deleteInstance(instance, { wait: false });
|
|
720
|
+
await this.leftRunning(instance);
|
|
721
|
+
this.options.logger.info(`${name} deleting`);
|
|
722
|
+
}
|
|
723
|
+
await this.proxyDownWhenIdle();
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Makes the running machine `instance` of `name` ready for commands: registered with the egress
|
|
727
|
+
* proxy under its address, its agent answering and configured.
|
|
728
|
+
*/
|
|
729
|
+
async ready(name, network, instance) {
|
|
467
730
|
const address = instance?.networkInterfaces?.[0]?.networkIP;
|
|
468
|
-
if (instance
|
|
731
|
+
if (instance === undefined ||
|
|
732
|
+
!this.holds(instance, name) ||
|
|
733
|
+
instance.status !== 'RUNNING' ||
|
|
734
|
+
address === undefined) {
|
|
469
735
|
throw new HttpError(503, `The machine of "${name}" did not start.`);
|
|
470
736
|
}
|
|
471
737
|
const endpoint = this.remember(name, instance);
|
|
@@ -516,6 +782,9 @@ export class Sandboxes {
|
|
|
516
782
|
const token = agentToken(this.options.agentSecret, instance.name, runOf(instance));
|
|
517
783
|
const endpoint = { host, port, token };
|
|
518
784
|
this.endpoints.set(name, { endpoint, until: Date.now() + ADDRESS_KEPT_MS });
|
|
785
|
+
if (instance.name !== this.instanceName(name)) {
|
|
786
|
+
this.machines.set(name, { instance: instance.name, until: Date.now() + MACHINE_KEPT_MS });
|
|
787
|
+
}
|
|
519
788
|
return endpoint;
|
|
520
789
|
}
|
|
521
790
|
allowedHosts(extra) {
|
|
@@ -567,12 +836,12 @@ export class Sandboxes {
|
|
|
567
836
|
this.bases.set(image, { namespace, until: Date.now() + IMAGE_KEPT_MS });
|
|
568
837
|
return namespace;
|
|
569
838
|
}
|
|
570
|
-
instanceBody(name, { sourceImage, image, standard = false, }) {
|
|
839
|
+
instanceBody(name, { sourceImage, image, labels = { [LABEL]: 'sandbox', [IMAGE_LABEL]: image }, standard = false, }) {
|
|
571
840
|
const { machine, zone } = this.options;
|
|
572
841
|
return {
|
|
573
842
|
name,
|
|
574
843
|
machineType: `zones/${zone}/machineTypes/${machine.machineType}`,
|
|
575
|
-
labels
|
|
844
|
+
labels,
|
|
576
845
|
tags: { items: machine.tags },
|
|
577
846
|
disks: [
|
|
578
847
|
{
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-sdk-sandbox-gce",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
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",
|
|
@@ -59,9 +59,9 @@
|
|
|
59
59
|
"zod": "^4.6.7",
|
|
60
60
|
"@repo/build": "0.0.0",
|
|
61
61
|
"@repo/eslint-config": "0.0.0",
|
|
62
|
-
"@repo/
|
|
62
|
+
"@repo/vitest-config": "0.0.0",
|
|
63
63
|
"@repo/typescript-config": "0.0.0",
|
|
64
|
-
"@repo/
|
|
64
|
+
"@repo/prettier-config": "0.0.0"
|
|
65
65
|
},
|
|
66
66
|
"author": {
|
|
67
67
|
"name": "Fabien Pasquet",
|