@munitoai/cli 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/dist/cli.js ADDED
@@ -0,0 +1,1182 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ AGENTS,
4
+ AGENT_TEMPLATE,
5
+ ApiError,
6
+ CLAUDE_MODEL,
7
+ Client,
8
+ DEFAULT_BASE_SIZE,
9
+ DEFAULT_DISK_GIB,
10
+ DEFAULT_MODEL,
11
+ DEFAULT_SMALL_MODEL,
12
+ ENV_KEY,
13
+ MissingKeyError,
14
+ PACKAGES,
15
+ PLUGINS,
16
+ PROVIDERS,
17
+ WiringError,
18
+ authPath,
19
+ clear,
20
+ createAgentSandbox,
21
+ drop,
22
+ findBase,
23
+ job,
24
+ mask,
25
+ require as require2,
26
+ resolveHost,
27
+ runAgent,
28
+ save,
29
+ warm,
30
+ wire
31
+ } from "./chunk-WSY6HMNS.js";
32
+
33
+ // src/cli.ts
34
+ import { runMain } from "citty";
35
+
36
+ // src/core/workspace.ts
37
+ import { execFile } from "child_process";
38
+ import { mkdtemp, readFile, rm, stat, writeFile } from "fs/promises";
39
+ import { tmpdir } from "os";
40
+ import { join, resolve } from "path";
41
+ import { promisify } from "util";
42
+ var run = promisify(execFile);
43
+ var MAX_FILES = 2e3;
44
+ var MAX_FILE_BYTES = 1 << 20;
45
+ var MAX_TOTAL_BYTES = 16 << 20;
46
+ var WorkspaceError = class extends Error {
47
+ };
48
+ async function collect(dir) {
49
+ const root = resolve(dir ?? process.cwd());
50
+ const listed = await listTracked(root);
51
+ if (!listed) return [];
52
+ const files = [];
53
+ let total = 0;
54
+ for (const relative of listed) {
55
+ if (files.length >= MAX_FILES) break;
56
+ const absolute = join(root, relative);
57
+ let info;
58
+ try {
59
+ info = await stat(absolute);
60
+ } catch {
61
+ continue;
62
+ }
63
+ if (!info.isFile() || info.size > MAX_FILE_BYTES) continue;
64
+ if (total + info.size > MAX_TOTAL_BYTES) break;
65
+ const buffer = await readFile(absolute);
66
+ if (isBinary(buffer)) continue;
67
+ total += info.size;
68
+ files.push({ path: relative, content: buffer.toString("utf8") });
69
+ }
70
+ return files;
71
+ }
72
+ async function listTracked(root) {
73
+ try {
74
+ const { stdout } = await run("git", ["-C", root, "ls-files", "-co", "--exclude-standard", "-z"], {
75
+ maxBuffer: 32 << 20
76
+ });
77
+ return stdout.split("\0").filter(Boolean);
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+ function isBinary(buffer) {
83
+ return buffer.subarray(0, 8e3).includes(0);
84
+ }
85
+ function describeUpload(files) {
86
+ const bytes = files.reduce((sum, file) => sum + Buffer.byteLength(file.content), 0);
87
+ const size = bytes > 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MiB` : `${Math.ceil(bytes / 1024)} KiB`;
88
+ return `${files.length} files, ${size}`;
89
+ }
90
+ async function applyPatch(patch, dir) {
91
+ const root = resolve(dir ?? process.cwd());
92
+ if (!patch.trim()) return [];
93
+ const file = join(await mkdtemp(join(tmpdir(), "munito-")), "patch.diff");
94
+ await writeFile(file, patch);
95
+ try {
96
+ await run("git", ["-C", root, "apply", "--check", file]);
97
+ const { stdout } = await run("git", ["-C", root, "apply", "--numstat", file]);
98
+ await run("git", ["-C", root, "apply", file]);
99
+ return stdout.split("\n").map((line) => line.split(" ").at(2)).filter((name) => Boolean(name));
100
+ } catch (error) {
101
+ throw new WorkspaceError(`The patch did not apply: ${error.message}`);
102
+ } finally {
103
+ await rm(file, { force: true });
104
+ }
105
+ }
106
+
107
+ // src/cli/main.ts
108
+ import { defineCommand as defineCommand8 } from "citty";
109
+
110
+ // src/cli/commands/agent.ts
111
+ import { defineCommand } from "citty";
112
+
113
+ // src/cli/theme.ts
114
+ var BRAND = {
115
+ violet: [112, 44, 246],
116
+ cubeTop: [154, 104, 250],
117
+ cubeSide: [74, 31, 168],
118
+ lime: [215, 250, 74],
119
+ lilac: [160, 129, 222],
120
+ paper: [240, 238, 243],
121
+ ink: [33, 22, 41],
122
+ night: [20, 16, 25]
123
+ };
124
+ function colorDepth(stream2 = process.stdout) {
125
+ if (process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "") return 0;
126
+ const forced = process.env.FORCE_COLOR;
127
+ if (forced !== void 0) {
128
+ if (forced === "0" || forced === "false") return 0;
129
+ if (forced === "1" || forced === "true") return 4;
130
+ if (forced === "2") return 8;
131
+ if (forced === "3") return 24;
132
+ }
133
+ if (!stream2.isTTY) return 0;
134
+ if (process.env.TERM === "dumb") return 0;
135
+ const colorterm = process.env.COLORTERM ?? "";
136
+ if (colorterm === "truecolor" || colorterm === "24bit") return 24;
137
+ if (/-256(color)?$/i.test(process.env.TERM ?? "")) return 8;
138
+ return 4;
139
+ }
140
+ var RESET = "\x1B[39m";
141
+ var BOLD = "\x1B[1m";
142
+ var UNBOLD = "\x1B[22m";
143
+ var DIM = "\x1B[2m";
144
+ var UNDIM = "\x1B[22m";
145
+ function to256([r, g, b]) {
146
+ const step = (value) => value < 48 ? 0 : value < 115 ? 1 : Math.min(5, Math.round((value - 35) / 40));
147
+ return 16 + 36 * step(r) + 6 * step(g) + step(b);
148
+ }
149
+ function to16([r, g, b]) {
150
+ const bright = Math.max(r, g, b) > 160;
151
+ const bit = (value) => value > 127 ? 1 : 0;
152
+ const code = bit(r) + bit(g) * 2 + bit(b) * 4;
153
+ return (bright ? 90 : 30) + code;
154
+ }
155
+ function palette(stream2 = process.stdout) {
156
+ const depth = colorDepth(stream2);
157
+ const fg = (color) => {
158
+ if (depth === 0) return (text2) => text2;
159
+ if (depth === 24) return (text2) => `\x1B[38;2;${color[0]};${color[1]};${color[2]}m${text2}${RESET}`;
160
+ if (depth === 8) return (text2) => `\x1B[38;5;${to256(color)}m${text2}${RESET}`;
161
+ return (text2) => `\x1B[${to16(color)}m${text2}${RESET}`;
162
+ };
163
+ const plain = depth === 0;
164
+ return {
165
+ depth,
166
+ primary: fg(BRAND.cubeTop),
167
+ accent: fg(BRAND.lime),
168
+ dim: plain ? (text2) => text2 : (text2) => `${DIM}${fg(BRAND.lilac)(text2)}${UNDIM}`,
169
+ text: fg(BRAND.paper),
170
+ bold: plain ? (text2) => text2 : (text2) => `${BOLD}${text2}${UNBOLD}`,
171
+ badge: plain ? (text2) => text2 : (text2) => depth === 24 ? `\x1B[48;2;${BRAND.violet.join(";")}m\x1B[38;2;${BRAND.paper.join(";")}m ${text2} \x1B[49m${RESET}` : `\x1B[45m\x1B[97m ${text2} \x1B[49m${RESET}`
172
+ };
173
+ }
174
+ function cube(p) {
175
+ const top = p.primary("\u2584\u2584\u2584\u2584\u2584\u2584");
176
+ const body = p.primary("\u2588\u2588\u2588\u2588\u2588\u2588");
177
+ return [` ${top}`, ` ${body}`, ` ${p.dim("\u2580\u2580\u2580\u2580\u2580\u2580")}`].join("\n");
178
+ }
179
+
180
+ // src/cli/output.ts
181
+ function out(json, stream2 = process.stdout) {
182
+ const p = palette(stream2);
183
+ const mode = json ? "json" : p.depth === 0 ? "plain" : "rich";
184
+ const write = (text2) => stream2.write(`${text2}
185
+ `);
186
+ return {
187
+ mode,
188
+ p,
189
+ line(text2 = "") {
190
+ if (mode !== "json") write(text2);
191
+ },
192
+ step(label, detail) {
193
+ if (mode === "json") return;
194
+ const mark = mode === "rich" ? p.primary("\u203A") : ">";
195
+ write(detail ? `${mark} ${label} ${p.dim(detail)}` : `${mark} ${label}`);
196
+ },
197
+ event(body) {
198
+ if (mode === "json") write(JSON.stringify(body));
199
+ },
200
+ result(text2, body) {
201
+ if (mode === "json") write(JSON.stringify({ type: "result", ...body, result: text2 }));
202
+ },
203
+ warn(text2) {
204
+ if (mode === "json") {
205
+ process.stderr.write(`${JSON.stringify({ type: "warning", message: text2 })}
206
+ `);
207
+ return;
208
+ }
209
+ process.stderr.write(`${mode === "rich" ? p.accent("!") : "!"} ${text2}
210
+ `);
211
+ },
212
+ error(text2) {
213
+ if (mode === "json") {
214
+ process.stderr.write(`${JSON.stringify({ type: "error", message: text2 })}
215
+ `);
216
+ return;
217
+ }
218
+ process.stderr.write(`${mode === "rich" ? "\x1B[31m\u2717\x1B[39m" : "x"} ${text2}
219
+ `);
220
+ },
221
+ raw(text2, target = "stdout") {
222
+ if (mode === "json") return;
223
+ (target === "stderr" ? process.stderr : stream2).write(text2);
224
+ }
225
+ };
226
+ }
227
+ function duration(ms) {
228
+ if (ms < 1e3) return `${Math.round(ms)} ms`;
229
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(1)} s`;
230
+ const minutes = Math.floor(ms / 6e4);
231
+ return `${minutes} min ${Math.round(ms % 6e4 / 1e3)} s`;
232
+ }
233
+ function table(rows, p, heading = true) {
234
+ if (!rows.length) return "";
235
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row2) => (row2[column] ?? "").length)));
236
+ return rows.map((row2, index) => {
237
+ const line = row2.map((cell, column) => (cell ?? "").padEnd(widths[column])).join(" ").trimEnd();
238
+ return heading && index === 0 ? p.dim(line) : line;
239
+ }).join("\n");
240
+ }
241
+
242
+ // src/cli/context.ts
243
+ var commonArgs = {
244
+ json: { type: "boolean", description: "Print NDJSON events instead of text." },
245
+ region: { type: "string", description: "global, eu or us. The default is global." },
246
+ host: { type: "string", description: "A full API URL, in place of a region." }
247
+ };
248
+ async function context(args) {
249
+ const channel2 = out(Boolean(args.json));
250
+ const credentials = await require2(args.host ?? args.region);
251
+ return {
252
+ client: new Client({ apiKey: credentials.apiKey, baseUrl: credentials.host }),
253
+ out: channel2,
254
+ host: credentials.host,
255
+ source: credentials.source
256
+ };
257
+ }
258
+ function channel(args) {
259
+ return out(Boolean(args.json));
260
+ }
261
+
262
+ // src/cli/desktop.ts
263
+ import { spawn } from "child_process";
264
+ var DESKTOP_PORT = 6080;
265
+ function openInBrowser(url) {
266
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
267
+ spawn(opener, [url], { stdio: "ignore", detached: true }).unref();
268
+ }
269
+ async function openDesktop(client, sandboxId, out2, expiresIn = 3600) {
270
+ try {
271
+ const signed = await client.signPortUrl(sandboxId, DESKTOP_PORT, expiresIn);
272
+ out2.event({ type: "url", url: signed.url, port: DESKTOP_PORT });
273
+ out2.step("desktop", signed.url);
274
+ if (out2.mode !== "json" && process.stdout.isTTY) openInBrowser(signed.url);
275
+ } catch (error) {
276
+ out2.warn(`The desktop did not open: ${error.message}`);
277
+ }
278
+ }
279
+
280
+ // src/cli/commands/agent.ts
281
+ var agent = defineCommand({
282
+ meta: {
283
+ name: "agent",
284
+ description: "Run a coding agent in a sandbox and bring its work back."
285
+ },
286
+ args: {
287
+ ...commonArgs,
288
+ agent: {
289
+ type: "positional",
290
+ required: false,
291
+ description: `Which harness: ${AGENTS.join(", ")}. The default is claude.`
292
+ },
293
+ prompt: { type: "positional", required: false, description: "What the agent should do." },
294
+ provider: {
295
+ type: "string",
296
+ description: `Where the model comes from: ${PROVIDERS.join(", ")}.`,
297
+ default: "munito"
298
+ },
299
+ auth: { type: "string", description: "token or subscription.", default: "token" },
300
+ model: { type: "string", description: "A model id, in place of the recommended one." },
301
+ repo: { type: "string", description: "A directory to upload. The default is the current git worktree." },
302
+ "no-upload": { type: "boolean", description: "Send no files at all." },
303
+ size: { type: "string", description: "tiny, small, default or large.", default: "default" },
304
+ template: { type: "string", description: "A sandbox template, in place of the agent one." },
305
+ timeout: { type: "string", description: "Seconds the sandbox may live. The default is 3600." },
306
+ "max-turns": { type: "string", description: "Stop the agent after this many turns." },
307
+ keep: { type: "boolean", description: "Leave the sandbox running when the task ends." },
308
+ desktop: { type: "boolean", description: "Give the agent a screen, and open the viewer. Implies --keep." },
309
+ "no-apply": { type: "boolean", description: "Do not apply the agent's patch to your worktree." }
310
+ },
311
+ async run({ args }) {
312
+ let name = args.agent ?? "claude";
313
+ let prompt = args.prompt;
314
+ if (!AGENTS.includes(name)) {
315
+ prompt = [args.agent, prompt].filter(Boolean).join(" ");
316
+ name = "claude";
317
+ }
318
+ if (!prompt) throw new Error('Give the agent something to do: munito agent "fix the failing test"');
319
+ const ctx = await context(args);
320
+ const { out: out2, client } = ctx;
321
+ const off = (name2) => args[`no-${name2}`] === true || args[name2] === false;
322
+ const upload = off("upload") ? [] : await collect(args.repo);
323
+ const started = Date.now();
324
+ const desktop = Boolean(args.desktop);
325
+ const keep = Boolean(args.keep) || desktop;
326
+ out2.line();
327
+ out2.line(`${out2.p.badge("munito")} ${out2.p.bold(name)} ${out2.p.dim(`on ${args.provider}`)}`);
328
+ out2.line(out2.p.dim(` ${prompt}`));
329
+ out2.line();
330
+ if (upload.length) out2.step("workspace", describeUpload(upload));
331
+ let streamed = false;
332
+ const onEvent = (event) => {
333
+ out2.event({ ...event });
334
+ switch (event.type) {
335
+ case "sandbox.creating":
336
+ out2.step("sandbox", "starting");
337
+ break;
338
+ case "sandbox.created":
339
+ out2.step("sandbox", `${event.sandboxId} in ${duration(event.ms)}`);
340
+ if (desktop) void openDesktop(client, event.sandboxId, out2);
341
+ break;
342
+ case "files.uploaded":
343
+ out2.step("uploaded", `${event.count} files`);
344
+ break;
345
+ case "harness.installing":
346
+ out2.step("installing", `${event.package}, once`);
347
+ break;
348
+ case "harness.installed":
349
+ out2.step("installed", duration(event.ms));
350
+ break;
351
+ case "agent.started":
352
+ out2.step("running", name);
353
+ out2.line();
354
+ break;
355
+ case "output":
356
+ if (name !== "claude") {
357
+ streamed = true;
358
+ out2.raw(event.data, event.stream);
359
+ }
360
+ break;
361
+ case "agent.finished":
362
+ if (streamed) out2.line();
363
+ out2.step("finished", `exit ${event.exitCode} in ${duration(event.ms)}`);
364
+ break;
365
+ case "sandbox.kept":
366
+ out2.step("kept", `${event.sandboxId} \u2014 munito ssh ${event.sandboxId}`);
367
+ break;
368
+ default:
369
+ break;
370
+ }
371
+ };
372
+ const run3 = await runAgent(client, {
373
+ agent: name,
374
+ prompt,
375
+ provider: args.provider,
376
+ auth: args.auth,
377
+ model: args.model,
378
+ size: args.size,
379
+ template: args.template ?? (desktop ? "desktop" : void 0),
380
+ timeout: args.timeout ? Number(args.timeout) : void 0,
381
+ maxTurns: args["max-turns"] ? Number(args["max-turns"]) : void 0,
382
+ keep,
383
+ files: upload,
384
+ onEvent
385
+ });
386
+ if (!streamed && run3.result && out2.mode !== "json") {
387
+ out2.line();
388
+ out2.line(run3.result);
389
+ }
390
+ let changed = [];
391
+ if (run3.patch && !off("apply")) {
392
+ try {
393
+ changed = await applyPatch(run3.patch, args.repo);
394
+ out2.line();
395
+ out2.step("applied", `${changed.length} files`);
396
+ for (const file of changed) out2.line(out2.p.dim(` ${file}`));
397
+ } catch (error) {
398
+ out2.warn(error.message);
399
+ out2.line(out2.p.dim(" The diff is in the JSON output: rerun with --json."));
400
+ }
401
+ } else if (run3.patch) {
402
+ out2.step("patch", `${Buffer.byteLength(run3.patch)} bytes, not applied`);
403
+ }
404
+ out2.line();
405
+ out2.step("done", duration(Date.now() - started));
406
+ out2.result(run3.result, {
407
+ sandbox_id: run3.sandboxId,
408
+ exit_code: run3.exitCode,
409
+ session_id: run3.sessionId,
410
+ duration_ms: run3.durationMs,
411
+ files_changed: changed,
412
+ patch: run3.patch || void 0
413
+ });
414
+ if (run3.exitCode !== 0) process.exitCode = run3.exitCode;
415
+ }
416
+ });
417
+
418
+ // src/cli/commands/ci.ts
419
+ import { defineCommand as defineCommand2 } from "citty";
420
+ var nameArg = {
421
+ name: { type: "string", description: "Which warm base. The default is the repository name.", default: "" }
422
+ };
423
+ var str = (value) => typeof value === "string" && value ? value : void 0;
424
+ var num = (value) => typeof value === "string" && value ? Number(value) : void 0;
425
+ function baseName(given) {
426
+ if (given) return given;
427
+ const repo = process.env.GITHUB_REPOSITORY ?? process.env.CI_PROJECT_PATH;
428
+ if (repo) return repo.replaceAll("/", "-");
429
+ return process.cwd().split("/").filter(Boolean).at(-1) ?? "default";
430
+ }
431
+ var ci = defineCommand2({
432
+ meta: { name: "ci", description: "Run CI jobs on a warm sandbox that already holds your dependencies." },
433
+ subCommands: {
434
+ warm: defineCommand2({
435
+ meta: { name: "warm", description: "Build the warm base and pause it." },
436
+ args: {
437
+ ...commonArgs,
438
+ ...nameArg,
439
+ setup: { type: "positional", required: true, description: "The command that installs everything." },
440
+ size: { type: "string", description: `The size of the base. The default is ${DEFAULT_BASE_SIZE}.` },
441
+ disk: { type: "string", description: `Root disk in GiB. The default is ${DEFAULT_DISK_GIB}.` },
442
+ template: { type: "string", description: "A template. The default is ubuntu." }
443
+ },
444
+ async run({ args }) {
445
+ const { client, out: out2 } = await context(args);
446
+ const name = baseName(str(args.name) ?? "");
447
+ const result = await warm(client, {
448
+ name,
449
+ setup: String(args.setup),
450
+ size: str(args.size),
451
+ diskGib: num(args.disk),
452
+ template: str(args.template),
453
+ onEvent: report(out2)
454
+ });
455
+ out2.step("ready", `base ${result.sandboxId} for ${name}`);
456
+ out2.line(out2.p.dim(` munito ci run --name ${name} "<your test command>"`));
457
+ out2.result("", { base: result.sandboxId, name });
458
+ }
459
+ }),
460
+ run: defineCommand2({
461
+ meta: { name: "run", description: "Fork the warm base, run one job, delete the fork." },
462
+ args: {
463
+ ...commonArgs,
464
+ ...nameArg,
465
+ command: { type: "positional", required: true, description: "The job command." },
466
+ cwd: { type: "string", description: "The working directory in the sandbox." },
467
+ timeout: { type: "string", description: "Seconds the job may take." },
468
+ keep: { type: "boolean", description: "Keep the fork, to look at a failure." }
469
+ },
470
+ async run({ args }) {
471
+ const { client, out: out2 } = await context(args);
472
+ const name = baseName(str(args.name) ?? "");
473
+ const exit = await job(client, {
474
+ name,
475
+ command: String(args.command),
476
+ cwd: str(args.cwd),
477
+ timeout: num(args.timeout),
478
+ keep: Boolean(args.keep),
479
+ onOutput: (text2, stream2) => out2.raw(text2, stream2),
480
+ onEvent: report(out2)
481
+ });
482
+ out2.result("", { exit_code: exit, name });
483
+ if (exit !== 0) process.exitCode = exit;
484
+ }
485
+ }),
486
+ status: defineCommand2({
487
+ meta: { name: "status", description: "Show the warm base of this repository." },
488
+ args: { ...commonArgs, ...nameArg },
489
+ async run({ args }) {
490
+ const { client, out: out2 } = await context(args);
491
+ const name = baseName(str(args.name) ?? "");
492
+ const base = await findBase(client, name);
493
+ if (!base) {
494
+ out2.line(out2.p.dim(`No warm base named ${name}.`));
495
+ out2.result("", { name, base: null });
496
+ return;
497
+ }
498
+ out2.step(name, `${base.id} ${base.status}`);
499
+ out2.result("", { name, base: base.id, status: base.status });
500
+ }
501
+ }),
502
+ drop: defineCommand2({
503
+ meta: { name: "drop", description: "Delete the warm base." },
504
+ args: { ...commonArgs, ...nameArg },
505
+ async run({ args }) {
506
+ const { client, out: out2 } = await context(args);
507
+ const name = baseName(str(args.name) ?? "");
508
+ const gone = await drop(client, name, report(out2));
509
+ if (!gone) out2.line(out2.p.dim(`No warm base named ${name}.`));
510
+ out2.result("", { name, deleted: gone });
511
+ }
512
+ })
513
+ }
514
+ });
515
+ function report(out2) {
516
+ return (event) => {
517
+ out2.event({ ...event });
518
+ switch (event.type) {
519
+ case "base.creating":
520
+ out2.step("base", `building ${event.name}`);
521
+ break;
522
+ case "base.created":
523
+ out2.step("base", `${event.sandboxId} in ${duration(event.ms)}`);
524
+ break;
525
+ case "base.setup":
526
+ out2.step("setup", event.command.length > 70 ? `${event.command.slice(0, 70)}\u2026` : event.command);
527
+ break;
528
+ case "base.paused":
529
+ out2.step("paused", duration(event.ms));
530
+ break;
531
+ case "base.found":
532
+ out2.step("base", `${event.sandboxId} ${event.status}`);
533
+ break;
534
+ case "fork.created":
535
+ out2.step("fork", `${event.sandboxId} in ${duration(event.ms)}`);
536
+ break;
537
+ case "job.finished":
538
+ out2.step("job", `exit ${event.exitCode} in ${duration(event.ms)}`);
539
+ break;
540
+ case "base.deleted":
541
+ out2.step("deleted", event.sandboxId);
542
+ break;
543
+ default:
544
+ break;
545
+ }
546
+ };
547
+ }
548
+
549
+ // src/cli/commands/auth.ts
550
+ import { defineCommand as defineCommand3 } from "citty";
551
+ var CONSOLE_KEYS = "https://console.munito.ai/keys";
552
+ var login = defineCommand3({
553
+ meta: { name: "login", description: "Save an API key for this machine." },
554
+ args: {
555
+ ...commonArgs,
556
+ key: { type: "string", description: "The key, when you cannot paste it at a prompt." }
557
+ },
558
+ async run({ args }) {
559
+ const out2 = channel(args);
560
+ const host = resolveHost(args.host ?? args.region);
561
+ let key = args.key?.trim();
562
+ if (!key) {
563
+ if (!process.stdin.isTTY) throw new Error(`No terminal to ask in. Pass --key, or set ${ENV_KEY}.`);
564
+ const clack = await import("@clack/prompts");
565
+ if (out2.mode === "rich") {
566
+ out2.line();
567
+ out2.line(cube(out2.p));
568
+ }
569
+ clack.intro(out2.p.bold("Sign in to Munito AI"));
570
+ clack.note(`Create a key with the Inference permission at
571
+ ${CONSOLE_KEYS}`, "API key");
572
+ const answer = await clack.password({
573
+ message: "Paste your API key",
574
+ validate: (value) => (value ?? "").trim().length < 8 ? "That is too short for a key." : void 0
575
+ });
576
+ if (clack.isCancel(answer)) {
577
+ clack.cancel("Nothing saved.");
578
+ process.exitCode = 1;
579
+ return;
580
+ }
581
+ key = String(answer).trim();
582
+ }
583
+ const probe = new Client({ apiKey: key, baseUrl: host, attempts: 1 });
584
+ await probe.listSandboxes();
585
+ const path = await save(key, host);
586
+ out2.step("saved", `${mask(key)} for ${host}`);
587
+ out2.line(out2.p.dim(` ${path}, readable by you only`));
588
+ out2.result("", { saved: true, host });
589
+ }
590
+ });
591
+ var logout = defineCommand3({
592
+ meta: { name: "logout", description: "Remove the saved API key." },
593
+ args: commonArgs,
594
+ async run({ args }) {
595
+ await clear();
596
+ channel(args).step("removed", authPath());
597
+ }
598
+ });
599
+ var whoami = defineCommand3({
600
+ meta: { name: "whoami", description: "Show which key and host this machine uses." },
601
+ args: commonArgs,
602
+ async run({ args }) {
603
+ const ctx = await context(args);
604
+ const sandboxes = await ctx.client.listSandboxes();
605
+ const running = sandboxes.filter((box) => box.status === "running").length;
606
+ ctx.out.step("host", ctx.host);
607
+ ctx.out.step("key", `${ctx.source}`);
608
+ ctx.out.step("sandboxes", `${running} running, ${sandboxes.length} known`);
609
+ ctx.out.result("", { host: ctx.host, source: ctx.source, running, total: sandboxes.length });
610
+ }
611
+ });
612
+
613
+ // src/cli/commands/herdr.ts
614
+ import { spawn as spawn2, spawnSync } from "child_process";
615
+ import { defineCommand as defineCommand4 } from "citty";
616
+ var herdr = defineCommand4({
617
+ meta: {
618
+ name: "herdr",
619
+ description: "Run coding agents on Munito sandboxes from herdr."
620
+ },
621
+ subCommands: {
622
+ add: defineCommand4({
623
+ meta: { name: "add", description: "Create a sandbox and add it to herdr as a machine." },
624
+ args: {
625
+ ...commonArgs,
626
+ name: { type: "string", description: "The machine name in herdr. The default is the sandbox id." },
627
+ template: { type: "string", description: "A template. The default is the agent one." },
628
+ size: { type: "string", description: "tiny, small, default or large.", default: "default" },
629
+ timeout: { type: "string", description: "Seconds the sandbox may live before it pauses." },
630
+ print: { type: "boolean", description: "Print the herdr command instead of running it." }
631
+ },
632
+ async run({ args }) {
633
+ const { client, out: out2 } = await context(args);
634
+ const box = await client.createSandbox({
635
+ template: args.template || AGENT_TEMPLATE,
636
+ size: args.size || "default",
637
+ internet: true,
638
+ persistent: true,
639
+ timeout: args.timeout ? Number(args.timeout) : 86400,
640
+ metadata: { "munito.cli": "herdr" }
641
+ });
642
+ out2.step("sandbox", `${box.id}, persistent`);
643
+ const access = await client.createSshAccess(box.id);
644
+ const via = `ssh -o StrictHostKeyChecking=accept-new ${access.user}@${access.host}`;
645
+ const name = args.name || box.id;
646
+ out2.step("ssh", `${access.host}, minted`);
647
+ const present = spawnSync("hc", ["--version"], { stdio: "ignore" });
648
+ if (args.print || present.status !== 0) {
649
+ if (present.status !== 0) out2.warn("herdr-core (`hc`) is not on PATH. Run this where it is:");
650
+ out2.line(`hc machine add --name ${name} --install --via '${via}'`);
651
+ out2.result("", { sandbox_id: box.id, machine: name, via });
652
+ return;
653
+ }
654
+ out2.step("herdr", `adding ${name}`);
655
+ const child = spawn2("hc", ["machine", "add", "--name", name, "--install", "--via", via], { stdio: "inherit" });
656
+ const code = await new Promise((done) => child.on("close", (c) => done(c ?? 0)));
657
+ if (code !== 0) {
658
+ out2.error(`hc machine add exited ${code}. The sandbox is ${box.id}.`);
659
+ process.exitCode = code;
660
+ return;
661
+ }
662
+ out2.line();
663
+ out2.step("ready", name);
664
+ out2.line(out2.p.dim(` hc run --bg --on ${name} --cwd /workspace --name agent claude`));
665
+ out2.line(out2.p.dim(` munito pause ${box.id} # keeps the terminal and the conversation`));
666
+ out2.line(out2.p.dim(` the SSH credential expires; run \`munito herdr add\` again for a new machine`));
667
+ out2.result("", { sandbox_id: box.id, machine: name });
668
+ }
669
+ })
670
+ }
671
+ });
672
+
673
+ // src/cli/commands/init.ts
674
+ import { mkdir, writeFile as writeFile2 } from "fs/promises";
675
+ import { homedir } from "os";
676
+ import { dirname } from "path";
677
+ import { defineCommand as defineCommand5 } from "citty";
678
+ var init = defineCommand5({
679
+ meta: {
680
+ name: "init",
681
+ description: "Point a coding agent on this machine at Munito AI."
682
+ },
683
+ args: {
684
+ ...commonArgs,
685
+ agent: { type: "positional", required: true, description: `Which harness: ${AGENTS.join(", ")}.` },
686
+ provider: {
687
+ type: "string",
688
+ description: `Where the model comes from: ${PROVIDERS.join(", ")}.`,
689
+ default: "munito"
690
+ },
691
+ auth: { type: "string", description: "token or subscription.", default: "token" },
692
+ model: { type: "string", description: "A model id, in place of the recommended one." },
693
+ "dry-run": { type: "boolean", description: "Show what would be written, and write nothing." }
694
+ },
695
+ async run({ args }) {
696
+ const name = args.agent;
697
+ if (!AGENTS.includes(name)) throw new Error(`Unknown agent ${name}. One of: ${AGENTS.join(", ")}`);
698
+ const { client, out: out2, host } = await context(args);
699
+ const home = homedir();
700
+ const guide = `https://docs.munito.ai/reference/agents/${name}`;
701
+ const plugin = PLUGINS[name];
702
+ if (plugin) {
703
+ out2.step(name, "installs a Munito AI provider plugin");
704
+ out2.line(`
705
+ ${out2.p.primary(plugin)}
706
+ `);
707
+ out2.line(out2.p.dim(` Then enter your key. See ${guide}`));
708
+ out2.result("", { agent: name, plugin, guide });
709
+ return;
710
+ }
711
+ const wiring = wire(
712
+ name,
713
+ args.provider,
714
+ args.auth,
715
+ {
716
+ host,
717
+ token: client.token,
718
+ model: args.model ?? (name === "claude" ? CLAUDE_MODEL : DEFAULT_MODEL),
719
+ smallModel: DEFAULT_SMALL_MODEL
720
+ },
721
+ process.cwd(),
722
+ home
723
+ );
724
+ for (const file of wiring.files) {
725
+ if (args["dry-run"]) {
726
+ out2.step("would write", file.path);
727
+ continue;
728
+ }
729
+ await mkdir(dirname(file.path), { recursive: true });
730
+ await writeFile2(file.path, file.content, { mode: 384 });
731
+ out2.step("wrote", file.path);
732
+ }
733
+ const exports = Object.entries(wiring.env).filter(([, value]) => value);
734
+ if (exports.length) {
735
+ out2.line();
736
+ out2.line(out2.p.dim(" Add these to your shell:"));
737
+ for (const [key, value] of exports) {
738
+ const shown = key.toLowerCase().includes("token") || key.toLowerCase().includes("key") ? "$MUNITO_API_KEY" : value;
739
+ out2.line(` export ${key}=${shown}`);
740
+ }
741
+ }
742
+ if (wiring.unset.length && !args["dry-run"]) {
743
+ out2.line();
744
+ out2.line(out2.p.dim(` Clear these if your shell sets them: ${wiring.unset.join(", ")}`));
745
+ }
746
+ out2.line();
747
+ if (!PACKAGES[name]) {
748
+ out2.line(out2.p.dim(` Install ${name} itself first. See ${guide}`));
749
+ out2.line();
750
+ }
751
+ out2.step("ready", `run ${out2.p.primary(name)}`);
752
+ out2.result("", { agent: name, files: wiring.files.map((file) => file.path) });
753
+ }
754
+ });
755
+
756
+ // src/cli/commands/mcp.ts
757
+ import { defineCommand as defineCommand6 } from "citty";
758
+ function text(body) {
759
+ return { content: [{ type: "text", text: typeof body === "string" ? body : JSON.stringify(body, null, 2) }] };
760
+ }
761
+ function failed(message) {
762
+ return { ...text(message), isError: true };
763
+ }
764
+ var mcp = defineCommand6({
765
+ meta: {
766
+ name: "mcp",
767
+ description: "Serve the Munito AI tools over MCP on stdio, for a coding agent to call."
768
+ },
769
+ args: commonArgs,
770
+ async run({ args }) {
771
+ const ctx = await context({ ...args, json: true });
772
+ const { client } = ctx;
773
+ const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
774
+ const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
775
+ const { z } = await import("zod");
776
+ const server = new McpServer({ name: "munito", version: "0.1.0" });
777
+ const register = server.registerTool.bind(server);
778
+ register(
779
+ "run_agent",
780
+ {
781
+ title: "Run a coding agent in a sandbox",
782
+ description: "Run a coding agent on a fresh Linux microVM and return its answer and a patch of what it changed. The sandbox is deleted afterwards. Use this to do work in isolation, or to run several agents at once.",
783
+ inputSchema: {
784
+ prompt: z.string().describe("What the agent should do."),
785
+ agent: z.enum(AGENTS).default("claude").describe("Which harness runs the task."),
786
+ provider: z.enum(PROVIDERS).default("munito").describe("Where the model comes from."),
787
+ model: z.string().optional().describe("A model id, in place of the recommended one."),
788
+ files: z.array(z.object({ path: z.string(), content: z.string() })).optional().describe("Files to put in /workspace before the agent starts."),
789
+ max_turns: z.number().int().positive().optional()
790
+ }
791
+ },
792
+ (async ({ prompt, agent: agent2, provider, model, files, max_turns }) => {
793
+ try {
794
+ const run3 = await runAgent(client, {
795
+ agent: agent2,
796
+ prompt,
797
+ provider,
798
+ auth: "token",
799
+ model,
800
+ files,
801
+ maxTurns: max_turns
802
+ });
803
+ return text({
804
+ result: run3.result,
805
+ exit_code: run3.exitCode,
806
+ patch: run3.patch || null,
807
+ sandbox_id: run3.sandboxId,
808
+ duration_ms: run3.durationMs
809
+ });
810
+ } catch (error) {
811
+ return failed(`The agent did not run: ${error.message}`);
812
+ }
813
+ })
814
+ );
815
+ register(
816
+ "run_command",
817
+ {
818
+ title: "Run a command in a sandbox",
819
+ description: "Run one shell command on a fresh Linux microVM and return its output. The sandbox is deleted afterwards. Use this for code you do not trust, or for a build that must start clean.",
820
+ inputSchema: {
821
+ command: z.string().describe("The command, which runs in bash."),
822
+ template: z.string().default("base").describe("base, ubuntu, agent or desktop."),
823
+ internet: z.boolean().default(false).describe("Allow outbound connections."),
824
+ timeout: z.number().int().positive().default(120).describe("Seconds the command may take.")
825
+ }
826
+ },
827
+ (async ({ command, template, internet, timeout }) => {
828
+ let id = "";
829
+ try {
830
+ const box = await client.createSandbox({
831
+ template,
832
+ size: "small",
833
+ internet,
834
+ timeout: Math.max(timeout + 60, 120),
835
+ metadata: { "munito.cli": "mcp" }
836
+ });
837
+ id = box.id;
838
+ const out2 = await client.exec(id, { command, timeout });
839
+ return text({ exit_code: out2.exit_code, stdout: out2.stdout, stderr: out2.stderr });
840
+ } catch (error) {
841
+ return failed(`The command did not run: ${error.message}`);
842
+ } finally {
843
+ if (id) await client.deleteSandbox(id).catch(() => {
844
+ });
845
+ }
846
+ })
847
+ );
848
+ register(
849
+ "list_agents",
850
+ {
851
+ title: "List the coding agents and providers",
852
+ description: "Which harnesses run in a sandbox, and where their model can come from.",
853
+ inputSchema: {}
854
+ },
855
+ (async () => text({ agents: AGENTS, providers: PROVIDERS, host: ctx.host }))
856
+ );
857
+ await server.connect(new StdioServerTransport());
858
+ await new Promise(() => {
859
+ });
860
+ }
861
+ });
862
+
863
+ // src/cli/commands/sandboxes.ts
864
+ import { spawn as spawn3 } from "child_process";
865
+ import { defineCommand as defineCommand7 } from "citty";
866
+
867
+ // src/core/ssh.ts
868
+ var LOOPBACK = "127.0.0.1";
869
+ var PORT = /^[0-9]{1,5}$/;
870
+ var ForwardError = class extends Error {
871
+ };
872
+ function port(value, spec) {
873
+ if (!PORT.test(value) || Number(value) < 1 || Number(value) > 65535) {
874
+ throw new ForwardError(`"${spec}" is not a port forward. Use 3080, 3081:3080, or 3081:127.0.0.1:3080.`);
875
+ }
876
+ return value;
877
+ }
878
+ function forwardSpec(spec) {
879
+ const parts = spec.split(":");
880
+ if (parts.length === 1) {
881
+ const only = port(parts[0], spec);
882
+ return `${only}:${LOOPBACK}:${only}`;
883
+ }
884
+ if (parts.length === 2) {
885
+ return `${port(parts[0], spec)}:${LOOPBACK}:${port(parts[1], spec)}`;
886
+ }
887
+ if (parts.length === 3) {
888
+ if (!parts[1]) throw new ForwardError(`"${spec}" names no host.`);
889
+ return `${port(parts[0], spec)}:${parts[1]}:${port(parts[2], spec)}`;
890
+ }
891
+ throw new ForwardError(`"${spec}" is not a port forward. Use 3080, 3081:3080, or 3081:127.0.0.1:3080.`);
892
+ }
893
+ function sshArgv(user, host, forwards = []) {
894
+ const argv = ["-o", "StrictHostKeyChecking=accept-new"];
895
+ for (const spec of forwards) argv.push("-L", forwardSpec(spec));
896
+ argv.push(`${user}@${host}`);
897
+ return argv;
898
+ }
899
+
900
+ // src/cli/commands/sandboxes.ts
901
+ var ls = defineCommand7({
902
+ meta: { name: "ls", description: "List your sandboxes." },
903
+ args: { ...commonArgs, all: { type: "boolean", alias: "a", description: "Stopped ones too." } },
904
+ async run({ args }) {
905
+ const { client, out: out2 } = await context(args);
906
+ const boxes = await client.listSandboxes();
907
+ const shown = args.all ? boxes : boxes.filter((box) => box.status !== "stopped");
908
+ for (const box of shown) out2.event({ type: "sandbox", ...box });
909
+ if (out2.mode === "json") return;
910
+ if (!shown.length) {
911
+ out2.line(out2.p.dim('No sandboxes. Start one with `munito agent "..."`.'));
912
+ return;
913
+ }
914
+ const rows = [["ID", "STATUS", "TEMPLATE", "SIZE", "AGE"], ...shown.map(row)];
915
+ out2.line(table(rows, out2.p));
916
+ }
917
+ });
918
+ function row(box) {
919
+ const age = box.created_at ? duration(Date.now() - box.created_at * 1e3) : "";
920
+ return [box.id, box.status, box.template, `${box.vcpus}c ${Math.round(box.memory_mib / 1024)}g`, age];
921
+ }
922
+ var run2 = defineCommand7({
923
+ meta: { name: "run", description: "Run one command in a throwaway sandbox." },
924
+ args: {
925
+ ...commonArgs,
926
+ command: { type: "positional", required: true, description: "The command to run." },
927
+ template: { type: "string", description: "A template. The default is base.", default: "base" },
928
+ size: { type: "string", description: "tiny, small, default or large.", default: "small" },
929
+ internet: { type: "boolean", description: "Allow outbound connections." },
930
+ timeout: { type: "string", description: "Seconds the command may take." }
931
+ },
932
+ async run({ args }) {
933
+ const { client, out: out2 } = await context(args);
934
+ const box = await client.createSandbox({
935
+ template: args.template,
936
+ size: args.size,
937
+ internet: Boolean(args.internet),
938
+ timeout: 600,
939
+ metadata: { "munito.cli": "run" }
940
+ });
941
+ try {
942
+ const exit = await stream(client, box.id, args.command, out2, args.timeout);
943
+ if (exit !== 0) process.exitCode = exit;
944
+ } finally {
945
+ await client.deleteSandbox(box.id).catch(() => {
946
+ });
947
+ }
948
+ }
949
+ });
950
+ var exec = defineCommand7({
951
+ meta: { name: "exec", description: "Run a command in a sandbox you already have." },
952
+ args: {
953
+ ...commonArgs,
954
+ id: { type: "positional", required: true, description: "The sandbox id." },
955
+ command: { type: "positional", required: true, description: "The command to run." },
956
+ cwd: { type: "string", description: "The working directory." },
957
+ timeout: { type: "string", description: "Seconds the command may take." }
958
+ },
959
+ async run({ args }) {
960
+ const { client, out: out2 } = await context(args);
961
+ const exit = await stream(client, args.id, args.command, out2, args.timeout, args.cwd);
962
+ if (exit !== 0) process.exitCode = exit;
963
+ }
964
+ });
965
+ async function stream(client, id, command, out2, timeout, cwd) {
966
+ let exit = 0;
967
+ const events = client.execStream(id, {
968
+ command,
969
+ cwd,
970
+ timeout: timeout ? Number(timeout) : void 0
971
+ });
972
+ for await (const event of events) {
973
+ if (event.type === "stdout") out2.raw(event.data);
974
+ else if (event.type === "stderr") out2.raw(event.data, "stderr");
975
+ else exit = event.exit_code;
976
+ out2.event({ ...event });
977
+ }
978
+ return exit;
979
+ }
980
+ var rm2 = defineCommand7({
981
+ meta: { name: "rm", description: "Delete sandboxes." },
982
+ args: { ...commonArgs, ids: { type: "positional", required: true, description: "One or more sandbox ids." } },
983
+ async run({ args, rawArgs }) {
984
+ const { client, out: out2 } = await context(args);
985
+ const ids = rawArgs.filter((value) => value.startsWith("sbx_"));
986
+ for (const id of ids.length ? ids : [args.ids]) {
987
+ await client.deleteSandbox(id);
988
+ out2.step("deleted", id);
989
+ }
990
+ }
991
+ });
992
+ var pause = defineCommand7({
993
+ meta: { name: "pause", description: "Pause a persistent sandbox." },
994
+ args: { ...commonArgs, id: { type: "positional", required: true, description: "The sandbox id." } },
995
+ async run({ args }) {
996
+ const { client, out: out2 } = await context(args);
997
+ const box = await client.pauseSandbox(args.id);
998
+ out2.step("paused", box.id);
999
+ }
1000
+ });
1001
+ var resume = defineCommand7({
1002
+ meta: { name: "resume", description: "Resume a paused sandbox." },
1003
+ args: { ...commonArgs, id: { type: "positional", required: true, description: "The sandbox id." } },
1004
+ async run({ args }) {
1005
+ const { client, out: out2 } = await context(args);
1006
+ const box = await client.resumeSandbox(args.id);
1007
+ out2.step("resumed", box.id);
1008
+ }
1009
+ });
1010
+ var fork = defineCommand7({
1011
+ meta: { name: "fork", description: "Start new sandboxes from a persistent one, as it is now." },
1012
+ args: {
1013
+ ...commonArgs,
1014
+ id: { type: "positional", required: true, description: "The sandbox to fork." },
1015
+ count: { type: "string", description: "How many. The default is 1." }
1016
+ },
1017
+ async run({ args }) {
1018
+ const { client, out: out2 } = await context(args);
1019
+ const count = args.count ? Number(args.count) : 1;
1020
+ const started = Date.now();
1021
+ const answer = await client.forkSandbox(args.id, count);
1022
+ const forks = Array.isArray(answer) ? answer : answer.data ?? [];
1023
+ out2.step("forked", `${forks.length} in ${duration(Date.now() - started)}`);
1024
+ for (const box of forks) out2.line(out2.p.dim(` ${box.id}`));
1025
+ out2.result("", { forks: forks.map((box) => box.id) });
1026
+ }
1027
+ });
1028
+ var ssh = defineCommand7({
1029
+ meta: { name: "ssh", description: "Open a shell in a sandbox." },
1030
+ args: {
1031
+ ...commonArgs,
1032
+ id: { type: "positional", required: true, description: "The sandbox id." },
1033
+ forward: {
1034
+ type: "string",
1035
+ alias: "L",
1036
+ description: "Forward a port: 3080, 3081:3080, or 3081:127.0.0.1:3080. Repeatable."
1037
+ },
1038
+ print: { type: "boolean", description: "Print the command instead of connecting." }
1039
+ },
1040
+ async run({ args }) {
1041
+ const { client, out: out2 } = await context(args);
1042
+ const forwards = [args.forward ?? []].flat().filter(Boolean);
1043
+ const flags = forwards.flatMap((spec) => ["-L", forwardSpec(spec)]);
1044
+ const access = await client.createSshAccess(args.id);
1045
+ if (args.print || !process.stdin.isTTY) {
1046
+ out2.line(flags.length ? access.command.replace(/^ssh /, `ssh ${flags.join(" ")} `) : access.command);
1047
+ return;
1048
+ }
1049
+ for (const spec of forwards) out2.step("forwarding", forwardSpec(spec));
1050
+ out2.step("connecting", access.host);
1051
+ const child = spawn3("ssh", sshArgv(access.user, access.host, forwards), {
1052
+ stdio: "inherit"
1053
+ });
1054
+ await new Promise(
1055
+ (done) => child.on("close", (code) => {
1056
+ process.exitCode = code ?? 0;
1057
+ done();
1058
+ })
1059
+ );
1060
+ }
1061
+ });
1062
+ var open = defineCommand7({
1063
+ meta: { name: "open", description: "Open a sandbox port, or its desktop, in your browser." },
1064
+ args: {
1065
+ ...commonArgs,
1066
+ id: { type: "positional", required: true, description: "The sandbox id." },
1067
+ port: { type: "string", description: `The port. The default is the desktop, ${DESKTOP_PORT}.` },
1068
+ expires: { type: "string", description: "Seconds the link stays valid. The default is 3600." },
1069
+ print: { type: "boolean", description: "Print the URL instead of opening it." }
1070
+ },
1071
+ async run({ args }) {
1072
+ const { client, out: out2 } = await context(args);
1073
+ const port2 = args.port ? Number(args.port) : DESKTOP_PORT;
1074
+ const signed = await client.signPortUrl(args.id, port2, args.expires ? Number(args.expires) : 3600);
1075
+ out2.event({ type: "url", url: signed.url, port: port2 });
1076
+ if (args.print || out2.mode === "json" || !process.stdout.isTTY) {
1077
+ out2.line(signed.url);
1078
+ return;
1079
+ }
1080
+ out2.step("opening", `port ${port2}`);
1081
+ out2.line(out2.p.dim(` ${signed.url}`));
1082
+ openInBrowser(signed.url);
1083
+ }
1084
+ });
1085
+ var create = defineCommand7({
1086
+ meta: { name: "create", description: "Create a sandbox and leave it running." },
1087
+ args: {
1088
+ ...commonArgs,
1089
+ template: { type: "string", description: "base, ubuntu, agent or desktop.", default: AGENT_TEMPLATE },
1090
+ agent: { type: "string", description: `Point one harness at a provider: ${AGENTS.join(", ")}.` },
1091
+ provider: { type: "string", description: `Where the model comes from: ${PROVIDERS.join(", ")}.` },
1092
+ auth: { type: "string", description: "token or subscription." },
1093
+ model: { type: "string", description: "A model id, in place of the recommended one." },
1094
+ size: { type: "string", description: "tiny, small, default or large.", default: "default" },
1095
+ internet: { type: "boolean", description: "Allow outbound connections.", default: true },
1096
+ persistent: { type: "boolean", description: "Keep files and processes across a pause." },
1097
+ timeout: { type: "string", description: "Seconds the sandbox may live." }
1098
+ },
1099
+ async run({ args }) {
1100
+ const { client, out: out2 } = await context(args);
1101
+ const common = {
1102
+ template: args.template,
1103
+ size: args.size,
1104
+ internet: Boolean(args.internet),
1105
+ persistent: Boolean(args.persistent),
1106
+ timeout: args.timeout ? Number(args.timeout) : void 0
1107
+ };
1108
+ const box = args.agent ? await createAgentSandbox(client, {
1109
+ ...common,
1110
+ agent: args.agent,
1111
+ provider: args.provider,
1112
+ auth: args.auth,
1113
+ model: args.model,
1114
+ metadata: { "munito.cli": "create", "munito.agent": args.agent }
1115
+ }) : await client.createSandbox({ ...common, metadata: { "munito.cli": "create" } });
1116
+ out2.step("created", box.id);
1117
+ out2.line(out2.p.dim(` munito ssh ${box.id}`));
1118
+ out2.result("", { sandbox_id: box.id });
1119
+ }
1120
+ });
1121
+
1122
+ // src/cli/main.ts
1123
+ var VERSION = true ? "0.1.0" : "0.0.0-dev";
1124
+ var main = defineCommand8({
1125
+ meta: {
1126
+ name: "munito",
1127
+ // Without this, `munito --version` exits with "No version specified".
1128
+ version: VERSION,
1129
+ description: "Run coding agents on European infrastructure, one command at a time."
1130
+ },
1131
+ subCommands: {
1132
+ agent,
1133
+ ci,
1134
+ herdr,
1135
+ init,
1136
+ mcp,
1137
+ login,
1138
+ logout,
1139
+ whoami,
1140
+ ls,
1141
+ create,
1142
+ run: run2,
1143
+ exec,
1144
+ ssh,
1145
+ open,
1146
+ rm: rm2,
1147
+ pause,
1148
+ resume,
1149
+ fork
1150
+ }
1151
+ });
1152
+
1153
+ // src/cli.ts
1154
+ var CONSOLE_BILLING = "https://console.munito.ai/billing";
1155
+ function report2(error) {
1156
+ const channel2 = out(false);
1157
+ if (error instanceof MissingKeyError) {
1158
+ channel2.error(error.message);
1159
+ return 2;
1160
+ }
1161
+ if (error instanceof WiringError || error instanceof WorkspaceError) {
1162
+ channel2.error(error.message);
1163
+ return 2;
1164
+ }
1165
+ if (error instanceof ApiError) {
1166
+ channel2.error(error.message);
1167
+ if (error.status === 401) channel2.line(channel2.p.dim(" The key is not valid here. Run `munito login`."));
1168
+ if (error.status === 402) channel2.line(channel2.p.dim(` Check your plan and credits at ${CONSOLE_BILLING}`));
1169
+ if (error.status === 429) channel2.line(channel2.p.dim(" Too many at once. Wait, or ask for a larger plan."));
1170
+ if (error.requestId) channel2.line(channel2.p.dim(` request ${error.requestId}`));
1171
+ return error.status === 401 || error.status === 402 ? 2 : 1;
1172
+ }
1173
+ channel2.error(error instanceof Error ? error.message : String(error));
1174
+ return 1;
1175
+ }
1176
+ process.on("unhandledRejection", (reason) => {
1177
+ process.exit(report2(reason));
1178
+ });
1179
+ await runMain(main).catch((error) => {
1180
+ process.exit(report2(error));
1181
+ });
1182
+ //# sourceMappingURL=cli.js.map