@munitoai/cli 0.3.0 → 0.4.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.
@@ -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, DeployTemplate, ExecCommand, FileEntry, PortUrl, Sandbox, SandboxCommand, SshAccess, Template } from "./types.ts";
2
+ import type { CommandEvent, CommandResult, CreateProxy, CreateSandbox, DeployTemplate, ExecCommand, FileEntry, OpenProxyPort, PortUrl, Proxy, ProxyPort, 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 {
@@ -69,6 +69,15 @@ export declare class Client {
69
69
  getTemplate(ref: string, signal?: AbortSignal): Promise<Template>;
70
70
  /** Delete a template and its versions. Its running sandboxes keep running. */
71
71
  deleteTemplate(ref: string): Promise<void>;
72
+ createProxy(spec: CreateProxy): Promise<Proxy>;
73
+ /** The proxies of the key's workspace, each with its addresses and its open ports. */
74
+ listProxies(): Promise<Proxy[]>;
75
+ getProxy(id: string): Promise<Proxy>;
76
+ /** Delete a proxy that no running or paused sandbox uses. */
77
+ deleteProxy(id: string): Promise<void>;
78
+ /** Let the internet reach one port of a sandbox of the proxy. The same port again answers the open port. */
79
+ openProxyPort(id: string, spec: OpenProxyPort): Promise<ProxyPort>;
80
+ closeProxyPort(id: string, portId: string): Promise<void>;
72
81
  }
73
82
  /** Each complete line of an NDJSON body, parsed. A half line at the end is dropped. */
74
83
  export declare function ndjson(body: ReadableStream<Uint8Array>): AsyncGenerator<unknown>;
@@ -22,6 +22,14 @@ export interface Sandbox {
22
22
  ended_at?: number;
23
23
  end_reason?: string;
24
24
  command?: CommandResult;
25
+ /** The proxy of the sandbox, when it has one. */
26
+ proxy?: SandboxProxy;
27
+ }
28
+ /** The proxy of a sandbox, and the public IPv6 address that the sandbox holds while it runs. */
29
+ export interface SandboxProxy {
30
+ id: string;
31
+ name: string;
32
+ ipv6?: string | null;
25
33
  }
26
34
  export interface CommandResult {
27
35
  exit_code: number;
@@ -64,6 +72,8 @@ export interface CreateSandbox {
64
72
  provider?: string;
65
73
  auth?: string;
66
74
  model?: string;
75
+ /** The id of a proxy: the sandbox gets its fixed public addresses, and internet access. */
76
+ proxy?: string;
67
77
  }
68
78
  export interface ExecCommand {
69
79
  command: string | string[];
@@ -149,6 +159,48 @@ export interface RegistryAuth {
149
159
  /** A password, or an access token of the registry. */
150
160
  password: string;
151
161
  }
162
+ /** One open port of a proxy. Over IPv4, `public_port` of each address of the proxy goes to `port` of the sandbox.
163
+ * Over IPv6, `port` opens on the address of the sandbox. */
164
+ export interface ProxyPort {
165
+ id: string;
166
+ object?: "proxy.port";
167
+ sandbox_id: string;
168
+ protocol: "tcp" | "udp";
169
+ port: number;
170
+ public_port: number;
171
+ /** Unix seconds. */
172
+ created_at: number;
173
+ }
174
+ /** Fixed public addresses for the sandboxes of a workspace. A preview, on for an organization with its switch. */
175
+ export interface Proxy {
176
+ id: string;
177
+ object?: "proxy";
178
+ name: string;
179
+ /** A sandbox leaves from one of the addresses, and an open port answers on each of them. */
180
+ ipv4: {
181
+ mode: "shared" | "dedicated";
182
+ addresses: string[];
183
+ };
184
+ /** The block of the IPv6 addresses of its sandboxes, or null while it has none. */
185
+ ipv6?: string | null;
186
+ ports: ProxyPort[];
187
+ /** Unix seconds. */
188
+ created_at: number;
189
+ }
190
+ export interface CreateProxy {
191
+ /** A DNS label, unique in the workspace. */
192
+ name: string;
193
+ /** `shared`, the default, or `dedicated` for IPv4 addresses that no other customer uses. */
194
+ ipv4?: "shared" | "dedicated";
195
+ }
196
+ export interface OpenProxyPort {
197
+ /** A sandbox of the proxy that runs or is paused. */
198
+ sandbox_id: string;
199
+ port: number;
200
+ protocol?: "tcp" | "udp";
201
+ /** Only a dedicated proxy takes one. Its default is `port`. */
202
+ public_port?: number;
203
+ }
152
204
  export interface DeployTemplate {
153
205
  /** A DNS label that no built-in template has. A name that exists gets a new version. */
154
206
  name: string;
@@ -221,7 +221,40 @@ var Client = class {
221
221
  deleteTemplate(ref) {
222
222
  return this.request("DELETE", `${SANDBOXES}/templates/${encodeURIComponent(ref)}`);
223
223
  }
224
+ // Proxies: fixed public addresses. A preview, so an organization without its switch gets a 404.
225
+ createProxy(spec) {
226
+ return withPreview(this.request("POST", `${SANDBOXES}/proxies`, spec));
227
+ }
228
+ /** The proxies of the key's workspace, each with its addresses and its open ports. */
229
+ async listProxies() {
230
+ const page = await withPreview(this.request("GET", `${SANDBOXES}/proxies`));
231
+ return page.data ?? [];
232
+ }
233
+ getProxy(id) {
234
+ return this.request("GET", `${SANDBOXES}/proxies/${encodeURIComponent(id)}`);
235
+ }
236
+ /** Delete a proxy that no running or paused sandbox uses. */
237
+ deleteProxy(id) {
238
+ return this.request("DELETE", `${SANDBOXES}/proxies/${encodeURIComponent(id)}`);
239
+ }
240
+ /** Let the internet reach one port of a sandbox of the proxy. The same port again answers the open port. */
241
+ openProxyPort(id, spec) {
242
+ return this.request("POST", `${SANDBOXES}/proxies/${encodeURIComponent(id)}/ports`, spec);
243
+ }
244
+ closeProxyPort(id, portId) {
245
+ const path = `${SANDBOXES}/proxies/${encodeURIComponent(id)}/ports/${encodeURIComponent(portId)}`;
246
+ return this.request("DELETE", path);
247
+ }
224
248
  };
249
+ async function withPreview(call) {
250
+ try {
251
+ return await call;
252
+ } catch (error) {
253
+ if (!(error instanceof ApiError) || error.status !== 404 || error.code !== "404") throw error;
254
+ const message = "Proxies are a preview, and your organization does not have it yet.";
255
+ throw new ApiError(404, "preview_not_enabled", message, error.requestId);
256
+ }
257
+ }
225
258
  async function toError(response) {
226
259
  const requestId = response.headers.get("x-request-id") ?? void 0;
227
260
  const text = await response.text().catch(() => "");
@@ -316,11 +349,17 @@ var BAKED = ["claude", "codex", "opencode", "dsh"];
316
349
  var PACKAGES = {
317
350
  claude: "@anthropic-ai/claude-code",
318
351
  codex: "@openai/codex",
319
- opencode: "opencode-ai",
352
+ opencode: "@opencode/cli",
320
353
  dsh: "@deepseek-ai/dsh",
321
354
  pi: "@earendil-works/pi-coding-agent",
322
355
  openclaw: "openclaw"
323
356
  };
357
+ var INSTALL_SCRIPTS = ["@opencode/cli", "openclaw"];
358
+ function opencodeMajor(output) {
359
+ const version = output.trim().split(/\s+/).at(-1) ?? "";
360
+ const [major, minor] = version.replace(/^v/, "").split(".");
361
+ return minor !== void 0 && /^\d{1,6}$/.test(major) ? Number(major) : null;
362
+ }
324
363
  var PLUGINS = {
325
364
  hermes: "hermes plugins install munitoai/hermes-provider",
326
365
  pi: "pi install npm:@munitoai/pi-provider",
@@ -464,11 +503,12 @@ function opencodeJson(baseUrl, model) {
464
503
  {
465
504
  $schema: "https://opencode.ai/config.json",
466
505
  model: `munito/${model}`,
467
- provider: {
506
+ providers: {
468
507
  munito: {
469
- npm: "@ai-sdk/openai-compatible",
470
508
  name: "Munito",
471
- options: { baseURL: baseUrl, apiKey: "{env:MUNITO_API_KEY}" },
509
+ env: ["MUNITO_API_KEY"],
510
+ package: "@opencode/ai/providers/openai-compatible",
511
+ settings: { baseURL: baseUrl },
472
512
  models: { [model]: { name: model } }
473
513
  }
474
514
  }
@@ -801,7 +841,7 @@ async function ensureHarness(client, sandboxId, agent, emit) {
801
841
  emit({ type: "harness.installing", agent, package: pkg });
802
842
  const startedAt = Date.now();
803
843
  const install = await client.exec(sandboxId, {
804
- command: `npm install -g --no-audit --no-fund ${pkg}`,
844
+ command: `npm install -g --no-audit --no-fund${INSTALL_SCRIPTS.includes(pkg) ? ` --allow-scripts=${pkg}` : ""} ${pkg}`,
805
845
  timeout: 600
806
846
  });
807
847
  if (install.exit_code !== 0) {
@@ -941,6 +981,19 @@ async function drop(client, name, onEvent) {
941
981
  return true;
942
982
  }
943
983
 
984
+ // src/core/proxies.ts
985
+ var PROXY_PREFIX = "prx_";
986
+ async function findProxy(client, ref) {
987
+ if (ref.startsWith(PROXY_PREFIX)) return client.getProxy(ref);
988
+ const found = (await client.listProxies()).find((proxy) => proxy.name === ref);
989
+ if (!found) throw new ApiError(404, "proxy_not_found", `No proxy of this workspace has the name ${ref}.`);
990
+ return found;
991
+ }
992
+ function endpoints(proxy, port, ipv6) {
993
+ const over4 = proxy.ipv4.addresses.map((address) => `${address}:${port.public_port}`);
994
+ return ipv6 ? [...over4, `[${ipv6}]:${port.port}`] : over4;
995
+ }
996
+
944
997
  export {
945
998
  DEFAULT_BASE_URL,
946
999
  REGIONS,
@@ -958,6 +1011,8 @@ export {
958
1011
  PROVIDERS,
959
1012
  BAKED,
960
1013
  PACKAGES,
1014
+ INSTALL_SCRIPTS,
1015
+ opencodeMajor,
961
1016
  PLUGINS,
962
1017
  DEFAULT_MODEL,
963
1018
  DEFAULT_SMALL_MODEL,
@@ -984,6 +1039,8 @@ export {
984
1039
  findBase,
985
1040
  warm,
986
1041
  job,
987
- drop
1042
+ drop,
1043
+ findProxy,
1044
+ endpoints
988
1045
  };
989
- //# sourceMappingURL=chunk-EZEXBJTZ.js.map
1046
+ //# sourceMappingURL=chunk-7XUGUENM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/api/urls.ts","../src/api/client.ts","../src/core/keys.ts","../src/core/providers.ts","../src/core/templates.ts","../src/core/agents.ts","../src/core/ci.ts","../src/core/proxies.ts"],"sourcesContent":["/** Small string work on URLs and paths, without a regular expression.\n\n`replace(/\\/+$/, \"\")` is quadratic on a string of many slashes, and every caller here takes its input from a flag, a\nfile or an environment variable. These loops are linear.\n*/\n\n/** `value` with every trailing slash removed. */\nexport function trimTrailingSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return value.slice(0, end);\n}\n\n/** `value` with one leading `./` or `/` removed, so a path joins under a base. */\nexport function trimLeadingSlash(value: string): string {\n let start = 0;\n if (value.charCodeAt(start) === 46 && value.charCodeAt(start + 1) === 47) start += 2;\n else if (value.charCodeAt(start) === 47) start += 1;\n return value.slice(start);\n}\n\n/** `path` under `base`, with one slash between them. */\nexport function joinPath(base: string, path: string): string {\n return `${trimTrailingSlash(base)}/${trimLeadingSlash(path)}`;\n}\n","/** The HTTP client of the Sandboxes API. No terminal output: every failure is an ApiError. */\n\nimport type {\n CommandEvent,\n CommandResult,\n CreateProxy,\n CreateSandbox,\n DeployTemplate,\n ExecCommand,\n FileEntry,\n OpenProxyPort,\n PortUrl,\n Proxy,\n ProxyPort,\n Sandbox,\n SandboxCommand,\n SshAccess,\n Template,\n} from \"./types.ts\";\nimport { trimTrailingSlash } from \"./urls.ts\";\n\nexport const DEFAULT_BASE_URL = \"https://api.munito.ai\";\nexport const REGIONS: Record<string, string> = {\n global: \"https://api.munito.ai\",\n eu: \"https://api.eu.munito.ai\",\n us: \"https://api.us.munito.ai\",\n};\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly requestId: string | undefined;\n\n constructor(status: number, code: string, message: string, requestId?: string) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.code = code;\n this.requestId = requestId;\n }\n\n /** Whether another attempt of the same request can succeed. */\n get retryable(): boolean {\n return this.status === 429 || this.status >= 500;\n }\n}\n\nexport interface ClientOptions {\n apiKey: string;\n baseUrl?: string;\n /** Attempts for a retryable failure, the first included. */\n attempts?: number;\n fetch?: typeof globalThis.fetch;\n}\n\nconst SANDBOXES = \"/sandboxes/v1\";\n\nexport class Client {\n readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly attempts: number;\n private readonly doFetch: typeof globalThis.fetch;\n\n constructor(options: ClientOptions) {\n this.apiKey = options.apiKey;\n this.baseUrl = trimTrailingSlash(options.baseUrl ?? DEFAULT_BASE_URL);\n this.attempts = Math.max(1, options.attempts ?? 3);\n this.doFetch = options.fetch ?? globalThis.fetch;\n }\n\n /** What this deployment has refused, so one process does not ask again. Per client: two clients can face two\n * deployments. */\n readonly lacks = { wiring: false, template: false };\n\n /** The caller's own key. The wiring of a harness has to put it in the guest's environment. */\n get token(): string {\n return this.apiKey;\n }\n\n private headers(): Record<string, string> {\n return { authorization: `Bearer ${this.apiKey}`, \"content-type\": \"application/json\" };\n }\n\n private async raw(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n headers: Record<string, string> = {},\n ): Promise<Response> {\n let last: ApiError | undefined;\n const replayable =\n [\"GET\", \"HEAD\", \"PUT\", \"DELETE\"].includes(method) ||\n (method === \"POST\" && path === `${SANDBOXES}/sandboxes` && Boolean(headers[\"idempotency-key\"]));\n const attempts = replayable ? this.attempts : 1;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const response = await this.doFetch(`${this.baseUrl}${path}`, {\n method,\n headers: { ...this.headers(), ...headers },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n if (response.ok) return response;\n last = await toError(response);\n if (!last.retryable || attempt === attempts) throw last;\n await sleep(250 * 2 ** (attempt - 1));\n }\n throw last ?? new ApiError(0, \"unknown\", \"The request failed.\");\n }\n\n async request<T>(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n headers: Record<string, string> = {},\n ): Promise<T> {\n const response = await this.raw(method, path, body, signal, headers);\n const text = await response.text();\n return (text ? JSON.parse(text) : {}) as T;\n }\n\n // Sandboxes.\n\n createSandbox(spec: CreateSandbox, signal?: AbortSignal, idempotencyKey?: string): Promise<Sandbox> {\n return this.request<Sandbox>(\n \"POST\",\n `${SANDBOXES}/sandboxes`,\n spec,\n signal,\n idempotencyKey ? { \"idempotency-key\": idempotencyKey } : {},\n );\n }\n\n getSandbox(id: string): Promise<Sandbox> {\n return this.request<Sandbox>(\"GET\", `${SANDBOXES}/sandboxes/${id}`);\n }\n\n async listSandboxes(): Promise<Sandbox[]> {\n const rows: Sandbox[] = [];\n const query = new URLSearchParams({ limit: \"100\" });\n while (true) {\n const page = await this.request<{ data?: Sandbox[]; has_more?: boolean } | Sandbox[]>(\n \"GET\",\n `${SANDBOXES}/sandboxes?${query}`,\n );\n if (Array.isArray(page)) return [...rows, ...page];\n rows.push(...(page.data ?? []));\n if (!page.has_more) return rows;\n if (!page.data?.length) throw new ApiError(0, \"invalid_page\", \"The sandbox list has no next cursor.\");\n query.set(\"after\", page.data[page.data.length - 1]!.id);\n }\n }\n\n deleteSandbox(id: string): Promise<void> {\n return this.request<void>(\"DELETE\", `${SANDBOXES}/sandboxes/${id}`);\n }\n\n pauseSandbox(id: string): Promise<Sandbox> {\n return this.request<Sandbox>(\"POST\", `${SANDBOXES}/sandboxes/${id}/pause`);\n }\n\n resumeSandbox(id: string): Promise<Sandbox> {\n return this.request<Sandbox>(\"POST\", `${SANDBOXES}/sandboxes/${id}/resume`);\n }\n\n setSandboxTimeout(id: string, timeout: number): Promise<Sandbox> {\n return this.request(\"POST\", `${SANDBOXES}/sandboxes/${id}/timeout`, { timeout });\n }\n\n forkSandbox(id: string, count = 1): Promise<{ data?: Sandbox[] } | Sandbox[]> {\n return this.request(\"POST\", `${SANDBOXES}/sandboxes/${id}/fork`, { count });\n }\n\n // Commands.\n\n exec(id: string, spec: ExecCommand, signal?: AbortSignal): Promise<CommandResult> {\n return this.request<CommandResult>(\"POST\", `${SANDBOXES}/sandboxes/${id}/exec`, spec, signal);\n }\n\n /** The same command, as the events arrive. The last event is always `exit`. */\n async *execStream(id: string, spec: ExecCommand, signal?: AbortSignal): AsyncGenerator<CommandEvent> {\n const response = await this.raw(\"POST\", `${SANDBOXES}/sandboxes/${id}/exec`, { ...spec, stream: true }, signal);\n if (!response.body) throw new ApiError(0, \"no_body\", \"The API sent no stream.\");\n let ended = false;\n for await (const line of ndjson(response.body)) {\n const event = line as CommandEvent | { type: \"error\"; error: { code: string; message: string } };\n if (event.type === \"error\") throw new ApiError(0, event.error.code, event.error.message);\n ended ||= event.type === \"exit\";\n yield event;\n }\n if (!ended) throw new ApiError(0, \"incomplete_stream\", \"The command stream ended without an exit event.\");\n }\n\n startCommand(id: string, spec: Omit<ExecCommand, \"stream\">): Promise<SandboxCommand> {\n return this.request(\"POST\", `${SANDBOXES}/sandboxes/${id}/commands`, spec);\n }\n\n getCommand(id: string, commandId: string, stdout = 0, stderr = 0): Promise<SandboxCommand> {\n const query = new URLSearchParams({ stdout: String(stdout), stderr: String(stderr) });\n return this.request(\"GET\", `${SANDBOXES}/sandboxes/${id}/commands/${encodeURIComponent(commandId)}?${query}`);\n }\n\n async listCommands(id: string): Promise<SandboxCommand[]> {\n const page = await this.request<{ data: SandboxCommand[] }>(\"GET\", `${SANDBOXES}/sandboxes/${id}/commands`);\n return page.data;\n }\n\n signalCommand(id: string, commandId: string, signal = 15): Promise<SandboxCommand> {\n return this.request(\"POST\", `${SANDBOXES}/sandboxes/${id}/commands/${encodeURIComponent(commandId)}/signal`, {\n signal,\n });\n }\n\n deleteCommand(id: string, commandId: string): Promise<void> {\n return this.request(\"DELETE\", `${SANDBOXES}/sandboxes/${id}/commands/${encodeURIComponent(commandId)}`);\n }\n\n // Files.\n\n async listFiles(id: string, path = \"/workspace\"): Promise<FileEntry[]> {\n const query = new URLSearchParams({ path });\n const page = await this.request<{ data: FileEntry[] }>(\"GET\", `${SANDBOXES}/sandboxes/${id}/files?${query}`);\n return page.data;\n }\n\n deleteFile(id: string, path: string, recursive = false): Promise<void> {\n const query = new URLSearchParams({ path, recursive: String(recursive) });\n return this.request(\"DELETE\", `${SANDBOXES}/sandboxes/${id}/files?${query}`);\n }\n\n async readFileBytes(id: string, path: string): Promise<Uint8Array> {\n const query = new URLSearchParams({ path });\n const response = await this.raw(\"GET\", `${SANDBOXES}/sandboxes/${id}/files/content?${query}`);\n return new Uint8Array(await response.arrayBuffer());\n }\n\n async readFile(id: string, path: string): Promise<string> {\n const query = new URLSearchParams({ path });\n const response = await this.raw(\"GET\", `${SANDBOXES}/sandboxes/${id}/files/content?${query}`);\n return response.text();\n }\n\n async writeFile(id: string, path: string, content: string | Uint8Array): Promise<void> {\n const query = new URLSearchParams({ path });\n const response = await this.doFetch(`${this.baseUrl}${SANDBOXES}/sandboxes/${id}/files/content?${query}`, {\n method: \"PUT\",\n headers: { authorization: `Bearer ${this.apiKey}`, \"content-type\": \"application/octet-stream\" },\n body: typeof content === \"string\" ? content : new Uint8Array(content).buffer,\n });\n if (!response.ok) throw await toError(response);\n }\n\n // Ports and SSH.\n\n signPortUrl(id: string, port: number, expiresIn = 3600): Promise<PortUrl> {\n return this.request<PortUrl>(\"POST\", `${SANDBOXES}/sandboxes/${id}/ports/${port}/url`, { expires_in: expiresIn });\n }\n\n setPort(id: string, port: number, isPublic: boolean): Promise<unknown> {\n return this.request(\"PUT\", `${SANDBOXES}/sandboxes/${id}/ports/${port}`, { public: isPublic });\n }\n\n createSshAccess(id: string): Promise<SshAccess> {\n return this.request<SshAccess>(\"POST\", `${SANDBOXES}/sandboxes/${id}/ssh/access`, {});\n }\n\n getSsh(id: string): Promise<SshAccess> {\n return this.request<SshAccess>(\"GET\", `${SANDBOXES}/sandboxes/${id}/ssh`);\n }\n\n // Custom templates. A deploy is never sent twice: each one makes a new version.\n\n /** Build an image into a template. The answer comes at once, with the build in `build`. */\n deployTemplate(spec: DeployTemplate, signal?: AbortSignal): Promise<Template> {\n return this.request<Template>(\"POST\", `${SANDBOXES}/templates`, spec, signal);\n }\n\n /** The custom templates of the key's workspace, by name. */\n async listTemplates(): Promise<Template[]> {\n const page = await this.request<{ data?: Template[] }>(\"GET\", `${SANDBOXES}/templates`);\n return page.data ?? [];\n }\n\n /** One template, by its name or its id. */\n getTemplate(ref: string, signal?: AbortSignal): Promise<Template> {\n return this.request<Template>(\"GET\", `${SANDBOXES}/templates/${encodeURIComponent(ref)}`, undefined, signal);\n }\n\n /** Delete a template and its versions. Its running sandboxes keep running. */\n deleteTemplate(ref: string): Promise<void> {\n return this.request<void>(\"DELETE\", `${SANDBOXES}/templates/${encodeURIComponent(ref)}`);\n }\n\n // Proxies: fixed public addresses. A preview, so an organization without its switch gets a 404.\n\n createProxy(spec: CreateProxy): Promise<Proxy> {\n return withPreview(this.request<Proxy>(\"POST\", `${SANDBOXES}/proxies`, spec));\n }\n\n /** The proxies of the key's workspace, each with its addresses and its open ports. */\n async listProxies(): Promise<Proxy[]> {\n const page = await withPreview(this.request<{ data?: Proxy[] }>(\"GET\", `${SANDBOXES}/proxies`));\n return page.data ?? [];\n }\n\n getProxy(id: string): Promise<Proxy> {\n return this.request<Proxy>(\"GET\", `${SANDBOXES}/proxies/${encodeURIComponent(id)}`);\n }\n\n /** Delete a proxy that no running or paused sandbox uses. */\n deleteProxy(id: string): Promise<void> {\n return this.request<void>(\"DELETE\", `${SANDBOXES}/proxies/${encodeURIComponent(id)}`);\n }\n\n /** Let the internet reach one port of a sandbox of the proxy. The same port again answers the open port. */\n openProxyPort(id: string, spec: OpenProxyPort): Promise<ProxyPort> {\n return this.request<ProxyPort>(\"POST\", `${SANDBOXES}/proxies/${encodeURIComponent(id)}/ports`, spec);\n }\n\n closeProxyPort(id: string, portId: string): Promise<void> {\n const path = `${SANDBOXES}/proxies/${encodeURIComponent(id)}/ports/${encodeURIComponent(portId)}`;\n return this.request<void>(\"DELETE\", path);\n }\n}\n\n/** The create and the list of the proxies exist only for an organization with the preview. Without it the API\n * answers 404 with no code, which says nothing to the caller. */\nasync function withPreview<T>(call: Promise<T>): Promise<T> {\n try {\n return await call;\n } catch (error) {\n if (!(error instanceof ApiError) || error.status !== 404 || error.code !== \"404\") throw error;\n const message = \"Proxies are a preview, and your organization does not have it yet.\";\n throw new ApiError(404, \"preview_not_enabled\", message, error.requestId);\n }\n}\n\nasync function toError(response: Response): Promise<ApiError> {\n const requestId = response.headers.get(\"x-request-id\") ?? undefined;\n const text = await response.text().catch(() => \"\");\n try {\n const body = JSON.parse(text) as { code?: string; detail?: string; title?: string; message?: string };\n const message = body.detail ?? body.message ?? body.title ?? response.statusText;\n return new ApiError(response.status, body.code ?? String(response.status), message, requestId);\n } catch {\n return new ApiError(response.status, String(response.status), text || response.statusText, requestId);\n }\n}\n\n/** Each complete line of an NDJSON body, parsed. A half line at the end is dropped. */\nexport async function* ndjson(body: ReadableStream<Uint8Array>): AsyncGenerator<unknown> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {\n buffer += decoder.decode(chunk, { stream: true });\n let index = buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = buffer.slice(0, index).trim();\n buffer = buffer.slice(index + 1);\n if (line) yield JSON.parse(line);\n index = buffer.indexOf(\"\\n\");\n }\n }\n const rest = buffer.trim();\n if (rest) yield JSON.parse(rest);\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n","/** Where the key comes from, and where a sign-in keeps it. Never logs or prints a key. */\n\nimport { chmod, mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { REGIONS } from \"../api/client.ts\";\nimport { trimTrailingSlash } from \"../api/urls.ts\";\n\nexport const ENV_KEY = \"MUNITO_API_KEY\";\nexport const ENV_HOST = \"MUNITO_HOST\";\n\nexport interface Credentials {\n apiKey: string;\n host: string;\n /** Where the key came from, for a diagnostic that never shows the key itself. */\n source: \"environment\" | \"file\";\n}\n\nexport function configDir(): string {\n const base = process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\");\n return join(base, \"munito\");\n}\n\nexport function authPath(): string {\n return join(configDir(), \"auth.json\");\n}\n\n/** The host for a region name, a full URL, or the default. */\nexport function resolveHost(value?: string): string {\n if (!value) return REGIONS.global;\n if (value in REGIONS) return REGIONS[value];\n if (value.startsWith(\"http://\") || value.startsWith(\"https://\")) return trimTrailingSlash(value);\n throw new Error(`Unknown region ${value}. Use global, eu, us, or a URL.`);\n}\n\n/** The environment wins, so a scripted run never picks up a stale sign-in. */\nexport async function load(hostOverride?: string): Promise<Credentials | null> {\n const host = resolveHost(hostOverride ?? process.env[ENV_HOST]);\n const fromEnv = process.env[ENV_KEY]?.trim();\n if (fromEnv) return { apiKey: fromEnv, host, source: \"environment\" };\n try {\n const saved = JSON.parse(await readFile(authPath(), \"utf8\")) as { apiKey?: string; host?: string };\n if (!saved.apiKey) return null;\n return { apiKey: saved.apiKey, host: hostOverride ? host : resolveHost(saved.host), source: \"file\" };\n } catch {\n return null;\n }\n}\n\nexport async function save(apiKey: string, host: string): Promise<string> {\n const path = authPath();\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await writeFile(path, `${JSON.stringify({ apiKey, host }, null, 2)}\\n`, { mode: 0o600 });\n await chmod(path, 0o600);\n return path;\n}\n\nexport async function clear(): Promise<void> {\n await rm(authPath(), { force: true });\n}\n\n/** The key with its middle removed, for a line a person reads. */\nexport function mask(apiKey: string): string {\n if (apiKey.length <= 12) return \"*\".repeat(apiKey.length);\n return `${apiKey.slice(0, 8)}…${apiKey.slice(-4)}`;\n}\n\nexport class MissingKeyError extends Error {\n constructor() {\n super(`No API key. Run \\`munito login\\`, or set ${ENV_KEY}.`);\n this.name = \"MissingKeyError\";\n }\n}\n\nexport async function require(hostOverride?: string): Promise<Credentials> {\n const found = await load(hostOverride);\n if (!found) throw new MissingKeyError();\n return found;\n}\n","/** The (agent, provider, auth) table: what each harness needs to talk to a model.\n\nThis is the whole point of the package. The same table is baked into the `agent` template, so a sandbox needs no\nwiring; here it wires a harness the API has not wired yet, and it configures a harness on a laptop for `munito init`.\nPure: it reads nothing and writes nothing.\n*/\n\nexport const AGENTS = [\"claude\", \"codex\", \"opencode\", \"dsh\", \"hermes\", \"pi\", \"openclaw\", \"prime\"] as const;\nexport type AgentName = (typeof AGENTS)[number];\n\nexport const PROVIDERS = [\"munito\", \"anthropic\", \"openai\"] as const;\nexport type ProviderName = (typeof PROVIDERS)[number];\n\nexport type AuthMode = \"token\" | \"subscription\";\n\n/** The harnesses the `agent` template installs, and that `munito agent` can run headless. */\nexport const BAKED: readonly AgentName[] = [\"claude\", \"codex\", \"opencode\", \"dsh\"];\n\n/** Each harness's npm package, for the image and for an on-demand install. */\nexport const PACKAGES: Partial<Record<AgentName, string>> = {\n claude: \"@anthropic-ai/claude-code\",\n codex: \"@openai/codex\",\n opencode: \"@opencode/cli\",\n dsh: \"@deepseek-ai/dsh\",\n pi: \"@earendil-works/pi-coding-agent\",\n openclaw: \"openclaw\",\n};\n\n/** The packages whose command comes from their install script. npm wants each one named in `--allow-scripts`. */\nexport const INSTALL_SCRIPTS: readonly string[] = [\"@opencode/cli\", \"openclaw\"];\n\n/** The major version in the output of `opencode --version`, such as `opencode v2.3.2` or `1.19.5`. */\nexport function opencodeMajor(output: string): number | null {\n const version = output.trim().split(/\\s+/).at(-1) ?? \"\";\n const [major, minor] = version.replace(/^v/, \"\").split(\".\");\n return minor !== undefined && /^\\d{1,6}$/.test(major) ? Number(major) : null;\n}\n\n/** The provider plugins we publish. The `agent` template installs the pi and OpenClaw ones; Hermes offers only a\nshell installer from its own domain, which no digest pins, so the image does not carry it. */\nexport const PLUGINS: Partial<Record<AgentName, string>> = {\n hermes: \"hermes plugins install munitoai/hermes-provider\",\n pi: \"pi install npm:@munitoai/pi-provider\",\n openclaw: \"openclaw plugins install --force --accept-capabilities npm:@munitoai/openclaw-provider\",\n};\n\nexport interface Target {\n /** The host, with no path: `https://api.eu.munito.ai`. */\n host: string;\n token: string;\n model: string;\n smallModel: string;\n}\n\nexport interface WiringFile {\n path: string;\n content: string;\n}\n\nexport interface Wiring {\n /** Variables to set for every command and shell. */\n env: Record<string, string>;\n /** Variables to clear. A subscription sign-in breaks when a base URL of ours survives. */\n unset: string[];\n files: WiringFile[];\n}\n\nexport const DEFAULT_MODEL = \"zai-org/glm-5.3-flash\";\nexport const DEFAULT_SMALL_MODEL = \"qwen/qwen3.8-27b\";\n/** Claude Code reads one context window for a model, so it takes the long variant. */\nexport const CLAUDE_MODEL = \"zai-org/glm-5.3-flash[1m]\";\n\n/** The guest runs its commands as root. `munito init` passes the user's own home instead. */\nexport const GUEST_HOME = \"/root\";\n\n/** Claude Code stops at a welcome screen and a trust dialog on a fresh machine. Neither touches authentication. */\nexport function claudeGates(workdir: string, home = GUEST_HOME): WiringFile {\n return {\n path: `${home}/.claude.json`,\n content: `${JSON.stringify(\n {\n hasCompletedOnboarding: true,\n bypassPermissionsModeAccepted: true,\n projects: { [workdir]: { hasTrustDialogAccepted: true, allowedTools: [] } },\n },\n null,\n 2,\n )}\\n`,\n };\n}\n\n/** Every variable the table can set, so a switch of provider clears what the last one left. */\nexport const MANAGED_ENV: readonly string[] = [\n \"ANTHROPIC_BASE_URL\",\n \"ANTHROPIC_AUTH_TOKEN\",\n \"ANTHROPIC_API_KEY\",\n \"ANTHROPIC_MODEL\",\n \"ANTHROPIC_DEFAULT_OPUS_MODEL\",\n \"ANTHROPIC_DEFAULT_SONNET_MODEL\",\n \"ANTHROPIC_DEFAULT_HAIKU_MODEL\",\n \"CLAUDE_CODE_AUTO_MODE_SERVER\",\n \"MUNITO_API_KEY\",\n \"OPENAI_API_KEY\",\n \"CODEX_API_KEY\",\n];\n\nexport class WiringError extends Error {}\n\n/** How `agent` reaches `provider`. Throws when the pair has no answer, rather than wiring something half right. */\nexport function wire(\n agent: AgentName,\n provider: ProviderName,\n auth: AuthMode,\n target: Target,\n workdir = \"/workspace\",\n home = GUEST_HOME,\n): Wiring {\n if (auth === \"subscription\") return subscription(agent, workdir, home);\n switch (provider) {\n case \"munito\":\n return munito(agent, target, workdir, home);\n case \"anthropic\":\n return vendor(agent, \"anthropic\", target, workdir, home);\n case \"openai\":\n return vendor(agent, \"openai\", target, workdir, home);\n }\n}\n\n/** A subscription signs in inside the machine. We never carry its token, so this clears ours and sets nothing. */\nfunction subscription(agent: AgentName, workdir: string, home: string): Wiring {\n if (agent === \"claude\") return { env: {}, unset: [...MANAGED_ENV], files: [claudeGates(workdir, home)] };\n if (agent === \"codex\" || agent === \"opencode\") return { env: {}, unset: [...MANAGED_ENV], files: [] };\n throw new WiringError(`${agent} has no subscription sign-in that Munito AI knows. Use --provider munito.`);\n}\n\nfunction munito(agent: AgentName, target: Target, workdir: string, home: string): Wiring {\n const openai = `${target.host}/inference/v1`;\n switch (agent) {\n case \"claude\":\n return {\n // The Anthropic surface takes no /v1: Claude Code appends it.\n env: {\n ANTHROPIC_BASE_URL: `${target.host}/inference`,\n ANTHROPIC_AUTH_TOKEN: target.token,\n ANTHROPIC_MODEL: target.model,\n ANTHROPIC_DEFAULT_OPUS_MODEL: target.model,\n ANTHROPIC_DEFAULT_SONNET_MODEL: target.model,\n ANTHROPIC_DEFAULT_HAIKU_MODEL: target.smallModel,\n CLAUDE_CODE_AUTO_MODE_SERVER: \"0\",\n },\n unset: [\"ANTHROPIC_API_KEY\"],\n files: [claudeGates(workdir, home)],\n };\n case \"codex\":\n return {\n env: { MUNITO_API_KEY: target.token },\n unset: [\"OPENAI_API_KEY\", \"CODEX_API_KEY\"],\n files: [{ path: `${home}/.codex/config.toml`, content: codexToml(openai, target.model) }],\n };\n case \"opencode\":\n return {\n env: { MUNITO_API_KEY: target.token },\n unset: [\"OPENAI_API_KEY\"],\n files: [{ path: `${home}/.config/opencode/opencode.json`, content: opencodeJson(openai, target.model) }],\n };\n case \"dsh\":\n return {\n env: { MUNITO_API_KEY: target.token },\n unset: [],\n files: [{ path: `${home}/.dsh/cordis.patch.yml`, content: dshYaml(openai, target.model) }],\n };\n case \"prime\":\n return {\n env: { MUNITO_API_KEY: target.token },\n unset: [],\n files: [{ path: `${home}/.prime/agent/models.json`, content: primeJson(openai, target.model) }],\n };\n case \"pi\":\n case \"openclaw\":\n case \"hermes\":\n // Their provider is a plugin we publish, and it reads this variable. The image carries the first two.\n return { env: { MUNITO_API_KEY: target.token }, unset: [], files: [] };\n default:\n throw new WiringError(\n `Munito AI has no wiring for ${agent}. See https://docs.munito.ai/reference/agents/${agent}.`,\n );\n }\n}\n\n/** The customer's own key at the vendor. We clear our base URL, or their key would reach us. */\nfunction vendor(\n agent: AgentName,\n provider: \"anthropic\" | \"openai\",\n target: Target,\n workdir: string,\n home: string,\n): Wiring {\n if (provider === \"anthropic\") {\n if (agent !== \"claude\") throw new WiringError(`${agent} does not take the Anthropic API. Use --provider munito.`);\n return {\n env: { ANTHROPIC_API_KEY: target.token },\n unset: MANAGED_ENV.filter((name) => name !== \"ANTHROPIC_API_KEY\"),\n files: [claudeGates(workdir, home)],\n };\n }\n if (agent !== \"codex\" && agent !== \"opencode\") {\n throw new WiringError(`${agent} does not take the OpenAI API. Use --provider munito.`);\n }\n return {\n env: { OPENAI_API_KEY: target.token },\n unset: MANAGED_ENV.filter((name) => name !== \"OPENAI_API_KEY\"),\n files: [],\n };\n}\n\nfunction codexToml(baseUrl: string, model: string): string {\n return [\n `model = \"${model}\"`,\n `model_provider = \"munito\"`,\n ``,\n `[model_providers.munito]`,\n `name = \"Munito\"`,\n `base_url = \"${baseUrl}\"`,\n `env_key = \"MUNITO_API_KEY\"`,\n `wire_api = \"responses\"`,\n ``,\n ].join(\"\\n\");\n}\n\n/** The configuration of OpenCode 2. Its server reads the key from the variable that `env` names. */\nfunction opencodeJson(baseUrl: string, model: string): string {\n return `${JSON.stringify(\n {\n $schema: \"https://opencode.ai/config.json\",\n model: `munito/${model}`,\n providers: {\n munito: {\n name: \"Munito\",\n env: [\"MUNITO_API_KEY\"],\n package: \"@opencode/ai/providers/openai-compatible\",\n settings: { baseURL: baseUrl },\n models: { [model]: { name: model } },\n },\n },\n },\n null,\n 2,\n )}\\n`;\n}\n\nfunction primeJson(baseUrl: string, model: string): string {\n const body = {\n providers: {\n munito: {\n name: \"Munito AI\",\n baseUrl,\n api: \"openai-completions\",\n apiKey: \"MUNITO_API_KEY\",\n models: [\n {\n id: model,\n name: model,\n reasoning: true,\n contextWindow: 1048576,\n maxTokens: 131072,\n compat: { sendSessionAffinityHeaders: true },\n },\n ],\n },\n },\n };\n return `${JSON.stringify(body, null, 2)}\\n`;\n}\n\nfunction dshYaml(baseUrl: string, model: string): string {\n return [\n `- id: llm-pi-ai`,\n ` config:`,\n ` providers:`,\n ` munito:`,\n ` displayName: Munito AI`,\n ` apiKeyEnv: MUNITO_API_KEY`,\n ` api: openai-completions`,\n ` baseURL: ${baseUrl}`,\n ` models:`,\n ` - id: ${model}`,\n ` name: ${model}`,\n ` contextWindow: 1048576`,\n ` maxTokens: 131072`,\n ` reasoningEfforts:`,\n ` low: low`,\n ` high: high`,\n ` max: max`,\n `- id: agent-default-model`,\n ` config:`,\n ` provider: munito`,\n ` model: ${model}`,\n ``,\n ].join(\"\\n\");\n}\n\nexport interface RunOptions {\n maxTurns?: number;\n resume?: string;\n /** The model, for a harness whose headless form names it on the command line. */\n model?: string;\n}\n\n/** The argv that runs one task and exits, for each harness we install. */\nexport function headlessArgv(agent: AgentName, prompt: string, options: RunOptions = {}): string[] {\n switch (agent) {\n case \"claude\": {\n // As root, Claude Code refuses --dangerously-skip-permissions, so the tools are named.\n const argv = [\n \"claude\",\n \"-p\",\n prompt,\n \"--allowedTools\",\n \"Bash\",\n \"Edit\",\n \"Write\",\n \"Read\",\n \"--output-format\",\n \"json\",\n ];\n if (options.maxTurns) argv.push(\"--max-turns\", String(options.maxTurns));\n if (options.resume) argv.push(\"--resume\", options.resume);\n return argv;\n }\n case \"codex\":\n return [\"codex\", \"exec\", prompt];\n case \"opencode\":\n return [\"opencode\", \"run\", prompt];\n case \"dsh\":\n return [\"dsh\", \"headless\", prompt];\n case \"pi\":\n return [\"pi\", \"--print\", \"--model\", `munito/${options.model ?? DEFAULT_MODEL}`, prompt];\n case \"openclaw\":\n // `openclaw agent` delivers a turn to a chat channel, not a coding task. Use it over SSH.\n throw new WiringError(\"OpenClaw has no headless coding turn. Use `munito ssh <id>` and run `openclaw`.\");\n default:\n throw new WiringError(`${agent} is not installed in the sandbox. ${PLUGINS[agent] ?? \"\"}`.trim());\n }\n}\n\n/** The interactive binary of a harness, for a terminal session. */\nexport function shellArgv(agent: AgentName): string[] {\n if (agent === \"dsh\") return [\"dsh\"];\n if (agent === \"opencode\") return [\"opencode\"];\n if (!PACKAGES[agent]) throw new WiringError(`${agent} is not installed in the sandbox.`);\n return [agent];\n}\n","/** Custom templates: a container image that a workspace deploys under a name. Core code: no terminal output. */\n\nimport type { Client } from \"../api/client.ts\";\nimport type { DeployTemplate, RegistryAuth, Template, TemplateStatus } from \"../api/types.ts\";\n\n/** The variable that holds the token of a private registry, for a run that cannot pipe it to standard input. */\nexport const ENV_REGISTRY_TOKEN = \"MUNITO_REGISTRY_TOKEN\";\n/** How often a wait reads the template. A build takes from seconds to minutes. */\nexport const POLL_MS = 5_000;\n/** A build ends within 20 minutes, so a wait that passes this has lost track of it. */\nexport const WAIT_MS = 25 * 60_000;\n\n/** A request that the command refuses before any call, such as a token with no user name. */\nexport class TemplateError extends Error {}\n\nexport interface RegistryOptions {\n username?: string;\n /** The token from standard input, when the caller asked for it there. */\n stdin?: string;\n /** The token from `ENV_REGISTRY_TOKEN`. */\n env?: string;\n}\n\n/**\n * The credential of a private registry, from a user name and a token on standard input or in the environment.\n * There is no flag for the token, so it never reaches a shell history or a process list. `ignored` says that the\n * environment holds a token that this deploy does not send, because no user name came with it.\n */\nexport function registryAuth(options: RegistryOptions): { auth?: RegistryAuth; ignored: boolean } {\n const username = options.username?.trim() ?? \"\";\n // A pipe from `echo` or a file ends with a line break, which is no part of the token.\n const token = options.stdin !== undefined ? options.stdin.replace(/\\r?\\n$/, \"\") : (options.env ?? \"\");\n if (!username) {\n if (options.stdin !== undefined) throw new TemplateError(\"Set --username with --password-stdin.\");\n return { ignored: Boolean(options.env) };\n }\n if (!token) {\n throw new TemplateError(\n `Give the registry token on standard input with --password-stdin, or in ${ENV_REGISTRY_TOKEN}.`,\n );\n }\n return { auth: { username, password: token }, ignored: false };\n}\n\n/** The body of a deploy. The API checks the name and the image again. */\nexport function deployBody(name: string, image: string, auth?: RegistryAuth): DeployTemplate {\n const body: DeployTemplate = { name: name.trim(), image: image.trim() };\n if (!body.name) throw new TemplateError(\"Give the template a name, such as acme-agent.\");\n if (!body.image) throw new TemplateError(\"Give the image to deploy, such as ghcr.io/acme/agent:1.4.\");\n return auth ? { ...body, registry_auth: auth } : body;\n}\n\nexport type TemplateEvent = { type: \"template.build\"; name: string; version: number; status: TemplateStatus };\n\nexport interface WaitOptions {\n intervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n onEvent?: (event: TemplateEvent) => void;\n /** For a test: the clock and the pause between reads. */\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}\n\n/** Read the template until its newest build ends, and return it. An event marks each change of the build's status. */\nexport async function waitForBuild(client: Client, ref: string, options: WaitOptions = {}): Promise<Template> {\n const now = options.now ?? Date.now;\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = now() + (options.timeoutMs ?? WAIT_MS);\n let seen = \"\";\n while (true) {\n const template = await client.getTemplate(ref, options.signal);\n const { build } = template;\n const mark = `${build.version} ${build.status}`;\n if (mark !== seen) {\n seen = mark;\n options.onEvent?.({ type: \"template.build\", name: template.name, version: build.version, status: build.status });\n }\n if (build.status !== \"building\") return template;\n if (now() >= deadline) {\n throw new Error(`The build of ${template.name} did not end in time. Read it again with munito templates get.`);\n }\n options.signal?.throwIfAborted();\n await sleep(options.intervalMs ?? POLL_MS);\n }\n}\n","/** Run one coding agent in one sandbox, end to end.\n\nSix API requests, seven environment variables and two levels of JSON escaping become one call. Core code: it emits\nevents and returns a result, and it never writes to a terminal.\n*/\n\nimport { ApiError, Client } from \"../api/client.ts\";\nimport { joinPath } from \"../api/urls.ts\";\nimport type { CommandEvent, CreateSandbox, Sandbox } from \"../api/types.ts\";\nimport {\n CLAUDE_MODEL,\n DEFAULT_MODEL,\n DEFAULT_SMALL_MODEL,\n INSTALL_SCRIPTS,\n PACKAGES,\n headlessArgv,\n shellArgv,\n wire,\n type AgentName,\n type AuthMode,\n type ProviderName,\n} from \"./providers.ts\";\n\n/** The template that carries the harnesses, and the one to use where a deployment does not have it yet. */\nexport const AGENT_TEMPLATE = \"agent\";\nexport const AGENT_TEMPLATE_FALLBACK = \"ubuntu\";\nexport const WORKDIR = \"/workspace\";\n\nexport type AgentEvent =\n | { type: \"sandbox.creating\" }\n | { type: \"sandbox.created\"; sandboxId: string; ms: number }\n | { type: \"wiring.written\"; files: number }\n | { type: \"files.uploaded\"; count: number; bytes: number }\n | { type: \"agent.started\"; argv: string[] }\n | { type: \"output\"; stream: \"stdout\" | \"stderr\"; data: string }\n | { type: \"agent.finished\"; exitCode: number; ms: number }\n | { type: \"patch.ready\"; bytes: number }\n | { type: \"harness.installing\"; agent: string; package: string }\n | { type: \"harness.installed\"; agent: string; ms: number }\n | { type: \"sandbox.deleted\"; sandboxId: string }\n | { type: \"sandbox.kept\"; sandboxId: string };\n\nexport interface UploadFile {\n path: string;\n content: string;\n}\n\nexport interface RunAgentOptions {\n agent: AgentName;\n prompt: string;\n provider?: ProviderName;\n auth?: AuthMode;\n model?: string;\n smallModel?: string;\n template?: string;\n size?: string;\n /** Seconds the sandbox may live. The command gets the same budget, capped by the API at 1,800. */\n timeout?: number;\n workdir?: string;\n maxTurns?: number;\n keep?: boolean;\n files?: UploadFile[];\n /** Bring the work back as a unified diff. On by default when files go up. */\n patch?: boolean;\n metadata?: Record<string, string>;\n onEvent?: (event: AgentEvent) => void;\n signal?: AbortSignal;\n}\n\nexport interface AgentRun {\n sandboxId: string;\n exitCode: number;\n /** The harness's own answer, unwrapped when it reports JSON. */\n result: string;\n stdout: string;\n stderr: string;\n /** A unified diff of what the agent changed, empty when nothing did. */\n patch: string;\n sessionId?: string;\n durationMs: number;\n kept: boolean;\n}\n\n/** The API caps one command at 1,800 seconds. */\nconst MAX_COMMAND_S = 1_800;\n\nexport async function runAgent(client: Client, options: RunAgentOptions): Promise<AgentRun> {\n const emit = options.onEvent ?? (() => {});\n const provider = options.provider ?? \"munito\";\n const auth = options.auth ?? \"token\";\n const workdir = options.workdir ?? WORKDIR;\n const agent = options.agent;\n const started = Date.now();\n\n const sandbox = await createAgentSandbox(client, {\n ...options,\n agent,\n provider,\n auth,\n workdir,\n internet: true,\n metadata: { \"munito.cli\": \"agent\", \"munito.agent\": agent, ...options.metadata },\n onEvent: emit,\n });\n\n let kept = false;\n try {\n const wantPatch = Boolean(options.files?.length) && options.patch !== false;\n if (options.files?.length) {\n let bytes = 0;\n for (const file of options.files) {\n await client.writeFile(sandbox.id, joinPath(workdir, file.path), file.content);\n bytes += Buffer.byteLength(file.content);\n }\n emit({ type: \"files.uploaded\", count: options.files.length, bytes });\n // A base commit is what makes a diff possible, so the work can come back as a patch.\n if (wantPatch) await client.exec(sandbox.id, { command: baseCommit(workdir), timeout: 60 });\n }\n\n await ensureHarness(client, sandbox.id, agent, emit);\n\n const argv = headlessArgv(agent, options.prompt, { maxTurns: options.maxTurns, model: options.model });\n emit({ type: \"agent.started\", argv });\n const ranAt = Date.now();\n let stdout = \"\";\n let stderr = \"\";\n let exitCode = -1;\n const stream = client.execStream(\n sandbox.id,\n {\n command: argv,\n cwd: workdir,\n timeout: Math.min(options.timeout ?? MAX_COMMAND_S, MAX_COMMAND_S),\n },\n options.signal,\n );\n for await (const event of stream as AsyncGenerator<CommandEvent>) {\n if (event.type === \"stdout\") {\n stdout += event.data;\n emit({ type: \"output\", stream: \"stdout\", data: event.data });\n } else if (event.type === \"stderr\") {\n stderr += event.data;\n emit({ type: \"output\", stream: \"stderr\", data: event.data });\n } else {\n exitCode = event.exit_code;\n }\n }\n const durationMs = Date.now() - ranAt;\n emit({ type: \"agent.finished\", exitCode, ms: durationMs });\n\n let patch = \"\";\n if (wantPatch) {\n const diff = await client.exec(sandbox.id, { command: diffCommand(workdir), timeout: 120 });\n patch = diff.exit_code === 0 ? diff.stdout : \"\";\n if (patch.trim()) emit({ type: \"patch.ready\", bytes: Buffer.byteLength(patch) });\n }\n\n const answer = unwrap(agent, stdout);\n kept = Boolean(options.keep);\n return {\n sandboxId: sandbox.id,\n exitCode,\n result: answer.result,\n sessionId: answer.sessionId,\n stdout,\n stderr,\n patch,\n durationMs: Date.now() - started,\n kept,\n };\n } finally {\n if (options.keep) {\n emit({ type: \"sandbox.kept\", sandboxId: sandbox.id });\n } else {\n await client.deleteSandbox(sandbox.id).catch(() => {});\n emit({ type: \"sandbox.deleted\", sandboxId: sandbox.id });\n }\n }\n}\n\n/** What a sandbox needs so one harness in it reaches one provider. */\nexport interface CreateAgentSandboxOptions {\n agent: AgentName;\n provider?: ProviderName;\n auth?: AuthMode;\n model?: string;\n smallModel?: string;\n template?: string;\n size?: string;\n timeout?: number;\n persistent?: boolean;\n internet?: boolean;\n workdir?: string;\n metadata?: Record<string, string>;\n onEvent?: (event: AgentEvent) => void;\n signal?: AbortSignal;\n}\n\n/** Create a sandbox with one harness already pointed at a provider, and leave it running. */\nexport async function createAgentSandbox(client: Client, options: CreateAgentSandboxOptions): Promise<Sandbox> {\n const emit = options.onEvent ?? (() => {});\n const { agent } = options;\n const provider = options.provider ?? \"munito\";\n const auth = options.auth ?? \"token\";\n const workdir = options.workdir ?? WORKDIR;\n\n const wiring = wire(\n agent,\n provider,\n auth,\n {\n host: client.baseUrl,\n token: tokenFor(client, provider, auth),\n model: options.model ?? (agent === \"claude\" ? CLAUDE_MODEL : DEFAULT_MODEL),\n smallModel: options.smallModel ?? DEFAULT_SMALL_MODEL,\n },\n workdir,\n );\n\n emit({ type: \"sandbox.creating\" });\n const createdAt = Date.now();\n const spec: CreateSandbox = {\n template: options.template ?? AGENT_TEMPLATE,\n size: options.size ?? \"default\",\n internet: options.internet ?? true,\n persistent: options.persistent,\n timeout: options.timeout ?? 3_600,\n metadata: options.metadata ?? { \"munito.cli\": \"agent\", \"munito.agent\": agent },\n };\n // The API owns the table. Older deployments do not know these fields, and refuse an unknown one, so the first\n // failure falls back to the environment this client computed. The two tables give the same answer.\n const sandbox = await createWithWiring(client, spec, {\n agent,\n provider,\n auth,\n model: options.model,\n token: provider === \"munito\" && auth === \"token\" ? client.token : \"\",\n fallbackEnv: wiring.env,\n signal: options.signal,\n });\n emit({ type: \"sandbox.created\", sandboxId: sandbox.id, ms: Date.now() - createdAt });\n\n try {\n // `unset` is empty against today's image, which bakes no wiring of ours. The `agent` template applies it.\n for (const file of wiring.files) await client.writeFile(sandbox.id, file.path, file.content);\n if (wiring.files.length) emit({ type: \"wiring.written\", files: wiring.files.length });\n } catch (error) {\n await client.deleteSandbox(sandbox.id).catch(() => {});\n throw error;\n }\n return sandbox;\n}\n\nconst UNKNOWN_FIELD = /extra inputs are not permitted/i;\nconst UNKNOWN_TEMPLATE = /unknown template/i;\n\n/** Ask the API to wire the agent and give it the agent template, and step back to what an older deployment has.\n\nBoth answers are exact, so nothing else is mistaken for them. A deployment that gains either one is used at once,\nwith no release of this package.\n*/\nasync function createWithWiring(\n client: Client,\n spec: CreateSandbox,\n options: {\n agent: AgentName;\n provider: ProviderName;\n auth: AuthMode;\n model?: string;\n token: string;\n fallbackEnv: Record<string, string>;\n signal?: AbortSignal;\n },\n): Promise<Sandbox> {\n const env: Record<string, string> = options.token ? { MUNITO_API_KEY: options.token } : {};\n for (;;) {\n const body: CreateSandbox = { ...spec };\n if (client.lacks.template && body.template === AGENT_TEMPLATE) body.template = AGENT_TEMPLATE_FALLBACK;\n if (client.lacks.wiring) {\n body.env = options.fallbackEnv;\n } else {\n Object.assign(body, {\n agent: options.agent,\n provider: options.provider,\n auth: options.auth,\n model: options.model,\n env,\n });\n }\n try {\n return await client.createSandbox(body, options.signal);\n } catch (error) {\n // Only these two exact answers step back. Any other refusal, such as a bad agent name, is the caller's to see.\n const refusal = error instanceof ApiError && (error.status === 422 || error.status === 400) ? error.message : \"\";\n if (!client.lacks.wiring && UNKNOWN_FIELD.test(refusal)) {\n client.lacks.wiring = true;\n continue;\n }\n if (!client.lacks.template && UNKNOWN_TEMPLATE.test(refusal) && body.template === AGENT_TEMPLATE) {\n client.lacks.template = true;\n continue;\n }\n throw error;\n }\n }\n}\n\n/** Install the harness when the template does not carry it, so every agent runs on every template.\n\nThe `agent` template ships all of them, and then this costs one `command -v`. On `ubuntu` it costs about a minute,\nonce, which is still the whole task working instead of exit 127.\n*/\nasync function ensureHarness(\n client: Client,\n sandboxId: string,\n agent: AgentName,\n emit: (event: AgentEvent) => void,\n): Promise<void> {\n const binary = shellArgv(agent)[0];\n const present = await client.exec(sandboxId, { command: `command -v ${binary}`, timeout: 30 });\n if (present.exit_code === 0) return;\n const pkg = PACKAGES[agent];\n if (!pkg) throw new Error(`${agent} is not installed in this sandbox, and Munito AI does not install it.`);\n emit({ type: \"harness.installing\", agent, package: pkg });\n const startedAt = Date.now();\n const install = await client.exec(sandboxId, {\n command: `npm install -g --no-audit --no-fund${INSTALL_SCRIPTS.includes(pkg) ? ` --allow-scripts=${pkg}` : \"\"} ${pkg}`,\n timeout: 600,\n });\n if (install.exit_code !== 0) {\n throw new Error(`Could not install ${pkg}: ${(install.stderr || install.stdout).trim().split(\"\\n\").at(-1)}`);\n }\n emit({ type: \"harness.installed\", agent, ms: Date.now() - startedAt });\n}\n\n/** Claude Code reports a JSON envelope. The others print their answer. */\nexport function unwrap(agent: AgentName, stdout: string): { result: string; sessionId?: string } {\n if (agent !== \"claude\") return { result: stdout.trim() };\n const line = stdout.trim().split(\"\\n\").at(-1) ?? \"\";\n try {\n const body = JSON.parse(line) as { result?: string; session_id?: string };\n if (typeof body.result === \"string\") return { result: body.result, sessionId: body.session_id };\n } catch {\n // Not the envelope. The raw output is the answer.\n }\n return { result: stdout.trim() };\n}\n\nfunction tokenFor(client: Client, provider: ProviderName, auth: AuthMode): string {\n if (auth === \"subscription\") return \"\";\n if (provider === \"munito\") return client.token;\n const name = provider === \"anthropic\" ? \"ANTHROPIC_API_KEY\" : \"OPENAI_API_KEY\";\n const value = process.env[name]?.trim();\n if (!value) throw new Error(`--provider ${provider} needs ${name} in your environment.`);\n return value;\n}\n\n/** A repository with one commit, so that `git diff` can describe the agent's work. */\nfunction baseCommit(workdir: string): string {\n return [\n `cd ${workdir}`,\n \"git init -q 2>/dev/null || true\",\n \"git config user.email agent@munito.ai\",\n \"git config user.name 'Munito agent'\",\n \"git add -A\",\n \"git commit -qm base --allow-empty\",\n ].join(\" && \");\n}\n\n/** Paths a build makes. Without this the agent's own test run comes back as a patch. */\nconst NOISE = [\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".pytest_cache\",\n \".ruff_cache\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \".next\",\n \"target\",\n];\n\nfunction diffCommand(workdir: string): string {\n const exclude = NOISE.map((name) => `':(exclude)**/${name}/**' ':(exclude)${name}/**'`).join(\" \");\n return `cd ${workdir} && git add -A && git diff --cached --binary HEAD -- . ${exclude}`;\n}\n","/** The warm-base CI loop: build one disk, pause it, fork it for each job.\n\nThe recipe at /reference/sandboxes/ci, as three calls. A base is found by its metadata, so one CI step can build it\nand another, in a different process, can use it. Core code: no terminal output.\n*/\n\nimport type { Client } from \"../api/client.ts\";\nimport type { CommandResult, Sandbox } from \"../api/types.ts\";\n\nexport const ROLE = \"munito.ci\";\nexport const NAME_KEY = \"munito.ci.name\";\nexport const DEFAULT_BASE_SIZE = \"large\";\nexport const DEFAULT_DISK_GIB = 40;\n\nexport type CiEvent =\n | { type: \"base.creating\"; name: string }\n | { type: \"base.created\"; sandboxId: string; ms: number }\n | { type: \"base.setup\"; command: string }\n | { type: \"base.paused\"; sandboxId: string; ms: number }\n | { type: \"base.found\"; sandboxId: string; status: string }\n | { type: \"fork.created\"; sandboxId: string; ms: number }\n | { type: \"job.finished\"; exitCode: number; ms: number }\n | { type: \"fork.deleted\"; sandboxId: string }\n | { type: \"base.deleted\"; sandboxId: string };\n\nexport class CiError extends Error {}\n\n/** The base of this name, running or paused. */\nexport async function findBase(client: Client, name: string): Promise<Sandbox | null> {\n const boxes = await client.listSandboxes();\n const matches = boxes.filter(\n (box) =>\n box.metadata?.[NAME_KEY] === name &&\n box.metadata?.[\"munito.cli\"] === ROLE &&\n (box.status === \"paused\" || box.status === \"running\"),\n );\n // The newest wins, so a rebuild takes over from the base it replaces.\n matches.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));\n return matches[0] ?? null;\n}\n\nexport interface WarmOptions {\n name: string;\n setup: string;\n size?: string;\n diskGib?: number;\n template?: string;\n timeout?: number;\n onEvent?: (event: CiEvent) => void;\n}\n\nexport interface WarmResult {\n sandboxId: string;\n setup: CommandResult;\n paused: boolean;\n}\n\n/** Build the warm disk and pause it. A base of the same name is deleted first. */\nexport async function warm(client: Client, options: WarmOptions): Promise<WarmResult> {\n const emit = options.onEvent ?? (() => {});\n const previous = await findBase(client, options.name);\n if (previous) await client.deleteSandbox(previous.id).catch(() => {});\n\n emit({ type: \"base.creating\", name: options.name });\n const createdAt = Date.now();\n const base = await client.createSandbox({\n template: options.template ?? \"ubuntu\",\n size: options.size ?? DEFAULT_BASE_SIZE,\n disk_gib: options.diskGib ?? DEFAULT_DISK_GIB,\n internet: true,\n persistent: true,\n timeout: options.timeout ?? 3_600,\n metadata: { \"munito.cli\": ROLE, [NAME_KEY]: options.name },\n });\n emit({ type: \"base.created\", sandboxId: base.id, ms: Date.now() - createdAt });\n\n emit({ type: \"base.setup\", command: options.setup });\n const setup = await client.exec(base.id, { command: options.setup, cwd: \"/workspace\", timeout: 1_800 });\n if (setup.exit_code !== 0) {\n // A half-built base is worse than none: the next job would fail with no sign of why.\n await client.deleteSandbox(base.id).catch(() => {});\n throw new CiError(`The setup command failed with exit ${setup.exit_code}. The base was not kept.`);\n }\n\n const pausedAt = Date.now();\n await client.pauseSandbox(base.id);\n emit({ type: \"base.paused\", sandboxId: base.id, ms: Date.now() - pausedAt });\n return { sandboxId: base.id, setup, paused: true };\n}\n\nexport interface JobOptions {\n name: string;\n command: string;\n cwd?: string;\n timeout?: number;\n env?: Record<string, string>;\n keep?: boolean;\n onOutput?: (text: string, stream: \"stdout\" | \"stderr\") => void;\n onEvent?: (event: CiEvent) => void;\n}\n\n/** Fork the base, run one job in the fork, delete it. */\nexport async function job(client: Client, options: JobOptions): Promise<number> {\n const emit = options.onEvent ?? (() => {});\n const base = await findBase(client, options.name);\n if (!base) throw new CiError(`No warm base named ${options.name}. Build one with \\`munito ci warm\\`.`);\n emit({ type: \"base.found\", sandboxId: base.id, status: base.status });\n\n const forkedAt = Date.now();\n const answer = await client.forkSandbox(base.id, 1);\n const forks = Array.isArray(answer) ? answer : (answer.data ?? []);\n const fork = forks[0];\n if (!fork) throw new CiError(\"The fork returned no sandbox.\");\n emit({ type: \"fork.created\", sandboxId: fork.id, ms: Date.now() - forkedAt });\n\n const ranAt = Date.now();\n let exitCode = -1;\n try {\n for await (const event of client.execStream(fork.id, {\n command: options.command,\n cwd: options.cwd ?? \"/workspace\",\n env: options.env,\n timeout: options.timeout ?? 1_800,\n })) {\n if (event.type === \"exit\") exitCode = event.exit_code;\n else options.onOutput?.(event.data, event.type);\n }\n emit({ type: \"job.finished\", exitCode, ms: Date.now() - ranAt });\n return exitCode;\n } finally {\n if (!options.keep) {\n await client.deleteSandbox(fork.id).catch(() => {});\n emit({ type: \"fork.deleted\", sandboxId: fork.id });\n }\n }\n}\n\n/** Delete the base of this name. */\nexport async function drop(client: Client, name: string, onEvent?: (event: CiEvent) => void): Promise<boolean> {\n const base = await findBase(client, name);\n if (!base) return false;\n await client.deleteSandbox(base.id);\n onEvent?.({ type: \"base.deleted\", sandboxId: base.id });\n return true;\n}\n","/** Proxies: fixed public addresses for sandboxes. A command names a proxy by its name or by its id. */\n\nimport { ApiError, type Client } from \"../api/client.ts\";\nimport type { Proxy, ProxyPort } from \"../api/types.ts\";\n\nexport const PROXY_PREFIX = \"prx_\";\n\n/** The proxy with this id, or with this name in the key's workspace. */\nexport async function findProxy(client: Client, ref: string): Promise<Proxy> {\n if (ref.startsWith(PROXY_PREFIX)) return client.getProxy(ref);\n const found = (await client.listProxies()).find((proxy) => proxy.name === ref);\n if (!found) throw new ApiError(404, \"proxy_not_found\", `No proxy of this workspace has the name ${ref}.`);\n return found;\n}\n\n/** Where the internet reaches an open port: each IPv4 address of the proxy with the public port, and the IPv6\n * address of the sandbox with the port itself, when the caller knows that address. */\nexport function endpoints(proxy: Proxy, port: ProxyPort, ipv6?: string | null): string[] {\n const over4 = proxy.ipv4.addresses.map((address) => `${address}:${port.public_port}`);\n return ipv6 ? [...over4, `[${ipv6}]:${port.port}`] : over4;\n}\n"],"mappings":";AAOO,SAAS,kBAAkB,OAAuB;AACvD,MAAI,MAAM,MAAM;AAChB,SAAO,MAAM,KAAK,MAAM,WAAW,MAAM,CAAC,MAAM,GAAI,QAAO;AAC3D,SAAO,MAAM,MAAM,GAAG,GAAG;AAC3B;AAGO,SAAS,iBAAiB,OAAuB;AACtD,MAAI,QAAQ;AACZ,MAAI,MAAM,WAAW,KAAK,MAAM,MAAM,MAAM,WAAW,QAAQ,CAAC,MAAM,GAAI,UAAS;AAAA,WAC1E,MAAM,WAAW,KAAK,MAAM,GAAI,UAAS;AAClD,SAAO,MAAM,MAAM,KAAK;AAC1B;AAGO,SAAS,SAAS,MAAc,MAAsB;AAC3D,SAAO,GAAG,kBAAkB,IAAI,CAAC,IAAI,iBAAiB,IAAI,CAAC;AAC7D;;;ACHO,IAAM,mBAAmB;AACzB,IAAM,UAAkC;AAAA,EAC7C,QAAQ;AAAA,EACR,IAAI;AAAA,EACJ,IAAI;AACN;AAEO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,QAAgB,MAAc,SAAiB,WAAoB;AAC7E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AACZ,SAAK,YAAY;AAAA,EACnB;AAAA;AAAA,EAGA,IAAI,YAAqB;AACvB,WAAO,KAAK,WAAW,OAAO,KAAK,UAAU;AAAA,EAC/C;AACF;AAUA,IAAM,YAAY;AAEX,IAAM,SAAN,MAAa;AAAA,EACT;AAAA,EACQ;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,SAAwB;AAClC,SAAK,SAAS,QAAQ;AACtB,SAAK,UAAU,kBAAkB,QAAQ,WAAW,gBAAgB;AACpE,SAAK,WAAW,KAAK,IAAI,GAAG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