@sandboxrouter/sdk 0.14.0 → 0.15.0
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/README.md +7 -5
- package/dist/catalog.d.ts +48 -3
- package/dist/catalog.js +78 -3
- package/dist/cli.js +4 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/leaderboard.js +5 -4
- package/dist/price-index.js +6 -3
- package/dist/providers/beam.js +5 -4
- package/dist/providers/digitalocean.d.ts +16 -0
- package/dist/providers/digitalocean.js +174 -0
- package/dist/providers/google.d.ts +23 -0
- package/dist/providers/google.js +206 -0
- package/dist/providers/morph.js +3 -2
- package/dist/providers/northflank.js +20 -3
- package/dist/providers/shell-files.d.ts +12 -0
- package/dist/providers/shell-files.js +52 -0
- package/dist/published.js +823 -162
- package/dist/recommend.d.ts +11 -4
- package/dist/recommend.js +3 -2
- package/dist/router.js +10 -1
- package/dist/types.d.ts +2 -2
- package/dist/verified.js +4 -0
- package/package.json +5 -1
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { GOOGLE_SHELL_SIZE } from "../catalog.js";
|
|
3
|
+
import { ProviderError } from "../types.js";
|
|
4
|
+
import { DEFAULT_EXEC_TIMEOUT_S, killedByTimeout, optionalImport, timeoutError, wrapCommand } from "../util.js";
|
|
5
|
+
import { ShellFiles } from "./shell-files.js";
|
|
6
|
+
/**
|
|
7
|
+
* Gemini Enterprise Agent Platform shell sandboxes, using the Agent Platform regional REST API.
|
|
8
|
+
* Reuse a default shell template so that creating a sandbox does not leave behind a new template.
|
|
9
|
+
* The optional google-auth-library package supplies Application Default Credentials.
|
|
10
|
+
* https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/sandbox/shell-sandbox-quickstart
|
|
11
|
+
* https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/sandbox/manage-templates
|
|
12
|
+
* Wire reference: https://github.com/googleapis/python-aiplatform/blob/main/agentplatform/_genai/sandboxes.py
|
|
13
|
+
*/
|
|
14
|
+
const ID = "google";
|
|
15
|
+
const ENGINE_NAME = /^projects\/([\w-]+)\/locations\/([\w-]+)\/reasoningEngines\/[\w-]+$/;
|
|
16
|
+
const RESOURCE_NAME = /^(?:[\w-]+\/)*[\w-]+$/;
|
|
17
|
+
const OPERATION_TIMEOUT_MS = 110_000;
|
|
18
|
+
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
19
|
+
function dataChunk(mimeType, text) {
|
|
20
|
+
return { mimeType, data: Buffer.from(text).toString("base64") };
|
|
21
|
+
}
|
|
22
|
+
export class GoogleAgentPlatformProvider {
|
|
23
|
+
engine;
|
|
24
|
+
template;
|
|
25
|
+
token;
|
|
26
|
+
baseUrl;
|
|
27
|
+
id = ID;
|
|
28
|
+
auth;
|
|
29
|
+
constructor(engine = process.env.GOOGLE_SANDBOX_ENGINE, template = process.env.GOOGLE_SANDBOX_TEMPLATE, token = process.env.GOOGLE_SANDBOX_ACCESS_TOKEN, baseUrl) {
|
|
30
|
+
this.engine = engine;
|
|
31
|
+
this.template = template;
|
|
32
|
+
this.token = token;
|
|
33
|
+
this.baseUrl = baseUrl;
|
|
34
|
+
}
|
|
35
|
+
configured() {
|
|
36
|
+
return !!this.engine && !!this.template;
|
|
37
|
+
}
|
|
38
|
+
engineName() {
|
|
39
|
+
if (!this.engine || !ENGINE_NAME.test(this.engine) || !this.template || !RESOURCE_NAME.test(this.template)) {
|
|
40
|
+
throw new ProviderError(ID, "set GOOGLE_SANDBOX_ENGINE to projects/PROJECT/locations/LOCATION/reasoningEngines/ID and GOOGLE_SANDBOX_TEMPLATE to a shell template resource name");
|
|
41
|
+
}
|
|
42
|
+
return this.engine;
|
|
43
|
+
}
|
|
44
|
+
async headers(url) {
|
|
45
|
+
if (this.token)
|
|
46
|
+
return new Headers({ Authorization: `Bearer ${this.token}` });
|
|
47
|
+
this.auth ??= optionalImport("google-auth-library", ID).then(({ GoogleAuth }) => new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] }));
|
|
48
|
+
return new Headers(await (await this.auth).getRequestHeaders(url));
|
|
49
|
+
}
|
|
50
|
+
/** @internal */
|
|
51
|
+
async request(method, resource, body, timeoutMs = 30_000) {
|
|
52
|
+
const engine = this.engineName();
|
|
53
|
+
const [, project, location] = ENGINE_NAME.exec(engine);
|
|
54
|
+
const prefix = `projects/${project}/locations/${location}/`;
|
|
55
|
+
// Limit both user-supplied IDs and returned operation names to this project and region.
|
|
56
|
+
if (!resource.startsWith(prefix) || !RESOURCE_NAME.test(resource.replace(/\/:(?:execute|pause|resume)$/, ""))) {
|
|
57
|
+
throw new ProviderError(ID, "resource is outside the configured Agent Platform location");
|
|
58
|
+
}
|
|
59
|
+
const host = this.baseUrl ?? `https://${location}-aiplatform.googleapis.com`;
|
|
60
|
+
const url = `${host.replace(/\/$/, "")}/v1beta1/${resource}`;
|
|
61
|
+
const headers = await this.headers(url);
|
|
62
|
+
headers.set("Accept", "application/json");
|
|
63
|
+
if (body !== undefined)
|
|
64
|
+
headers.set("Content-Type", "application/json");
|
|
65
|
+
const response = await fetch(url, {
|
|
66
|
+
method,
|
|
67
|
+
headers,
|
|
68
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
69
|
+
redirect: "error",
|
|
70
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
71
|
+
});
|
|
72
|
+
const text = await response.text();
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
let detail = text.slice(0, 280);
|
|
75
|
+
try {
|
|
76
|
+
detail = JSON.parse(text).error?.message ?? detail;
|
|
77
|
+
}
|
|
78
|
+
catch { /* non-JSON error */ }
|
|
79
|
+
throw new ProviderError(ID, `${method}: HTTP ${response.status} ${detail}`, response.status);
|
|
80
|
+
}
|
|
81
|
+
return (text ? JSON.parse(text) : {});
|
|
82
|
+
}
|
|
83
|
+
sandboxName(id) {
|
|
84
|
+
const parent = `${this.engineName()}/sandboxEnvironments/`;
|
|
85
|
+
if (!id.startsWith(parent) || !/^[\w-]+$/.test(id.slice(parent.length))) {
|
|
86
|
+
throw new ProviderError(ID, "invalid sandbox name for the configured Agent Platform instance", 404);
|
|
87
|
+
}
|
|
88
|
+
return id;
|
|
89
|
+
}
|
|
90
|
+
async create(spec) {
|
|
91
|
+
const engine = this.engineName();
|
|
92
|
+
if ((spec.vcpu ?? 0) > GOOGLE_SHELL_SIZE.vcpu || (spec.memoryGb ?? 0) > GOOGLE_SHELL_SIZE.memoryGb) {
|
|
93
|
+
throw new ProviderError(ID, "the standard shell sandbox is 1 vCPU / 2 GiB");
|
|
94
|
+
}
|
|
95
|
+
const { response } = await this.wait(await this.request("POST", `${engine}/sandboxEnvironments`, {
|
|
96
|
+
displayName: `sbr-${randomBytes(8).toString("hex")}`,
|
|
97
|
+
spec: { shellEnvironment: {} },
|
|
98
|
+
sandboxEnvironmentTemplate: this.template,
|
|
99
|
+
ttl: `${Math.max(60, Math.ceil((spec.timeoutMinutes ?? 30) * 60))}s`,
|
|
100
|
+
}));
|
|
101
|
+
if (!response?.name)
|
|
102
|
+
throw new ProviderError(ID, "create operation returned no sandbox name");
|
|
103
|
+
const name = this.sandboxName(response.name);
|
|
104
|
+
try {
|
|
105
|
+
const resource = await this.request("GET", name);
|
|
106
|
+
if (resource.state !== "STATE_RUNNING")
|
|
107
|
+
throw new ProviderError(ID, `sandbox is ${resource.state ?? "not running"}`);
|
|
108
|
+
return new GoogleBox(this, name, spec.env);
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
await this.remove(name).catch(() => { });
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async connect(nativeId) {
|
|
116
|
+
const name = this.sandboxName(nativeId);
|
|
117
|
+
const sandbox = await this.request("GET", name);
|
|
118
|
+
if (sandbox.state === "STATE_PAUSED")
|
|
119
|
+
await this.action(name, "resume");
|
|
120
|
+
else if (sandbox.state !== "STATE_RUNNING")
|
|
121
|
+
throw new ProviderError(ID, `sandbox is ${sandbox.state ?? "not running"}`);
|
|
122
|
+
return new GoogleBox(this, name);
|
|
123
|
+
}
|
|
124
|
+
/** @internal */
|
|
125
|
+
async action(name, action) {
|
|
126
|
+
await this.wait(await this.request("POST", `${this.sandboxName(name)}/:${action}`, {}));
|
|
127
|
+
}
|
|
128
|
+
/** @internal */
|
|
129
|
+
async remove(name) {
|
|
130
|
+
try {
|
|
131
|
+
await this.wait(await this.request("DELETE", this.sandboxName(name)));
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
if (!(err instanceof ProviderError) || err.status !== 404)
|
|
135
|
+
throw err;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
async wait(operation) {
|
|
139
|
+
// Some delete responses have an empty body.
|
|
140
|
+
const until = Date.now() + OPERATION_TIMEOUT_MS;
|
|
141
|
+
while (!operation.done && operation.name && Date.now() < until) {
|
|
142
|
+
await delay(500);
|
|
143
|
+
operation = await this.request("GET", operation.name);
|
|
144
|
+
}
|
|
145
|
+
if (operation.error) {
|
|
146
|
+
const status = { 5: 404, 7: 403, 8: 429, 16: 401 }[operation.error.code ?? 0];
|
|
147
|
+
throw new ProviderError(ID, operation.error.message ?? "sandbox operation failed", status);
|
|
148
|
+
}
|
|
149
|
+
if (operation.name && !operation.done)
|
|
150
|
+
throw new ProviderError(ID, "sandbox operation timed out", 504);
|
|
151
|
+
return operation;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
class GoogleBox {
|
|
155
|
+
provider;
|
|
156
|
+
nativeId;
|
|
157
|
+
env;
|
|
158
|
+
files = new ShellFiles(ID, (command) => this.exec(command));
|
|
159
|
+
constructor(provider, nativeId, env) {
|
|
160
|
+
this.provider = provider;
|
|
161
|
+
this.nativeId = nativeId;
|
|
162
|
+
this.env = env;
|
|
163
|
+
}
|
|
164
|
+
async exec(command, opts = {}) {
|
|
165
|
+
const t0 = Date.now();
|
|
166
|
+
const seconds = Math.max(1, Math.ceil(opts.timeoutSeconds ?? DEFAULT_EXEC_TIMEOUT_S));
|
|
167
|
+
const cmd = wrapCommand(command, { env: { ...this.env, ...opts.env } });
|
|
168
|
+
const inputs = [
|
|
169
|
+
dataChunk("application/x.sandbox-request-uri", "/exec"),
|
|
170
|
+
dataChunk("application/x.sandbox-request-port", "8080"),
|
|
171
|
+
dataChunk("application/json", JSON.stringify({ command: cmd, cwd: opts.cwd, timeout: seconds })),
|
|
172
|
+
];
|
|
173
|
+
let result;
|
|
174
|
+
try {
|
|
175
|
+
result = await this.provider.request("POST", `${this.nativeId}/:execute`, { inputs }, (seconds + 15) * 1000);
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
// Agent Platform wraps confirmed guest command kills in a 400 DEADLINE_EXCEEDED response.
|
|
179
|
+
if (err instanceof ProviderError &&
|
|
180
|
+
err.status === 400 &&
|
|
181
|
+
/\bDEADLINE_EXCEEDED\b/.test(err.message) &&
|
|
182
|
+
/\bcommand exceeded \d+(?:\.\d+)?s and was killed\b/i.test(err.message)) {
|
|
183
|
+
throw timeoutError(ID, seconds);
|
|
184
|
+
}
|
|
185
|
+
throw err;
|
|
186
|
+
}
|
|
187
|
+
const out = result.outputs?.find((chunk) => chunk.data)?.data;
|
|
188
|
+
if (!out)
|
|
189
|
+
throw new ProviderError(ID, "shell sandbox returned no output");
|
|
190
|
+
const { returncode, stdout = "", stderr = "", duration_ms } = JSON.parse(Buffer.from(out, "base64").toString("utf8"));
|
|
191
|
+
if (typeof returncode !== "number" || !Number.isInteger(returncode))
|
|
192
|
+
throw new ProviderError(ID, "shell sandbox returned no exit code");
|
|
193
|
+
const durationMs = duration_ms ?? Date.now() - t0;
|
|
194
|
+
if (killedByTimeout(returncode, durationMs, seconds))
|
|
195
|
+
throw timeoutError(ID, seconds);
|
|
196
|
+
if (stdout)
|
|
197
|
+
opts.onStdout?.(stdout);
|
|
198
|
+
if (stderr)
|
|
199
|
+
opts.onStderr?.(stderr);
|
|
200
|
+
return { stdout, stderr, exitCode: returncode, durationMs };
|
|
201
|
+
}
|
|
202
|
+
readFile(path) { return this.files.readFile(path); }
|
|
203
|
+
writeFile(path, data) { return this.files.writeFile(path, data); }
|
|
204
|
+
pause() { return this.provider.action(this.nativeId, "pause"); }
|
|
205
|
+
kill() { return this.provider.remove(this.nativeId); }
|
|
206
|
+
}
|
package/dist/providers/morph.js
CHANGED
|
@@ -109,8 +109,9 @@ class MorphBox {
|
|
|
109
109
|
// and would leave the process running, so it is set past ours as a fallback.
|
|
110
110
|
const script = guardTimeout(`[ -r ${ENV_FILE} ] && . ${ENV_FILE}; ${wrapCommand(cmd, { cwd: opts.cwd, env: opts.env })}`, seconds);
|
|
111
111
|
try {
|
|
112
|
-
//
|
|
113
|
-
|
|
112
|
+
// Morph joins command array entries into shell text. Pass the complete script so the
|
|
113
|
+
// timeout guard keeps its quoting on both buffered and streaming requests.
|
|
114
|
+
const r = await this.inst.exec(script, {
|
|
114
115
|
timeout: seconds + 15,
|
|
115
116
|
onStdout: opts.onStdout,
|
|
116
117
|
onStderr: opts.onStderr,
|
|
@@ -7,6 +7,7 @@ const DEFAULT_IMAGE = "ubuntu:22.04";
|
|
|
7
7
|
const MIN_EXPIRY_SECONDS = 300;
|
|
8
8
|
const MAX_EXPIRY_SECONDS = 604_800;
|
|
9
9
|
const READY_TIMEOUT_MS = 5 * 60_000;
|
|
10
|
+
const DELETE_TIMEOUT_MS = 60_000;
|
|
10
11
|
/**
|
|
11
12
|
* Northflank sandboxes via `@northflank/js-client`. Auth: NORTHFLANK_API_TOKEN plus
|
|
12
13
|
* NORTHFLANK_PROJECT_ID (the project every sandbox is created in; its region is fixed at
|
|
@@ -155,7 +156,23 @@ class NorthflankBox {
|
|
|
155
156
|
return new Uint8Array(Buffer.from(r.stdout, "base64"));
|
|
156
157
|
}
|
|
157
158
|
async kill() {
|
|
158
|
-
|
|
159
|
+
try {
|
|
160
|
+
await call(() => this.nf.delete.service({ parameters: this.params }));
|
|
161
|
+
// The delete request acknowledges scheduling. The service can still execute commands
|
|
162
|
+
// until teardown completes, so keep polling until Northflank reports it gone.
|
|
163
|
+
const deadline = Date.now() + DELETE_TIMEOUT_MS;
|
|
164
|
+
for (;;) {
|
|
165
|
+
await this.info();
|
|
166
|
+
if (Date.now() >= deadline)
|
|
167
|
+
throw new ProviderError("northflank", `service ${this.nativeId} did not disappear after deletion`, 504);
|
|
168
|
+
await sleep(1000);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
if (err instanceof ProviderError && err.status === 404)
|
|
173
|
+
return;
|
|
174
|
+
throw err;
|
|
175
|
+
}
|
|
159
176
|
}
|
|
160
177
|
/** One exec session: optional stdin, streamed stdout/stderr, exit code. `expired` is thrown when limitMs passes. */
|
|
161
178
|
async run(command, limitMs, opts = {}, stdin, expired = () => timeoutError("northflank", Math.round(limitMs / 1000))) {
|
|
@@ -190,7 +207,6 @@ class NorthflankBox {
|
|
|
190
207
|
let timer;
|
|
191
208
|
const timedOut = new Promise((resolve) => {
|
|
192
209
|
timer = setTimeout(() => resolve("timeout"), limitMs);
|
|
193
|
-
timer.unref();
|
|
194
210
|
});
|
|
195
211
|
try {
|
|
196
212
|
const res = await Promise.race([session.waitForCommandResult(), failed, timedOut]);
|
|
@@ -255,5 +271,6 @@ function plan(vcpu, memoryGb) {
|
|
|
255
271
|
return (fits[0] ?? PLANS[PLANS.length - 1])[0];
|
|
256
272
|
}
|
|
257
273
|
function sleep(ms) {
|
|
258
|
-
|
|
274
|
+
// Keep standalone callers running until the next readiness poll.
|
|
275
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
259
276
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type ExecResult, type ProviderId } from "../types.js";
|
|
2
|
+
type ShellExec = (command: string) => Promise<ExecResult>;
|
|
3
|
+
/** Binary-safe files for shell APIs whose command arguments and output have bounded sizes. */
|
|
4
|
+
export declare class ShellFiles {
|
|
5
|
+
private provider;
|
|
6
|
+
private run;
|
|
7
|
+
constructor(provider: ProviderId, run: ShellExec);
|
|
8
|
+
private checked;
|
|
9
|
+
writeFile(path: string, content: Uint8Array | string): Promise<void>;
|
|
10
|
+
readFile(path: string): Promise<Uint8Array>;
|
|
11
|
+
}
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { ProviderError } from "../types.js";
|
|
3
|
+
import { shq, toBytes } from "../util.js";
|
|
4
|
+
/** Binary-safe files for shell APIs whose command arguments and output have bounded sizes. */
|
|
5
|
+
export class ShellFiles {
|
|
6
|
+
provider;
|
|
7
|
+
run;
|
|
8
|
+
constructor(provider, run) {
|
|
9
|
+
this.provider = provider;
|
|
10
|
+
this.run = run;
|
|
11
|
+
}
|
|
12
|
+
async checked(command) {
|
|
13
|
+
const result = await this.run(command);
|
|
14
|
+
if (result.exitCode !== 0)
|
|
15
|
+
throw new ProviderError(this.provider, result.stderr.trim() || "sandbox file command failed");
|
|
16
|
+
return result.stdout;
|
|
17
|
+
}
|
|
18
|
+
async writeFile(path, content) {
|
|
19
|
+
const destination = shq(path);
|
|
20
|
+
const temporary = shq(`${path}.sbr-${randomUUID()}`);
|
|
21
|
+
const bytes = Buffer.from(toBytes(content));
|
|
22
|
+
const chunkSize = 32 * 1024;
|
|
23
|
+
await this.checked(`mkdir -p -- "$(dirname -- ${destination})" && umask 077 && : > ${temporary}`);
|
|
24
|
+
try {
|
|
25
|
+
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
|
|
26
|
+
const chunk = bytes.subarray(offset, offset + chunkSize).toString("base64");
|
|
27
|
+
await this.checked(`printf '%s' '${chunk}' | base64 -d >> ${temporary}`);
|
|
28
|
+
}
|
|
29
|
+
await this.checked(`mv -f -- ${temporary} ${destination}`);
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
await this.run(`rm -f -- ${temporary}`).catch(() => { });
|
|
33
|
+
throw err;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async readFile(path) {
|
|
37
|
+
const source = shq(path);
|
|
38
|
+
const length = Number((await this.checked(`test -f ${source} && wc -c < ${source}`)).trim());
|
|
39
|
+
if (!Number.isSafeInteger(length) || length < 0)
|
|
40
|
+
throw new ProviderError(this.provider, "invalid sandbox file length");
|
|
41
|
+
const chunks = [];
|
|
42
|
+
const chunkSize = 128 * 1024;
|
|
43
|
+
for (let offset = 0; offset < length; offset += chunkSize) {
|
|
44
|
+
const read = await this.checked(`bash -o pipefail -c ${shq(`dd if=${source} bs=${chunkSize} skip=${offset / chunkSize} count=1 2>/dev/null | base64`)}`);
|
|
45
|
+
const chunk = Buffer.from(read, "base64");
|
|
46
|
+
if (chunk.length !== Math.min(chunkSize, length - offset))
|
|
47
|
+
throw new ProviderError(this.provider, "sandbox file changed or the response was truncated");
|
|
48
|
+
chunks.push(chunk);
|
|
49
|
+
}
|
|
50
|
+
return Buffer.concat(chunks);
|
|
51
|
+
}
|
|
52
|
+
}
|