@nomac/cli 0.22.1 → 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.1",
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.1` (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.1 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
@@ -157,8 +158,9 @@ testing an app's own.
157
158
  Never ask for a secret in the chat. `nomac secrets request NAME --description
158
159
  TEXT` (MCP `request_secret`) gives the human a link to enter it; they can also
159
160
  run `nomac secrets set NAME` themselves. Every Mac receives the account's
160
- secrets as variables and files, masked in command output; `nomac secrets
161
- install` refreshes a running Mac.
161
+ secrets as variables and files, masked in command output, and a change
162
+ reaches running Macs within a minute; `nomac secrets install NAME` adds one
163
+ set to on request.
162
164
 
163
165
  The human connects Apple once at https://nomac.app/apple; the App Store
164
166
  Connect key stays on NoMac's server. Check `nomac apple` (MCP
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/mac-tools.mjs CHANGED
@@ -29,11 +29,11 @@ export const MAC_TOOLS = [
29
29
  { name: "get_mac_drive", description: "Read the account's persistent drive: a disk kept between sessions and mounted at ~/drive on every Mac (20 GB). What is there stays for the next session: keep projects in ~/drive/src for incremental builds; package and build caches (DerivedData, Swift packages, CocoaPods, npm) are kept there already. NoMac saves it when a Mac stops, with nothing to call. Shows the space used, the newest saved version, a save still in progress, recent versions, and the date it is deleted after 90 days without a Mac.", inputSchema: schema({}), handler: async () => text(await api("GET", "/api/v1/mac/drive")) },
30
30
  { name: "reset_mac_drive", description: "Empty the account's persistent drive: the next Mac starts with a new, empty ~/drive, and everything on the old drive is deleted, with no way back. Stop any running session first (stop_mac). For a single Mac without the drive, start_mac with access drive none instead.", inputSchema: schema({}), handler: async () => text(await api("DELETE", "/api/v1/mac/drive")) },
31
31
  { name: "list_secrets", description: "List the account's secrets by name: variables (set in every shell and command on the Mac) and files (with their path on the Mac), whether every Mac receives them or only when asked, sizes, and secrets an agent asked for that the person has not entered yet. Values are never returned.", inputSchema: schema({}), handler: async () => text(await api("GET", "/api/v1/secrets")) },
32
- { name: "request_secret", description: "Get a link where the person enters a secret in their browser, so its value never passes through this chat: an API token, a .env value, a .p12 certificate or a config file. kind variable is one line of text, set as an environment variable on the Mac; kind file is stored at destination (under the home folder, like ~/.netrc; default ~/.nomac/secrets/<name>). Give the url to the person who holds the value; they need no NoMac account, and it works once, for 24 hours. Then list_secrets shows it, new Macs receive it, and install_secrets puts it on a running Mac. With a shell on this machine, the person can also run nomac secrets set NAME themselves. Never ask for a secret in the chat.", inputSchema: schema({ name: { type: "string", minLength: 1, maxLength: 128 }, kind: { type: "string", enum: ["variable", "file"] }, description: { type: "string", minLength: 1, maxLength: 500, description: "What the person should enter and why; shown to them" }, destination: { type: "string", maxLength: 256 }, delivery: { type: "string", enum: ["every_mac", "on_request"] } }, ["name", "kind", "description"]), handler: async body => text(await api("POST", "/api/v1/secrets/requests", { body })) },
32
+ { name: "request_secret", description: "Get a link where the person enters a secret in their browser, so its value never passes through this chat: an API token, a .env value, a .p12 certificate or a config file. kind variable is one line of text, set as an environment variable on the Mac; kind file is stored at destination (under the home folder, like ~/.netrc; default ~/.nomac/secrets/<name>). Give the url to the person who holds the value; they need no NoMac account, and it works once, for 24 hours. Then list_secrets shows it, and it reaches running Macs within a minute, and new ones unless it is on_request. With a shell on this machine, the person can also run nomac secrets set NAME themselves. Never ask for a secret in the chat.", inputSchema: schema({ name: { type: "string", minLength: 1, maxLength: 128 }, kind: { type: "string", enum: ["variable", "file"] }, description: { type: "string", minLength: 1, maxLength: 500, description: "What the person should enter and why; shown to them" }, destination: { type: "string", maxLength: 256 }, delivery: { type: "string", enum: ["every_mac", "on_request"] } }, ["name", "kind", "description"]), handler: async body => text(await api("POST", "/api/v1/secrets/requests", { body })) },
33
33
  { name: "set_up_signing", description: "Set up App Store signing for a project on the Mac, with the App Store Connect key kept on NoMac's server: reads the project at path (its scheme, app and every extension, with entitlements), registers missing bundle IDs, switches on the capabilities Apple's API can, makes the App Store profiles, and installs them with the account's certificate in a keychain on the Mac. The project never changes. Returns a build settings file (.xcconfig) and export options with the exact xcodebuild, Flutter and fastlane commands. Creates a distribution certificate at Apple only when the account has none. Expo and Capacitor apps need their ios folder first. A step only a person can take comes back as needs_human with its link.", inputSchema: schema({ session_id: session, path: { type: "string", minLength: 1, maxLength: 1024, description: "The project folder on the Mac, relative to the workspace" }, scheme: { type: "string", minLength: 1, maxLength: 256 }, container: { type: "string", minLength: 1, maxLength: 1024 }, issuer_id: { type: "string", maxLength: 64 } }, ["session_id"]), handler: async ({ session_id, ...body }) => text(await api("POST", `${base({ session_id })}/signing`, { body })) },
34
34
  { name: "send_to_testflight", description: "Send a signed .ipa on the Mac to TestFlight, with the App Store Connect key kept on NoMac's server: NoMac creates the upload at Apple and the Mac sends only the file. Apple then processes the build, usually for 5 to 15 minutes with no Mac needed, and NoMac sets the app's export-compliance answer and What to Test and puts it on TestFlight for the internal testers. Repeat the call with the returned request_key to follow it: sending, processing, on_testflight or failed. Once on_testflight, publish with the returned project_id and build_id submits it for App Review. Apple asks once per app whether it uses encryption beyond HTTPS and Apple's own: pass the person's answer as uses_non_exempt_encryption, never a guess. A build number Apple already has comes back with the next free one. A step only a person can take, such as creating the app in App Store Connect, comes back as needs_human with its link.", inputSchema: schema({ session_id: session, path: { type: "string", minLength: 1, maxLength: 1024, description: "The signed .ipa on the Mac, relative to the workspace or absolute" }, notes: { type: "string", minLength: 1, maxLength: 4000, description: "What to Test, shown to testers" }, uses_non_exempt_encryption: { type: "boolean", description: "The person's answer, asked once per app: does it use encryption beyond HTTPS and Apple's own?" }, issuer_id: { type: "string", maxLength: 64 }, request_key: { ...key, description: "Repeat with the request_key from the first answer to follow that send" }, wait_seconds: { type: "integer", minimum: 0, maximum: 50, description: "Wait up to this long for progress (50 while following)" } }, ["session_id", "path"]), handler: async ({ session_id, ...body }) => text(await api("POST", `${base({ session_id })}/testflight`, { body })) },
35
35
  { name: "notarize", description: "Notarize a Developer ID-signed Mac app, disk image or installer on the Mac (.app, .dmg, .pkg or .zip), with the App Store Connect key kept on NoMac's server: the Mac zips an .app and sends the file to Apple with temporary credentials for this one submission. Apple checks it, usually for a few minutes, then the Mac staples the ticket so it opens without a warning, even offline. Repeat the call with the returned request_key to follow it: preparing, uploading, in_progress, stapling, then accepted, invalid or rejected with Apple's issues. Sign first with the Developer ID Application certificate (the person uploads it at nomac.app/apple), the hardened runtime and a secure timestamp: codesign --force --options runtime --timestamp --sign \"Developer ID Application: …\". Keep the Mac running until it is stapled.", inputSchema: schema({ session_id: session, path: { type: "string", minLength: 1, maxLength: 1024, description: "The .app, .dmg, .pkg or .zip on the Mac, relative to the workspace or absolute" }, issuer_id: { type: "string", maxLength: 64 }, request_key: { ...key, description: "Repeat with the request_key from the first answer to follow that notarization" }, wait_seconds: { type: "integer", minimum: 0, maximum: 50, description: "Wait up to this long for progress (50 while following)" } }, ["session_id", "path"]), handler: async ({ session_id, ...body }) => text(await api("POST", `${base({ session_id })}/notarize`, { body })) },
36
- { name: "install_secrets", description: "Install the account's secrets and signing identities on a running Mac now: every-Mac secrets, the on-request secrets named in names, and what the Mac already has; a deleted secret is removed. Macs receive every-Mac secrets on their own when they become ready, so call this after the person adds or changes one.", inputSchema: schema({ session_id: session, names: { type: "array", items: { type: "string", minLength: 1, maxLength: 128 }, maxItems: 100 } }, ["session_id"]), handler: async ({ session_id, names = [] }) => text(await api("POST", `${base({ session_id })}/secrets`, { body: { names } })) },
36
+ { name: "install_secrets", description: "Install the account's secrets and signing identities on a running Mac now: every-Mac secrets, the on-request secrets named in names, and what the Mac already has; a deleted secret is removed. Changes reach running Macs on their own within a minute: call this for on-request secrets, or after a failed install. Without names it also rebuilds files and the keychain: not during an archive.", inputSchema: schema({ session_id: session, names: { type: "array", items: { type: "string", minLength: 1, maxLength: 128 }, maxItems: 100 } }, ["session_id"]), handler: async ({ session_id, names = [] }) => text(await api("POST", `${base({ session_id })}/secrets`, { body: { names } })) },
37
37
  { name: "open_mac_desktop", description: "Open the Mac's full macOS desktop in the human's browser on this machine, with mouse and keyboard and nothing to install. Use it when the human wants to see or click something on the Mac, for example Xcode, the Simulator or a sign-in window. The session must be ready. If opened_in_browser is false, give the human the returned url; it opens after they sign in to nomac.app. The session stays busy while the desktop is open and the page disconnects after 15 minutes without input. To show the iOS Simulator there, boot a device with simctl, then run open -a Simulator || open -a DeviceHub in a shell with exec_mac (Xcode 27 replaced Simulator.app with Device Hub; Xcode 26's Simulator.app, kept beside it, shows iOS 27 devices too). macOS has no RDP.", inputSchema: schema({ session_id: session, open: { type: "boolean", default: true, description: "Open the link in this machine's browser." } }, ["session_id"]), handler: async ({ session_id, open = true }) => {
38
38
  const view = await api("GET", base({ session_id }));
39
39
  if (view?.session?.state !== "ready") return text({ error: { code: "session_not_ready", message: "The Mac is not ready. Wait until get_mac_session shows ready, then call open_mac_desktop again." } });
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
+ }
package/src/secrets.mjs CHANGED
@@ -12,7 +12,8 @@ come back from NoMac, and are never taken as command-line arguments.
12
12
  nomac secrets set --from-env-file .env every NAME=value line as a variable
13
13
  --on-request only when asked (install NAME), not on every Mac
14
14
  nomac secrets rm NAME delete it
15
- nomac secrets install [NAME...] put them on this folder's Mac now [--session ses_…]
15
+ nomac secrets install [NAME...] on-request ones on this folder's Mac now [--session ses_…]
16
+ (changes to the others reach running Macs on their own)
16
17
  nomac secrets request NAME --description TEXT [--kind file] [--destination ~/x]
17
18
  a link for whoever holds it to enter it once,
18
19
  in the browser, with no NoMac account
@@ -109,12 +110,13 @@ export async function secretsCommand(args, { api = defaultApi, print = console.l
109
110
  body = { kind: "variable", value: await readValue(stdin, write), delivery };
110
111
  }
111
112
  const result = await api("PUT", path(names[0]), { body });
112
- return out(result, `Saved ${result.secret.name}. New Macs receive it; run nomac secrets install to put it on a running Mac.`);
113
+ // The server says where it goes (running Macs, new ones, or only when asked), so an installed CLI stays right.
114
+ return out(result, `Saved ${result.secret.name}.${result.next_action ? ` ${result.next_action}` : ""}`);
113
115
  }
114
116
  if (command === "rm" || command === "delete") {
115
117
  if (names.length !== 1) throw new CliError("rm usage", "Usage: nomac secrets rm NAME");
116
118
  const result = await api("DELETE", path(names[0]));
117
- return out(result, `Deleted ${names[0]}. Macs started from now on do not receive it; a running Mac keeps its copy until it stops.`);
119
+ return out(result, `Deleted ${names[0]}.${result.next_action ? ` ${result.next_action}` : ""}`);
118
120
  }
119
121
  if (command === "install") {
120
122
  const session = values.session ?? store?.load()?.id;