@nomac/cli 0.22.2 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nomac/cli",
3
- "version": "0.22.2",
3
+ "version": "0.23.0",
4
4
  "description": "A real cloud Mac for AI agents: Xcode, the iOS Simulator, signing, TestFlight and App Store publishing, by the minute, over MCP, SSH and HTTPS.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/skill/SKILL.md CHANGED
@@ -38,10 +38,10 @@ Store screenshots start the phone with `device: "iphone-pro-max"` (6.9-inch,
38
38
  not a payment. No Apple Developer account is needed for an unsigned build.
39
39
  Under an hour left, answers say `low_credit` with a `buy_url`: tell the
40
40
  human before a long build (a refill of 3 packs, $30, earns bonus credit).
41
- 2. Install `npm install -g @nomac/cli@0.22.2` (it updates itself after), run `nomac login`, and give the human
41
+ 2. Install `npm install -g @nomac/cli@0.23.0` (it updates itself after), run `nomac login`, and give the human
42
42
  the printed device URL and code. With a key the human made at
43
43
  https://nomac.app/keys: `nomac login --with-token < key.txt`, or set
44
- `NOMAC_API_KEY`. MCP: `claude mcp add nomac -- npx -y @nomac/cli@0.22.2 mcp`.
44
+ `NOMAC_API_KEY`. MCP: `claude mcp add nomac -- npx -y @nomac/cli@0.23.0 mcp`.
45
45
  Hosted MCP: https://mcp.nomac.app/mcp with `Authorization: Bearer <nmk_key>`.
46
46
  3. `nomac start --json`, wait until ready, `nomac sync .`, then `nomac ssh`.
47
47
  Run commands with `nomac exec -- COMMAND`: it prints the output as it
@@ -54,7 +54,8 @@ Store screenshots start the phone with `device: "iphone-pro-max"` (6.9-inch,
54
54
  3600`); longer, use `nomac ssh -- COMMAND`. A command ends with everything
55
55
  it started, so keep a dev server running with `nomac exec -- nomac-service
56
56
  start api -- npx wrangler dev` (`nomac-service logs api`, `stop api`).
57
- `nomac cancel JOB_ID` stops a command. MCP equivalents are `start_mac`, `exec_mac` (also waits),
57
+ `nomac cancel JOB_ID` stops a command. From CI or a script, `nomac run -- COMMAND`
58
+ does it all on a Mac of its own and stops it after. MCP equivalents are `start_mac`, `exec_mac` (also waits),
58
59
  `write_mac_file`, `read_mac_file`, `fetch_to_mac`, `stop_mac`. For a file
59
60
  up to 2 GiB from the human, or to hand them a build, use
60
61
  `create_mac_upload_link` and `create_mac_download_link`: each returns a url
package/src/cli.mjs CHANGED
@@ -15,6 +15,8 @@ Use it:
15
15
  nomac exec -- ls run a command; prints its output, keeps its exit code
16
16
  nomac exec --wait 600 -- xcodebuild test
17
17
  wait up to 10 minutes (the default is 30 seconds)
18
+ nomac run -- xcodebuild test one command on a Mac of its own, then it is stopped: for CI systems
19
+ (GitLab, Buildkite, Jenkins) and scripts (nomac run --help)
18
20
  nomac cancel JOB_ID stop a running command and everything it started
19
21
  nomac ssh open a shell (nomac ssh -- command runs one)
20
22
  nomac ssh-config name this Mac "nomac" in your SSH config: VS Code, Cursor, Claude Code
@@ -70,6 +72,13 @@ export async function main(argv) {
70
72
  const { transportCommand } = await import("./transport-command.mjs");
71
73
  return transportCommand(rest);
72
74
  }
75
+ case "run": {
76
+ // One command on a Mac of its own, stopped after: for CI systems and scripts (nomac run --help).
77
+ const { runCommand } = await import("./run.mjs");
78
+ const { hostedSessionCommand } = await import("./hosted-sessions.mjs");
79
+ process.exitCode = await runCommand(rest, { hosted: hostedSessionCommand });
80
+ return;
81
+ }
73
82
  // Only a cloud Mac has a session password and NoMac's input.
74
83
  case "password":
75
84
  case "input":
@@ -52,7 +52,8 @@ const HELP = `Nomac cloud Mac sessions
52
52
  nomac start --drive none this Mac without the drive
53
53
  nomac start --parallel a second Mac beside the account's running one, from another
54
54
  folder (accounts that bought credit, while a Mac is spare);
55
- it runs without ~/drive. Without it, start uses the running Mac.
55
+ it runs without ~/drive. Without it, a start while the account's Mac
56
+ runs elsewhere is refused and names it: nomac attach ID uses it.
56
57
  nomac ssh-config [--alias nomac] [--print]
57
58
  name this folder's Mac in your SSH config (Host nomac), for
58
59
  VS Code or Cursor Remote-SSH, Claude Code SSH sessions, ssh nomac,
@@ -84,7 +85,7 @@ const HELP = `Nomac cloud Mac sessions
84
85
  nomac extend [MINUTES] [--json] keep the Mac running longer: its time limit goes up by
85
86
  MINUTES (60 by default; 8 hours in all), its spend cap with it
86
87
  nomac attach [SESSION_ID] use the account's running Mac from this folder, when your
87
- agent started it elsewhere (MCP, the dashboard); start does it too
88
+ agent started it elsewhere (MCP, the dashboard); start never does
88
89
  nomac stop [--wait 60] [--json] stop the Mac: deletes it and its files, not ~/drive
89
90
  (your synced project stays there)
90
91
 
@@ -352,7 +353,7 @@ export function tailAfter(part) {
352
353
  /** A command line the person can paste back: simple words as they are, the rest single-quoted. */
353
354
  const shellWords = words => words.map(w => /^[A-Za-z0-9_\/.:=@%+,-]+$/.test(w) ? w : `'${w.replaceAll("'", "'\\''")}'`).join(" ");
354
355
  /** Errors after which the command may or may not have started on the Mac. */
355
- const uncertainOutcome = error => !Number.isInteger(error?.status) || error.status >= 500 || ["outcome_unknown", "operation_pending"].includes(error?.code);
356
+ export const uncertainOutcome = error => !Number.isInteger(error?.status) || error.status >= 500 || ["outcome_unknown", "operation_pending"].includes(error?.code);
356
357
  /** Dollars to the cent, half a cent up, in integers (toFixed rounds an exact half cent down). */
357
358
  const usd = microunits => { const m = BigInt(microunits ?? 0), negative = m < 0n, cents = ((negative ? -m : m) + 5_000n) / 10_000n; return `${negative ? "-" : ""}$${cents / 100n}.${String(cents % 100n).padStart(2, "0")}`; };
358
359
  /** A session's own hourly price (the one it started at), from its offer: "$0.90/hour, ". */
@@ -465,8 +466,9 @@ export async function hostedSessionCommand(command, argv, { store = sessionStore
465
466
  if (!local.workspaceDecided) await placeWorkspace(local);
466
467
  Object.assign(local, { generation: access.generation, hostKey: access.ssh.host_key, target: `agent@nomac-${local.id}`, workspace: local.workspace ?? WORKSPACE, knownHosts: join(store.directory, "known_hosts") });
467
468
  writeFileSync(local.knownHosts, `nomac-${local.id} ${access.ssh.host_key}\n`, { mode: 0o600 }); chmodSync(local.knownHosts, 0o600); store.save(local);
468
- // An SSH config entry this folder made earlier (nomac ssh-config) follows it to this Mac.
469
- refreshSshConfig(local, store.project);
469
+ // An SSH config entry this folder made earlier (nomac ssh-config) follows it to this Mac; a run's own Mac
470
+ // (nomac run, an ephemeral store) never takes the folder's entry.
471
+ if (!store.ephemeral) refreshSshConfig(local, store.project);
470
472
  return local;
471
473
  }
472
474
  /**
package/src/run.mjs ADDED
@@ -0,0 +1,163 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, rmSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { parseArgs } from "node:util";
6
+ import { api, CliError } from "./api.mjs";
7
+ import { uncertainOutcome } from "./hosted-sessions.mjs";
8
+ import { sessionStore } from "./session-store.mjs";
9
+
10
+ export const RUN_HELP = `nomac run [options] -- command args
11
+ One command on a fresh Mac of its own, then the Mac is stopped: for CI systems (GitLab,
12
+ Buildkite, Bitbucket, Jenkins) and scripts. It starts a Mac, uploads this folder as
13
+ nomac sync . does (not .git, build output, dependency folders or secret files), runs the
14
+ command there, copies back what --pull names (also when the command failed), and stops the
15
+ Mac. stdout is the command's output; nomac run's own lines go to stderr. Its exit code is
16
+ the command's. It never uses or stops a Mac you or your agents run, and runs without the
17
+ drive: nothing carries over from one run to the next. While it runs it counts as one of
18
+ the account's Macs.
19
+ --timeout SECONDS the command's limit, 60 to 3540 (the default)
20
+ --pull PATH after the command, copy PATH (relative to the project folder) here;
21
+ repeat it for more
22
+ --no-sync upload nothing (the command fetches what it needs)
23
+ --queue SECONDS how long to wait for a Mac when the account runs as many as it may
24
+ (600 by default; 0 fails at once)
25
+ --max-cost DOLLARS what this run may spend at most (5 by default)
26
+ The command is one argv; for a shell line: nomac run -- bash -lc 'pod install && make test'.
27
+ Nothing is read from stdin. Needs NOMAC_API_KEY (a CI secret) or nomac login, and the
28
+ OpenSSH client (ssh, ssh-keygen). A cancelled job (SIGTERM, SIGINT, SIGHUP) stops the Mac.
29
+ One killed outright (SIGKILL) cannot: the command runs on to --timeout and the Mac stops
30
+ 15 minutes after. Billed per minute.
31
+ Example: nomac run --pull build/tests.xcresult -- xcodebuild test -scheme App
32
+ -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -resultBundlePath build/tests.xcresult`;
33
+
34
+ const options = {
35
+ timeout: { type: "string" }, pull: { type: "string", multiple: true }, "no-sync": { type: "boolean" },
36
+ queue: { type: "string" }, "max-cost": { type: "string" }, help: { type: "boolean", short: "h" },
37
+ };
38
+ /** A command's limit: the CLI waits a minute past it (up to the gateway's hour), so it sees the command end. */
39
+ const MAX_TIMEOUT = 3540;
40
+
41
+ /** A promise, or an error after ms on a real clock (a hung connection must not hold a cancelled job past its grace time). */
42
+ function within(promise, ms) {
43
+ let timer;
44
+ const late = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`no answer in ${ms / 1000} s`)), ms); });
45
+ return Promise.race([promise, late]).finally(() => clearTimeout(timer));
46
+ }
47
+
48
+ function whole(value, fallback, min, max, what) {
49
+ if (value === undefined) return fallback;
50
+ if (!/^\d{1,5}$/.test(value) || Number(value) < min || Number(value) > max) throw new CliError(`${what} is whole seconds from ${min} to ${max}.`);
51
+ return Number(value);
52
+ }
53
+
54
+ /**
55
+ * nomac run: start, sync, exec and pull as those commands do them, under a session state of the run's own (a fresh
56
+ * directory, removed after, marked ephemeral so the folder's SSH config entry is left alone), always with --parallel and
57
+ * without the drive, so it never takes or touches a Mac or drive someone uses. The Mac is stopped with one API call (no
58
+ * folder lock to wait for) at the end, after any failure, and on the first SIGTERM or SIGINT (later ones, such as npm
59
+ * forwarding the same signal, are ignored), which then exits 143 or 130. Returns the command's exit code.
60
+ */
61
+ export async function runCommand(argv, {
62
+ hosted, request = api, print = console.log, stderr = data => process.stderr.write(data), cwd = process.cwd(),
63
+ stateRoot = join(homedir(), ".nomac", "runs"), signals = process, exit = code => process.exit(code),
64
+ sleep = ms => new Promise(resolve => setTimeout(resolve, ms)), now = Date.now,
65
+ } = {}) {
66
+ const at = argv.indexOf("--");
67
+ const usage = () => new CliError("Usage: nomac run [options] -- command args (nomac run --help)");
68
+ if (at < 0 && !argv.some(arg => arg === "--help" || arg === "-h")) throw usage();
69
+ let parsed;
70
+ try { parsed = parseArgs({ args: at < 0 ? argv : argv.slice(0, at), options, allowPositionals: false }); }
71
+ catch (error) { throw new CliError(`${error.message} (nomac run --help)`); }
72
+ if (parsed.values.help) { print(RUN_HELP); return 0; }
73
+ if (at < 0 || at === argv.length - 1) throw usage();
74
+ const { values } = parsed, command = argv.slice(at + 1);
75
+ const timeout = whole(values.timeout, MAX_TIMEOUT, 60, MAX_TIMEOUT, "--timeout"), queue = whole(values.queue, 600, 0, 3600, "--queue");
76
+ if (values["max-cost"] !== undefined && !/^\d+(\.\d{1,2})?$/.test(values["max-cost"])) throw new CliError("--max-cost is dollars, such as 5 or 2.50.");
77
+
78
+ const state = join(stateRoot, randomUUID());
79
+ mkdirSync(state, { recursive: true, mode: 0o700 });
80
+ const store = { ...sessionStore(cwd, state), ephemeral: true };
81
+ const say = line => stderr(`nomac run: ${line}\n`);
82
+ // Every step's own summary goes to stderr: stdout carries the command's output only.
83
+ const step = (name, args, extra = {}) => hosted(name, args, { store, request, print: line => stderr(`${line}\n`), readInput: async () => null, ...extra });
84
+ let code = 1, stopping, signalled = false;
85
+
86
+ /** Stops the run's Mac once. A start whose answer was lost is asked again with its own key, which answers with the Mac it made (or makes it, to be stopped at once). */
87
+ const stop = () => stopping ??= (async () => {
88
+ const local = store.load();
89
+ let id = local?.id;
90
+ // Only a start whose outcome is unknown: one refused (no credit, the account's limit) made no Mac, and asking again could make one.
91
+ if (!id && local?.requestKey && local.outcomeUnknown && local.state !== "failed" && local.request) {
92
+ try { id = (await request("POST", "/api/v1/mac/sessions", { idempotencyKey: local.requestKey, body: local.request }))?.session?.id; } catch { /* it was never made */ }
93
+ }
94
+ if (!id) return;
95
+ for (let attempt = 1; ; attempt++) {
96
+ try {
97
+ await within(request("DELETE", `/api/v1/mac/sessions/${encodeURIComponent(id)}`), 20_000);
98
+ say(`stopped ${id}`); return;
99
+ }
100
+ catch (error) {
101
+ if (attempt >= 3) { say(`could not confirm ${id} stopped (${error.friendly ?? error.message}); it stops at its time limit, and nomac credits shows what it used`); return; }
102
+ await sleep(2000 * attempt);
103
+ }
104
+ }
105
+ })();
106
+ const cleanup = () => {
107
+ signals.off("SIGINT", onInt); signals.off("SIGTERM", onTerm); signals.off("SIGHUP", onHup);
108
+ rmSync(state, { recursive: true, force: true });
109
+ };
110
+ const onSignal = signal => {
111
+ if (signalled) return;
112
+ signalled = true;
113
+ say(`${signal}: stopping the Mac`);
114
+ void stop().finally(() => { cleanup(); exit({ SIGINT: 130, SIGHUP: 129 }[signal] ?? 143); });
115
+ };
116
+ // on, not once: npm exec forwards a group's signal to this process, which would otherwise die of the second one.
117
+ const onInt = () => onSignal("SIGINT"), onTerm = () => onSignal("SIGTERM"), onHup = () => onSignal("SIGHUP");
118
+ signals.on("SIGINT", onInt); signals.on("SIGTERM", onTerm); signals.on("SIGHUP", onHup);
119
+
120
+ try {
121
+ // The Mac lives a little past the command's limit (the start, the upload, the pull), and stops at the end anyway.
122
+ const start = ["--wait", "600", "--parallel", "--drive", "none", "--max-duration", String(Math.min(28_800, timeout + 1800)), "--idle-timeout", "900",
123
+ ...(values["max-cost"] ? ["--max-cost", values["max-cost"]] : [])];
124
+ const until = now() + queue * 1000;
125
+ let started;
126
+ for (let waited = false; ; waited = true) {
127
+ if (signalled) return code;
128
+ say(waited ? "starting a Mac (another try)" : "starting a Mac");
129
+ try { started = await step("start", start); break; }
130
+ catch (error) {
131
+ // The account already runs as many Macs as it may: a pipeline waits its turn, a bounded time.
132
+ if (error?.code !== "session_limit_reached" || now() >= until) throw error;
133
+ say(`the account runs as many Macs as it may; waiting for one to stop (up to ${Math.ceil((until - now()) / 1000)} s more)`);
134
+ await sleep(15_000);
135
+ }
136
+ }
137
+ if (started?.session?.state !== "ready") throw new CliError(`The Mac did not become ready (it is ${started?.session?.state ?? "unknown"}).`);
138
+ if (!values["no-sync"]) { say("uploading this folder"); await step("sync", ["."]); }
139
+ say(`running ${command.join(" ").slice(0, 200)}`);
140
+ // A key of its own: after a lost connection the same command is asked for again (it keeps running), never run twice.
141
+ const exec = ["--wait", String(timeout + 60), "--timeout", String(timeout), "--request-key", `run-${randomUUID()}`, "--", ...command];
142
+ for (let attempt = 1; ; attempt++) {
143
+ try { await step("exec", exec, { exitWith: exitCode => { code = exitCode; } }); break; }
144
+ catch (error) {
145
+ if (signalled || attempt >= 4 || !uncertainOutcome(error)) throw error;
146
+ say(`lost the answer from the Mac (${error.friendly ?? error.message}); asking for the same command again, which keeps running (its output so far is printed again)`);
147
+ await sleep(5000 * attempt);
148
+ }
149
+ }
150
+ for (const path of values.pull ?? []) {
151
+ try { await step("pull", [path]); }
152
+ catch (error) { say(`could not copy ${path} back: ${error.friendly ?? error.message}`); if (code === 0) code = 1; }
153
+ }
154
+ return code;
155
+ } catch (error) {
156
+ // A step a signal broke (sync's child killed by the group's SIGTERM) must not exit before the Mac is stopped: the
157
+ // signal path stops it and exits 143 or 130.
158
+ if (signalled) await new Promise(() => {});
159
+ throw error;
160
+ } finally {
161
+ if (!signalled) { await stop(); cleanup(); }
162
+ }
163
+ }