@munitoai/cli 0.3.0 → 0.5.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.
@@ -0,0 +1,6 @@
1
+ /** How the files of a sandbox show in a list. */
2
+ import type { FileEntry } from "../api/types.ts";
3
+ /** The size of a file, from bytes up: "30 B", "1.5 KiB", "2.0 GiB". */
4
+ export declare function fileSize(bytes: number): string;
5
+ /** One row of a file list: the name, the type, the size and the last change in UTC. Only a file has a size. */
6
+ export declare function fileRow(entry: FileEntry): string[];
@@ -13,6 +13,10 @@ export type AuthMode = "token" | "subscription";
13
13
  export declare const BAKED: readonly AgentName[];
14
14
  /** Each harness's npm package, for the image and for an on-demand install. */
15
15
  export declare const PACKAGES: Partial<Record<AgentName, string>>;
16
+ /** The packages whose command comes from their install script. npm wants each one named in `--allow-scripts`. */
17
+ export declare const INSTALL_SCRIPTS: readonly string[];
18
+ /** The major version in the output of `opencode --version`, such as `opencode v2.3.2` or `1.19.5`. */
19
+ export declare function opencodeMajor(output: string): number | null;
16
20
  /** The provider plugins we publish. The `agent` template installs the pi and OpenClaw ones; Hermes offers only a
17
21
  shell installer from its own domain, which no digest pins, so the image does not carry it. */
18
22
  export declare const PLUGINS: Partial<Record<AgentName, string>>;
@@ -0,0 +1,9 @@
1
+ /** Proxies: fixed public addresses for sandboxes. A command names a proxy by its name or by its id. */
2
+ import { type Client } from "../api/client.ts";
3
+ import type { Proxy, ProxyPort } from "../api/types.ts";
4
+ export declare const PROXY_PREFIX = "prx_";
5
+ /** The proxy with this id, or with this name in the key's workspace. */
6
+ export declare function findProxy(client: Client, ref: string): Promise<Proxy>;
7
+ /** Where the internet reaches an open port: each IPv4 address of the proxy with the public port, and the IPv6
8
+ * address of the sandbox with the port itself, when the caller knows that address. */
9
+ export declare function endpoints(proxy: Proxy, port: ProxyPort, ipv6?: string | null): string[];
@@ -0,0 +1,12 @@
1
+ /** Which sandboxes a list shows. A workspace keeps each ended sandbox, so a list reads only what it shows. */
2
+ import type { Client } from "../api/client.ts";
3
+ import type { Sandbox } from "../api/types.ts";
4
+ /** The sandboxes that exist now, the newest first. */
5
+ export declare function liveSandboxes(client: Client): Promise<Sandbox[]>;
6
+ /** The seconds of a timeout that a person typed. The API holds the range, so a new limit needs no release. */
7
+ export declare function timeoutSeconds(value: string): number;
8
+ /** The newest sandboxes in any status, at most `limit`, and whether the workspace has older ones. */
9
+ export declare function newestSandboxes(client: Client, limit: number): Promise<{
10
+ sandboxes: Sandbox[];
11
+ older: boolean;
12
+ }>;
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ export type { TrainingRun } from "./api/training.ts";
12
12
  import { Client, REGIONS, type ClientOptions } from "./api/client.ts";
13
13
  import { type AgentRun, type RunAgentOptions } from "./core/agents.ts";
14
14
  import { job as jobCi, warm as warmCi } from "./core/ci.ts";
15
- import type { CreateSandbox, DeployTemplate, Sandbox, Template } from "./api/types.ts";
15
+ import type { CreateProxy, CreateSandbox, DeployTemplate, ListSandboxes, OpenProxyPort, Proxy, ProxyPort, Sandbox, Template } from "./api/types.ts";
16
16
  import { type WaitOptions } from "./core/templates.ts";
17
17
  export { ApiError, Client, DEFAULT_BASE_URL, REGIONS } from "./api/client.ts";
18
18
  export type { ClientOptions } from "./api/client.ts";
