@finalai/sandbox-router-agent-provider 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +63 -2
- package/dist/modules/computer-use.d.mts +15 -0
- package/dist/modules/computer-use.mjs +149 -0
- package/dist/modules/computer-use.mjs.map +7 -0
- package/dist/modules/environment.d.mts +42 -0
- package/dist/modules/environment.mjs +35 -0
- package/dist/modules/environment.mjs.map +7 -0
- package/dist/modules/index.d.mts +6 -0
- package/dist/modules/index.mjs +40 -0
- package/dist/modules/index.mjs.map +7 -0
- package/dist/modules/network.d.mts +4 -0
- package/dist/modules/network.mjs +23 -0
- package/dist/modules/network.mjs.map +7 -0
- package/dist/modules/provider.d.mts +75 -0
- package/dist/modules/provider.mjs +924 -0
- package/dist/modules/provider.mjs.map +7 -0
- package/dist/modules/session.d.mts +30 -0
- package/dist/modules/session.mjs +327 -0
- package/dist/modules/session.mjs.map +7 -0
- package/package.json +39 -4
|
@@ -0,0 +1,924 @@
|
|
|
1
|
+
import { Capability, FilesAccess, ScreenAccess, ShellAccess } from "@finalai/agent-protocol";
|
|
2
|
+
import { jsonObjectSchema } from "@finalai/agent-provider";
|
|
3
|
+
import {
|
|
4
|
+
defineSandboxProvider,
|
|
5
|
+
materializeSandboxSeeds,
|
|
6
|
+
NetworkPolicy,
|
|
7
|
+
platformProcessEnvironment,
|
|
8
|
+
PortProtocol,
|
|
9
|
+
ProcessInspectionOperation,
|
|
10
|
+
SandboxSnapshotOperation,
|
|
11
|
+
reportPlatformNetworkPolicy,
|
|
12
|
+
SandboxCapability,
|
|
13
|
+
sandboxSeedArtifact,
|
|
14
|
+
sandboxSeedArtifactSchema,
|
|
15
|
+
sandboxSeedFiles,
|
|
16
|
+
sandboxSeedFilesForAttach,
|
|
17
|
+
sandboxSeedIdentity,
|
|
18
|
+
withPlatformEgressHosts,
|
|
19
|
+
writePlatformFiles
|
|
20
|
+
} from "@finalai/agent-provider/sandbox";
|
|
21
|
+
import { bytesToBase64 } from "@finalai/agent-provider/sandbox/bytes";
|
|
22
|
+
import {
|
|
23
|
+
Capability as RouterCapability,
|
|
24
|
+
DesktopState,
|
|
25
|
+
IdleAction,
|
|
26
|
+
ImageBuildState,
|
|
27
|
+
image as routerImage,
|
|
28
|
+
PortAuth,
|
|
29
|
+
ProcessSignal,
|
|
30
|
+
SandboxState
|
|
31
|
+
} from "@finalai/sandbox-router";
|
|
32
|
+
import * as z from "zod";
|
|
33
|
+
import { createComputerUseEndpoint } from "./computer-use.mjs";
|
|
34
|
+
import {
|
|
35
|
+
ROUTED_SANDBOX_PROVIDER,
|
|
36
|
+
routedEnvironmentSchema,
|
|
37
|
+
routedNeedsBuild
|
|
38
|
+
} from "./environment.mjs";
|
|
39
|
+
import { routerNetworkOf } from "./network.mjs";
|
|
40
|
+
import {
|
|
41
|
+
createRouterSession,
|
|
42
|
+
isRouterNotFound,
|
|
43
|
+
isRouterUnsupported,
|
|
44
|
+
readOnlySession,
|
|
45
|
+
resolvePosixPath,
|
|
46
|
+
statOf,
|
|
47
|
+
entryTypeOf
|
|
48
|
+
} from "./session.mjs";
|
|
49
|
+
const WORKSPACE_ROOT = "/workspaces";
|
|
50
|
+
const SANDBOX_LABEL = "agent-sandbox";
|
|
51
|
+
const DEFAULT_IDLE_TIMEOUT_SECONDS = 15 * 60;
|
|
52
|
+
const IDLE_TIMEOUT_MARGIN_SECONDS = 5 * 60;
|
|
53
|
+
const BUILDER_IDLE_TIMEOUT_SECONDS = 2 * 60 * 60;
|
|
54
|
+
const BUILD_ROOT = "/tmp/agent-sandbox-build";
|
|
55
|
+
const BUILD_SCRUB_PATHS = [
|
|
56
|
+
"/tmp/*",
|
|
57
|
+
"$HOME/.bash_history",
|
|
58
|
+
"$HOME/.git-credentials",
|
|
59
|
+
"$HOME/.config/gh/hosts.yml",
|
|
60
|
+
"$HOME/.npmrc",
|
|
61
|
+
"$HOME/.pypirc",
|
|
62
|
+
"$HOME/.cargo/credentials",
|
|
63
|
+
"$HOME/.cargo/credentials.toml",
|
|
64
|
+
"$HOME/.docker/config.json",
|
|
65
|
+
"$HOME/.netrc"
|
|
66
|
+
];
|
|
67
|
+
const ARTIFACT_KEY_VERSION = 1;
|
|
68
|
+
const PORT_TOKEN_TTL_S = 60 * 60;
|
|
69
|
+
const PORT_ENDPOINT_RENEW_MS = 5 * 6e4;
|
|
70
|
+
const RUNNING_POLL_MAX_MS = 5e3;
|
|
71
|
+
const SNAPSHOT_READY_WAIT_MS = 30 * 6e4;
|
|
72
|
+
const DEFAULT_CPU_LIMIT = 2;
|
|
73
|
+
const BUILD_LABEL = "agent-sandbox-build";
|
|
74
|
+
const SNAPSHOT_READ_MAX_BYTES = 1024 * 1024;
|
|
75
|
+
const SNAPSHOT_DIRECTORY_LIMIT = 1e3;
|
|
76
|
+
var RoutedSandboxErrorCode = /* @__PURE__ */ ((RoutedSandboxErrorCode2) => {
|
|
77
|
+
RoutedSandboxErrorCode2["ArtifactUnavailable"] = "artifact_unavailable";
|
|
78
|
+
RoutedSandboxErrorCode2["SandboxGone"] = "sandbox_gone";
|
|
79
|
+
RoutedSandboxErrorCode2["SandboxNotRunning"] = "sandbox_not_running";
|
|
80
|
+
RoutedSandboxErrorCode2["InvalidEnvironment"] = "invalid_environment";
|
|
81
|
+
RoutedSandboxErrorCode2["BuildFailed"] = "build_failed";
|
|
82
|
+
return RoutedSandboxErrorCode2;
|
|
83
|
+
})(RoutedSandboxErrorCode || {});
|
|
84
|
+
const routedSandboxError = (code, message) => Object.assign(new Error(message), { name: "RoutedSandboxError", code });
|
|
85
|
+
const artifactSchema = sandboxSeedArtifactSchema.extend({
|
|
86
|
+
version: z.literal(1),
|
|
87
|
+
key: z.string(),
|
|
88
|
+
image: z.union([z.string(), jsonObjectSchema]).nullable(),
|
|
89
|
+
base: z.discriminatedUnion("kind", [
|
|
90
|
+
z.object({ kind: z.literal("image") }),
|
|
91
|
+
z.object({ kind: z.literal("snapshot"), snapshotId: z.string() })
|
|
92
|
+
])
|
|
93
|
+
});
|
|
94
|
+
const networkPolicySchema = z.object({
|
|
95
|
+
mode: z.nativeEnum(NetworkPolicy),
|
|
96
|
+
allow: z.array(z.string()).optional()
|
|
97
|
+
});
|
|
98
|
+
const stateSchema = z.object({
|
|
99
|
+
version: z.literal(1),
|
|
100
|
+
// The router sandbox; null until the first attach creates it.
|
|
101
|
+
sandboxId: z.string().nullable(),
|
|
102
|
+
// The setup's network policy, enforced from the sandbox's first boot.
|
|
103
|
+
network: networkPolicySchema,
|
|
104
|
+
// Ports the setup's services listen on.
|
|
105
|
+
ports: z.array(z.number().int()).default([])
|
|
106
|
+
});
|
|
107
|
+
const sha256Hex = async (text) => {
|
|
108
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
109
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
110
|
+
};
|
|
111
|
+
const canonicalJson = (value) => {
|
|
112
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
113
|
+
if (value != null && typeof value === "object")
|
|
114
|
+
return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
|
|
115
|
+
return JSON.stringify(value);
|
|
116
|
+
};
|
|
117
|
+
const storedImageOf = (image) => image == null || typeof image === "string" ? image : jsonObjectSchema.parse(JSON.parse(JSON.stringify(image)));
|
|
118
|
+
const errorText = (cause) => cause instanceof Error ? cause.message : String(cause);
|
|
119
|
+
const routedNetworkPolicyOf = (setup) => {
|
|
120
|
+
const network = setup?.network;
|
|
121
|
+
if (network == null) return { mode: NetworkPolicy.AllowAll };
|
|
122
|
+
if ((network.deny ?? []).length > 0)
|
|
123
|
+
throw routedSandboxError(
|
|
124
|
+
"invalid_environment" /* InvalidEnvironment */,
|
|
125
|
+
"A routed sandbox cannot deny individual hosts; list the hosts to allow instead"
|
|
126
|
+
);
|
|
127
|
+
if (network.allow == null) return { mode: NetworkPolicy.AllowAll };
|
|
128
|
+
return network.allow.length === 0 ? { mode: NetworkPolicy.DenyAll } : { mode: NetworkPolicy.Allowlist, allow: [...network.allow] };
|
|
129
|
+
};
|
|
130
|
+
const artifactKeyOf = async (inputs) => {
|
|
131
|
+
if (!routedNeedsBuild(inputs.build)) {
|
|
132
|
+
const hex2 = await sha256Hex(canonicalJson({ v: ARTIFACT_KEY_VERSION, image: inputs.image }));
|
|
133
|
+
return `img-${hex2.slice(0, 16)}`;
|
|
134
|
+
}
|
|
135
|
+
const hex = await sha256Hex(
|
|
136
|
+
canonicalJson({
|
|
137
|
+
v: ARTIFACT_KEY_VERSION,
|
|
138
|
+
image: inputs.image,
|
|
139
|
+
build: { steps: inputs.build?.steps ?? [], verify: inputs.build?.verify ?? [] },
|
|
140
|
+
machine: inputs.machine ?? null
|
|
141
|
+
})
|
|
142
|
+
);
|
|
143
|
+
return `snap-${hex.slice(0, 16)}`;
|
|
144
|
+
};
|
|
145
|
+
const noNetwork = {
|
|
146
|
+
ports: [],
|
|
147
|
+
getPortEndpoint: async () => {
|
|
148
|
+
throw new Error("setup sessions expose no ports");
|
|
149
|
+
},
|
|
150
|
+
stop: async () => void 0,
|
|
151
|
+
destroy: async () => void 0
|
|
152
|
+
};
|
|
153
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
154
|
+
const createRoutedSandboxProvider = (config) => {
|
|
155
|
+
const log = config.log ?? (() => void 0);
|
|
156
|
+
const now = config.now ?? (() => Date.now());
|
|
157
|
+
const sleep = config.sleep ?? defaultSleep;
|
|
158
|
+
const runningWaitMs = config.runningWaitMs ?? 5 * 6e4;
|
|
159
|
+
const routerImageOf = (name) => {
|
|
160
|
+
if (name == null) return null;
|
|
161
|
+
const alias = config.images?.[name];
|
|
162
|
+
if (alias != null)
|
|
163
|
+
return typeof alias === "string" || !("toJSON" in alias) ? alias : alias.toJSON();
|
|
164
|
+
if (name.startsWith("simg_")) return name;
|
|
165
|
+
return routerImage.from(name).toJSON();
|
|
166
|
+
};
|
|
167
|
+
const imageFromArtifact = (stored) => {
|
|
168
|
+
if (stored == null) return void 0;
|
|
169
|
+
return typeof stored === "string" ? stored : routerImage.fromJSON(stored);
|
|
170
|
+
};
|
|
171
|
+
const sizeOf = (machine) => {
|
|
172
|
+
const limit = machine?.vcpu;
|
|
173
|
+
const request = config.cpuRequest;
|
|
174
|
+
return {
|
|
175
|
+
cpu: request == null ? limit : {
|
|
176
|
+
request: Math.min(request, limit ?? DEFAULT_CPU_LIMIT),
|
|
177
|
+
limit: limit ?? DEFAULT_CPU_LIMIT
|
|
178
|
+
},
|
|
179
|
+
memoryMib: machine?.memoryMb,
|
|
180
|
+
diskGib: machine?.diskGb
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
const routed = (options) => ({
|
|
184
|
+
...options,
|
|
185
|
+
routing: config.routing,
|
|
186
|
+
providerOptions: config.providerOptions
|
|
187
|
+
});
|
|
188
|
+
const findSandbox = async (router, id) => {
|
|
189
|
+
try {
|
|
190
|
+
const sandbox = await router.sandboxes.get(id);
|
|
191
|
+
return sandbox.info.state === SandboxState.Deleted ? null : sandbox;
|
|
192
|
+
} catch (cause) {
|
|
193
|
+
if (isRouterNotFound(cause)) return null;
|
|
194
|
+
throw cause;
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
const awaitSandboxRunning = async (sandbox, timeoutMs) => {
|
|
198
|
+
const deadline = now() + timeoutMs;
|
|
199
|
+
let pollMs = config.runningPollMs ?? 250;
|
|
200
|
+
let info = sandbox.info;
|
|
201
|
+
for (; ; ) {
|
|
202
|
+
if (info.state === SandboxState.Running) return;
|
|
203
|
+
if (info.state === SandboxState.Deleted || info.state === SandboxState.Failed)
|
|
204
|
+
throw routedSandboxError(
|
|
205
|
+
"sandbox_gone" /* SandboxGone */,
|
|
206
|
+
`sandbox ${sandbox.id} is ${info.state}${info.nativeError == null ? "" : `: ${info.nativeError}`}`
|
|
207
|
+
);
|
|
208
|
+
const left = deadline - now();
|
|
209
|
+
if (left <= 0)
|
|
210
|
+
throw routedSandboxError(
|
|
211
|
+
"sandbox_not_running" /* SandboxNotRunning */,
|
|
212
|
+
`sandbox ${sandbox.id} was not running within ${Math.round(timeoutMs / 1e3)} s (it is ${info.state})`
|
|
213
|
+
);
|
|
214
|
+
await sleep(Math.min(pollMs, left));
|
|
215
|
+
pollMs = Math.min(pollMs * 2, RUNNING_POLL_MAX_MS);
|
|
216
|
+
info = await sandbox.refresh();
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
const mcpClosers = /* @__PURE__ */ new Map();
|
|
220
|
+
const closeMcp = async (sandboxId) => {
|
|
221
|
+
const results = await Promise.allSettled(
|
|
222
|
+
[...mcpClosers.get(sandboxId) ?? []].map((close) => close())
|
|
223
|
+
);
|
|
224
|
+
for (const result of results) if (result.status === "rejected") throw result.reason;
|
|
225
|
+
};
|
|
226
|
+
const settledFailures = (failures, message) => {
|
|
227
|
+
if (failures.length === 1) throw failures[0];
|
|
228
|
+
if (failures.length > 1) throw new AggregateError(failures, message);
|
|
229
|
+
};
|
|
230
|
+
const desktopState = async (sandbox) => {
|
|
231
|
+
try {
|
|
232
|
+
return (await Promise.race([
|
|
233
|
+
sandbox.desktop.status(),
|
|
234
|
+
new Promise(
|
|
235
|
+
(_, reject) => setTimeout(() => reject(new Error("desktop status timed out")), 2e3)
|
|
236
|
+
)
|
|
237
|
+
])).state;
|
|
238
|
+
} catch {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
const readySnapshot = async (router, snapshotId) => {
|
|
243
|
+
const deadline = now() + SNAPSHOT_READY_WAIT_MS;
|
|
244
|
+
let pollMs = config.runningPollMs ?? 250;
|
|
245
|
+
for (; ; ) {
|
|
246
|
+
let info;
|
|
247
|
+
try {
|
|
248
|
+
info = await router.snapshots.get(snapshotId);
|
|
249
|
+
} catch (cause) {
|
|
250
|
+
if (isRouterNotFound(cause)) return null;
|
|
251
|
+
if (isRouterUnsupported(cause)) return snapshotId;
|
|
252
|
+
throw cause;
|
|
253
|
+
}
|
|
254
|
+
if (info.state === "ready") return snapshotId;
|
|
255
|
+
if (info.state === "failed") {
|
|
256
|
+
await deleteSnapshot(router, snapshotId);
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
const left = deadline - now();
|
|
260
|
+
if (left <= 0)
|
|
261
|
+
throw routedSandboxError(
|
|
262
|
+
"artifact_unavailable" /* ArtifactUnavailable */,
|
|
263
|
+
`sandbox snapshot ${snapshotId} was not ready within ${Math.round(SNAPSHOT_READY_WAIT_MS / 6e4)} min`
|
|
264
|
+
);
|
|
265
|
+
await sleep(Math.min(pollMs, left));
|
|
266
|
+
pollMs = Math.min(pollMs * 2, RUNNING_POLL_MAX_MS);
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
const deleteSnapshot = async (router, snapshotId) => {
|
|
270
|
+
try {
|
|
271
|
+
await router.snapshots.delete(snapshotId);
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (!isRouterNotFound(error))
|
|
274
|
+
log("routed_sandbox.snapshot_delete_failed", { snapshotId, error: errorText(error) });
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
const builtSnapshot = async (router, key) => {
|
|
278
|
+
let listed;
|
|
279
|
+
try {
|
|
280
|
+
listed = await router.snapshots.list({ provider: config.routing?.provider });
|
|
281
|
+
} catch (cause) {
|
|
282
|
+
if (isRouterUnsupported(cause)) return null;
|
|
283
|
+
throw cause;
|
|
284
|
+
}
|
|
285
|
+
const newestFirst = listed.filter((snapshot) => snapshot.name === key || snapshot.name.startsWith(`${key}-`)).sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
|
|
286
|
+
for (const snapshot of newestFirst) {
|
|
287
|
+
if (snapshot.state === "failed") await deleteSnapshot(router, snapshot.id);
|
|
288
|
+
else if (await readySnapshot(router, snapshot.id) != null) return snapshot.id;
|
|
289
|
+
}
|
|
290
|
+
return null;
|
|
291
|
+
};
|
|
292
|
+
const buildHandle = async (args) => {
|
|
293
|
+
const { sandbox } = args;
|
|
294
|
+
const endpoints = /* @__PURE__ */ new Map();
|
|
295
|
+
const portEndpoint = async (port) => {
|
|
296
|
+
const cached = endpoints.get(port);
|
|
297
|
+
if (cached != null && cached.renewAtMs > now()) return cached;
|
|
298
|
+
const access = await sandbox.ports.url(
|
|
299
|
+
port,
|
|
300
|
+
sandbox.info.capabilities.includes(RouterCapability.PortTokens) ? { ttlS: config.portTokenTtlS ?? PORT_TOKEN_TTL_S } : {}
|
|
301
|
+
);
|
|
302
|
+
const headers = {};
|
|
303
|
+
if (access.auth === PortAuth.Bearer && access.token != null)
|
|
304
|
+
headers.authorization = `Bearer ${access.token}`;
|
|
305
|
+
else if (access.auth === PortAuth.Header && access.token != null && access.header != null)
|
|
306
|
+
headers[access.header] = access.token;
|
|
307
|
+
else if (access.auth === PortAuth.Cookie)
|
|
308
|
+
throw new Error(`port ${port} is reached only through a browser session`);
|
|
309
|
+
const expiresAtMs = access.expiresAt == null ? null : Date.parse(access.expiresAt);
|
|
310
|
+
const endpoint = {
|
|
311
|
+
url: access.url,
|
|
312
|
+
headers,
|
|
313
|
+
renewAtMs: expiresAtMs == null ? Number.POSITIVE_INFINITY : expiresAtMs - PORT_ENDPOINT_RENEW_MS
|
|
314
|
+
};
|
|
315
|
+
endpoints.set(port, endpoint);
|
|
316
|
+
return endpoint;
|
|
317
|
+
};
|
|
318
|
+
const session = createRouterSession({
|
|
319
|
+
sandbox,
|
|
320
|
+
description: `routed sandbox ${sandbox.id}`,
|
|
321
|
+
workspaceRoot: WORKSPACE_ROOT,
|
|
322
|
+
baseEnv: args.env,
|
|
323
|
+
network: {
|
|
324
|
+
ports: [...args.ports],
|
|
325
|
+
getPortEndpoint: async ({ port, protocol }) => {
|
|
326
|
+
const endpoint = await portEndpoint(port);
|
|
327
|
+
const url = protocol === PortProtocol.Ws ? endpoint.url.replace(/^http/, "ws") : endpoint.url;
|
|
328
|
+
return { url, headers: { ...endpoint.headers } };
|
|
329
|
+
},
|
|
330
|
+
stop: async () => {
|
|
331
|
+
const failures = [];
|
|
332
|
+
for (const finish of [() => closeMcp(sandbox.id), () => sandbox.stop()])
|
|
333
|
+
try {
|
|
334
|
+
await finish();
|
|
335
|
+
} catch (cause) {
|
|
336
|
+
if (!isRouterNotFound(cause)) failures.push(cause);
|
|
337
|
+
}
|
|
338
|
+
settledFailures(failures, "Sandbox stop or MCP cleanup failed");
|
|
339
|
+
},
|
|
340
|
+
destroy: async () => {
|
|
341
|
+
const failures = [];
|
|
342
|
+
for (const finish of [() => closeMcp(sandbox.id), () => sandbox.delete()])
|
|
343
|
+
try {
|
|
344
|
+
await finish();
|
|
345
|
+
} catch (cause) {
|
|
346
|
+
if (!isRouterNotFound(cause)) failures.push(cause);
|
|
347
|
+
}
|
|
348
|
+
settledFailures(failures, "Sandbox delete or MCP cleanup failed");
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
const desktop = await desktopState(sandbox);
|
|
353
|
+
const desktopUp = desktop === DesktopState.Running || desktop === DesktopState.Starting;
|
|
354
|
+
const computerUse = args.passive || !desktopUp || config.computerUse == null ? null : createComputerUseEndpoint({ sandbox, server: config.computerUse, cwd: WORKSPACE_ROOT });
|
|
355
|
+
const closeComputerUse = async () => {
|
|
356
|
+
try {
|
|
357
|
+
await computerUse?.close();
|
|
358
|
+
} catch (error) {
|
|
359
|
+
log("computer_use.close_failed", { sandboxId: sandbox.id, error: errorText(error) });
|
|
360
|
+
}
|
|
361
|
+
const closers = mcpClosers.get(sandbox.id);
|
|
362
|
+
closers?.delete(closeComputerUse);
|
|
363
|
+
if (closers?.size === 0) mcpClosers.delete(sandbox.id);
|
|
364
|
+
};
|
|
365
|
+
if (computerUse != null) {
|
|
366
|
+
const closers = mcpClosers.get(sandbox.id) ?? /* @__PURE__ */ new Set();
|
|
367
|
+
closers.add(closeComputerUse);
|
|
368
|
+
mcpClosers.set(sandbox.id, closers);
|
|
369
|
+
}
|
|
370
|
+
const capabilities = [SandboxCapability.Files, SandboxCapability.Ports];
|
|
371
|
+
if (desktopUp) capabilities.push(SandboxCapability.Screen);
|
|
372
|
+
if (computerUse != null) capabilities.push(SandboxCapability.ComputerUse);
|
|
373
|
+
if (!args.passive)
|
|
374
|
+
capabilities.push(
|
|
375
|
+
SandboxCapability.Process,
|
|
376
|
+
SandboxCapability.DurableProcesses,
|
|
377
|
+
SandboxCapability.NetworkPolicy
|
|
378
|
+
);
|
|
379
|
+
const full = {
|
|
380
|
+
...session,
|
|
381
|
+
setNetworkPolicy: async (policy) => {
|
|
382
|
+
if (args.passive) throw new Error("this sandbox handle is read-only");
|
|
383
|
+
await sandbox.network.set(routerNetworkOf(withPlatformEgressHosts(args.ctx, policy)));
|
|
384
|
+
},
|
|
385
|
+
capabilities
|
|
386
|
+
};
|
|
387
|
+
if (computerUse != null) full.computerUse = async () => computerUse.endpoint;
|
|
388
|
+
if (desktopUp)
|
|
389
|
+
full.screen = async (options) => {
|
|
390
|
+
const screen = await sandbox.desktop.screen({ viewOnly: options?.viewOnly !== false });
|
|
391
|
+
if (screen.token == null || screen.expiresAt == null)
|
|
392
|
+
throw new Error("the screen session has no token or expiry");
|
|
393
|
+
return { url: screen.url, token: screen.token, expiresAt: screen.expiresAt };
|
|
394
|
+
};
|
|
395
|
+
return {
|
|
396
|
+
sandbox: args.passive ? readOnlySession(full) : full,
|
|
397
|
+
onSandboxStop: closeComputerUse,
|
|
398
|
+
onSandboxDelete: async () => {
|
|
399
|
+
const failures = [];
|
|
400
|
+
for (const finish of [closeComputerUse, () => sandbox.delete()])
|
|
401
|
+
try {
|
|
402
|
+
await finish();
|
|
403
|
+
} catch (cause) {
|
|
404
|
+
if (!isRouterNotFound(cause)) failures.push(cause);
|
|
405
|
+
}
|
|
406
|
+
settledFailures(failures, "Sandbox delete or MCP cleanup failed");
|
|
407
|
+
},
|
|
408
|
+
onRuntimeShutdown: closeComputerUse
|
|
409
|
+
};
|
|
410
|
+
};
|
|
411
|
+
const build = async (args) => {
|
|
412
|
+
const { ctx, router, key } = args;
|
|
413
|
+
const builder = await router.sandboxes.create(
|
|
414
|
+
routed({
|
|
415
|
+
image: args.image ?? void 0,
|
|
416
|
+
...sizeOf(args.machine),
|
|
417
|
+
lifecycle: {
|
|
418
|
+
idle: { afterS: BUILDER_IDLE_TIMEOUT_SECONDS, action: IdleAction.Delete },
|
|
419
|
+
autoResume: false
|
|
420
|
+
},
|
|
421
|
+
labels: { ...config.labels, [BUILD_LABEL]: key },
|
|
422
|
+
region: args.region ?? void 0
|
|
423
|
+
})
|
|
424
|
+
);
|
|
425
|
+
ctx.log?.(`building sandbox snapshot ${key} on ${builder.id}`);
|
|
426
|
+
try {
|
|
427
|
+
const run = (command, timeoutMs) => builder.run(command, { cwd: BUILD_ROOT, timeoutMs, autoResume: false });
|
|
428
|
+
await builder.files.mkdir(BUILD_ROOT, { recursive: true });
|
|
429
|
+
const steps = [
|
|
430
|
+
...args.build.steps.map((step) => ({ step, label: "build step" })),
|
|
431
|
+
...args.build.verify.map((step) => ({ step, label: "verify step" }))
|
|
432
|
+
];
|
|
433
|
+
for (const [index, { step, label }] of steps.entries()) {
|
|
434
|
+
ctx.log?.(`${label} ${index + 1}/${steps.length}`);
|
|
435
|
+
const result = await run(`set -eu
|
|
436
|
+
${step.run}`, step.timeoutMinutes * 6e4);
|
|
437
|
+
if (result.exitCode !== 0)
|
|
438
|
+
throw routedSandboxError(
|
|
439
|
+
"build_failed" /* BuildFailed */,
|
|
440
|
+
`${label} ${index + 1} failed (exit ${result.exitCode ?? result.signal ?? result.reason}): ${result.stderr.trim().slice(-2e3)}`
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
const scrubbed = await builder.run(
|
|
444
|
+
`rm -rf ${BUILD_SCRUB_PATHS.join(" ")} "$HOME/.ssh" "$HOME/.aws" "$HOME/.config/gcloud" "$HOME/.azure"`,
|
|
445
|
+
{ cwd: "/", autoResume: false }
|
|
446
|
+
);
|
|
447
|
+
if (scrubbed.exitCode !== 0)
|
|
448
|
+
throw routedSandboxError(
|
|
449
|
+
"build_failed" /* BuildFailed */,
|
|
450
|
+
`could not clean the builder before its snapshot: ${scrubbed.stderr.trim().slice(-2e3)}`
|
|
451
|
+
);
|
|
452
|
+
const { snapshotId } = await builder.snapshot({ name: key, retain: true });
|
|
453
|
+
if (await readySnapshot(router, snapshotId) == null)
|
|
454
|
+
throw routedSandboxError(
|
|
455
|
+
"build_failed" /* BuildFailed */,
|
|
456
|
+
`sandbox snapshot ${snapshotId} of ${key} failed`
|
|
457
|
+
);
|
|
458
|
+
ctx.log?.(`captured sandbox snapshot ${key} as ${snapshotId}`);
|
|
459
|
+
return { snapshotId };
|
|
460
|
+
} finally {
|
|
461
|
+
try {
|
|
462
|
+
await builder.delete();
|
|
463
|
+
} catch (error) {
|
|
464
|
+
log("routed_sandbox.builder_delete_failed", {
|
|
465
|
+
sandboxId: builder.id,
|
|
466
|
+
error: errorText(error)
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
const environment = (rawOptions) => {
|
|
472
|
+
const parsed = routedEnvironmentSchema.safeParse(rawOptions ?? {});
|
|
473
|
+
if (!parsed.success)
|
|
474
|
+
throw routedSandboxError(
|
|
475
|
+
"invalid_environment" /* InvalidEnvironment */,
|
|
476
|
+
`invalid routed environment: ${parsed.error.message}`
|
|
477
|
+
);
|
|
478
|
+
const options = parsed.data;
|
|
479
|
+
const imageName = options.image ?? config.defaultImage ?? null;
|
|
480
|
+
const image = routerImageOf(imageName);
|
|
481
|
+
const machine = options.machine ?? config.machine;
|
|
482
|
+
const region = options.region ?? config.region ?? null;
|
|
483
|
+
const idleTimeoutFor = (ctx) => options.idleTimeoutSeconds ?? (ctx.lifecycle.parkAfterIdleMs == null ? DEFAULT_IDLE_TIMEOUT_SECONDS : Math.ceil(ctx.lifecycle.parkAfterIdleMs / 1e3) + IDLE_TIMEOUT_MARGIN_SECONDS);
|
|
484
|
+
const seedsFor = (ctx) => sandboxSeedFiles({ files: ctx.files, resources: ctx.resources });
|
|
485
|
+
const keyFor = async (files) => {
|
|
486
|
+
const baseKey = await artifactKeyOf({ image: imageName, build: options.build, machine });
|
|
487
|
+
return Object.keys(files).length === 0 ? baseKey : `${baseKey}-s${await sha256Hex(sandboxSeedIdentity(files))}`;
|
|
488
|
+
};
|
|
489
|
+
const stateOf = (raw) => {
|
|
490
|
+
const state = stateSchema.safeParse(raw);
|
|
491
|
+
if (!state.success)
|
|
492
|
+
throw routedSandboxError(
|
|
493
|
+
"sandbox_gone" /* SandboxGone */,
|
|
494
|
+
"this sandbox was recorded by another sandbox provider; create it again"
|
|
495
|
+
);
|
|
496
|
+
return state.data;
|
|
497
|
+
};
|
|
498
|
+
const runningSandbox = async (ctx, state) => {
|
|
499
|
+
if (state.sandboxId == null) return null;
|
|
500
|
+
const sandbox = await findSandbox(config.router(ctx), state.sandboxId);
|
|
501
|
+
return sandbox?.info.state === SandboxState.Running ? sandbox : null;
|
|
502
|
+
};
|
|
503
|
+
const parkedDisk = async (sandbox) => {
|
|
504
|
+
const { events } = await sandbox.events({ limit: 20 });
|
|
505
|
+
const parked = events.find(
|
|
506
|
+
(event) => event.state === SandboxState.Paused || event.state === SandboxState.Stopped
|
|
507
|
+
);
|
|
508
|
+
return parked == null ? {
|
|
509
|
+
id: `${sandbox.id}:${sandbox.info.generation ?? 0}`,
|
|
510
|
+
capturedAt: sandbox.info.createdAt
|
|
511
|
+
} : { id: `${sandbox.id}:${parked.id}`, capturedAt: parked.at };
|
|
512
|
+
};
|
|
513
|
+
return {
|
|
514
|
+
// Reads a parked sandbox's workspace without waking it (capability `coldFiles`). Null while
|
|
515
|
+
// it runs, before its first attach, or where the provider cannot read a parked disk.
|
|
516
|
+
readSnapshot: async (ctx, rawState, request) => {
|
|
517
|
+
const state = stateOf(rawState);
|
|
518
|
+
const path = resolvePosixPath(WORKSPACE_ROOT, request.path ?? WORKSPACE_ROOT);
|
|
519
|
+
if (path !== WORKSPACE_ROOT && !path.startsWith(`${WORKSPACE_ROOT}/`))
|
|
520
|
+
throw new Error("snapshot path is outside the workspace");
|
|
521
|
+
if (state.sandboxId == null) return null;
|
|
522
|
+
const sandbox = await findSandbox(config.router(ctx), state.sandboxId);
|
|
523
|
+
if (sandbox == null) throw new Error(`sandbox ${state.sandboxId} no longer exists`);
|
|
524
|
+
const { info } = sandbox;
|
|
525
|
+
const parked = info.state === SandboxState.Paused || info.state === SandboxState.Stopped;
|
|
526
|
+
if (!parked || !info.capabilities.includes(RouterCapability.ColdFiles)) {
|
|
527
|
+
if (request.snapshotId != null)
|
|
528
|
+
throw new Error("the sandbox ran since this snapshot; read it again");
|
|
529
|
+
if (info.state === SandboxState.Failed)
|
|
530
|
+
throw new Error(`sandbox ${sandbox.id} failed; its files cannot be read`);
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
const snapshot = await parkedDisk(sandbox);
|
|
534
|
+
if (request.snapshotId != null && request.snapshotId !== snapshot.id)
|
|
535
|
+
throw new Error("the sandbox ran since this snapshot; read it again");
|
|
536
|
+
const base = { root: WORKSPACE_ROOT, path, snapshot };
|
|
537
|
+
const cold = { autoResume: false };
|
|
538
|
+
let response;
|
|
539
|
+
if (request.operation === SandboxSnapshotOperation.Stat) {
|
|
540
|
+
const entry = await sandbox.files.stat(path, cold);
|
|
541
|
+
response = {
|
|
542
|
+
...base,
|
|
543
|
+
result: { operation: request.operation, stat: entry == null ? null : statOf(entry) }
|
|
544
|
+
};
|
|
545
|
+
} else if (request.operation === SandboxSnapshotOperation.ReadDirectory) {
|
|
546
|
+
const page = await sandbox.files.listPage(path, {
|
|
547
|
+
limit: SNAPSHOT_DIRECTORY_LIMIT,
|
|
548
|
+
...cold
|
|
549
|
+
});
|
|
550
|
+
response = {
|
|
551
|
+
...base,
|
|
552
|
+
result: {
|
|
553
|
+
operation: request.operation,
|
|
554
|
+
entries: page.entries.map((entry) => ({
|
|
555
|
+
name: entry.name,
|
|
556
|
+
path: entry.path,
|
|
557
|
+
type: entryTypeOf(entry.kind),
|
|
558
|
+
size: entry.size
|
|
559
|
+
})),
|
|
560
|
+
truncated: page.nextCursor != null
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
} else {
|
|
564
|
+
const entry = await sandbox.files.stat(path, cold);
|
|
565
|
+
if (entry == null) throw new Error(`${path} does not exist in the snapshot`);
|
|
566
|
+
const offset = request.offset ?? 0;
|
|
567
|
+
const bytes = offset >= entry.size ? new Uint8Array() : await sandbox.files.read(path, {
|
|
568
|
+
offset,
|
|
569
|
+
length: Math.min(
|
|
570
|
+
request.length ?? SNAPSHOT_READ_MAX_BYTES,
|
|
571
|
+
SNAPSHOT_READ_MAX_BYTES
|
|
572
|
+
),
|
|
573
|
+
...cold
|
|
574
|
+
});
|
|
575
|
+
response = {
|
|
576
|
+
...base,
|
|
577
|
+
result: {
|
|
578
|
+
operation: request.operation,
|
|
579
|
+
offset,
|
|
580
|
+
size: entry.size,
|
|
581
|
+
contentBase64: bytesToBase64(bytes),
|
|
582
|
+
truncated: offset + bytes.byteLength < entry.size
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
const after = await sandbox.refresh();
|
|
587
|
+
if (after.state !== info.state || (await parkedDisk(sandbox)).id !== snapshot.id)
|
|
588
|
+
throw new Error("the sandbox ran during this snapshot read; read it again");
|
|
589
|
+
return response;
|
|
590
|
+
},
|
|
591
|
+
capabilities: async () => ({
|
|
592
|
+
[Capability.Files]: FilesAccess.Write,
|
|
593
|
+
[Capability.Shell]: ShellAccess.Execute,
|
|
594
|
+
...config.computerUse == null ? {} : { [Capability.ComputerUse]: ScreenAccess.Control }
|
|
595
|
+
}),
|
|
596
|
+
processes: async (ctx, rawState, request) => {
|
|
597
|
+
const sandbox = await runningSandbox(ctx, stateOf(rawState));
|
|
598
|
+
if (request.operation === ProcessInspectionOperation.Available)
|
|
599
|
+
return { available: sandbox != null, canStop: true };
|
|
600
|
+
if (sandbox == null) throw new Error("this sandbox is not running");
|
|
601
|
+
if (request.operation === ProcessInspectionOperation.List) {
|
|
602
|
+
const listed = await sandbox.processes.list({ autoResume: false });
|
|
603
|
+
return {
|
|
604
|
+
status: "available",
|
|
605
|
+
processes: listed.map((entry) => {
|
|
606
|
+
const startedAtMs = entry.startedAt == null ? 0 : Date.parse(entry.startedAt);
|
|
607
|
+
return {
|
|
608
|
+
id: entry.processId,
|
|
609
|
+
bootId: sandbox.id,
|
|
610
|
+
command: entry.command,
|
|
611
|
+
leaderPid: entry.pid,
|
|
612
|
+
state: entry.running ? "running" : "exited",
|
|
613
|
+
keepsAwake: false,
|
|
614
|
+
createdAtMs: startedAtMs,
|
|
615
|
+
updatedAtMs: startedAtMs,
|
|
616
|
+
endedAtMs: null,
|
|
617
|
+
cpuUsec: null,
|
|
618
|
+
memoryBytes: null,
|
|
619
|
+
memoryPeakBytes: null,
|
|
620
|
+
ioReadBytes: null,
|
|
621
|
+
ioWriteBytes: null,
|
|
622
|
+
processCount: null
|
|
623
|
+
};
|
|
624
|
+
}),
|
|
625
|
+
nextCursor: null
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
if (request.operation === ProcessInspectionOperation.Stop) {
|
|
629
|
+
if (request.bootId !== sandbox.id) return { stopped: false };
|
|
630
|
+
try {
|
|
631
|
+
const process = await sandbox.attach(request.processId);
|
|
632
|
+
await process.kill(ProcessSignal.Kill);
|
|
633
|
+
process.detach();
|
|
634
|
+
return { stopped: true };
|
|
635
|
+
} catch (cause) {
|
|
636
|
+
if (isRouterNotFound(cause)) return { stopped: false };
|
|
637
|
+
throw cause;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
throw new Error("process details are not available through the Sandbox Router");
|
|
641
|
+
},
|
|
642
|
+
artifactKey: async (ctx) => keyFor(seedsFor(ctx)),
|
|
643
|
+
// Builds the snapshot an environment with build steps needs, or prepares its image so it
|
|
644
|
+
// is ready ahead of the first attach.
|
|
645
|
+
prepare: async (ctx) => {
|
|
646
|
+
const seedFiles = seedsFor(ctx);
|
|
647
|
+
const key = await keyFor(seedFiles);
|
|
648
|
+
const seedArtifact = await sandboxSeedArtifact(ctx, seedFiles);
|
|
649
|
+
const router = config.router(ctx);
|
|
650
|
+
if (routedNeedsBuild(options.build) && options.build != null) {
|
|
651
|
+
const baseKey = await keyFor({});
|
|
652
|
+
const cached = artifactSchema.safeParse(await ctx.artifacts?.get(baseKey));
|
|
653
|
+
if (cached.success && cached.data.base.kind === "snapshot" && await readySnapshot(router, cached.data.base.snapshotId) != null)
|
|
654
|
+
return { ...cached.data, key, ...seedArtifact };
|
|
655
|
+
const snapshotId = await builtSnapshot(router, baseKey) ?? (await build({
|
|
656
|
+
ctx,
|
|
657
|
+
router,
|
|
658
|
+
image,
|
|
659
|
+
build: options.build,
|
|
660
|
+
machine,
|
|
661
|
+
region,
|
|
662
|
+
key: baseKey
|
|
663
|
+
})).snapshotId;
|
|
664
|
+
const built = {
|
|
665
|
+
version: 1,
|
|
666
|
+
key: baseKey,
|
|
667
|
+
image: storedImageOf(image),
|
|
668
|
+
seedFiles: {},
|
|
669
|
+
base: { kind: "snapshot", snapshotId }
|
|
670
|
+
};
|
|
671
|
+
await ctx.artifacts?.put(baseKey, built);
|
|
672
|
+
return { ...built, key, ...seedArtifact };
|
|
673
|
+
}
|
|
674
|
+
let stored = null;
|
|
675
|
+
if (typeof image === "string") stored = image;
|
|
676
|
+
else if (image != null) {
|
|
677
|
+
const record = await router.images.prepare({
|
|
678
|
+
image,
|
|
679
|
+
providers: config.routing?.provider == null ? void 0 : [config.routing.provider],
|
|
680
|
+
providerOptions: config.providerOptions
|
|
681
|
+
});
|
|
682
|
+
const failed = record.builds.filter((entry) => entry.state === ImageBuildState.Failed);
|
|
683
|
+
if (failed.length > 0 && failed.length === record.builds.length)
|
|
684
|
+
throw routedSandboxError(
|
|
685
|
+
"artifact_unavailable" /* ArtifactUnavailable */,
|
|
686
|
+
`image ${imageName} failed to build: ${failed.map((entry) => `${entry.provider} ${entry.errorCode ?? "failed"}`).join(", ")}`
|
|
687
|
+
);
|
|
688
|
+
stored = record.id.startsWith("simg_") ? record.id : storedImageOf(image);
|
|
689
|
+
}
|
|
690
|
+
ctx.log?.(`sandbox base ${key} is image ${imageName ?? "default"}`);
|
|
691
|
+
return { version: 1, key, image: stored, ...seedArtifact, base: { kind: "image" } };
|
|
692
|
+
},
|
|
693
|
+
// Records the sandbox; the first attach creates it. The setup's network policy is checked
|
|
694
|
+
// now so a policy the router cannot enforce never boots.
|
|
695
|
+
create: async (_ctx, { setup }) => {
|
|
696
|
+
const network = routedNetworkPolicyOf(setup);
|
|
697
|
+
const ports = [
|
|
698
|
+
...new Set(
|
|
699
|
+
(setup?.services ?? []).flatMap(
|
|
700
|
+
(service) => service.port == null ? [] : [service.port]
|
|
701
|
+
)
|
|
702
|
+
)
|
|
703
|
+
];
|
|
704
|
+
return { state: { version: 1, sandboxId: null, network, ports }, region };
|
|
705
|
+
},
|
|
706
|
+
awaitRunning: async (ctx, rawState, awaitOptions) => {
|
|
707
|
+
const state = stateOf(rawState);
|
|
708
|
+
if (state.sandboxId == null)
|
|
709
|
+
throw routedSandboxError(
|
|
710
|
+
"sandbox_not_running" /* SandboxNotRunning */,
|
|
711
|
+
"this sandbox has not started yet"
|
|
712
|
+
);
|
|
713
|
+
const sandbox = await findSandbox(config.router(ctx), state.sandboxId);
|
|
714
|
+
if (sandbox == null)
|
|
715
|
+
throw routedSandboxError(
|
|
716
|
+
"sandbox_gone" /* SandboxGone */,
|
|
717
|
+
`sandbox ${state.sandboxId} is gone`
|
|
718
|
+
);
|
|
719
|
+
await awaitSandboxRunning(sandbox, awaitOptions.timeoutMs);
|
|
720
|
+
},
|
|
721
|
+
attach: async (ctx, { artifact: rawArtifact, state: rawState }) => {
|
|
722
|
+
const state = stateOf(rawState);
|
|
723
|
+
const artifact = artifactSchema.safeParse(rawArtifact);
|
|
724
|
+
if (!artifact.success)
|
|
725
|
+
throw routedSandboxError(
|
|
726
|
+
"artifact_unavailable" /* ArtifactUnavailable */,
|
|
727
|
+
"this sandbox base was prepared by another sandbox provider; prepare it again"
|
|
728
|
+
);
|
|
729
|
+
const base = artifact.data.base;
|
|
730
|
+
if (routedNeedsBuild(options.build) && base.kind !== "snapshot")
|
|
731
|
+
throw routedSandboxError(
|
|
732
|
+
"artifact_unavailable" /* ArtifactUnavailable */,
|
|
733
|
+
`sandbox base ${artifact.data.key} was prepared without its build steps; prepare it again`
|
|
734
|
+
);
|
|
735
|
+
const router = config.router(ctx);
|
|
736
|
+
const env = platformProcessEnvironment(ctx, {});
|
|
737
|
+
const policy = withPlatformEgressHosts(ctx, state.network);
|
|
738
|
+
const network = routerNetworkOf(policy);
|
|
739
|
+
const existing = state.sandboxId == null ? null : await findSandbox(router, state.sandboxId);
|
|
740
|
+
let sandbox;
|
|
741
|
+
let booted;
|
|
742
|
+
if (existing != null) {
|
|
743
|
+
sandbox = existing;
|
|
744
|
+
if (existing.info.state === SandboxState.Failed)
|
|
745
|
+
throw routedSandboxError(
|
|
746
|
+
"sandbox_gone" /* SandboxGone */,
|
|
747
|
+
`sandbox ${existing.id} failed${existing.info.nativeError == null ? "" : `: ${existing.info.nativeError}`}; its disk is kept for recovery through the router`
|
|
748
|
+
);
|
|
749
|
+
if (existing.info.state === SandboxState.Paused)
|
|
750
|
+
booted = (await existing.resume()).coldRestart;
|
|
751
|
+
else if (existing.info.state === SandboxState.Stopped) {
|
|
752
|
+
await existing.start();
|
|
753
|
+
booted = true;
|
|
754
|
+
} else booted = existing.info.state === SandboxState.Creating;
|
|
755
|
+
} else {
|
|
756
|
+
booted = true;
|
|
757
|
+
const source = base.kind === "snapshot" ? base.snapshotId : canonicalJson(artifact.data.image);
|
|
758
|
+
const idempotencyKey = `agent-sandbox-${(await sha256Hex(`${ctx.sandboxId}:${state.sandboxId ?? "first"}:${source}`)).slice(0, 32)}`;
|
|
759
|
+
try {
|
|
760
|
+
sandbox = await router.sandboxes.create(
|
|
761
|
+
routed({
|
|
762
|
+
...base.kind === "snapshot" ? { snapshot: base.snapshotId } : { image: imageFromArtifact(artifact.data.image) },
|
|
763
|
+
...sizeOf(machine),
|
|
764
|
+
network,
|
|
765
|
+
lifecycle: {
|
|
766
|
+
// Idle must keep files: the sandbox is deleted only by its owner.
|
|
767
|
+
idle: { afterS: idleTimeoutFor(ctx), action: IdleAction.Pause },
|
|
768
|
+
autoResume: true,
|
|
769
|
+
...config.maxLifetime === void 0 ? {} : { max: config.maxLifetime }
|
|
770
|
+
},
|
|
771
|
+
labels: { ...config.labels, [SANDBOX_LABEL]: ctx.sandboxId },
|
|
772
|
+
region: region ?? void 0,
|
|
773
|
+
idempotencyKey
|
|
774
|
+
})
|
|
775
|
+
);
|
|
776
|
+
} catch (cause) {
|
|
777
|
+
if (base.kind === "snapshot" && isRouterNotFound(cause))
|
|
778
|
+
throw routedSandboxError(
|
|
779
|
+
"artifact_unavailable" /* ArtifactUnavailable */,
|
|
780
|
+
`sandbox snapshot ${base.snapshotId} is gone; prepare it again`
|
|
781
|
+
);
|
|
782
|
+
throw cause;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const fresh = existing == null;
|
|
786
|
+
log("routed_sandbox.attached", { sandboxId: sandbox.id, fresh, booted });
|
|
787
|
+
try {
|
|
788
|
+
await awaitSandboxRunning(sandbox, runningWaitMs);
|
|
789
|
+
if (!fresh) await sandbox.network.set(network);
|
|
790
|
+
await reportPlatformNetworkPolicy(ctx, policy);
|
|
791
|
+
const setup = createRouterSession({
|
|
792
|
+
sandbox,
|
|
793
|
+
description: `setup of ${sandbox.id}`,
|
|
794
|
+
workspaceRoot: WORKSPACE_ROOT,
|
|
795
|
+
baseEnv: env,
|
|
796
|
+
network: noNetwork
|
|
797
|
+
});
|
|
798
|
+
await writePlatformFiles(ctx, setup);
|
|
799
|
+
if (fresh) {
|
|
800
|
+
const seedMarker = `${WORKSPACE_ROOT}/.final/workspace-prepared/${await sha256Hex(artifact.data.key)}`;
|
|
801
|
+
if (await setup.stat({ path: seedMarker }) == null) {
|
|
802
|
+
await materializeSandboxSeeds({
|
|
803
|
+
sandbox: setup,
|
|
804
|
+
root: WORKSPACE_ROOT,
|
|
805
|
+
files: await sandboxSeedFilesForAttach(ctx, artifact.data)
|
|
806
|
+
});
|
|
807
|
+
await setup.writeTextFile({ path: seedMarker, content: "complete" });
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
const handle = await buildHandle({
|
|
811
|
+
ctx,
|
|
812
|
+
sandbox,
|
|
813
|
+
env,
|
|
814
|
+
ports: state.ports,
|
|
815
|
+
passive: false
|
|
816
|
+
});
|
|
817
|
+
return {
|
|
818
|
+
handle,
|
|
819
|
+
region: sandbox.info.region,
|
|
820
|
+
state: { ...state, sandboxId: sandbox.id },
|
|
821
|
+
fresh,
|
|
822
|
+
booted
|
|
823
|
+
};
|
|
824
|
+
} catch (error) {
|
|
825
|
+
if (fresh) {
|
|
826
|
+
try {
|
|
827
|
+
await sandbox.delete();
|
|
828
|
+
} catch (cleanupError) {
|
|
829
|
+
throw new AggregateError(
|
|
830
|
+
[error, cleanupError],
|
|
831
|
+
`sandbox ${sandbox.id} attach and cleanup failed`
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
throw error;
|
|
836
|
+
}
|
|
837
|
+
},
|
|
838
|
+
attachPassive: async (ctx, { state: rawState }) => {
|
|
839
|
+
const state = stateOf(rawState);
|
|
840
|
+
const sandbox = await runningSandbox(ctx, state);
|
|
841
|
+
if (sandbox == null)
|
|
842
|
+
throw routedSandboxError(
|
|
843
|
+
"sandbox_not_running" /* SandboxNotRunning */,
|
|
844
|
+
"sandbox is not running for passive access"
|
|
845
|
+
);
|
|
846
|
+
return buildHandle({
|
|
847
|
+
ctx,
|
|
848
|
+
sandbox,
|
|
849
|
+
env: platformProcessEnvironment(ctx, {}),
|
|
850
|
+
ports: state.ports,
|
|
851
|
+
passive: true
|
|
852
|
+
});
|
|
853
|
+
},
|
|
854
|
+
// The sandbox pauses on its own idle lifecycle; nothing to do.
|
|
855
|
+
detach: async (_ctx, { state }) => stateOf(state),
|
|
856
|
+
park: async (ctx, { state: rawState }) => {
|
|
857
|
+
const state = stateOf(rawState);
|
|
858
|
+
if (state.sandboxId == null) return state;
|
|
859
|
+
const sandboxId = state.sandboxId;
|
|
860
|
+
const failures = [];
|
|
861
|
+
try {
|
|
862
|
+
await closeMcp(sandboxId);
|
|
863
|
+
} catch (cause) {
|
|
864
|
+
failures.push(cause);
|
|
865
|
+
}
|
|
866
|
+
const atRest = (current) => current == null || current.info.state === SandboxState.Paused || current.info.state === SandboxState.Stopped || current.info.state === SandboxState.Failed;
|
|
867
|
+
try {
|
|
868
|
+
const router = config.router(ctx);
|
|
869
|
+
const current = await findSandbox(router, sandboxId);
|
|
870
|
+
if (atRest(current)) log("routed_sandbox.park_at_rest", { sandboxId });
|
|
871
|
+
else if (current != null) {
|
|
872
|
+
try {
|
|
873
|
+
await current.pause();
|
|
874
|
+
} catch (error) {
|
|
875
|
+
if (!atRest(await findSandbox(router, sandboxId))) throw error;
|
|
876
|
+
log("routed_sandbox.park_at_rest", { sandboxId });
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
} catch (cause) {
|
|
880
|
+
failures.push(cause);
|
|
881
|
+
}
|
|
882
|
+
settledFailures(failures, "Sandbox pause failed");
|
|
883
|
+
return state;
|
|
884
|
+
},
|
|
885
|
+
delete: async (ctx, { state: rawState }) => {
|
|
886
|
+
const state = stateOf(rawState);
|
|
887
|
+
const router = config.router(ctx);
|
|
888
|
+
const failures = [];
|
|
889
|
+
if (state.sandboxId != null)
|
|
890
|
+
try {
|
|
891
|
+
await closeMcp(state.sandboxId);
|
|
892
|
+
} catch (cause) {
|
|
893
|
+
failures.push(cause);
|
|
894
|
+
}
|
|
895
|
+
try {
|
|
896
|
+
const { deleted } = await router.sandboxes.deleteByLabels({
|
|
897
|
+
labels: { [SANDBOX_LABEL]: ctx.sandboxId }
|
|
898
|
+
});
|
|
899
|
+
log("routed_sandbox.delete", { deleted: deleted.join(",") });
|
|
900
|
+
if (state.sandboxId != null && !deleted.includes(state.sandboxId)) {
|
|
901
|
+
const sandbox = await findSandbox(router, state.sandboxId);
|
|
902
|
+
await sandbox?.delete();
|
|
903
|
+
}
|
|
904
|
+
} catch (cause) {
|
|
905
|
+
if (!isRouterNotFound(cause)) failures.push(cause);
|
|
906
|
+
}
|
|
907
|
+
settledFailures(failures, "Sandbox delete or MCP cleanup failed");
|
|
908
|
+
}
|
|
909
|
+
};
|
|
910
|
+
};
|
|
911
|
+
return defineSandboxProvider({
|
|
912
|
+
name: config.name ?? ROUTED_SANDBOX_PROVIDER,
|
|
913
|
+
stateProtocolVersion: 1,
|
|
914
|
+
environment
|
|
915
|
+
});
|
|
916
|
+
};
|
|
917
|
+
export {
|
|
918
|
+
RoutedSandboxErrorCode,
|
|
919
|
+
SANDBOX_LABEL,
|
|
920
|
+
WORKSPACE_ROOT,
|
|
921
|
+
createRoutedSandboxProvider,
|
|
922
|
+
routedNetworkPolicyOf
|
|
923
|
+
};
|
|
924
|
+
//# sourceMappingURL=provider.mjs.map
|