Metadata-Version: 2.5
Name: nomac
Version: 1.1.0
Summary: NoMac from Python: a cloud Mac or an iPhone Simulator for each of your users and agents, billed per minute. Commands, files, screen, live desktop and phone links, per-user drives and tokens, webhooks.
Project-URL: Homepage, https://nomac.app/platform
Project-URL: Documentation, https://nomac.app/docs/sdks
License-Expression: MIT
License-File: LICENSE
Keywords: agents,ios,iphone,mac,macos,nomac,sandbox,simulator,xcode
Classifier: Framework :: AsyncIO
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Description-Content-Type: text/markdown

# nomac

NoMac from Python: a cloud Mac or an iPhone Simulator for each of your users and agents, billed per minute. A Mac runs commands, holds files, shows its screen and desktop, and keeps each user's drive between sessions. A phone builds, runs and tests an iOS app, ready in seconds. Tokens for one Mac or phone, and webhooks for your backend.

```sh
pip install nomac
```

Python 3.10 and later, one dependency (`httpx`), typed. `NoMac` for sync code, `AsyncNoMac` for asyncio: the same calls, awaited.

## A Mac for each of your users

```python
from nomac import NoMac

nomac = NoMac()  # NOMAC_API_KEY from the environment
mac = nomac.macs.start(label="user-42", reuse=True)
mac.wait_until_ready()
result = mac.run("sw_vers && xcodebuild -version")
print(result.exit_code, result.stdout)

link = mac.view_link(control=True)["url"]  # the Mac's desktop, for your user, no sign-in
token = mac.token()["token"]               # this Mac only, for your user's own agent
mac.stop()                                 # ~/drive is saved for user-42's next Mac
```

```python
from nomac import AsyncNoMac

async with AsyncNoMac() as nomac:
    mac = await nomac.macs.start(label="user-42", reuse=True)
    await mac.wait_until_ready()
    print((await mac.run(["/usr/bin/uname", "-a"])).stdout)
    await mac.stop()
```

A Mac and a phone are billed per minute from the account's prepaid credit, with a one-minute minimum ([pricing](https://nomac.app/docs/pricing)). Waiting in line is free. `nomac.credits()` answers what the credit can spend and the time that buys.

## Macs

`nomac.macs.start(...)` starts a Mac and answers it at once, `queued` or `provisioning`. `mac.wait_until_ready()` follows it, usually under a minute.