@@ -24,6 +24,7 @@ export { drop as dropCiBase, findBase as findCiBase, job as runCiJob, warm as wa
24
24
  export type { CiEvent, JobOptions, WarmOptions, WarmResult } from "./core/ci.ts";
25
25
  export { TemplateError, waitForBuild } from "./core/templates.ts";
26
26
  export type { TemplateEvent, WaitOptions } from "./core/templates.ts";
27
+ export { endpoints as proxyEndpoints, findProxy } from "./core/proxies.ts";
27
28
  export interface MunitoOptions extends Omit<ClientOptions, "baseUrl"> {
28
29
  /** `global`, `eu`, `us`, or a full URL. */
29
30
  region?: string;
@@ -63,7 +64,7 @@ export declare class Munito {
63
64
  get sandboxes(): {
64
65
  create: (spec: CreateSandbox, idempotencyKey?: string) => Promise<Sandbox>;
65
66
  get: (id: string) => Promise<Sandbox>;
66
- list: () => Promise<Sandbox[]>;
67
+ list: (options?: ListSandboxes) => Promise<Sandbox[]>;
67
68
  delete: (id: string) => Promise<void>;
68
69
  pause: (id: string) => Promise<Sandbox>;
69
70
  resume: (id: string) => Promise<Sandbox>;
@@ -97,5 +98,15 @@ export declare class Munito {
97
98
  /** Read the template until its newest build is `ready` or `failed`, and return it. */
98
99
  wait: (ref: string, options?: WaitOptions) => Promise<Template>;
99
100
  };
101
+ /** Proxies: fixed public addresses for sandboxes. A preview, on for an organization with its switch. */
102
+ get proxies(): {
103
+ create: (spec: CreateProxy) => Promise<Proxy>;
104
+ list: () => Promise<Proxy[]>;
105
+ /** One proxy, by its id or its name. */
106
+ get: (ref: string) => Promise<Proxy>;
107
+ delete: (id: string) => Promise<void>;
108
+ openPort: (id: string, spec: OpenProxyPort) => Promise<ProxyPort>;
109
+ closePort: (id: string, portId: string) => Promise<void>;
110
+ };
100
111
  }
101
112
  export { REGIONS as regions };
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  DEFAULT_MODEL,
10
10
  DEFAULT_SMALL_MODEL,
11
11
  GUEST_HOME,
12
+ INSTALL_SCRIPTS,
12
13
  MANAGED_ENV,
13
14
  PACKAGES,
14
15
  PLUGINS,
@@ -20,9 +21,12 @@ import {
20
21
  claudeGates,
21
22
  createAgentSandbox,
22
23
  drop,
24
+ endpoints,
23
25
  findBase,
26
+ findProxy,
24
27
  headlessArgv,
25
28
  job,
29
+ opencodeMajor,
26
30
  resolveHost,
27
31
  runAgent,
28
32
  shellArgv,
@@ -30,7 +34,7 @@ import {
30
34
  waitForBuild,
31
35
  warm,
32
36
  wire
33
- } from "./chunk-EZEXBJTZ.js";
37
+ } from "./chunk-JHSIZLVR.js";
34
38
 
35
39
  // src/api/training.ts
36
40
  var base = "/sandboxes/v1/training-runs";
@@ -83,7 +87,7 @@ var Munito = class {
83
87
  idempotencyKey
84
88
  ),
85
89
  get: (id) => client.getSandbox(id),
86
- list: () => client.listSandboxes(),
90
+ list: (options) => client.listSandboxes(options),
87
91
  delete: (id) => client.deleteSandbox(id),
88
92
  pause: (id) => client.pauseSandbox(id),
89
93
  resume: (id) => client.resumeSandbox(id),
@@ -119,6 +123,19 @@ var Munito = class {
119
123
  wait: (ref, options) => waitForBuild(client, ref, options)
120
124
  };
121
125
  }
126
+ /** Proxies: fixed public addresses for sandboxes. A preview, on for an organization with its switch. */
127
+ get proxies() {
128
+ const client = this.client;
129
+ return {
130
+ create: (spec) => client.createProxy(spec),
131
+ list: () => client.listProxies(),
132
+ /** One proxy, by its id or its name. */
133
+ get: (ref) => findProxy(client, ref),
134
+ delete: (id) => client.deleteProxy(id),
135
+ openPort: (id, spec) => client.openProxyPort(id, spec),
136
+ closePort: (id, portId) => client.closeProxyPort(id, portId)
137
+ };
138
+ }
122
139
  };
123
140
  export {
124
141
  AGENTS,
@@ -131,6 +148,7 @@ export {
131
148
  DEFAULT_MODEL,
132
149
  DEFAULT_SMALL_MODEL,
133
150
  GUEST_HOME,
151
+ INSTALL_SCRIPTS,
134
152
  MANAGED_ENV,
135
153
  Munito,
136
154
  PACKAGES,
@@ -144,7 +162,10 @@ export {
144
162
  createAgentSandbox,
145
163
  drop as dropCiBase,
146
164
  findBase as findCiBase,
165
+ findProxy,
147
166
  headlessArgv,
167
+ opencodeMajor,
168
+ endpoints as proxyEndpoints,
148
169
  REGIONS as regions,
149
170
  runAgent,
150
171
  job as runCiJob,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/training.ts","../src/index.ts"],"sourcesContent":["import type { Client } from \"./client.ts\";\n\nexport type TrainingRun = {\n id: string;\n name: string;\n sandbox_id: string;\n command_id: string;\n status: \"running\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"interrupted\";\n cancel_requested: boolean;\n created_at: number;\n updated_at: number;\n started_at: number | null;\n ended_at: number | null;\n exit_code: number | null;\n timed_out: boolean;\n gpu_type: string;\n gpu_count: number;\n vcpus: number;\n memory_mib: number;\n stdout: string;\n stderr: string;\n truncated: boolean;\n observation_error: boolean;\n metrics: { step: number; values: Record<string, number> }[];\n artifacts: { path: string; bytes: number; sha256: string }[];\n};\n\nconst base = \"/sandboxes/v1/training-runs\";\nconst path = (id: string) => `${base}/${encodeURIComponent(id)}`;\n\n/** Internal preview. Artifact metadata describes files exported to the SDK client. */\nexport function training(client: Client) {\n return {\n list: (options: { limit?: number; after?: string } = {}) =>\n client.request<{ data: TrainingRun[]; has_more: boolean }>(\n \"GET\",\n `${base}?${new URLSearchParams({ limit: String(options.limit ?? 20), after: options.after ?? \"\" })}`,\n ),\n create: (body: { name: string; sandbox_id: string; command_id: string }) =>\n client.request<TrainingRun>(\"POST\", base, body),\n get: (id: string) => client.request<TrainingRun>(\"GET\", path(id)),\n cancel: (id: string) => client.request<TrainingRun>(\"POST\", `${path(id)}/cancel`, {}),\n artifacts: (id: string, artifacts: TrainingRun[\"artifacts\"]) =>\n client.request<TrainingRun>(\"PUT\", `${path(id)}/artifacts`, { artifacts }),\n delete: (id: string) => client.request<void>(\"DELETE\", path(id)),\n };\n}\n","/** The SDK. `npx @munitoai/cli` and `import { Munito } from \"@munitoai/cli\"` run the same code.\n\n```ts\nimport { Munito } from \"@munitoai/cli\";\n\nconst munito = new Munito({ apiKey: process.env.MUNITO_API_KEY! });\nconst run = await munito.agent.run({ agent: \"claude\", prompt: \"fix the failing test\" });\nconsole.log(run.result);\n```\n*/\n\nimport { training } from \"./api/training.ts\";\nexport type { TrainingRun } from \"./api/training.ts\";\n\nimport { Client, DEFAULT_BASE_URL, REGIONS, type ClientOptions } from \"./api/client.ts\";\nimport { runAgent, type AgentRun, type RunAgentOptions } from \"./core/agents.ts\";\nimport { drop as dropCi, findBase as findCi, job as jobCi, warm as warmCi } from \"./core/ci.ts\";\nimport type { CreateSandbox, DeployTemplate, Sandbox, Template } from \"./api/types.ts\";\nimport { resolveHost } from \"./core/keys.ts\";\nimport { waitForBuild, type WaitOptions } from \"./core/templates.ts\";\n\nexport { ApiError, Client, DEFAULT_BASE_URL, REGIONS } from \"./api/client.ts\";\nexport type { ClientOptions } from \"./api/client.ts\";\nexport * from \"./api/types.ts\";\nexport { AGENT_TEMPLATE, WORKDIR, createAgentSandbox, runAgent, unwrap } from \"./core/agents.ts\";\nexport type { AgentEvent, AgentRun, CreateAgentSandboxOptions, RunAgentOptions, UploadFile } from \"./core/agents.ts\";\nexport * from \"./core/providers.ts\";\nexport { drop as dropCiBase, findBase as findCiBase, job as runCiJob, warm as warmCiBase } from \"./core/ci.ts\";\nexport type { CiEvent, JobOptions, WarmOptions, WarmResult } from \"./core/ci.ts\";\nexport { TemplateError, waitForBuild } from \"./core/templates.ts\";\nexport type { TemplateEvent, WaitOptions } from \"./core/templates.ts\";\n\nexport interface MunitoOptions extends Omit<ClientOptions, \"baseUrl\"> {\n /** `global`, `eu`, `us`, or a full URL. */\n region?: string;\n baseUrl?: string;\n}\n\n/** One object for the whole product, in the shape a reader expects from an SDK. */\nexport class Munito {\n readonly client: Client;\n\n constructor(options: MunitoOptions) {\n const baseUrl = options.baseUrl ?? (options.region ? resolveHost(options.region) : DEFAULT_BASE_URL);\n this.client = new Client({ ...options, baseUrl });\n }\n\n get training() {\n return training(this.client);\n }\n\n get agent() {\n return {\n run: (options: RunAgentOptions): Promise<AgentRun> => runAgent(this.client, options),\n };\n }\n\n get ci() {\n const client = this.client;\n return {\n warm: (options: Parameters<typeof warmCi>[1]) => warmCi(client, options),\n job: (options: Parameters<typeof jobCi>[1]) => jobCi(client, options),\n find: (name: string) => findCi(client, name),\n drop: (name: string) => dropCi(client, name),\n };\n }\n\n get sandboxes() {\n const client = this.client;\n return {\n // The API configures the agent. Supply its default key without changing the caller's sandbox options.\n create: (spec: CreateSandbox, idempotencyKey?: string): Promise<Sandbox> =>\n client.createSandbox(\n spec.agent && (spec.provider ?? \"munito\") === \"munito\" && (spec.auth ?? \"token\") === \"token\"\n ? { ...spec, env: { MUNITO_API_KEY: client.token, ...spec.env } }\n : spec,\n undefined,\n idempotencyKey,\n ),\n get: (id: string): Promise<Sandbox> => client.getSandbox(id),\n list: (): Promise<Sandbox[]> => client.listSandboxes(),\n delete: (id: string): Promise<void> => client.deleteSandbox(id),\n pause: (id: string): Promise<Sandbox> => client.pauseSandbox(id),\n resume: (id: string): Promise<Sandbox> => client.resumeSandbox(id),\n setTimeout: client.setSandboxTimeout.bind(client),\n fork: client.forkSandbox.bind(client),\n exec: client.exec.bind(client),\n execStream: client.execStream.bind(client),\n readFile: client.readFile.bind(client),\n readFileBytes: client.readFileBytes.bind(client),\n writeFile: client.writeFile.bind(client),\n listFiles: client.listFiles.bind(client),\n deleteFile: client.deleteFile.bind(client),\n startCommand: client.startCommand.bind(client),\n getCommand: client.getCommand.bind(client),\n listCommands: client.listCommands.bind(client),\n signalCommand: client.signalCommand.bind(client),\n deleteCommand: client.deleteCommand.bind(client),\n signPortUrl: client.signPortUrl.bind(client),\n setPort: client.setPort.bind(client),\n createSshAccess: client.createSshAccess.bind(client),\n getSsh: client.getSsh.bind(client),\n };\n }\n\n /** Custom templates: a container image that new sandboxes start from. A deploy answers before its build ends. */\n get templates() {\n const client = this.client;\n return {\n deploy: (spec: DeployTemplate): Promise<Template> => client.deployTemplate(spec),\n list: (): Promise<Template[]> => client.listTemplates(),\n get: (ref: string): Promise<Template> => client.getTemplate(ref),\n delete: (ref: string): Promise<void> => client.deleteTemplate(ref),\n /** Read the template until its newest build is `ready` or `failed`, and return it. */\n wait: (ref: string, options?: WaitOptions): Promise<Template> => waitForBuild(client, ref, options),\n };\n }\n}\n\nexport { REGIONS as regions };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,OAAO;AACb,IAAM,OAAO,CAAC,OAAe,GAAG,IAAI,IAAI,mBAAmB,EAAE,CAAC;AAGvD,SAAS,SAAS,QAAgB;AACvC,SAAO;AAAA,IACL,MAAM,CAAC,UAA8C,CAAC,MACpD,OAAO;AAA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AAiB,OAAO,gBAAgB,KAAK,MAAM;AAAA,MACnD,QAAQ,OAAO,OAAO,KAAK,MAAM;AAAA,IACnC;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,YAAY;AACd,UAAM,SAAS,KAAK;AACpB,WAAO;AAAA,MACL,QAAQ,CAAC,SAA4C,OAAO,eAAe,IAAI;AAAA,MAC/E,MAAM,MAA2B,OAAO,cAAc;AAAA,MACtD,KAAK,CAAC,QAAmC,OAAO,YAAY,GAAG;AAAA,MAC/D,QAAQ,CAAC,QAA+B,OAAO,eAAe,GAAG;AAAA;AAAA,MAEjE,MAAM,CAAC,KAAa,YAA6C,aAAa,QAAQ,KAAK,OAAO;AAAA,IACpG;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/api/training.ts","../src/index.ts"],"sourcesContent":["import type { Client } from \"./client.ts\";\n\nexport type TrainingRun = {\n id: string;\n name: string;\n sandbox_id: string;\n command_id: string;\n status: \"running\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"interrupted\";\n cancel_requested: boolean;\n created_at: number;\n updated_at: number;\n started_at: number | null;\n ended_at: number | null;\n exit_code: number | null;\n timed_out: boolean;\n gpu_type: string;\n gpu_count: number;\n vcpus: number;\n memory_mib: number;\n stdout: string;\n stderr: string;\n truncated: boolean;\n observation_error: boolean;\n metrics: { step: number; values: Record<string, number> }[];\n artifacts: { path: string; bytes: number; sha256: string }[];\n};\n\nconst base = \"/sandboxes/v1/training-runs\";\nconst path = (id: string) => `${base}/${encodeURIComponent(id)}`;\n\n/** Internal preview. Artifact metadata describes files exported to the SDK client. */\nexport function training(client: Client) {\n return {\n list: (options: { limit?: number; after?: string } = {}) =>\n client.request<{ data: TrainingRun[]; has_more: boolean }>(\n \"GET\",\n `${base}?${new URLSearchParams({ limit: String(options.limit ?? 20), after: options.after ?? \"\" })}`,\n ),\n create: (body: { name: string; sandbox_id: string; command_id: string }) =>\n client.request<TrainingRun>(\"POST\", base, body),\n get: (id: string) => client.request<TrainingRun>(\"GET\", path(id)),\n cancel: (id: string) => client.request<TrainingRun>(\"POST\", `${path(id)}/cancel`, {}),\n artifacts: (id: string, artifacts: TrainingRun[\"artifacts\"]) =>\n client.request<TrainingRun>(\"PUT\", `${path(id)}/artifacts`, { artifacts }),\n delete: (id: string) => client.request<void>(\"DELETE\", path(id)),\n };\n}\n","/** The SDK. `npx @munitoai/cli` and `import { Munito } from \"@munitoai/cli\"` run the same code.\n\n```ts\nimport { Munito } from \"@munitoai/cli\";\n\nconst munito = new Munito({ apiKey: process.env.MUNITO_API_KEY! });\nconst run = await munito.agent.run({ agent: \"claude\", prompt: \"fix the failing test\" });\nconsole.log(run.result);\n```\n*/\n\nimport { training } from \"./api/training.ts\";\nexport type { TrainingRun } from \"./api/training.ts\";\n\nimport { Client, DEFAULT_BASE_URL, REGIONS, type ClientOptions } from \"./api/client.ts\";\nimport { runAgent, type AgentRun, type RunAgentOptions } from \"./core/agents.ts\";\nimport { drop as dropCi, findBase as findCi, job as jobCi, warm as warmCi } from \"./core/ci.ts\";\nimport type {\n CreateProxy,\n CreateSandbox,\n DeployTemplate,\n ListSandboxes,\n OpenProxyPort,\n Proxy,\n ProxyPort,\n Sandbox,\n Template,\n} from \"./api/types.ts\";\nimport { findProxy } from \"./core/proxies.ts\";\nimport { resolveHost } from \"./core/keys.ts\";\nimport { waitForBuild, type WaitOptions } from \"./core/templates.ts\";\n\nexport { ApiError, Client, DEFAULT_BASE_URL, REGIONS } from \"./api/client.ts\";\nexport type { ClientOptions } from \"./api/client.ts\";\nexport * from \"./api/types.ts\";\nexport { AGENT_TEMPLATE, WORKDIR, createAgentSandbox, runAgent, unwrap } from \"./core/agents.ts\";\nexport type { AgentEvent, AgentRun, CreateAgentSandboxOptions, RunAgentOptions, UploadFile } from \"./core/agents.ts\";\nexport * from \"./core/providers.ts\";\nexport { drop as dropCiBase, findBase as findCiBase, job as runCiJob, warm as warmCiBase } from \"./core/ci.ts\";\nexport type { CiEvent, JobOptions, WarmOptions, WarmResult } from \"./core/ci.ts\";\nexport { TemplateError, waitForBuild } from \"./core/templates.ts\";\nexport type { TemplateEvent, WaitOptions } from \"./core/templates.ts\";\nexport { endpoints as proxyEndpoints, findProxy } from \"./core/proxies.ts\";\n\nexport interface MunitoOptions extends Omit<ClientOptions, \"baseUrl\"> {\n /** `global`, `eu`, `us`, or a full URL. */\n region?: string;\n baseUrl?: string;\n}\n\n/** One object for the whole product, in the shape a reader expects from an SDK. */\nexport class Munito {\n readonly client: Client;\n\n constructor(options: MunitoOptions) {\n const baseUrl = options.baseUrl ?? (options.region ? resolveHost(options.region) : DEFAULT_BASE_URL);\n this.client = new Client({ ...options, baseUrl });\n }\n\n get training() {\n return training(this.client);\n }\n\n get agent() {\n return {\n run: (options: RunAgentOptions): Promise<AgentRun> => runAgent(this.client, options),\n };\n }\n\n get ci() {\n const client = this.client;\n return {\n warm: (options: Parameters<typeof warmCi>[1]) => warmCi(client, options),\n job: (options: Parameters<typeof jobCi>[1]) => jobCi(client, options),\n find: (name: string) => findCi(client, name),\n drop: (name: string) => dropCi(client, name),\n };\n }\n\n get sandboxes() {\n const client = this.client;\n return {\n // The API configures the agent. Supply its default key without changing the caller's sandbox options.\n create: (spec: CreateSandbox, idempotencyKey?: string): Promise<Sandbox> =>\n client.createSandbox(\n spec.agent && (spec.provider ?? \"munito\") === \"munito\" && (spec.auth ?? \"token\") === \"token\"\n ? { ...spec, env: { MUNITO_API_KEY: client.token, ...spec.env } }\n : spec,\n undefined,\n idempotencyKey,\n ),\n get: (id: string): Promise<Sandbox> => client.getSandbox(id),\n list: (options?: ListSandboxes): Promise<Sandbox[]> => client.listSandboxes(options),\n delete: (id: string): Promise<void> => client.deleteSandbox(id),\n pause: (id: string): Promise<Sandbox> => client.pauseSandbox(id),\n resume: (id: string): Promise<Sandbox> => client.resumeSandbox(id),\n setTimeout: client.setSandboxTimeout.bind(client),\n fork: client.forkSandbox.bind(client),\n exec: client.exec.bind(client),\n execStream: client.execStream.bind(client),\n readFile: client.readFile.bind(client),\n readFileBytes: client.readFileBytes.bind(client),\n writeFile: client.writeFile.bind(client),\n listFiles: client.listFiles.bind(client),\n deleteFile: client.deleteFile.bind(client),\n startCommand: client.startCommand.bind(client),\n getCommand: client.getCommand.bind(client),\n listCommands: client.listCommands.bind(client),\n signalCommand: client.signalCommand.bind(client),\n deleteCommand: client.deleteCommand.bind(client),\n signPortUrl: client.signPortUrl.bind(client),\n setPort: client.setPort.bind(client),\n createSshAccess: client.createSshAccess.bind(client),\n getSsh: client.getSsh.bind(client),\n };\n }\n\n /** Custom templates: a container image that new sandboxes start from. A deploy answers before its build ends. */\n get templates() {\n const client = this.client;\n return {\n deploy: (spec: DeployTemplate): Promise<Template> => client.deployTemplate(spec),\n list: (): Promise<Template[]> => client.listTemplates(),\n get: (ref: string): Promise<Template> => client.getTemplate(ref),\n delete: (ref: string): Promise<void> => client.deleteTemplate(ref),\n /** Read the template until its newest build is `ready` or `failed`, and return it. */\n wait: (ref: string, options?: WaitOptions): Promise<Template> => waitForBuild(client, ref, options),\n };\n }\n\n /** Proxies: fixed public addresses for sandboxes. A preview, on for an organization with its switch. */\n get proxies() {\n const client = this.client;\n return {\n create: (spec: CreateProxy): Promise<Proxy> => client.createProxy(spec),\n list: (): Promise<Proxy[]> => client.listProxies(),\n /** One proxy, by its id or its name. */\n get: (ref: string): Promise<Proxy> => findProxy(client, ref),\n delete: (id: string): Promise<void> => client.deleteProxy(id),\n openPort: (id: string, spec: OpenProxyPort): Promise<ProxyPort> => client.openProxyPort(id, spec),\n closePort: (id: string, portId: string): Promise<void> => client.closeProxyPort(id, portId),\n };\n }\n}\n\nexport { REGIONS as regions };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,OAAO;AACb,IAAM,OAAO,CAAC,OAAe,GAAG,IAAI,IAAI,mBAAmB,EAAE,CAAC;AAGvD,SAAS,SAAS,QAAgB;AACvC,SAAO;AAAA,IACL,MAAM,CAAC,UAA8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O,QAAQ,KAAK,MAAM;AAAA,MACnC,iBAAiB,OAAO,gBAAgB,KAAK,MAAM;AAAA,MACnD,QAAQ,OAAO,OAAO,KAAK,MAAM;AAAA,IACnC;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,YAAY;AACd,UAAM,SAAS,KAAK;AACpB,WAAO;AAAA,MACL,QAAQ,CAAC,SAA4C,OAAO,eAAe,IAAI;AAAA,MAC/E,MAAM,MAA2B,OAAO,cAAc;AAAA,MACtD,KAAK,CAAC,QAAmC,OAAO,YAAY,GAAG;AAAA,MAC/D,QAAQ,CAAC,QAA+B,OAAO,eAAe,GAAG;AAAA;AAAA,MAEjE,MAAM,CAAC,KAAa,YAA6C,aAAa,QAAQ,KAAK,OAAO;AAAA,IACpG;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,UAAU;AACZ,UAAM,SAAS,KAAK;AACpB,WAAO;AAAA,MACL,QAAQ,CAAC,SAAsC,OAAO,YAAY,IAAI;AAAA,MACtE,MAAM,MAAwB,OAAO,YAAY;AAAA;AAAA,MAEjD,KAAK,CAAC,QAAgC,UAAU,QAAQ,GAAG;AAAA,MAC3D,QAAQ,CAAC,OAA8B,OAAO,YAAY,EAAE;AAAA,MAC5D,UAAU,CAAC,IAAY,SAA4C,OAAO,cAAc,IAAI,IAAI;AAAA,MAChG,WAAW,CAAC,IAAY,WAAkC,OAAO,eAAe,IAAI,MAAM;AAAA,IAC5F;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@munitoai/cli",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "The Munito AI command line tool and SDK: run a coding agent in a sandbox with one command.",
6
6
  "comment": "Three layers, and the rule is one way: cli/ imports core/, core/ imports api/, and nothing imports back. core/ never writes to a terminal, so the same code serves `npx munito` and `import { Munito } from \"munito\"`.",
@@ -1 +0,0 @@
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"],"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 CreateSandbox,\n DeployTemplate,\n ExecCommand,\n FileEntry,\n PortUrl,\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\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-ai\",\n dsh: \"@deepseek-ai/dsh\",\n pi: \"@earendil-works/pi-coding-agent\",\n openclaw: \"openclaw\",\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\nfunction opencodeJson(baseUrl: string, model: string): string {\n return `${JSON.stringify(\n {\n $schema: \"https://opencode.ai/config.json\",\n model: `munito/${model}`,\n provider: {\n munito: {\n npm: \"@ai-sdk/openai-compatible\",\n name: \"Munito\",\n options: { baseURL: baseUrl, apiKey: \"{env:MUNITO_API_KEY}\" },\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 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 ${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"],"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,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