@gresearch/marimohub-compute-armada 0.0.0 → 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/dist/index.js ADDED
@@ -0,0 +1,1571 @@
1
+ // src/config.ts
2
+ import { readFileSync } from "node:fs";
3
+
4
+ // src/auth.ts
5
+ import { readFile } from "node:fs/promises";
6
+ async function authorizationHeader(auth) {
7
+ switch (auth.kind) {
8
+ case "anonymous":
9
+ return;
10
+ case "basic": {
11
+ const credentials = `${auth.username}:${auth.password}`;
12
+ return `Basic ${Buffer.from(credentials, "utf8").toString("base64")}`;
13
+ }
14
+ case "bearer":
15
+ return `Bearer ${auth.token}`;
16
+ case "bearerFile": {
17
+ const token = (await readFile(auth.path, "utf8")).trim();
18
+ if (!token)
19
+ throw new Error(`ARMADA_AUTH_TOKEN_FILE is empty: ${auth.path}`);
20
+ return `Bearer ${token}`;
21
+ }
22
+ default: {
23
+ const unhandled = auth;
24
+ throw new Error(`Unhandled Armada auth kind: ${JSON.stringify(unhandled)}`);
25
+ }
26
+ }
27
+ }
28
+
29
+ // src/ndjson.ts
30
+ async function* readNdjson(body) {
31
+ const decoder = new TextDecoder;
32
+ const reader = body.getReader();
33
+ let buffered = "";
34
+ try {
35
+ for (;; ) {
36
+ const { done, value } = await reader.read();
37
+ if (done)
38
+ break;
39
+ buffered += decoder.decode(value, { stream: true });
40
+ let newline = buffered.indexOf(`
41
+ `);
42
+ while (newline !== -1) {
43
+ const line = buffered.slice(0, newline).trim();
44
+ buffered = buffered.slice(newline + 1);
45
+ if (line !== "")
46
+ yield JSON.parse(line);
47
+ newline = buffered.indexOf(`
48
+ `);
49
+ }
50
+ }
51
+ const last = buffered.trim();
52
+ if (last !== "")
53
+ yield JSON.parse(last);
54
+ } finally {
55
+ await reader.cancel().catch(() => {
56
+ return;
57
+ });
58
+ }
59
+ }
60
+
61
+ // src/podspec.ts
62
+ var KERNEL_CONTAINER = "kernel";
63
+ var AGENT_DIR = "/mh-agent";
64
+ var AGENT_PATH = `${AGENT_DIR}/agent`;
65
+ var AGENT_VOLUME = "mh-agent";
66
+ var AGENT_TOKEN_HASH_ENV = "MH_AGENT_TOKEN_SHA256";
67
+ var DEFAULT_CPU = "1";
68
+ var DEFAULT_MEMORY = "2Gi";
69
+ var TERMINATION_GRACE_SECONDS = 30;
70
+ var AGENT_INSTALL_RESOURCES = { cpu: "100m", memory: "64Mi" };
71
+ var MI = 1024 ** 2;
72
+ var GI = 1024 ** 3;
73
+ function memoryQuantity(bytes) {
74
+ if (bytes % GI === 0)
75
+ return `${String(bytes / GI)}Gi`;
76
+ if (bytes % MI === 0)
77
+ return `${String(bytes / MI)}Mi`;
78
+ return String(Math.ceil(bytes));
79
+ }
80
+ function parseGpu(gpu) {
81
+ const [type = "", count = "1"] = gpu.split(":");
82
+ return { type: type.toUpperCase(), count };
83
+ }
84
+ function quantities(resources) {
85
+ const requested = {
86
+ cpu: resources?.cpu === undefined ? DEFAULT_CPU : String(resources.cpu),
87
+ memory: resources?.memoryBytes === undefined ? DEFAULT_MEMORY : memoryQuantity(resources.memoryBytes)
88
+ };
89
+ if (resources?.gpu !== undefined && resources.gpu !== "") {
90
+ requested["nvidia.com/gpu"] = parseGpu(resources.gpu).count;
91
+ }
92
+ return requested;
93
+ }
94
+ function gpuNodeSelector(config, resources) {
95
+ if (resources?.gpu === undefined || resources.gpu === "")
96
+ return;
97
+ const { type } = parseGpu(resources.gpu);
98
+ const selector = config.gpuNodeSelectors[type];
99
+ if (selector === undefined) {
100
+ throw new Error(`GPU type ${type} has no node selector in ARMADA_GPU_NODE_SELECTORS, so a pod cannot be placed on it`);
101
+ }
102
+ return selector;
103
+ }
104
+ function securityContext(config) {
105
+ const context = {
106
+ ...config.runAsUser === undefined ? {} : { runAsUser: config.runAsUser },
107
+ ...config.runAsGroup === undefined ? {} : { runAsGroup: config.runAsGroup },
108
+ ...config.fsGroup === undefined ? {} : { fsGroup: config.fsGroup }
109
+ };
110
+ return Object.keys(context).length === 0 ? undefined : context;
111
+ }
112
+ function buildPodSpec(config, agent, options) {
113
+ const resources = quantities(options?.resources);
114
+ const nodeSelector = gpuNodeSelector(config, options?.resources);
115
+ const context = securityContext(config);
116
+ return {
117
+ restartPolicy: "Never",
118
+ terminationGracePeriodSeconds: TERMINATION_GRACE_SECONDS,
119
+ activeDeadlineSeconds: config.maxLifetimeSeconds,
120
+ ...config.priorityClassName === undefined ? {} : { priorityClassName: config.priorityClassName },
121
+ ...nodeSelector === undefined ? {} : { nodeSelector },
122
+ ...config.imagePullSecrets.length === 0 ? {} : {
123
+ imagePullSecrets: config.imagePullSecrets.map((name) => ({
124
+ name
125
+ }))
126
+ },
127
+ ...context === undefined ? {} : { securityContext: context },
128
+ volumes: [{ name: AGENT_VOLUME, emptyDir: {} }],
129
+ initContainers: [
130
+ {
131
+ name: "agent-install",
132
+ image: config.agentImage,
133
+ command: ["/agent", "install", AGENT_PATH],
134
+ resources: { requests: AGENT_INSTALL_RESOURCES, limits: AGENT_INSTALL_RESOURCES },
135
+ volumeMounts: [{ name: AGENT_VOLUME, mountPath: AGENT_DIR }]
136
+ }
137
+ ],
138
+ containers: [
139
+ {
140
+ name: KERNEL_CONTAINER,
141
+ image: options?.image ?? config.image,
142
+ command: [AGENT_PATH, "--port", String(config.agentPort)],
143
+ env: [{ name: AGENT_TOKEN_HASH_ENV, value: agent.tokenSha256 }],
144
+ ports: [config.port, config.agentPort, ...config.surfacePorts].map((port) => ({
145
+ containerPort: port,
146
+ protocol: "TCP"
147
+ })),
148
+ resources: { requests: resources, limits: resources },
149
+ volumeMounts: [{ name: AGENT_VOLUME, mountPath: AGENT_DIR }]
150
+ }
151
+ ]
152
+ };
153
+ }
154
+ function exposedPorts(spec) {
155
+ const ports = [];
156
+ for (const container of spec.containers) {
157
+ for (const port of container.ports ?? [])
158
+ ports.push(port.containerPort);
159
+ }
160
+ return ports;
161
+ }
162
+
163
+ // src/armada.ts
164
+ function asObject(value, what) {
165
+ if (typeof value !== "object" || value === null) {
166
+ throw new Error(`Armada returned ${what} that is not a JSON object: ${JSON.stringify(value)}`);
167
+ }
168
+ return value;
169
+ }
170
+ var DEFAULT_RUNNING_TIMEOUT_MS = 5 * 60 * 1000;
171
+ var DEFAULT_INGRESS_TIMEOUT_MS = 60 * 1000;
172
+ var SANDBOX_MARK = "marimohub/sandbox";
173
+ var ACTIVE_JOB_STATES = ["QUEUED", "LEASED", "PENDING", "RUNNING"];
174
+ var LIST_ACTIVE_PAGE = 500;
175
+
176
+ class ArmadaClient {
177
+ config;
178
+ constructor(config) {
179
+ this.config = config;
180
+ }
181
+ async requestHeaders() {
182
+ const authorization = await authorizationHeader(this.config.auth);
183
+ return {
184
+ "content-type": "application/json",
185
+ ...authorization === undefined ? {} : { authorization }
186
+ };
187
+ }
188
+ async submit(sandboxId, podSpec, queue) {
189
+ const ports = exposedPorts(podSpec);
190
+ const expose = this.config.expose;
191
+ const exposure = expose.kind === "ingress" ? {
192
+ ingress: [
193
+ {
194
+ ports,
195
+ tlsEnabled: expose.tls,
196
+ ...expose.certName === undefined ? {} : { certName: expose.certName },
197
+ useClusterIP: true,
198
+ ...Object.keys(expose.annotations).length === 0 ? {} : { annotations: expose.annotations }
199
+ }
200
+ ]
201
+ } : { services: [{ type: "NodePort", ports }] };
202
+ const request = {
203
+ queue,
204
+ jobSetId: sandboxId,
205
+ jobRequestItems: [
206
+ {
207
+ clientId: sandboxId,
208
+ externalJobUri: sandboxId,
209
+ namespace: this.config.namespace,
210
+ podSpec,
211
+ ...Object.keys(this.config.podLabels).length === 0 ? {} : { labels: this.config.podLabels },
212
+ annotations: {
213
+ ...this.config.podAnnotations,
214
+ "armadaproject.io/failFast": "true",
215
+ [SANDBOX_MARK]: this.config.queue
216
+ },
217
+ ...exposure
218
+ }
219
+ ]
220
+ };
221
+ const response = await this.postJson("/v1/job/submit", request);
222
+ const item = response.jobResponseItems?.[0];
223
+ if (item?.error !== undefined && item.error !== "") {
224
+ throw new Error(`Armada rejected the job for sandbox ${sandboxId}: ${item.error}`);
225
+ }
226
+ if (item?.jobId === undefined || item.jobId === "") {
227
+ throw new Error(`Armada returned no job id for sandbox ${sandboxId}`);
228
+ }
229
+ return { jobId: item.jobId, jobSetId: sandboxId, queue };
230
+ }
231
+ async waitForRunning(job, timeoutMs = DEFAULT_RUNNING_TIMEOUT_MS) {
232
+ const request = {
233
+ queue: job.queue,
234
+ id: job.jobSetId,
235
+ watch: true,
236
+ errorIfMissing: false
237
+ };
238
+ const path = `/v1/job-set/${encodeURIComponent(job.queue)}/${encodeURIComponent(job.jobSetId)}`;
239
+ const response = await this.post(path, request, AbortSignal.timeout(timeoutMs));
240
+ if (response.body === null)
241
+ throw new Error(`Armada returned no event stream for ${path}`);
242
+ for await (const value of readNdjson(response.body)) {
243
+ const line = asObject(value, "an event stream line");
244
+ if (line.error !== undefined) {
245
+ throw new Error(`Armada event stream failed: ${line.error.message ?? "unknown error"}`);
246
+ }
247
+ const message = line.result?.message;
248
+ if (message === undefined)
249
+ continue;
250
+ const running = message.running;
251
+ if (running !== undefined && running.jobId === job.jobId) {
252
+ return {
253
+ clusterId: running.clusterId ?? "",
254
+ podName: running.podName ?? "",
255
+ podNamespace: running.podNamespace ?? this.config.namespace,
256
+ ...running.nodeName === undefined ? {} : { nodeName: running.nodeName }
257
+ };
258
+ }
259
+ const failed = message.failed;
260
+ if (failed !== undefined && failed.jobId === job.jobId && failed.retryable !== true) {
261
+ throw new Error(`Armada job ${job.jobId} failed: ${failed.reason ?? "no reason given"}`);
262
+ }
263
+ if (message.cancelled !== undefined && message.cancelled.jobId === job.jobId) {
264
+ throw new Error(`Armada job ${job.jobId} was cancelled before it started`);
265
+ }
266
+ }
267
+ throw new Error(`Armada event stream ended before job ${job.jobId} started`);
268
+ }
269
+ async ingressAddress(job, port, timeoutMs = DEFAULT_INGRESS_TIMEOUT_MS) {
270
+ const request = {
271
+ queue: job.queue,
272
+ id: job.jobSetId,
273
+ watch: true,
274
+ errorIfMissing: false
275
+ };
276
+ const path = `/v1/job-set/${encodeURIComponent(job.queue)}/${encodeURIComponent(job.jobSetId)}`;
277
+ const response = await this.post(path, request, AbortSignal.timeout(timeoutMs));
278
+ if (response.body === null)
279
+ throw new Error(`Armada returned no event stream for ${path}`);
280
+ for await (const value of readNdjson(response.body)) {
281
+ const line = asObject(value, "an event stream line");
282
+ if (line.error !== undefined) {
283
+ throw new Error(`Armada event stream failed: ${line.error.message ?? "unknown error"}`);
284
+ }
285
+ const message = line.result?.message;
286
+ if (message === undefined)
287
+ continue;
288
+ const info = message.ingressInfo;
289
+ if (info !== undefined && info.jobId === job.jobId) {
290
+ const address = info.ingressAddresses?.[String(port)];
291
+ if (address !== undefined && address !== "")
292
+ return address;
293
+ const known = Object.keys(info.ingressAddresses ?? {}).join(", ");
294
+ throw new Error(`Armada reported no address for port ${String(port)} of job ${job.jobId}; it exposes: ${known === "" ? "nothing" : known}`);
295
+ }
296
+ const failed = message.failed;
297
+ if (failed !== undefined && failed.jobId === job.jobId && failed.retryable !== true) {
298
+ throw new Error(`Armada job ${job.jobId} failed: ${failed.reason ?? "no reason given"}`);
299
+ }
300
+ if (message.cancelled !== undefined && message.cancelled.jobId === job.jobId) {
301
+ throw new Error(`Armada job ${job.jobId} was cancelled`);
302
+ }
303
+ }
304
+ throw new Error(`Armada event stream ended before job ${job.jobId} reported an ingress address`);
305
+ }
306
+ async portUrl(job, port) {
307
+ const address = await this.ingressAddress(job, port);
308
+ if (address.includes("://"))
309
+ return address;
310
+ const expose = this.config.expose;
311
+ const scheme = expose.kind === "ingress" && expose.tls ? "https" : "http";
312
+ return `${scheme}://${address}`;
313
+ }
314
+ async cancel(job) {
315
+ const request = {
316
+ queue: job.queue,
317
+ jobSetId: job.jobSetId,
318
+ jobId: job.jobId
319
+ };
320
+ await this.post("/v1/job/cancel", request);
321
+ }
322
+ async cancelSet(jobSetId, queue) {
323
+ const request = { queue, jobSetId };
324
+ await this.post("/v1/job/cancel", request);
325
+ }
326
+ async findQueue(jobSetId) {
327
+ const lookout = this.config.lookoutUrl;
328
+ if (lookout === undefined)
329
+ return;
330
+ const jobs = await this.lookoutJobs(lookout, [{ field: "jobSet", value: jobSetId, match: "exact" }], { field: "submitted", direction: "DESC" }, 0, 1);
331
+ const queue = jobs[0]?.queue;
332
+ return queue === undefined || queue === "" ? undefined : queue;
333
+ }
334
+ async lookoutJobs(lookout, filters, order, skip, take) {
335
+ const request = {
336
+ filters: [
337
+ ...filters,
338
+ { field: SANDBOX_MARK, value: this.config.queue, match: "exact", isAnnotation: true }
339
+ ],
340
+ order,
341
+ skip,
342
+ take
343
+ };
344
+ const response = await this.postJsonTo(lookout, "/api/v1/jobs", request);
345
+ return response.jobs ?? [];
346
+ }
347
+ async listActive() {
348
+ const lookout = this.config.lookoutUrl;
349
+ if (lookout === undefined) {
350
+ throw new Error("listActive needs ARMADA_LOOKOUT_URL, which is not configured");
351
+ }
352
+ const sandboxes = new Map;
353
+ for (let skip = 0;; skip += LIST_ACTIVE_PAGE) {
354
+ const jobs = await this.lookoutJobs(lookout, [{ field: "state", value: ACTIVE_JOB_STATES, match: "anyOf" }], { field: "submitted", direction: "ASC" }, skip, LIST_ACTIVE_PAGE);
355
+ for (const job of jobs) {
356
+ if (job.jobSet === undefined || job.jobSet === "")
357
+ continue;
358
+ if (job.queue === undefined || job.queue === "")
359
+ continue;
360
+ sandboxes.set(job.jobSet, {
361
+ id: job.jobSet,
362
+ queue: job.queue,
363
+ ...job.submitted === undefined ? {} : { createdAt: job.submitted }
364
+ });
365
+ }
366
+ if (jobs.length < LIST_ACTIVE_PAGE)
367
+ return [...sandboxes.values()];
368
+ }
369
+ }
370
+ async post(path, body, signal) {
371
+ return this.postTo(this.config.url, path, body, signal);
372
+ }
373
+ async postTo(base, path, body, signal) {
374
+ const response = await fetch(`${base.replace(/\/$/, "")}${path}`, {
375
+ method: "POST",
376
+ headers: await this.requestHeaders(),
377
+ body: JSON.stringify(body),
378
+ ...signal === undefined ? {} : { signal }
379
+ });
380
+ if (!response.ok) {
381
+ const detail = (await response.text()).trim();
382
+ throw new Error(`Armada ${path} failed (${response.status}): ${detail === "" ? response.statusText : detail}`);
383
+ }
384
+ return response;
385
+ }
386
+ async postJson(path, body) {
387
+ const response = await this.post(path, body);
388
+ return asObject(await response.json(), `a response to ${path}`);
389
+ }
390
+ async postJsonTo(base, path, body) {
391
+ const response = await this.postTo(base, path, body);
392
+ return asObject(await response.json(), `a response to ${path}`);
393
+ }
394
+ }
395
+
396
+ // src/config.ts
397
+ var MIN_TOKEN_SECRET_LENGTH = 32;
398
+ function readTokenSecret(env) {
399
+ const secret = required(env, "ARMADA_AGENT_TOKEN_SECRET");
400
+ if (secret.length < MIN_TOKEN_SECRET_LENGTH) {
401
+ throw new Error(`ARMADA_AGENT_TOKEN_SECRET must be at least ${String(MIN_TOKEN_SECRET_LENGTH)} characters; generate one with \`openssl rand -hex 32\``);
402
+ }
403
+ return secret;
404
+ }
405
+ function required(env, name) {
406
+ const value = env[name];
407
+ if (!value)
408
+ throw new Error(`Missing required env var: ${name}`);
409
+ return value;
410
+ }
411
+ function requiredUrl(env, name) {
412
+ const value = required(env, name);
413
+ const parsed = URL.canParse(value) ? new URL(value) : null;
414
+ if (parsed === null || parsed.protocol !== "http:" && parsed.protocol !== "https:") {
415
+ throw new Error(`${name} must be an http(s) URL, got: ${value}`);
416
+ }
417
+ return value;
418
+ }
419
+ function optionalUrl(env, name) {
420
+ if (env[name] === undefined)
421
+ return;
422
+ return requiredUrl(env, name);
423
+ }
424
+ function optionalPort(env, name, fallback) {
425
+ const raw = env[name];
426
+ if (raw === undefined)
427
+ return fallback;
428
+ const value = Number(raw);
429
+ if (!Number.isInteger(value) || value < 1 || value > 65535) {
430
+ throw new Error(`${name} must be a port number between 1 and 65535, got: ${raw}`);
431
+ }
432
+ return value;
433
+ }
434
+ function optionalSeconds(env, name, fallback, least = 1) {
435
+ const raw = env[name];
436
+ if (raw === undefined)
437
+ return fallback;
438
+ const value = Number(raw);
439
+ if (!Number.isInteger(value) || value < least) {
440
+ throw new Error(`${name} must be a whole number of seconds, got: ${raw}`);
441
+ }
442
+ return value;
443
+ }
444
+ function optionalId(env, name) {
445
+ const raw = env[name];
446
+ if (raw === undefined)
447
+ return;
448
+ const value = raw.trim() === "" ? Number.NaN : Number(raw);
449
+ if (!Number.isInteger(value) || value < 0) {
450
+ throw new Error(`${name} must be a whole number, got: ${raw}`);
451
+ }
452
+ return value;
453
+ }
454
+ function readImagePullSecrets(env) {
455
+ const raw = env.ARMADA_IMAGE_PULL_SECRETS;
456
+ if (raw === undefined)
457
+ return [];
458
+ const names = raw.split(",").map((name) => name.trim()).filter((name) => name !== "");
459
+ if (names.length === 0) {
460
+ throw new Error("ARMADA_IMAGE_PULL_SECRETS must name at least one secret");
461
+ }
462
+ return names;
463
+ }
464
+ function readAuth(env) {
465
+ const username = env.ARMADA_AUTH_USERNAME;
466
+ const password = env.ARMADA_AUTH_PASSWORD;
467
+ const token = env.ARMADA_AUTH_TOKEN;
468
+ const tokenFile = env.ARMADA_AUTH_TOKEN_FILE;
469
+ const configured = [
470
+ username !== undefined || password !== undefined ? "ARMADA_AUTH_USERNAME/PASSWORD" : undefined,
471
+ token !== undefined ? "ARMADA_AUTH_TOKEN" : undefined,
472
+ tokenFile !== undefined ? "ARMADA_AUTH_TOKEN_FILE" : undefined
473
+ ].filter((name) => name !== undefined);
474
+ if (configured.length > 1) {
475
+ throw new Error(`Configure one Armada auth mechanism, found: ${configured.join(", ")}`);
476
+ }
477
+ if (username !== undefined || password !== undefined) {
478
+ if (!username || !password) {
479
+ throw new Error("ARMADA_AUTH_USERNAME and ARMADA_AUTH_PASSWORD must be set together");
480
+ }
481
+ return { kind: "basic", username, password };
482
+ }
483
+ if (token !== undefined) {
484
+ if (!token.trim())
485
+ throw new Error("ARMADA_AUTH_TOKEN is empty");
486
+ return { kind: "bearer", token: token.trim() };
487
+ }
488
+ if (tokenFile !== undefined) {
489
+ let contents;
490
+ try {
491
+ contents = readFileSync(tokenFile, "utf8");
492
+ } catch {
493
+ throw new Error(`ARMADA_AUTH_TOKEN_FILE cannot be read: ${tokenFile}`);
494
+ }
495
+ if (!contents.trim())
496
+ throw new Error(`ARMADA_AUTH_TOKEN_FILE is empty: ${tokenFile}`);
497
+ return { kind: "bearerFile", path: tokenFile };
498
+ }
499
+ return { kind: "anonymous" };
500
+ }
501
+ function readExposure(env) {
502
+ const kind = env.ARMADA_EXPOSE ?? "nodeport";
503
+ const ingressVars = [
504
+ "ARMADA_INGRESS_TLS",
505
+ "ARMADA_INGRESS_CERT_NAME",
506
+ "ARMADA_INGRESS_ANNOTATIONS"
507
+ ].filter((name) => env[name] !== undefined);
508
+ if (kind === "nodeport") {
509
+ if (ingressVars.length > 0) {
510
+ throw new Error(`${ingressVars.join(", ")} only apply with ARMADA_EXPOSE=ingress, and ARMADA_EXPOSE is nodeport`);
511
+ }
512
+ return { kind: "nodeport" };
513
+ }
514
+ if (kind !== "ingress") {
515
+ throw new Error(`ARMADA_EXPOSE must be nodeport or ingress, got: ${kind}`);
516
+ }
517
+ const tlsRaw = env.ARMADA_INGRESS_TLS ?? "true";
518
+ if (tlsRaw !== "true" && tlsRaw !== "false") {
519
+ throw new Error(`ARMADA_INGRESS_TLS must be true or false, got: ${tlsRaw}`);
520
+ }
521
+ const certName = env.ARMADA_INGRESS_CERT_NAME;
522
+ if (certName !== undefined && !certName.trim()) {
523
+ throw new Error("ARMADA_INGRESS_CERT_NAME is empty");
524
+ }
525
+ return {
526
+ kind: "ingress",
527
+ tls: tlsRaw === "true",
528
+ certName,
529
+ annotations: readStringMap(env, "ARMADA_INGRESS_ANNOTATIONS")
530
+ };
531
+ }
532
+ function readStringMap(env, name, allowEmpty = false) {
533
+ const raw = env[name];
534
+ if (raw === undefined)
535
+ return {};
536
+ let parsed;
537
+ try {
538
+ parsed = JSON.parse(raw);
539
+ } catch {
540
+ throw new Error(`${name} must be a JSON object, got: ${raw}`);
541
+ }
542
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
543
+ throw new Error(`${name} must be a JSON object, got: ${raw}`);
544
+ }
545
+ const map = {};
546
+ for (const [key, value] of Object.entries(parsed)) {
547
+ if (typeof value !== "string" || !allowEmpty && !value.trim()) {
548
+ throw new Error(`${name}: ${key} must be a ${allowEmpty ? "" : "non-empty "}string`);
549
+ }
550
+ map[key] = value;
551
+ }
552
+ return map;
553
+ }
554
+ var SURFACES = [
555
+ { id: "vscode", variable: "MARIMOHUB_SURFACE_VSCODE_PORT", defaultPort: 8443 },
556
+ { id: "opencode", variable: "MARIMOHUB_SURFACE_OPENCODE_PORT", defaultPort: 4096 }
557
+ ];
558
+ var PRIMARY_SURFACE = "marimo";
559
+ function readSurfacePorts(env) {
560
+ const enabled = new Set((env.MARIMOHUB_SURFACES ?? PRIMARY_SURFACE).split(",").map((id) => id.trim()).filter((id) => id !== ""));
561
+ for (const id of enabled) {
562
+ if (id !== PRIMARY_SURFACE && !SURFACES.some((surface) => surface.id === id)) {
563
+ throw new Error(`MARIMOHUB_SURFACES names "${id}", a surface this adapter does not know; it knows ${SURFACES.map((surface) => surface.id).join(", ")}`);
564
+ }
565
+ }
566
+ const ports = [];
567
+ for (const surface of SURFACES) {
568
+ if (!enabled.has(surface.id))
569
+ continue;
570
+ ports.push(optionalPort(env, surface.variable, surface.defaultPort));
571
+ }
572
+ return ports;
573
+ }
574
+ function readGpuNodeSelectors(env) {
575
+ const name = "ARMADA_GPU_NODE_SELECTORS";
576
+ const raw = env[name];
577
+ if (raw === undefined)
578
+ return {};
579
+ let parsed;
580
+ try {
581
+ parsed = JSON.parse(raw);
582
+ } catch {
583
+ throw new Error(`${name} must be a JSON object, got: ${raw}`);
584
+ }
585
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
586
+ throw new Error(`${name} must be a JSON object, got: ${raw}`);
587
+ }
588
+ const selectors = {};
589
+ for (const [type, selector] of Object.entries(parsed)) {
590
+ const invalid = new Error(`${name}: ${type} must be an object of node label to value, like {"nvidia.com/gpu.product": "NVIDIA-A100-SXM4-80GB"}`);
591
+ if (typeof selector !== "object" || selector === null || Array.isArray(selector)) {
592
+ throw invalid;
593
+ }
594
+ const labels = {};
595
+ for (const [label, value] of Object.entries(selector)) {
596
+ if (!label.trim() || typeof value !== "string" || !value.trim())
597
+ throw invalid;
598
+ labels[label] = value;
599
+ }
600
+ if (Object.keys(labels).length === 0)
601
+ throw invalid;
602
+ selectors[type.toUpperCase()] = labels;
603
+ }
604
+ if (Object.keys(selectors).length === 0) {
605
+ throw new Error(`${name} must map at least one GPU type`);
606
+ }
607
+ return selectors;
608
+ }
609
+ var K8S_NAME = /^[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/;
610
+ var K8S_PREFIX = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;
611
+ function isQualifiedName(key) {
612
+ const slash = key.lastIndexOf("/");
613
+ if (slash === -1)
614
+ return K8S_NAME.test(key);
615
+ const prefix = key.slice(0, slash);
616
+ return prefix.length <= 253 && K8S_PREFIX.test(prefix) && K8S_NAME.test(key.slice(slash + 1));
617
+ }
618
+ function isReservedKey(key) {
619
+ return key.startsWith("armada_") || key.startsWith("armadaproject.io/") || key === SANDBOX_MARK;
620
+ }
621
+ function readPodMetadata(env, name, kind) {
622
+ const map = readStringMap(env, name, true);
623
+ for (const [key, value] of Object.entries(map)) {
624
+ if (!isQualifiedName(key)) {
625
+ throw new Error(`${name}: ${key} is not a valid ${kind} key, which is an optional DNS subdomain prefix and a slash, then up to 63 letters, digits, '-', '_' or '.'`);
626
+ }
627
+ if (isReservedKey(key)) {
628
+ throw new Error(`${name}: ${key} is reserved for Armada or for the adapter itself`);
629
+ }
630
+ if (kind === "label" && value !== "" && !K8S_NAME.test(value)) {
631
+ throw new Error(`${name}: the value of ${key} is not a valid label value, which is empty or up to 63 letters, digits, '-', '_' or '.', starting and ending with a letter or digit`);
632
+ }
633
+ }
634
+ return map;
635
+ }
636
+ function profileGpuTypes(env) {
637
+ const types = [];
638
+ for (const profile of (env.MARIMOHUB_COMPUTE_PROFILES ?? "").split(",")) {
639
+ const body = profile.slice(profile.indexOf(":") + 1);
640
+ for (const pair of body.split(";")) {
641
+ const [key = "", value = ""] = pair.split("=");
642
+ if (key.trim() !== "gpu")
643
+ continue;
644
+ const type = value.split(":")[0]?.trim().toUpperCase() ?? "";
645
+ if (type !== "")
646
+ types.push(type);
647
+ }
648
+ }
649
+ return types;
650
+ }
651
+ var DEFAULT_MAX_LIFETIME_SECONDS = 24 * 60 * 60;
652
+ var DEFAULT_COMMAND_MAX_SECONDS = 6 * 60 * 60;
653
+ var DEFAULT_IMAGE = "ghcr.io/marimo-team/marimo-sandbox:latest";
654
+ function readConfig(env, compute) {
655
+ const image = env.MARIMOHUB_COMPUTE_IMAGE === undefined ? DEFAULT_IMAGE : env.MARIMOHUB_COMPUTE_IMAGE.split(",")[0]?.trim();
656
+ if (!image)
657
+ throw new Error("MARIMOHUB_COMPUTE_IMAGE must contain at least one image");
658
+ const config = {
659
+ url: requiredUrl(env, "ARMADA_URL"),
660
+ expose: readExposure(env),
661
+ queue: required(env, "ARMADA_QUEUE"),
662
+ queueByUser: readStringMap(env, "ARMADA_QUEUE_BY_USER"),
663
+ queueByProject: readStringMap(env, "ARMADA_QUEUE_BY_PROJECT"),
664
+ namespace: env.ARMADA_NAMESPACE ?? "default",
665
+ priorityClassName: env.ARMADA_PRIORITY_CLASS,
666
+ image,
667
+ sandboxHostname: env.MARIMOHUB_COMPUTE_SANDBOX_HOSTNAME,
668
+ port: optionalPort(env, "ARMADA_KERNEL_PORT", 2718),
669
+ agentImage: required(env, "ARMADA_AGENT_IMAGE"),
670
+ agentPort: optionalPort(env, "ARMADA_AGENT_PORT", 8718),
671
+ agentTokenSecret: readTokenSecret(env),
672
+ imagePullSecrets: readImagePullSecrets(env),
673
+ runAsUser: optionalId(env, "ARMADA_RUN_AS_USER"),
674
+ runAsGroup: optionalId(env, "ARMADA_RUN_AS_GROUP"),
675
+ fsGroup: optionalId(env, "ARMADA_FS_GROUP"),
676
+ surfacePorts: readSurfacePorts(env),
677
+ gpuNodeSelectors: readGpuNodeSelectors(env),
678
+ podLabels: readPodMetadata(env, "ARMADA_POD_LABELS", "label"),
679
+ podAnnotations: readPodMetadata(env, "ARMADA_POD_ANNOTATIONS", "annotation"),
680
+ lookoutUrl: optionalUrl(env, "ARMADA_LOOKOUT_URL"),
681
+ maxLifetimeSeconds: compute?.sessionMaxLifetimeSeconds ?? optionalSeconds(env, "ARMADA_KERNEL_MAX_LIFETIME_SECONDS", DEFAULT_MAX_LIFETIME_SECONDS),
682
+ commandMaxSeconds: optionalSeconds(env, "ARMADA_COMMAND_MAX_SECONDS", DEFAULT_COMMAND_MAX_SECONDS, 0),
683
+ auth: readAuth(env)
684
+ };
685
+ if (config.agentPort === config.port) {
686
+ throw new Error(`ARMADA_AGENT_PORT and ARMADA_KERNEL_PORT are both ${String(config.port)}; the agent and the kernel each need a port`);
687
+ }
688
+ for (const port of config.surfacePorts) {
689
+ if (port === config.agentPort || port === config.port) {
690
+ throw new Error(`A surface port (MARIMOHUB_SURFACE_*_PORT) is ${String(port)}, which is the ${port === config.port ? "kernel" : "agent"} port; each needs its own`);
691
+ }
692
+ }
693
+ if (Object.keys(config.gpuNodeSelectors).length > 0) {
694
+ const unmapped = profileGpuTypes(env).filter((type) => config.gpuNodeSelectors[type] === undefined);
695
+ if (unmapped.length > 0) {
696
+ throw new Error(`MARIMOHUB_COMPUTE_PROFILES names GPU type ${[...new Set(unmapped)].join(", ")}, which ARMADA_GPU_NODE_SELECTORS does not map; it maps ${Object.keys(config.gpuNodeSelectors).join(", ")}`);
697
+ }
698
+ }
699
+ const mappedQueues = [
700
+ ...Object.values(config.queueByUser),
701
+ ...Object.values(config.queueByProject)
702
+ ].filter((queue) => queue !== config.queue);
703
+ if (mappedQueues.length > 0 && config.lookoutUrl === undefined) {
704
+ throw new Error("ARMADA_QUEUE_BY_USER / ARMADA_QUEUE_BY_PROJECT name queues other than ARMADA_QUEUE, which needs ARMADA_LOOKOUT_URL: a sandbox addressed by id alone can only be placed through Lookout");
705
+ }
706
+ return config;
707
+ }
708
+
709
+ // src/channel.ts
710
+ class CommandTimeoutError extends Error {
711
+ }
712
+ var READY_POLL_MS = 250;
713
+ var TIMEOUT_SLACK_MS = 1e4;
714
+ var BOUNDED_READ_SLACK_MS = 1000;
715
+ var MAX_TIMER_MS = 2 ** 31 - 1;
716
+ function asEvent(value) {
717
+ if (typeof value !== "object" || value === null) {
718
+ throw new Error(`the agent sent something that is not an event: ${JSON.stringify(value)}`);
719
+ }
720
+ return value;
721
+ }
722
+ function describe(cause) {
723
+ return cause instanceof Error ? cause.message : String(cause);
724
+ }
725
+ async function refusalOf(response) {
726
+ const text = await response.text();
727
+ let code;
728
+ let message = text.trim();
729
+ try {
730
+ const parsed = JSON.parse(text);
731
+ if (typeof parsed === "object" && parsed !== null) {
732
+ if ("error" in parsed && typeof parsed.error === "string")
733
+ message = parsed.error;
734
+ if ("code" in parsed && typeof parsed.code === "string")
735
+ code = parsed.code;
736
+ }
737
+ } catch {}
738
+ return { code, message: `HTTP ${String(response.status)}: ${message}` };
739
+ }
740
+ async function sleep(ms) {
741
+ await new Promise((resolve) => setTimeout(resolve, ms));
742
+ }
743
+ function pidOf(value) {
744
+ return typeof value === "object" && value !== null && "pid" in value && typeof value.pid === "number" ? value.pid : undefined;
745
+ }
746
+ function statusOf(value) {
747
+ if (typeof value !== "object" || value === null || !("running" in value) || typeof value.running !== "boolean") {
748
+ return;
749
+ }
750
+ const exitCode = "exitCode" in value && typeof value.exitCode === "number" ? value.exitCode : undefined;
751
+ return { running: value.running, ...exitCode === undefined ? {} : { exitCode } };
752
+ }
753
+ function portWaitOf(value) {
754
+ if (typeof value !== "object" || value === null || !("open" in value) || typeof value.open !== "boolean") {
755
+ return;
756
+ }
757
+ const exited = "exited" in value && value.exited === true;
758
+ const exitCode = "exitCode" in value && typeof value.exitCode === "number" ? value.exitCode : undefined;
759
+ return {
760
+ open: value.open,
761
+ ...exited ? { exited } : {},
762
+ ...exitCode === undefined ? {} : { exitCode }
763
+ };
764
+ }
765
+ function isFileType(value) {
766
+ return value === "file" || value === "directory" || value === "symlink" || value === "other";
767
+ }
768
+ function entryOf(value) {
769
+ if (typeof value !== "object" || value === null)
770
+ return;
771
+ if (!("path" in value) || typeof value.path !== "string")
772
+ return;
773
+ const type = "type" in value && typeof value.type === "string" && isFileType(value.type) ? value.type : "other";
774
+ const size = "size" in value && typeof value.size === "number" ? value.size : 0;
775
+ return { path: value.path, type, size };
776
+ }
777
+ function entriesOf(value) {
778
+ if (typeof value !== "object" || value === null || !("entries" in value) || !Array.isArray(value.entries)) {
779
+ return;
780
+ }
781
+ const entries = [];
782
+ for (const raw of value.entries) {
783
+ const entry = entryOf(raw);
784
+ if (entry === undefined)
785
+ return;
786
+ entries.push(entry);
787
+ }
788
+ return entries;
789
+ }
790
+
791
+ class AgentChannel {
792
+ endpoint;
793
+ base;
794
+ where;
795
+ constructor(endpoint) {
796
+ this.endpoint = endpoint;
797
+ this.base = endpoint.url;
798
+ this.where = `${endpoint.pod.podNamespace}/${endpoint.pod.podName}`;
799
+ }
800
+ async ready(timeoutMs) {
801
+ const deadline = Date.now() + timeoutMs;
802
+ let last = "no answer";
803
+ for (;; ) {
804
+ try {
805
+ const response = await fetch(`${this.base}/healthz`, {
806
+ signal: AbortSignal.timeout(READY_POLL_MS * 4)
807
+ });
808
+ if (response.ok)
809
+ return;
810
+ last = `HTTP ${String(response.status)}`;
811
+ } catch (cause) {
812
+ last = describe(cause);
813
+ }
814
+ if (Date.now() >= deadline)
815
+ break;
816
+ await sleep(READY_POLL_MS);
817
+ }
818
+ throw new Error(`The agent in ${this.where} at ${this.base} did not answer within ${String(timeoutMs)}ms: ${last}`);
819
+ }
820
+ async run(command, options = {}) {
821
+ const controller = new AbortController;
822
+ const guard = options.timeoutMs === undefined ? undefined : setTimeout(() => controller.abort(), options.timeoutMs + TIMEOUT_SLACK_MS);
823
+ const out = [];
824
+ const err = [];
825
+ let exit;
826
+ try {
827
+ const response = await this.exec({
828
+ cmd: [...command],
829
+ ...options.stdin === undefined ? {} : { stdin: Buffer.from(options.stdin).toString("base64") },
830
+ ...options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }
831
+ }, controller.signal);
832
+ for await (const value of readNdjson(bodyOf(response))) {
833
+ const event = asEvent(value);
834
+ if (event.stdout !== undefined)
835
+ out.push(Buffer.from(event.stdout, "base64"));
836
+ if (event.stderr !== undefined)
837
+ err.push(Buffer.from(event.stderr, "base64"));
838
+ if (event.error !== undefined)
839
+ throw new Error(event.error);
840
+ if (event.exit !== undefined)
841
+ exit = event;
842
+ }
843
+ } catch (cause) {
844
+ throw this.failure(runWhat(command), cause);
845
+ } finally {
846
+ clearTimeout(guard);
847
+ }
848
+ if (exit?.exit === undefined) {
849
+ throw this.failure(runWhat(command), new Error("the response ended without an exit status"));
850
+ }
851
+ if (exit.timedOut === true) {
852
+ throw new CommandTimeoutError(`Command timed out after ${String(options.timeoutMs)}ms in ${this.where}: ${programOf(command)}`);
853
+ }
854
+ return {
855
+ stdout: Buffer.concat(out).toString("utf8"),
856
+ stderr: Buffer.concat(err).toString("utf8"),
857
+ exitCode: exit.exit
858
+ };
859
+ }
860
+ async stream(command, options = {}) {
861
+ const controller = new AbortController;
862
+ let response;
863
+ try {
864
+ response = await this.exec({ cmd: [...command] }, controller.signal);
865
+ } catch (cause) {
866
+ throw this.failure(runWhat(command), cause);
867
+ }
868
+ const events = readNdjson(bodyOf(response));
869
+ const failure = (cause) => this.failure(runWhat(command), cause);
870
+ const stop = () => {
871
+ controller.abort();
872
+ };
873
+ const timer = options.timeoutMs === undefined ? undefined : setTimeout(stop, options.timeoutMs);
874
+ return new ReadableStream({
875
+ async pull(output) {
876
+ for (;; ) {
877
+ let next;
878
+ try {
879
+ next = await events.next();
880
+ } catch (cause) {
881
+ if (!controller.signal.aborted) {
882
+ clearTimeout(timer);
883
+ output.error(failure(cause));
884
+ return;
885
+ }
886
+ next = { done: true, value: undefined };
887
+ }
888
+ if (next.done) {
889
+ clearTimeout(timer);
890
+ closeQuietly(output);
891
+ return;
892
+ }
893
+ const event = asEvent(next.value);
894
+ if (event.error !== undefined) {
895
+ clearTimeout(timer);
896
+ output.error(failure(new Error(event.error)));
897
+ return;
898
+ }
899
+ if (event.stdout !== undefined) {
900
+ output.enqueue(new Uint8Array(Buffer.from(event.stdout, "base64")));
901
+ return;
902
+ }
903
+ }
904
+ },
905
+ cancel() {
906
+ clearTimeout(timer);
907
+ stop();
908
+ }
909
+ });
910
+ }
911
+ async writeFile(path, content) {
912
+ const what = `write ${path}`;
913
+ const body = typeof content === "string" ? content : new Uint8Array(content);
914
+ const response = await this.request(what, "PUT", filePath("/files", path), {
915
+ body
916
+ });
917
+ if (!response.ok) {
918
+ throw this.failure(what, new Error((await refusalOf(response)).message));
919
+ }
920
+ }
921
+ async readFile(path) {
922
+ const what = `read ${path}`;
923
+ const response = await this.request(what, "GET", filePath("/files", path));
924
+ if (response.ok) {
925
+ return { outcome: "ok", bytes: new Uint8Array(await response.arrayBuffer()) };
926
+ }
927
+ return this.readRefused(what, response);
928
+ }
929
+ async readRefused(what, response) {
930
+ const refusal = await refusalOf(response);
931
+ if (refusal.code === "not_found")
932
+ return { outcome: "not-found" };
933
+ if (refusal.code === "read_failed")
934
+ return { outcome: "failed", message: refusal.message };
935
+ throw this.failure(what, new Error(refusal.message));
936
+ }
937
+ async readFileBounded(path, budget) {
938
+ const what = `read ${path}`;
939
+ const response = await this.request(what, "GET", `${filePath("/files/bounded", path)}&maxBytes=${String(budget.maxBytes)}&timeoutMs=${String(budget.timeoutMs)}`, { signal: AbortSignal.timeout(boundedReadGiveUpMs(budget.timeoutMs)) });
940
+ if (!response.ok)
941
+ return this.readRefused(what, response);
942
+ let bytes;
943
+ try {
944
+ bytes = await readAtMost(bodyOf(response), budget.maxBytes);
945
+ } catch (cause) {
946
+ throw this.failure(what, cause);
947
+ }
948
+ if (bytes === undefined) {
949
+ return {
950
+ outcome: "failed",
951
+ message: `the agent sent more than the budget of ${String(budget.maxBytes)} bytes`
952
+ };
953
+ }
954
+ return { outcome: "ok", bytes };
955
+ }
956
+ async listFiles(path, recursive) {
957
+ const what = `list ${path}`;
958
+ const response = await this.request(what, "GET", `${filePath("/files/list", path)}${recursive ? "&recursive=true" : ""}`);
959
+ if (!response.ok) {
960
+ const refusal = await refusalOf(response);
961
+ if (refusal.code === "not_a_directory")
962
+ return { outcome: "not-a-directory" };
963
+ if (refusal.code === "not_found" || refusal.code === "list_failed") {
964
+ return { outcome: "failed", message: refusal.message };
965
+ }
966
+ throw this.failure(what, new Error(refusal.message));
967
+ }
968
+ const entries = entriesOf(await response.json());
969
+ if (entries === undefined) {
970
+ throw this.failure(what, new Error("the agent sent a listing with no entries"));
971
+ }
972
+ return { outcome: "ok", entries };
973
+ }
974
+ async startProcess(command, cwd) {
975
+ const what = `start ${programOf(command)}`;
976
+ const response = await this.request(what, "POST", "/process/start", {
977
+ json: { cmd: [...command], ...cwd === undefined ? {} : { cwd } }
978
+ });
979
+ if (!response.ok) {
980
+ throw this.failure(what, new Error((await refusalOf(response)).message));
981
+ }
982
+ const pid = pidOf(await response.json());
983
+ if (pid === undefined) {
984
+ throw this.failure(what, new Error("the agent named no pid"));
985
+ }
986
+ return pid;
987
+ }
988
+ async processStatus(pid) {
989
+ const what = `check process ${String(pid)}`;
990
+ const response = await this.request(what, "GET", `/process/status?pid=${String(pid)}`);
991
+ if (!response.ok) {
992
+ throw this.failure(what, new Error((await refusalOf(response)).message));
993
+ }
994
+ const status = statusOf(await response.json());
995
+ if (status === undefined) {
996
+ throw this.failure(what, new Error("the agent sent no status"));
997
+ }
998
+ return status;
999
+ }
1000
+ async signalProcess(pid, signal) {
1001
+ const what = `signal process ${String(pid)}`;
1002
+ const response = await this.request(what, "POST", "/process/signal", {
1003
+ json: { pid, signal }
1004
+ });
1005
+ if (!response.ok) {
1006
+ throw this.failure(what, new Error((await refusalOf(response)).message));
1007
+ }
1008
+ }
1009
+ async processLogs(pid) {
1010
+ const what = `read the log of process ${String(pid)}`;
1011
+ const response = await this.request(what, "GET", `/process/logs?pid=${String(pid)}`);
1012
+ if (!response.ok) {
1013
+ throw this.failure(what, new Error((await refusalOf(response)).message));
1014
+ }
1015
+ return response.text();
1016
+ }
1017
+ async waitForPort(port, timeoutMs, pid, probe) {
1018
+ const what = `wait for port ${String(port)}`;
1019
+ const response = await this.request(what, "POST", "/process/waitport", {
1020
+ json: {
1021
+ port,
1022
+ timeoutMs,
1023
+ ...pid === undefined ? {} : { pid },
1024
+ ...probe?.mode === undefined ? {} : { mode: probe.mode },
1025
+ ...probe?.path === undefined ? {} : { path: probe.path }
1026
+ },
1027
+ signal: AbortSignal.timeout(timeoutMs + TIMEOUT_SLACK_MS)
1028
+ });
1029
+ if (!response.ok) {
1030
+ throw this.failure(what, new Error((await refusalOf(response)).message));
1031
+ }
1032
+ const wait = portWaitOf(await response.json());
1033
+ if (wait === undefined) {
1034
+ throw this.failure(what, new Error("the agent sent no answer for the wait"));
1035
+ }
1036
+ return wait;
1037
+ }
1038
+ async exec(body, signal) {
1039
+ const response = await fetch(`${this.base}/exec`, {
1040
+ method: "POST",
1041
+ headers: {
1042
+ "content-type": "application/json",
1043
+ authorization: `Bearer ${this.endpoint.token}`
1044
+ },
1045
+ body: JSON.stringify(body),
1046
+ signal
1047
+ });
1048
+ if (!response.ok) {
1049
+ throw new Error((await refusalOf(response)).message);
1050
+ }
1051
+ return response;
1052
+ }
1053
+ async request(what, method, path, options = {}) {
1054
+ const headers = { authorization: `Bearer ${this.endpoint.token}` };
1055
+ if (options.json !== undefined)
1056
+ headers["content-type"] = "application/json";
1057
+ const body = options.json === undefined ? options.body : JSON.stringify(options.json);
1058
+ try {
1059
+ return await fetch(`${this.base}${path}`, {
1060
+ method,
1061
+ headers,
1062
+ ...body === undefined ? {} : { body },
1063
+ ...options.signal === undefined ? {} : { signal: options.signal }
1064
+ });
1065
+ } catch (cause) {
1066
+ throw this.failure(what, cause);
1067
+ }
1068
+ }
1069
+ failure(what, cause) {
1070
+ return new Error(`The agent in ${this.where} could not ${what}: ${describe(cause)}`, { cause });
1071
+ }
1072
+ }
1073
+ function runWhat(command) {
1074
+ return `run ${programOf(command)}`;
1075
+ }
1076
+ function programOf(command) {
1077
+ return JSON.stringify(command[0] ?? "");
1078
+ }
1079
+ function filePath(endpoint, path) {
1080
+ return `${endpoint}?path=${encodeURIComponent(path)}`;
1081
+ }
1082
+ function bodyOf(response) {
1083
+ if (response.body === null)
1084
+ throw new Error("the response had no body");
1085
+ return response.body;
1086
+ }
1087
+ function boundedReadGiveUpMs(timeoutMs) {
1088
+ return Math.min(timeoutMs + BOUNDED_READ_SLACK_MS, MAX_TIMER_MS);
1089
+ }
1090
+ async function readAtMost(body, maxBytes) {
1091
+ const reader = body.getReader();
1092
+ const chunks = [];
1093
+ let total = 0;
1094
+ for (;; ) {
1095
+ const { done, value } = await reader.read();
1096
+ if (done)
1097
+ break;
1098
+ total += value.byteLength;
1099
+ if (total > maxBytes) {
1100
+ await reader.cancel();
1101
+ return;
1102
+ }
1103
+ chunks.push(value);
1104
+ }
1105
+ return Buffer.concat(chunks);
1106
+ }
1107
+ function closeQuietly(output) {
1108
+ try {
1109
+ output.close();
1110
+ } catch {}
1111
+ }
1112
+
1113
+ // src/queues.ts
1114
+ class QueueUnknownError extends Error {
1115
+ constructor(id, cause) {
1116
+ super(`cannot tell which queue sandbox ${id} is in: Lookout did not answer (${cause instanceof Error ? cause.message : String(cause)})`, { cause });
1117
+ this.name = "QueueUnknownError";
1118
+ }
1119
+ }
1120
+
1121
+ class QueueDirectory {
1122
+ config;
1123
+ lookup;
1124
+ all;
1125
+ mapped;
1126
+ remembered = new Map;
1127
+ constructor(config, lookup) {
1128
+ this.config = config;
1129
+ this.lookup = lookup;
1130
+ this.all = [
1131
+ ...new Set([
1132
+ config.queue,
1133
+ ...Object.values(config.queueByUser),
1134
+ ...Object.values(config.queueByProject)
1135
+ ])
1136
+ ];
1137
+ this.mapped = this.all.length > 1;
1138
+ }
1139
+ forOwner(owner) {
1140
+ const byUser = owner.userId === undefined ? undefined : this.config.queueByUser[owner.userId];
1141
+ return byUser ?? this.config.queueByProject[owner.projectId] ?? this.config.queue;
1142
+ }
1143
+ remember(id, queue) {
1144
+ this.remembered.set(id, queue);
1145
+ }
1146
+ forget(id) {
1147
+ this.remembered.delete(id);
1148
+ }
1149
+ async resolve(id, owner) {
1150
+ const known = this.remembered.get(id);
1151
+ if (known !== undefined)
1152
+ return known;
1153
+ if (!this.mapped)
1154
+ return this.config.queue;
1155
+ if (this.lookup !== undefined) {
1156
+ let found;
1157
+ try {
1158
+ found = await this.lookup(id);
1159
+ } catch (cause) {
1160
+ throw new QueueUnknownError(id, cause);
1161
+ }
1162
+ if (found !== undefined) {
1163
+ this.remembered.set(id, found);
1164
+ return found;
1165
+ }
1166
+ }
1167
+ const queue = owner === undefined ? this.config.queue : this.forOwner(owner);
1168
+ this.remembered.set(id, queue);
1169
+ return queue;
1170
+ }
1171
+ }
1172
+
1173
+ // src/sandbox.ts
1174
+ import { createHash, createHmac } from "node:crypto";
1175
+
1176
+ // src/shell.ts
1177
+ function shellQuote(value) {
1178
+ return `'${value.replaceAll("'", `'\\''`)}'`;
1179
+ }
1180
+ function withEnvPrefix(cmd, env, defaults = {}) {
1181
+ const forced = Object.entries(env).map(([key, value]) => `export ${assertEnvName(key)}=${shellQuote(value)}; `);
1182
+ const guarded = Object.entries(defaults).map(([key, value]) => `[ -n "\${${assertEnvName(key)}:-}" ] || export ${key}=${shellQuote(value)}; `);
1183
+ return forced.join("") + guarded.join("") + cmd;
1184
+ }
1185
+ function assertEnvName(name) {
1186
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
1187
+ throw new Error(`Invalid environment variable name: ${JSON.stringify(name)}`);
1188
+ }
1189
+ return name;
1190
+ }
1191
+ function gitCloneCommand(repo, options) {
1192
+ const parts = ["git", "clone"];
1193
+ if (options?.branch !== undefined)
1194
+ parts.push("--branch", shellQuote(options.branch));
1195
+ parts.push(shellQuote(repo), shellQuote(options?.targetDir ?? "."));
1196
+ return parts.join(" ");
1197
+ }
1198
+
1199
+ // src/sandbox.ts
1200
+ function decodeUtf8(bytes) {
1201
+ try {
1202
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
1203
+ } catch {
1204
+ return;
1205
+ }
1206
+ }
1207
+ function oneLine(text) {
1208
+ return text.replace(/[\u0000-\u001f\u007f]/g, (char) => JSON.stringify(char).slice(1, -1));
1209
+ }
1210
+ function reason(error) {
1211
+ return error instanceof Error ? error.message : String(error);
1212
+ }
1213
+ function isValidBudget(options) {
1214
+ return Number.isSafeInteger(options.maxBytes) && options.maxBytes >= 0 && Number.isSafeInteger(4 * Math.ceil(options.maxBytes / 3)) && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 && options.timeoutMs <= 2 ** 31 - 1;
1215
+ }
1216
+ function agentToken(secret, id) {
1217
+ return createHmac("sha256", secret).update(id).digest("hex");
1218
+ }
1219
+ var WRITE_CONCURRENCY = 8;
1220
+ var AGENT_READY_TIMEOUT_MS = 30000;
1221
+ var PORT_READY_TIMEOUT_MS = 0;
1222
+ function toExecResult(result) {
1223
+ if (result.exitCode === 0) {
1224
+ return { success: true, stdout: result.stdout, stderr: result.stderr };
1225
+ }
1226
+ return {
1227
+ success: false,
1228
+ stdout: result.stdout,
1229
+ stderr: result.stderr,
1230
+ error: { code: "COMMAND_FAILED" }
1231
+ };
1232
+ }
1233
+ function toFileInfos(entries, rootPath, options) {
1234
+ const files = [];
1235
+ for (const entry of entries) {
1236
+ const name = entry.path.slice(entry.path.lastIndexOf("/") + 1);
1237
+ if (options?.includeHidden !== true && name.startsWith("."))
1238
+ continue;
1239
+ files.push({
1240
+ name,
1241
+ absolutePath: entry.path,
1242
+ relativePath: entry.path.startsWith(rootPath) ? entry.path.slice(rootPath.length).replace(/^\//, "") : entry.path,
1243
+ type: entry.type,
1244
+ size: entry.size
1245
+ });
1246
+ }
1247
+ return files;
1248
+ }
1249
+
1250
+ class ArmadaSandbox {
1251
+ id;
1252
+ config;
1253
+ armada;
1254
+ openChannel;
1255
+ queues;
1256
+ placements;
1257
+ options;
1258
+ supportsBucketMount = false;
1259
+ job;
1260
+ pod;
1261
+ channel;
1262
+ token;
1263
+ env = {};
1264
+ envDefaults = {};
1265
+ constructor(id, config, armada, openChannel, queues, placements, options) {
1266
+ this.id = id;
1267
+ this.config = config;
1268
+ this.armada = armada;
1269
+ this.openChannel = openChannel;
1270
+ this.queues = queues;
1271
+ this.placements = placements;
1272
+ this.options = options;
1273
+ this.token = agentToken(config.agentTokenSecret, id);
1274
+ }
1275
+ async ready() {
1276
+ if (this.channel !== undefined)
1277
+ return;
1278
+ const known = this.placements.get(this.id);
1279
+ if (known !== undefined) {
1280
+ try {
1281
+ await known.channel.ready(0);
1282
+ this.job = known.job;
1283
+ this.pod = known.pod;
1284
+ this.channel = known.channel;
1285
+ return;
1286
+ } catch {
1287
+ this.placements.delete(this.id);
1288
+ }
1289
+ }
1290
+ const tokenSha256 = createHash("sha256").update(this.token).digest("hex");
1291
+ this.job ??= await this.armada.submit(this.id, buildPodSpec(this.config, { tokenSha256 }, this.options), await this.queue());
1292
+ this.pod = await this.armada.waitForRunning(this.job);
1293
+ const url = await this.armada.portUrl(this.job, this.config.agentPort);
1294
+ const channel = this.openChannel({ url, token: this.token, pod: this.pod });
1295
+ await channel.ready(AGENT_READY_TIMEOUT_MS);
1296
+ this.channel = channel;
1297
+ this.placements.set(this.id, { job: this.job, pod: this.pod, channel });
1298
+ }
1299
+ get placement() {
1300
+ return this.pod;
1301
+ }
1302
+ async queue() {
1303
+ return this.job?.queue ?? this.queues.resolve(this.id, this.options?.owner);
1304
+ }
1305
+ async isPortReady(port, options) {
1306
+ const channel = this.channel ?? this.placements.get(this.id)?.channel;
1307
+ if (channel === undefined)
1308
+ return false;
1309
+ try {
1310
+ const wait = await channel.waitForPort(port, PORT_READY_TIMEOUT_MS, undefined, probeOf({ ...options, mode: options?.mode ?? "http" }));
1311
+ return wait.open;
1312
+ } catch {
1313
+ return false;
1314
+ }
1315
+ }
1316
+ async exec(cmd, options) {
1317
+ const command = withEnvPrefix(cmd, this.env, this.envDefaults);
1318
+ const timeout = options?.timeout;
1319
+ const backstopMs = timeout === undefined && this.config.commandMaxSeconds > 0 ? this.config.commandMaxSeconds * 1000 : undefined;
1320
+ const deadline = timeout ?? backstopMs;
1321
+ try {
1322
+ const channel = await this.open();
1323
+ const result = await channel.run(["sh", "-lc", command], deadline === undefined ? {} : { timeoutMs: deadline });
1324
+ return toExecResult(result);
1325
+ } catch (error) {
1326
+ const stderr = error instanceof CommandTimeoutError && backstopMs !== undefined ? `Command ran past ARMADA_COMMAND_MAX_SECONDS (${String(this.config.commandMaxSeconds)}s) and was killed: ${cmd}` : reason(error);
1327
+ return {
1328
+ success: false,
1329
+ stdout: "",
1330
+ stderr,
1331
+ error: { code: "BACKEND_ERROR" }
1332
+ };
1333
+ }
1334
+ }
1335
+ async open() {
1336
+ if (this.channel === undefined)
1337
+ await this.ready();
1338
+ if (this.channel === undefined)
1339
+ throw new Error(`Sandbox ${this.id} has no agent after ready()`);
1340
+ return this.channel;
1341
+ }
1342
+ async execStream(cmd, options) {
1343
+ const channel = await this.open();
1344
+ const command = withEnvPrefix(cmd, this.env, this.envDefaults);
1345
+ return channel.stream(["sh", "-lc", command], options?.timeout === undefined ? {} : { timeoutMs: options.timeout });
1346
+ }
1347
+ async readFile(path) {
1348
+ return this.readThrough(path, async (channel) => channel.readFile(path), (bytes) => {
1349
+ const text = decodeUtf8(bytes);
1350
+ return text === undefined ? { success: true, content: Buffer.from(bytes).toString("base64"), encoding: "base64" } : { success: true, content: text, encoding: "utf-8" };
1351
+ });
1352
+ }
1353
+ async readFileBounded(path, options) {
1354
+ if (!isValidBudget(options)) {
1355
+ return this.readFailed(path, "READ_FAILED", `maxBytes ${String(options.maxBytes)} and timeoutMs ${String(options.timeoutMs)} are not a valid budget`);
1356
+ }
1357
+ const budget = {
1358
+ maxBytes: options.maxBytes,
1359
+ timeoutMs: Math.ceil(options.timeoutMs)
1360
+ };
1361
+ return this.readThrough(path, async (channel) => channel.readFileBounded(path, budget), (bytes) => ({
1362
+ success: true,
1363
+ content: Buffer.from(bytes).toString("base64"),
1364
+ encoding: "base64"
1365
+ }));
1366
+ }
1367
+ async readThrough(path, read, encode) {
1368
+ let outcome;
1369
+ try {
1370
+ outcome = await read(await this.open());
1371
+ } catch (error) {
1372
+ return this.readFailed(path, "BACKEND_ERROR", reason(error));
1373
+ }
1374
+ if (outcome.outcome === "not-found") {
1375
+ return { success: false, content: "", error: { code: "NOT_FOUND" } };
1376
+ }
1377
+ if (outcome.outcome === "failed") {
1378
+ return this.readFailed(path, "READ_FAILED", outcome.message);
1379
+ }
1380
+ return encode(outcome.bytes);
1381
+ }
1382
+ readFailed(path, code, why) {
1383
+ const line = `marimohub-compute-armada: sandbox ${this.id} could not read ${oneLine(path)} (${code}): ${oneLine(why)}`;
1384
+ console.warn(line.replaceAll(this.token, "<token>"));
1385
+ return { success: false, content: "", error: { code } };
1386
+ }
1387
+ async listFiles(path, options) {
1388
+ let listed;
1389
+ try {
1390
+ listed = await (await this.open()).listFiles(path, options?.recursive === true);
1391
+ } catch {
1392
+ return { success: false, files: [], error: { code: "BACKEND_ERROR" } };
1393
+ }
1394
+ if (listed.outcome === "not-a-directory") {
1395
+ return { success: false, files: [], error: { code: "NOT_A_DIRECTORY" } };
1396
+ }
1397
+ if (listed.outcome === "failed") {
1398
+ return { success: false, files: [], error: { code: "LIST_FAILED" } };
1399
+ }
1400
+ return { success: true, files: toFileInfos(listed.entries, path, options) };
1401
+ }
1402
+ async writeFiles(files) {
1403
+ if (files.length === 0)
1404
+ return;
1405
+ const channel = await this.open();
1406
+ const write = async (file) => {
1407
+ try {
1408
+ await channel.writeFile(file.path, file.content);
1409
+ } catch (error) {
1410
+ throw new Error(`Writing ${file.path} failed: ${reason(error)}`, { cause: error });
1411
+ }
1412
+ };
1413
+ for (let start = 0;start < files.length; start += WRITE_CONCURRENCY) {
1414
+ await Promise.all(files.slice(start, start + WRITE_CONCURRENCY).map(write));
1415
+ }
1416
+ }
1417
+ async gitCheckout(repo, options) {
1418
+ const result = await this.exec(gitCloneCommand(repo, options));
1419
+ if (!result.success)
1420
+ throw new Error(`git checkout failed: ${result.stderr}`);
1421
+ }
1422
+ async setEnvVars(vars, options) {
1423
+ for (const name of Object.keys(vars))
1424
+ assertEnvName(name);
1425
+ if (options?.onlyIfUnset) {
1426
+ this.envDefaults = { ...this.envDefaults, ...vars };
1427
+ } else {
1428
+ this.env = { ...this.env, ...vars };
1429
+ }
1430
+ }
1431
+ async mountBucket(_options) {
1432
+ throw new Error("mountBucket is not supported on the armada backend; using file copy fallback");
1433
+ }
1434
+ async unmountBucket(_mountPath) {}
1435
+ async startProcess(cmd, options) {
1436
+ const channel = await this.open();
1437
+ const processEnv = {};
1438
+ for (const [name, value] of Object.entries(options?.env ?? {})) {
1439
+ if (value !== undefined)
1440
+ processEnv[name] = value;
1441
+ }
1442
+ const command = withEnvPrefix(withEnvPrefix(cmd, processEnv), this.env, this.envDefaults);
1443
+ let pid;
1444
+ try {
1445
+ pid = await channel.startProcess(["sh", "-lc", command], options?.cwd);
1446
+ } catch (error) {
1447
+ throw new Error(`Starting "${cmd}" failed: ${reason(error)}`, { cause: error });
1448
+ }
1449
+ return new ArmadaProcess(options?.processId ?? `armada-proc-${String(pid)}`, cmd, channel, this.pod === undefined ? this.id : `${this.pod.podNamespace}/${this.pod.podName}`, pid);
1450
+ }
1451
+ async exposePort(port, _options) {
1452
+ await this.ready();
1453
+ if (this.job === undefined)
1454
+ throw new Error(`Sandbox ${this.id} has no job after ready()`);
1455
+ return { url: await this.armada.portUrl(this.job, port) };
1456
+ }
1457
+ async destroy() {
1458
+ if (this.job === undefined)
1459
+ await this.armada.cancelSet(this.id, await this.queue());
1460
+ else
1461
+ await this.armada.cancel(this.job);
1462
+ this.queues.forget(this.id);
1463
+ this.placements.delete(this.id);
1464
+ this.pod = undefined;
1465
+ this.channel = undefined;
1466
+ }
1467
+ }
1468
+ function probeOf(options) {
1469
+ if (options?.mode === undefined && options?.path === undefined)
1470
+ return;
1471
+ return {
1472
+ ...options.mode === undefined ? {} : { mode: options.mode },
1473
+ ...options.path === undefined ? {} : { path: options.path }
1474
+ };
1475
+ }
1476
+
1477
+ class ArmadaProcess {
1478
+ id;
1479
+ command;
1480
+ channel;
1481
+ where;
1482
+ pid;
1483
+ constructor(id, command, channel, where, pid) {
1484
+ this.id = id;
1485
+ this.command = command;
1486
+ this.channel = channel;
1487
+ this.where = where;
1488
+ this.pid = pid;
1489
+ }
1490
+ async kill(signal) {
1491
+ try {
1492
+ await this.channel.signalProcess(this.pid, signal ?? "TERM");
1493
+ } catch {}
1494
+ }
1495
+ async waitForPort(port, options) {
1496
+ const timeout = options?.timeout ?? 30000;
1497
+ const wait = await this.channel.waitForPort(port, timeout, this.pid, probeOf(options));
1498
+ if (wait.open)
1499
+ return;
1500
+ const log = await this.logsQuietly();
1501
+ if (wait.exited === true) {
1502
+ throw new Error(`process exited before port ${String(port)} opened.
1503
+ ${log}`.trim());
1504
+ }
1505
+ throw new Error(`timed out waiting for port ${String(port)} in ${this.where} after ${String(timeout)}ms.
1506
+ ${log}`);
1507
+ }
1508
+ async getLogs() {
1509
+ return { stdout: await this.channel.processLogs(this.pid), stderr: "" };
1510
+ }
1511
+ async logsQuietly() {
1512
+ try {
1513
+ return await this.channel.processLogs(this.pid);
1514
+ } catch {
1515
+ return "";
1516
+ }
1517
+ }
1518
+ }
1519
+
1520
+ // src/provider.ts
1521
+ class ArmadaCompute {
1522
+ config;
1523
+ armada;
1524
+ queues;
1525
+ placements = new Map;
1526
+ listActive;
1527
+ capabilities;
1528
+ constructor(config) {
1529
+ this.config = config;
1530
+ this.armada = new ArmadaClient(config);
1531
+ this.capabilities = {
1532
+ multiPort: config.surfacePorts.length > 0,
1533
+ computeProfiles: true,
1534
+ gpuProfiles: Object.keys(config.gpuNodeSelectors).length > 0
1535
+ };
1536
+ this.queues = new QueueDirectory(config, async (id) => this.armada.findQueue(id));
1537
+ if (config.lookoutUrl !== undefined) {
1538
+ this.listActive = async () => {
1539
+ const jobs = await this.armada.listActive();
1540
+ for (const job of jobs)
1541
+ this.queues.remember(job.id, job.queue);
1542
+ return jobs.map(({ queue: _queue, ...sandbox }) => sandbox);
1543
+ };
1544
+ }
1545
+ }
1546
+ create(id, options) {
1547
+ return new ArmadaSandbox(id, this.config, this.armada, openAgent, this.queues, this.placements, options);
1548
+ }
1549
+ async proxy(_request) {
1550
+ return null;
1551
+ }
1552
+ }
1553
+ function openAgent(endpoint) {
1554
+ return new AgentChannel(endpoint);
1555
+ }
1556
+
1557
+ // src/index.ts
1558
+ var manifest = {
1559
+ apiVersion: 1,
1560
+ kind: "compute",
1561
+ create(context) {
1562
+ return new ArmadaCompute(readConfig(context.env, context.compute));
1563
+ }
1564
+ };
1565
+ var src_default = manifest;
1566
+ export {
1567
+ src_default as default
1568
+ };
1569
+
1570
+ //# debugId=592227A3E0D43A8764756E2164756E21
1571
+ //# sourceMappingURL=index.js.map