- `label`: your user's id (letters, digits and `. _ : @ -`, up to 64). The Mac gets that user's drive at `~/drive` and none of the account's secrets.
- `reuse`: with `label`, the user's starting or running Mac is the answer (`mac.reused`) instead of a second one.
- `require_drive`: with `label`, the start ends (`drive_unavailable`, nothing charged) rather than run without the user's drive.
- `queue_seconds`: wait in line, free, up to this long (300 to 3,600 s) when no Mac is free or the account runs its most at once.
- `limits`: `max_duration_seconds` (7,200 by default; a Mac has no longest time), `idle_timeout_seconds` (600 by default, 60 to 3,600) and `spend_cap_microunits` (`"5000000"`, $5, by default).
- `access`, `parallel` and `public_key`: macOS prompts and permissions, a second Mac beside a running one, and an SSH key, as in the [REST API](https://nomac.app/docs/api).

A retry of a start with the same `idempotency_key` answers the same Mac, never a second one.

`nomac.macs.list(label=, labeled=, state=, before=, limit=)` answers a `MacPage`: `macs`, newest first, and `more`. Pass `label` for one user's Macs, `labeled=True` for all your users', `state="live"` or `"ended"`, and the last Mac's id as `before` for the next page. `nomac.macs.get(id)` reads one; `nomac.mac(id)` is a Mac by its id without reading it.

`mac.session` has its state, label, drive, cost and limits; `mac.refresh()` reads it again. In its last 15 minutes before a limit or the credit's end, `mac.stop_notice` says when it stops, why and what to do first. `mac.extend(minutes=60)` keeps it running longer, its spend cap with it. `mac.stop()` ends it: the Mac and every file outside `~/drive` are deleted, and `~/drive` is saved for the next Mac.

## Commands

`mac.run(command, cwd=, env=, timeout_seconds=)` runs a command and waits for it to end. A string runs in `bash -lc` (pipes, `&&`, globs); a list runs as it is. It answers a `CommandResult`: `exit_code`, `stdout`, `stderr` and `truncated`. A non-zero exit code is answered, not raised. The output is whole; past 8 MiB it is the kept start and each stream's last 64 KiB, with `truncated` set. If the output can no longer be read at all, `output_error` says why and `exit_code` still holds.

`timeout_seconds` stops the command on the Mac (300 by default, 3,600 at most); `timeout` is how long `run` waits for it (2 hours). The same `idempotency_key` never runs a command twice, so a retry after a lost answer is safe. `mac.jobs.start(command)`, `get(id, wait_seconds=)`, `wait(id)` and `cancel(id)` work with a command as a job: never run a command again for its output, wait for its job.

## Files

`mac.files.write(path, content, executable=)` writes text (a `str`) or bytes; `mac.files.read(path)` reads text, `read_bytes(path)` bytes. Relative paths are in the workspace and `~` is home. Files over 3 MiB go through a link by themselves, up to 2 GiB.

`mac.files.upload(path, data, extract=)` puts text, bytes or a local file (a `pathlib.Path`, read in pieces) on the Mac and waits until it is there; `extract="zip"` or `"tar"` unpacks an archive. `mac.files.download(path)` answers a file's bytes, or a folder's as a zip, and `mac.files.download_to(path, destination)` streams it into a local file, for files too large to hold (up to 2 GiB). `upload_link(path)` and `download_link(path)` make links for a person, with no NoMac account; a download link keeps working after the Mac stops, until it expires.

## Screen, keyboard and mouse

`mac.screenshot()` answers a `Screenshot`: `image` (JPEG bytes, 1440x900, pixels are screen points), `front_app`, `screen_locked`, `dialog` and `next_step`. `target="simulator"` shows the Mac's booted Simulator instead. `mac.input("click", x=100, y=200)` clicks, and `"type"` (`text=`), `"key"` (`keys=["cmd+s"]`, one key may be a string), `"move"`, `"scroll"`, `"password"` and `"unlock"` work the same way; macOS takes them as a person's. `mac.start_recording(max_seconds=)` and `stop_recording()` make a video of the screen. `mac.password()` answers the Mac's login password, also `$NOMAC_MAC_PASSWORD` on the Mac.

## Your users on their Mac

`mac.view_link(control=True, minutes=120)` is a link to the Mac's desktop for your user, with no NoMac sign-in, in a browser or an iframe (add `?embed=1`). Without `control` it is watch only. One person controls at a time; the newest takes over.

Keep a link on your site and for your user:

```python
from nomac import sign_visitor

secret = nomac.embed.new_secret()["secret"]  # once; keep it on your server as NOMAC_EMBED_SECRET
url = mac.view_link(control=True, allowed_origins=["https://app.example.com"], visitor=user.id)["url"]
visitor = sign_visitor(os.environ["NOMAC_EMBED_SECRET"], mac.id, user.id)
# In your page: <iframe src="{url}?embed=1#visitor={visitor}">
```

`allowed_origins` lets only those sites frame the link, and browsers open it nowhere else. `visitor` makes it open only with your server's signature for that user, so a copied link opens nothing, in a browser or not. A signature lasts 5 minutes by default (15 at most), so sign one each time your page loads; the page then keeps working until the link expires. `nomac.embed.set(allowed_origins=[...], require_visitor=True)` makes both the default for every link made over the API from then on, the links in each phone's answer and those a token makes among them. `phone.view_link` takes the same options.

`mac.token(minutes=)` is a token for that Mac only, to hand your user or their own agent: `NoMac(token=...).mac(id)` reaches its commands, files, screen, input and view links. It never reaches another Mac, a start, a stop or the account. Both last 2 hours by default, a day at most, and work only on your user's Mac (started with a `label`). `mac.revoke_tokens()` revokes every token and link of the Mac made so far.

`nomac.labels.get("user-42")` answers what NoMac keeps for a user: their running Macs and phones, and their drive (what it holds, its last save, whether its saves are charged, when it expires unused).

## Phones

```python
phone = nomac.phones.start(label="user-42", reuse=True)
phone.wait_until_ready()
root = phone.fetch_git("https://github.com/acme/app", token=github_token)["root"]
print(phone.tool("app_run", path=root, scheme="App").text)
phone.stop()
```

`nomac.phones.start(device=, label=, reuse=, limits=)` starts a phone and answers it at once, usually `queued`; `phone.wait_until_ready()` follows it. A phone from the pool is ready in seconds. When every phone is in use, the start waits in line, free, up to 5 minutes.

- `device`: `"iphone"` (iPhone 17 Pro, the default), `"ipad"` (iPad Pro 11-inch (M5)) or `"iphone-pro-max"` (iPhone 17 Pro Max), all on iOS 27.
- `label`: your own name for the phone, such as your user's id: letters, digits and `. _ : @ -`, up to 64.
- `reuse`: with `label`, answer the live phone with that label instead of starting another (`phone.reused`).
- `limits`: `max_duration_seconds` (7,200 by default, 28,800 at most), `idle_timeout_seconds` (600 by default, 60 to 3,600) and `spend_cap_microunits` (`"5000000"`, $5, by default).

An account runs two phones at once by default; [NoMac Platform](https://nomac.app/platform) runs more. A retry of a start with the same `idempotency_key` answers the same phone, never a second one.

`nomac.phones.list(label=)` lists the account's phones, newest first, and `nomac.phones.get(id)` reads one. `phone.session` has its state, device, label, cost and deadlines; `phone.refresh()` reads it again. `phone.extend(minutes=)` keeps a running phone longer, up to 8 hours in all. `phone.stop()` ends it: its apps and data go with it, and its workspace (projects and build output) stays for the next phone with the same label, so the next build is incremental.

### Tools

`phone.tool(name, arguments)` runs one of [simulator-use](https://simulator-use.dev)'s tools on the phone, its arguments as a dict or as keywords, and answers a `ToolResult`: `text` says what happened and what to do next, `content` has its text and images, `is_error`, and `stop_notice` in the phone's last 15 minutes. A long build is followed to its end.

| Tool | |
| --- | --- |
| `app_run` | Builds an Xcode project or workspace (`path`, `scheme`) with Xcode 27.1, installs it and launches it. |
| `tests_run` | Runs XCTest and XCUITest, each case's result as it finishes. |
| `ui_look` | The screen as text, one line per element with its label and position. |
| `ui_act` | Taps, types, swipes and keys by label: `steps=['tap "Sign In"', "fill #email a@b.co"]`. |
| `app_control` | Installs, launches and terminates apps, opens links, sets permissions, appearance, locale, time zone and location. |
| `app_logs`, `screen_record`, `devices`, `job_status`, `job_cancel` | Logs, video, the phone and Xcodes, long jobs. |

Projects reach the phone's workspace with `phone.fetch_git(url, ref=, token=)` or `phone.upload_archive(data, name=)` (bytes or a file's path: a `.tar.gz` or `.zip` of a project, or of a `.app` built for the Simulator, up to 2 GiB). Both answer `root`, the path `app_run` and `tests_run` take; only what changed is written.

A private repository on github.com, gitlab.com or bitbucket.org takes its token one of two ways, and it goes only to that host:

- `token`: the token itself, sent with this fetch and kept nowhere, not even for the phone's next fetch. Your user's token stays with you, and a short-lived one (GitHub's one-hour tokens) works. A phone's token may send one.
- `secret`: the name of one of the account's own secrets that holds it, for your own repositories (the account's key only).

Values your app needs go with the run, as `env` on `app_run` (`"API_URL=https://staging.example KEY=..."`): the phone keeps them for its relaunches until it stops, and they are erased with it.

### A phone's live view and tokens

`phone.links["view"]` (watch) and `phone.links["control"]` (use) are links a person opens with no NoMac sign-in; `phone.view_link(control=True, minutes=120)` makes one for your user. [`@nomac/phone`](https://www.npmjs.com/package/@nomac/phone) embeds it in your page.

`phone.token(minutes=)` gives a token for that phone only, to hand your own user or agent: `NoMac(token=...)` reaches that phone's tools, files, state, view and replay until the token expires (2 hours by default, a day at most). It cannot start, list or stop phones, make another token, use the account's secrets, or reach your webhooks. `phone.revoke_tokens()` revokes every token and link of the phone made so far.

Phones are kept apart by `label`: a workspace and saved states are shared only by phones with the same label. Give each of your users their own label, and one user's phone, or its token, never reaches another's.

### Saved state and replays

`phone.save_state("signed-in")` keeps the phone's apps, their data, its keychain and permissions for the phones with its label; `phone.restore_state("signed-in")` puts them back onto any of them of the same model and iOS. `phone.list_states()` and `phone.delete_state(name)` manage them. Every phone is recorded: `phone.replay()` answers its video and its calls (typed text left out) once it has stopped, kept 7 days. `screen_record` cuts its MP4 out of the replay; one still running when the phone stops ends there, and `phone.recording` (after `stop()`, or `refresh()` once the phone stopped by itself) has its `url`, which opens about a minute after the stop.

## Deleting a user's data

When one of your users deletes their account, `nomac.labels.delete("user-42")` deletes what NoMac keeps for that label: their Mac drive and file copies, and their phones' workspaces, saved states, replays and file copies. A repeat finds nothing left. It is refused while a Mac or phone of theirs runs (`label_in_use`). Just after their last Mac or phone ends, its drive or replay may still be saving (`label_busy`): call again after `details["retry_after_seconds"]`. The sessions' records (times and cost, under the label) stay for billing, so use your own user id as the label, not an email.

## Webhooks

```python
hook = nomac.webhooks.create("https://platform.example/nomac")
# Keep hook["secret"]: it is shown once.
```

A webhook takes every kind of event unless `events` names some: `mac.ready`, `mac.ending_soon`, `mac.ended`, `drive.saved`, `drive.deleted`, `credit.low`, `phone.ready` and `phone.ended`. Check every delivery before trusting it, with the raw body as received:

```python
from nomac import verify_webhook

event = verify_webhook(request.body, request.headers["nomac-signature"], os.environ["NOMAC_WEBHOOK_SECRET"])
if event["type"] == "mac.ended":
    release(event["data"]["session"]["label"], event["data"]["reason"])
```

`mac.ended` and `phone.ended` carry the label, the cost and why it ended (`stopped`, `idle`, `time_limit`, `spend_cap`, `credit`, `crashed`, `no_capacity`, `start_failed`, `queue_expired` or `drive_unavailable`). `drive.saved` carries each save's charge, so you can bill your users. `credit.low` comes before the credit runs out and every Mac and phone of the account stops. A delivery is tried up to 12 times, 1, 2, 4 ... 60 minutes apart, until answered 2xx, and can come more than once: key on its `id`. `nomac.webhooks.list()`, `delete(id)` and `deliveries(id)` manage them, up to 5 an account.

## Errors

A refusal is a `NoMacError` with NoMac's `code` (for code to branch on), `message` (for a person), HTTP `status` and `details`, such as `insufficient_credit` (402), `session_limit_reached`, `drive_in_use`, `capacity_unavailable` or `label_in_use` (409). A read, a stop and any request with a request key (a start, a command) are sent again when NoMac is busy for a moment, with the same key, so they are never done twice; when one still fails, its error's `request_key` is the key to send it with again and read what it did. A transfer to or from NoMac's storage that fails is a `NoMacError` too (`upload_failed`, `download_failed`).

The REST API it calls is at [nomac.app/docs/api](https://nomac.app/docs/api) for Macs and [nomac.app/docs/simulator](https://nomac.app/docs/simulator) for phones; `nomac.request(method, path, body=, idempotency_key=)` calls it directly.

## Changes in 1.0

- Macs: `nomac.macs`, `nomac.mac(id)` and `Mac`, with commands, files, the screen, view links, tokens, `extend` and `stop`. Also `nomac.labels.get(label)` and `nomac.credits()`.
- `NoMac(token=...)` takes a Mac's token (`nmm_`) as well as a phone's (`nmp_`).
- Webhooks and label deletion moved to the account-wide routes, `/api/v1/webhooks` and `/api/v1/labels`, which cover Macs and phones. A webhook made without `events` now takes every kind; pass `events=["phone.ready", "phone.ended"]` to keep only a phone's. `nomac.labels.delete` deletes the user's Mac drive too.
- Phones work as before.

MIT licensed.
