@munitoai/cli 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,6 +48,16 @@ munito fork <id> --count 8 # eight copies of a paused sandbox
48
48
  munito rm <id>
49
49
  ```
50
50
 
51
+ ## Your own image
52
+
53
+ ```bash
54
+ munito templates deploy acme-agent ghcr.io/acme/agent:1.4 --wait # build it into a template
55
+ munito create --template acme-agent # a sandbox with its files
56
+ ```
57
+
58
+ For a private registry, add `--username` and pipe the token to `--password-stdin`, or set
59
+ `MUNITO_REGISTRY_TOKEN`. See [Custom templates](https://docs.munito.ai/sandboxes/custom-templates).
60
+
51
61
  ## As an SDK
52
62
 
53
63
  The package is the library as well as the binary.
@@ -1,5 +1,5 @@
1
1
  /** The HTTP client of the Sandboxes API. No terminal output: every failure is an ApiError. */
2
- import type { CommandEvent, CommandResult, CreateSandbox, ExecCommand, PortUrl, Sandbox, SshAccess } from "./types.ts";
2
+ import type { CommandEvent, CommandResult, CreateSandbox, DeployTemplate, ExecCommand, FileEntry, PortUrl, Sandbox, SandboxCommand, SshAccess, Template } from "./types.ts";
3
3
  export declare const DEFAULT_BASE_URL = "https://api.munito.ai";
4
4
  export declare const REGIONS: Record<string, string>;
5
5
  export declare class ApiError extends Error {
@@ -33,25 +33,42 @@ export declare class Client {
33
33
  get token(): string;
34
34
  private headers;
35
35
  private raw;
36
- request<T>(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<T>;
37
- createSandbox(spec: CreateSandbox, signal?: AbortSignal): Promise<Sandbox>;
36
+ request<T>(method: string, path: string, body?: unknown, signal?: AbortSignal, headers?: Record<string, string>): Promise<T>;
37
+ createSandbox(spec: CreateSandbox, signal?: AbortSignal, idempotencyKey?: string): Promise<Sandbox>;
38
38
  getSandbox(id: string): Promise<Sandbox>;
39
39
  listSandboxes(): Promise<Sandbox[]>;
40
40
  deleteSandbox(id: string): Promise<void>;
41
41
  pauseSandbox(id: string): Promise<Sandbox>;
42
42
  resumeSandbox(id: string): Promise<Sandbox>;
43
+ setSandboxTimeout(id: string, timeout: number): Promise<Sandbox>;
43
44
  forkSandbox(id: string, count?: number): Promise<{
44
45
  data?: Sandbox[];
45
46
  } | Sandbox[]>;
46
47
  exec(id: string, spec: ExecCommand, signal?: AbortSignal): Promise<CommandResult>;
47
48
  /** The same command, as the events arrive. The last event is always `exit`. */
48
49
  execStream(id: string, spec: ExecCommand, signal?: AbortSignal): AsyncGenerator<CommandEvent>;
50
+ startCommand(id: string, spec: Omit<ExecCommand, "stream">): Promise<SandboxCommand>;
51
+ getCommand(id: string, commandId: string, stdout?: number, stderr?: number): Promise<SandboxCommand>;
52
+ listCommands(id: string): Promise<SandboxCommand[]>;
53
+ signalCommand(id: string, commandId: string, signal?: number): Promise<SandboxCommand>;
54
+ deleteCommand(id: string, commandId: string): Promise<void>;
55
+ listFiles(id: string, path?: string): Promise<FileEntry[]>;
56
+ deleteFile(id: string, path: string, recursive?: boolean): Promise<void>;
57
+ readFileBytes(id: string, path: string): Promise<Uint8Array>;
49
58
  readFile(id: string, path: string): Promise<string>;
50
- writeFile(id: string, path: string, content: string): Promise<void>;
59
+ writeFile(id: string, path: string, content: string | Uint8Array): Promise<void>;
51
60
  signPortUrl(id: string, port: number, expiresIn?: number): Promise<PortUrl>;
52
61
  setPort(id: string, port: number, isPublic: boolean): Promise<unknown>;
53
62
  createSshAccess(id: string): Promise<SshAccess>;
54
63
  getSsh(id: string): Promise<SshAccess>;
64
+ /** Build an image into a template. The answer comes at once, with the build in `build`. */
65
+ deployTemplate(spec: DeployTemplate, signal?: AbortSignal): Promise<Template>;
66
+ /** The custom templates of the key's workspace, by name. */
67
+ listTemplates(): Promise<Template[]>;
68
+ /** One template, by its name or its id. */
69
+ getTemplate(ref: string, signal?: AbortSignal): Promise<Template>;
70
+ /** Delete a template and its versions. Its running sandboxes keep running. */
71
+ deleteTemplate(ref: string): Promise<void>;
55
72
  }
56
73
  /** Each complete line of an NDJSON body, parsed. A half line at the end is dropped. */
57
74
  export declare function ndjson(body: ReadableStream<Uint8Array>): AsyncGenerator<unknown>;
@@ -0,0 +1,51 @@
1
+ import type { Client } from "./client.ts";
2
+ export type TrainingRun = {
3
+ id: string;
4
+ name: string;
5
+ sandbox_id: string;
6
+ command_id: string;
7
+ status: "running" | "succeeded" | "failed" | "cancelled" | "interrupted";
8
+ cancel_requested: boolean;
9
+ created_at: number;
10
+ updated_at: number;
11
+ started_at: number | null;
12
+ ended_at: number | null;
13
+ exit_code: number | null;
14
+ timed_out: boolean;
15
+ gpu_type: string;
16
+ gpu_count: number;
17
+ vcpus: number;
18
+ memory_mib: number;
19
+ stdout: string;
20
+ stderr: string;
21
+ truncated: boolean;
22
+ observation_error: boolean;
23
+ metrics: {
24
+ step: number;
25
+ values: Record<string, number>;
26
+ }[];
27
+ artifacts: {
28
+ path: string;
29
+ bytes: number;
30
+ sha256: string;
31
+ }[];
32
+ };
33
+ /** Internal preview. Artifact metadata describes files exported to the SDK client. */
34
+ export declare function training(client: Client): {
35
+ list: (options?: {
36
+ limit?: number;
37
+ after?: string;
38
+ }) => Promise<{
39
+ data: TrainingRun[];
40
+ has_more: boolean;
41
+ }>;
42
+ create: (body: {
43
+ name: string;
44
+ sandbox_id: string;
45
+ command_id: string;
46
+ }) => Promise<TrainingRun>;
47
+ get: (id: string) => Promise<TrainingRun>;
48
+ cancel: (id: string) => Promise<TrainingRun>;
49
+ artifacts: (id: string, artifacts: TrainingRun["artifacts"]) => Promise<TrainingRun>;
50
+ delete: (id: string) => Promise<void>;
51
+ };
@@ -1,5 +1,10 @@
1
1
  /** The shapes of the Sandboxes API that this package uses. A generated client replaces this file. */
2
- export type SandboxStatus = "pending" | "running" | "paused" | "stopped";
2
+ export type SandboxStatus = "pending" | "running" | "paused" | "stopped" | "failed";
3
+ export interface Gpu {
4
+ type: "L4";
5
+ /** Whole devices on one host. The API accepts 1 through 8. */
6
+ count?: number;
7
+ }
3
8
  export interface Sandbox {
4
9
  id: string;
5
10
  status: SandboxStatus;
@@ -7,6 +12,7 @@ export interface Sandbox {
7
12
  vcpus: number;
8
13
  memory_mib: number;
9
14
  disk_gib?: number;
15
+ gpu?: Gpu;
10
16
  internet: boolean;
11
17
  persistent?: boolean;
12
18
  metadata?: Record<string, string>;
@@ -44,6 +50,8 @@ export interface CreateSandbox {
44
50
  vcpus?: number;
45
51
  memory_mib?: number;
46
52
  disk_gib?: number;
53
+ /** GPU access requires an internal organization. */
54
+ gpu?: Gpu | null;
47
55
  internet?: boolean;
48
56
  persistent?: boolean;
49
57
  timeout?: number;
@@ -63,6 +71,30 @@ export interface ExecCommand {
63
71
  env?: Record<string, string>;
64
72
  timeout?: number;
65
73
  stream?: boolean;
74
+ stdin?: string;
75
+ }
76
+ export interface SandboxCommand {
77
+ id: string;
78
+ command: string[];
79
+ cwd: string;
80
+ status: "running" | "exited" | "failed";
81
+ started_at: number;
82
+ ended_at?: number | null;
83
+ exit_code?: number | null;
84
+ timed_out: boolean;
85
+ stdout: string;
86
+ stderr: string;
87
+ stdout_bytes: number;
88
+ stderr_bytes: number;
89
+ truncated: boolean;
90
+ }
91
+ export interface FileEntry {
92
+ name: string;
93
+ path: string;
94
+ type: "file" | "directory" | "symlink" | "other";
95
+ size: number;
96
+ mode: number;
97
+ modified_at: number;
66
98
  }
67
99
  export interface SshAccess {
68
100
  command: string;
@@ -76,3 +108,51 @@ export interface PortUrl {
76
108
  url: string;
77
109
  expires_at?: number;
78
110
  }
111
+ export type TemplateStatus = "building" | "ready" | "failed";
112
+ /** The newest version of a custom template, which can still build. */
113
+ export interface TemplateBuild {
114
+ version: number;
115
+ image: string;
116
+ status: TemplateStatus;
117
+ /** The digest of the image's manifest, once the build read it. */
118
+ digest?: string | null;
119
+ /** Why the build failed. */
120
+ error?: {
121
+ code: string;
122
+ message: string;
123
+ } | null;
124
+ /** The end of the build's output, when it failed. */
125
+ log?: string;
126
+ /** Unix seconds. */
127
+ started_at: number;
128
+ ended_at?: number | null;
129
+ }
130
+ /** A container image that a workspace deployed as a template. `version` is the one that new sandboxes start from. */
131
+ export interface Template {
132
+ id: string;
133
+ object?: "template";
134
+ name: string;
135
+ /** `ready` once a version starts sandboxes, `building` before, and `failed` when no version ever built. */
136
+ status: TemplateStatus;
137
+ version?: number | null;
138
+ image?: string | null;
139
+ digest?: string | null;
140
+ /** The bytes of the image's files. */
141
+ size_bytes?: number | null;
142
+ build: TemplateBuild;
143
+ created_at: number;
144
+ updated_at: number;
145
+ }
146
+ /** The credential of a private registry. The build uses it once, and no answer returns it. */
147
+ export interface RegistryAuth {
148
+ username: string;
149
+ /** A password, or an access token of the registry. */
150
+ password: string;
151
+ }
152
+ export interface DeployTemplate {
153
+ /** A DNS label that no built-in template has. A name that exists gets a new version. */
154
+ name: string;
155
+ /** An image with a tag or a digest, for linux/amd64, such as `ghcr.io/acme/agent:1.4`. */
156
+ image: string;
157
+ registry_auth?: RegistryAuth;
158
+ }
@@ -59,37 +59,56 @@ var Client = class {
59
59
  headers() {
60
60
  return { authorization: `Bearer ${this.apiKey}`, "content-type": "application/json" };
61
61
  }
62
- async raw(method, path, body, signal) {
62
+ async raw(method, path, body, signal, headers = {}) {
63
63
  let last;
64
- for (let attempt = 1; attempt <= this.attempts; attempt++) {
64
+ const replayable = ["GET", "HEAD", "PUT", "DELETE"].includes(method) || method === "POST" && path === `${SANDBOXES}/sandboxes` && Boolean(headers["idempotency-key"]);
65
+ const attempts = replayable ? this.attempts : 1;
66
+ for (let attempt = 1; attempt <= attempts; attempt++) {
65
67
  const response = await this.doFetch(`${this.baseUrl}${path}`, {
66
68
  method,
67
- headers: this.headers(),
69
+ headers: { ...this.headers(), ...headers },
68
70
  body: body === void 0 ? void 0 : JSON.stringify(body),
69
71
  signal
70
72
  });
71
73
  if (response.ok) return response;
72
74
  last = await toError(response);
73
- if (!last.retryable || attempt === this.attempts) throw last;
75
+ if (!last.retryable || attempt === attempts) throw last;
74
76
  await sleep(250 * 2 ** (attempt - 1));
75
77
  }
76
78
  throw last ?? new ApiError(0, "unknown", "The request failed.");
77
79
  }
78
- async request(method, path, body, signal) {
79
- const response = await this.raw(method, path, body, signal);
80
+ async request(method, path, body, signal, headers = {}) {
81
+ const response = await this.raw(method, path, body, signal, headers);
80
82
  const text = await response.text();
81
83
  return text ? JSON.parse(text) : {};
82
84
  }
83
85
  // Sandboxes.
84
- createSandbox(spec, signal) {
85
- return this.request("POST", `${SANDBOXES}/sandboxes`, spec, signal);
86
+ createSandbox(spec, signal, idempotencyKey) {
87
+ return this.request(
88
+ "POST",
89
+ `${SANDBOXES}/sandboxes`,
90
+ spec,
91
+ signal,
92
+ idempotencyKey ? { "idempotency-key": idempotencyKey } : {}
93
+ );
86
94
  }
87
95
  getSandbox(id) {
88
96
  return this.request("GET", `${SANDBOXES}/sandboxes/${id}`);
89
97
  }
90
98
  async listSandboxes() {
91
- const page = await this.request("GET", `${SANDBOXES}/sandboxes`);
92
- return Array.isArray(page) ? page : page.data ?? [];
99
+ const rows = [];
100
+ const query = new URLSearchParams({ limit: "100" });
101
+ while (true) {
102
+ const page = await this.request(
103
+ "GET",
104
+ `${SANDBOXES}/sandboxes?${query}`
105
+ );
106
+ if (Array.isArray(page)) return [...rows, ...page];
107
+ rows.push(...page.data ?? []);
108
+ if (!page.has_more) return rows;
109
+ if (!page.data?.length) throw new ApiError(0, "invalid_page", "The sandbox list has no next cursor.");
110
+ query.set("after", page.data[page.data.length - 1].id);
111
+ }
93
112
  }
94
113
  deleteSandbox(id) {
95
114
  return this.request("DELETE", `${SANDBOXES}/sandboxes/${id}`);
@@ -100,6 +119,9 @@ var Client = class {
100
119
  resumeSandbox(id) {
101
120
  return this.request("POST", `${SANDBOXES}/sandboxes/${id}/resume`);
102
121
  }
122
+ setSandboxTimeout(id, timeout) {
123
+ return this.request("POST", `${SANDBOXES}/sandboxes/${id}/timeout`, { timeout });
124
+ }
103
125
  forkSandbox(id, count = 1) {
104
126
  return this.request("POST", `${SANDBOXES}/sandboxes/${id}/fork`, { count });
105
127
  }
@@ -111,9 +133,49 @@ var Client = class {
111
133
  async *execStream(id, spec, signal) {
112
134
  const response = await this.raw("POST", `${SANDBOXES}/sandboxes/${id}/exec`, { ...spec, stream: true }, signal);
113
135
  if (!response.body) throw new ApiError(0, "no_body", "The API sent no stream.");
114
- for await (const line of ndjson(response.body)) yield line;
136
+ let ended = false;
137
+ for await (const line of ndjson(response.body)) {
138
+ const event = line;
139
+ if (event.type === "error") throw new ApiError(0, event.error.code, event.error.message);
140
+ ended ||= event.type === "exit";
141
+ yield event;
142
+ }
143
+ if (!ended) throw new ApiError(0, "incomplete_stream", "The command stream ended without an exit event.");
144
+ }
145
+ startCommand(id, spec) {
146
+ return this.request("POST", `${SANDBOXES}/sandboxes/${id}/commands`, spec);
147
+ }
148
+ getCommand(id, commandId, stdout = 0, stderr = 0) {
149
+ const query = new URLSearchParams({ stdout: String(stdout), stderr: String(stderr) });
150
+ return this.request("GET", `${SANDBOXES}/sandboxes/${id}/commands/${encodeURIComponent(commandId)}?${query}`);
151
+ }
152
+ async listCommands(id) {
153
+ const page = await this.request("GET", `${SANDBOXES}/sandboxes/${id}/commands`);
154
+ return page.data;
155
+ }
156
+ signalCommand(id, commandId, signal = 15) {
157
+ return this.request("POST", `${SANDBOXES}/sandboxes/${id}/commands/${encodeURIComponent(commandId)}/signal`, {
158
+ signal
159
+ });
160
+ }
161
+ deleteCommand(id, commandId) {
162
+ return this.request("DELETE", `${SANDBOXES}/sandboxes/${id}/commands/${encodeURIComponent(commandId)}`);
115
163
  }
116
164
  // Files.
165
+ async listFiles(id, path = "/workspace") {
166
+ const query = new URLSearchParams({ path });
167
+ const page = await this.request("GET", `${SANDBOXES}/sandboxes/${id}/files?${query}`);
168
+ return page.data;
169
+ }
170
+ deleteFile(id, path, recursive = false) {
171
+ const query = new URLSearchParams({ path, recursive: String(recursive) });
172
+ return this.request("DELETE", `${SANDBOXES}/sandboxes/${id}/files?${query}`);
173
+ }
174
+ async readFileBytes(id, path) {
175
+ const query = new URLSearchParams({ path });
176
+ const response = await this.raw("GET", `${SANDBOXES}/sandboxes/${id}/files/content?${query}`);
177
+ return new Uint8Array(await response.arrayBuffer());
178
+ }
117
179
  async readFile(id, path) {
118
180
  const query = new URLSearchParams({ path });
119
181
  const response = await this.raw("GET", `${SANDBOXES}/sandboxes/${id}/files/content?${query}`);
@@ -124,7 +186,7 @@ var Client = class {
124
186
  const response = await this.doFetch(`${this.baseUrl}${SANDBOXES}/sandboxes/${id}/files/content?${query}`, {
125
187
  method: "PUT",
126
188
  headers: { authorization: `Bearer ${this.apiKey}`, "content-type": "application/octet-stream" },
127
- body: content
189
+ body: typeof content === "string" ? content : new Uint8Array(content).buffer
128
190
  });
129
191
  if (!response.ok) throw await toError(response);
130
192
  }
@@ -141,9 +203,27 @@ var Client = class {
141
203
  getSsh(id) {
142
204
  return this.request("GET", `${SANDBOXES}/sandboxes/${id}/ssh`);
143
205
  }
206
+ // Custom templates. A deploy is never sent twice: each one makes a new version.
207
+ /** Build an image into a template. The answer comes at once, with the build in `build`. */
208
+ deployTemplate(spec, signal) {
209
+ return this.request("POST", `${SANDBOXES}/templates`, spec, signal);
210
+ }
211
+ /** The custom templates of the key's workspace, by name. */
212
+ async listTemplates() {
213
+ const page = await this.request("GET", `${SANDBOXES}/templates`);
214
+ return page.data ?? [];
215
+ }
216
+ /** One template, by its name or its id. */
217
+ getTemplate(ref, signal) {
218
+ return this.request("GET", `${SANDBOXES}/templates/${encodeURIComponent(ref)}`, void 0, signal);
219
+ }
220
+ /** Delete a template and its versions. Its running sandboxes keep running. */
221
+ deleteTemplate(ref) {
222
+ return this.request("DELETE", `${SANDBOXES}/templates/${encodeURIComponent(ref)}`);
223
+ }
144
224
  };
145
225
  async function toError(response) {
146
- const requestId = response.headers.get("munito-request-id") ?? void 0;
226
+ const requestId = response.headers.get("x-request-id") ?? void 0;
147
227
  const text = await response.text().catch(() => "");
148
228
  try {
149
229
  const body = JSON.parse(text);
@@ -330,7 +410,7 @@ function munito(agent, target, workdir, home) {
330
410
  return {
331
411
  env: { MUNITO_API_KEY: target.token },
332
412
  unset: [],
333
- files: [{ path: `${home}/.dsh/profiles/headless/cordis.patch.yml`, content: dshYaml(openai, target.model) }]
413
+ files: [{ path: `${home}/.dsh/cordis.patch.yml`, content: dshYaml(openai, target.model) }]
334
414
  };
335
415
  case "prime":
336
416
  return {
@@ -488,6 +568,54 @@ function shellArgv(agent) {
488
568
  return [agent];
489
569
  }
490
570
 
571
+ // src/core/templates.ts
572
+ var ENV_REGISTRY_TOKEN = "MUNITO_REGISTRY_TOKEN";
573
+ var POLL_MS = 5e3;
574
+ var WAIT_MS = 25 * 6e4;
575
+ var TemplateError = class extends Error {
576
+ };
577
+ function registryAuth(options) {
578
+ const username = options.username?.trim() ?? "";
579
+ const token = options.stdin !== void 0 ? options.stdin.replace(/\r?\n$/, "") : options.env ?? "";
580
+ if (!username) {
581
+ if (options.stdin !== void 0) throw new TemplateError("Set --username with --password-stdin.");
582
+ return { ignored: Boolean(options.env) };
583
+ }
584
+ if (!token) {
585
+ throw new TemplateError(
586
+ `Give the registry token on standard input with --password-stdin, or in ${ENV_REGISTRY_TOKEN}.`
587
+ );
588
+ }
589
+ return { auth: { username, password: token }, ignored: false };
590
+ }
591
+ function deployBody(name, image, auth) {
592
+ const body = { name: name.trim(), image: image.trim() };
593
+ if (!body.name) throw new TemplateError("Give the template a name, such as acme-agent.");
594
+ if (!body.image) throw new TemplateError("Give the image to deploy, such as ghcr.io/acme/agent:1.4.");
595
+ return auth ? { ...body, registry_auth: auth } : body;
596
+ }
597
+ async function waitForBuild(client, ref, options = {}) {
598
+ const now = options.now ?? Date.now;
599
+ const sleep2 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
600
+ const deadline = now() + (options.timeoutMs ?? WAIT_MS);
601
+ let seen = "";
602
+ while (true) {
603
+ const template = await client.getTemplate(ref, options.signal);
604
+ const { build } = template;
605
+ const mark = `${build.version} ${build.status}`;
606
+ if (mark !== seen) {
607
+ seen = mark;
608
+ options.onEvent?.({ type: "template.build", name: template.name, version: build.version, status: build.status });
609
+ }
610
+ if (build.status !== "building") return template;
611
+ if (now() >= deadline) {
612
+ throw new Error(`The build of ${template.name} did not end in time. Read it again with munito templates get.`);
613
+ }
614
+ options.signal?.throwIfAborted();
615
+ await sleep2(options.intervalMs ?? POLL_MS);
616
+ }
617
+ }
618
+
491
619
  // src/core/agents.ts
492
620
  var AGENT_TEMPLATE = "agent";
493
621
  var AGENT_TEMPLATE_FALLBACK = "ubuntu";
@@ -841,6 +969,11 @@ export {
841
969
  wire,
842
970
  headlessArgv,
843
971
  shellArgv,
972
+ ENV_REGISTRY_TOKEN,
973
+ TemplateError,
974
+ registryAuth,
975
+ deployBody,
976
+ waitForBuild,
844
977
  AGENT_TEMPLATE,
845
978
  WORKDIR,
846
979
  runAgent,
@@ -853,4 +986,4 @@ export {
853
986
  job,
854
987
  drop
855
988
  };
856
- //# sourceMappingURL=chunk-WSY6HMNS.js.map
989
+ //# sourceMappingURL=chunk-EZEXBJTZ.js.map