# zc agent local API (v1 and v2)
`/v1` is unchanged and stays for the shipped widget. `/v2` is additive
([ADR ZC-0019](adr/0019-agent-api-v2.md)) and is documented in
[v2](#v2) below, together with the files the agent and the desktop app
share ([agent.json](#agentjson), [the app file](#the-app-file)) and the
[presence](#presence) report to the hub.
`zc agent` serves this API to the Zakuro menu-bar app and widget, and to the
`zc` CLI's hand-off. It is loopback-only and never reachable from the network.
- **Base URL:** `http://127.0.0.1:<port>`. Read `port` and `token` from
`~/.zakuro/agent/agent.json` (`$ZAKURO_HOME/agent/agent.json` when set).
4720 (or `ZAKURO_AGENT_PORT`) is the *preferred* port, tried first; the
agent never runs two instances for one zc dir, so a port already held by
another running zc agent refuses to start, but a port held by anything
else falls back to an OS-assigned one -- always read the real port from
`agent.json`, never assume 4720.
- **Auth:** every route needs `Authorization: Bearer <token>` → 401 otherwise.
- **Browser guards:** any `Origin` header → 403. A `Host` other than
`127.0.0.1:<port>` / `localhost:<port>` → 403. No CORS headers are sent.
- **Errors:** `{"error":{"code":"…","message":"…"}}`. `message` is for people;
branch on `code`. The guards run before routing, so an unknown route or a
wrong method without a valid token is 401 (or 403), not 404 or 405.
| 400 | `invalid_input` | the body isn't JSON the route accepts (a wrong type, an unknown field in a price body, a missing `price_per_hour`), a `scope` other than `device` or `default`, or a worker count or price out of range |
| 401 | `unauthorized` | the bearer token is missing or wrong |
| 403 | `forbidden` | an `Origin` header, or an unexpected `Host` |
| 404 | `not_found` | no such route |
| 405 | `method_not_allowed` | the route exists, but not with this method |
| 409 | `conflict` | sharing on while a broker the agent didn't start is running (`zc down` stops it), or a device price while the hub has no worker rows for this Mac yet |
| 500 | `internal` | the agent couldn't save its own state file (`state.json`) |
| 502 | `hub_error` | a hub write failed, or the hub never answered; `message` carries the hub's reason (see `hub.error`) |
| 503 | `prerequisite_missing` | a prerequisite is missing: this Mac isn't signed in (`zc login`) |
| `GET /v1/summary` | — | cached merged summary |
| `POST /v1/refresh` | — | re-poll the hub now, then return the summary. The broker and workers are re-observed on the agent's own tick (every 2 s, 1 s while a worker drains); refresh wakes that tick but doesn't wait for it |
| `PUT /v1/sharing` | `{"on": bool}` | persist, then reconcile (start, or drain and stop) |
| `PUT /v1/workers` | `{"count": 0..max}` | persist, then reconcile; out of range → 400 |
| `PUT /v1/price` | `{"scope":"device"\|"default","price_per_hour": number\|null}` | hub write (below) |
Every write returns the fresh summary.
### `PUT /v1/price`
- The body is strict. `scope` and `price_per_hour` are both required, and any
other field is a 400.
- `"price_per_hour": null` clears the price: `device` puts this Mac's workers
back on the account default, `default` removes the account default. A
missing `price_per_hour` is a 400, never a clear.
- A number must be finite and within `prices.bounds`.
- `device` writes every one of this Mac's worker rows on the hub at once,
retrying each failed row once.
## Summary v1
[`agent-api/summary.v1.json`](agent-api/summary.v1.json) is the contract.
`zc`'s test suite serializes to it and the macOS app's `swift test` decodes it;
any incompatible change bumps `v`. Field rules:
poll, then the last good values, kept while the hub is unreachable.
- `account.is_admin`: `true` for a hub admin or superadmin; `false` when an older hub omits it (see [Logs](#logs)).
- `devices`: `[]` means the hub answered and lists no devices; `null` means it
hasn't answered yet.
- Timestamps (`as_of`, `hub.last_ok`, `devices[].last_seen_at`): RFC 3339 in
UTC, whole seconds, with a `Z`, e.g. `2026-09-13T01:41:30Z`, whatever form
the hub sent. A hub timestamp the agent can't parse becomes `null`.
- `hub.reachable`: `false` while the hub can't be reached (or rejects this
Mac's key). A hub that answers but predates the summary route stays
`reachable: true`, alongside the `hub_too_old` problem.
- `hub.error`: the last hub failure, or `null`. For an HTTP error it carries
FastAPI's `detail` string, otherwise at most about 200 characters of the
body, never a whole HTML page. For a failure that never reached the hub it
carries the cause, not just the url: the HTTP client's message with its
error chain folded in (`… : tcp connect error: Connection refused (os error
61)`), again at most about 200 characters.
- `prices.this_mac.state`: one of four values.
- `set`: every worker of this Mac has the same explicit price.
- `inherited`: every one is `null` (all inherit the account default).
- `mixed`: anything else; `per_hour` is `null` and `effective_per_hour` is
the minimum across this Mac's workers.
- `disabled`: every one of this Mac's workers is disabled on the hub;
`per_hour` and `effective_per_hour` are both `null`.
- `prices.default_per_hour`: `null` when the account has no default price set
(a negative account default arrives on the wire as `null`, never as a
negative number).
- `this_mac.broker`: `running` | `starting` | `stopping` | `stopped` | `unmanaged` | `error`.
- `this_mac.workers.max`: `ZAKURO_AGENT_MAX_WORKERS`, else logical CPUs / 2, at least 1.
- `devices_total` = number of devices; `devices_online` = devices whose
`freshness` is `fresh`; `devices[].link` uses the first online worker, or `null`.
- `history`: rolling hourly usage/earnings (`agent::history`), added without a
`v` bump -- an older app simply doesn't decode it. Omitted entirely until
there is something to show.
- `hours`: oldest to newest, at most 12 buckets, one per clock UTC hour;
the last one is the current, partial hour. `start` is RFC 3339 UTC with a
`Z`, aligned to the top of the hour, like every other timestamp here.
- `requests` is a count for that hour, sampled as the delta of the
supervisor's summed `requests_5h` (a decrease -- a worker restarting, or
the window rolling off -- contributes 0, never a negative).
- `earned` is what was earned in that hour, sampled as the delta of
`earnings.today` (a decrease is `earnings.tz`'s local-midnight reset, and
contributes the new value itself, not a negative).
- Samples are only taken when the hub was reachable; an hour the agent
wasn't running, or couldn't reach the hub for, is absent, not zeroed --
the chart can tell "no data" from "no work".
- `network`: network-wide resource capacity (network contract §5), from the
hub's `GET /api/status/network`, authenticated with this Mac's own `zk_`
provider key in `X-Broker-Api-Key`. Added without a `v` bump: omitted
entirely (never `null`) whenever there is nothing fresh enough to report --
this Mac has never reached that endpoint, or the last good answer is more
than 5 minutes old. Polled at most once every 60s, independent of the hub
summary poll: network capacity changes slowly, and a stale figure is worse
than no number.
- `workers` / `cpu_cores` / `ram_gb` / `gpus`: totals across the whole
network, under the same freshness gate the hub's other network totals use.
- `workers_busy` / `cpu_cores_busy` / `ram_gb_busy` / `gpus_busy`: the
subset of those totals with at least one request in flight right now.
- "Available" is never on the wire: `available = total - busy`, computed at
the display edge, not stored or sent (network contract §6).
- `problems[].code`:
| `not_logged_in` | no credentials, or the hub answered 401 | Run `zc login` |
| `hub_unreachable` | the last hub poll failed; for a failure that never reached the hub, `detail` says the host may answer only over a VPN tunnel (the zakuro mesh is a different one), otherwise `null` | Showing the last known values, or "No cached values yet: showing this Mac only" when no poll has ever succeeded (`account`, `earnings` and `devices` are all `null`) |
| `hub_too_old` | the summary route returned 404 | Local status only until the hub is updated |
| `uv_missing` | `uv` isn't installed | `brew install uv` |
| `zakuro_dir_missing` | the zakuro worker directory can't be found; `detail` names the setting that pointed at an invalid path, or `null` when nothing was set | Clone zak-zakuro into `~/.zakuro/zak-zakuro`, or set `ZAKURO_WORKER_DIR` |
| `docker_missing` | this agent's workers are containers (`ZAKURO_SHARE_RUNTIME`) and the Docker daemon isn't reachable; `uv` and the zakuro directory are not prerequisites on that backend | Start Docker, or set `ZAKURO_SHARE_RUNTIME=host` to share with a host process |
| `unmanaged_broker` | a broker the agent didn't start is running; `zc down` pauses the agent and stops it | Run `zc down` so the agent can manage sharing |
| `port_in_use` | no free port was found for the broker: 9000, the 9001-9010 fallback range, and an OS-assigned port were all unavailable | No free port for the broker (9000–9010 and a random port were all unavailable) |
| `broker_port_unrelayable` | on the proxy route (through the zakuro-wg container) no port the mesh relay carries was free: 9000 and the 9001-9010 fallback range were all taken, and an OS-assigned port would be unreachable from the mesh | Free one of them, or connect through a host VPN (the WireGuard app) instead of the zakuro-wg container |
| `worker_crashloop` | a worker keeps crashing; `detail` holds the last 20 log lines | See `~/.zakuro/agent/workers/` |
| `drain_timeout` | a drain took longer than allowed | Check the worker's log for a stuck request |
| `broker_crashloop` | the broker keeps crashing | Check `~/.zakuro/agent/agent.log` |
## Settings read when the agent starts
`zc agent run` reads these once, when it starts. A running agent keeps the
values it started with, so restart it after changing any of them (`zc agent
install` rewrites the LaunchAgent and restarts it).
- `ZAKURO_HOME`, `ZAKURO_AGENT_PORT`, `ZAKURO_WORKER_DIR`,
`ZAKURO_AGENT_MAX_WORKERS` and `ZAKURO_AGENT_WORKER_CMD`: `zc agent install`
copies each one set in its shell into the LaunchAgent.
- The settings the agent spawns its broker and workers with: `ZAKURO_P2P`
(whether the broker joins the P2P mesh; unset, it does whenever this Mac
reaches the mesh, through a host VPN or the zakuro-wg container, checked at
each broker start) and the worker command (`ZAKURO_AGENT_WORKER_CMD`).
- `ZAKURO_SHARE_RUNTIME` (`auto` | `host` | `container`; unset is `auto`) picks
how the agent's workers run. `auto` uses a Docker container when Docker is
reachable (checked once, when the agent starts) and otherwise falls back to
the host process with a warning in the agent log; `host` always uses the host
process; `container` requires Docker and raises `docker_missing` without it.
The older `ZC_SHARE_CONTAINER` (truthy = `container`, `0`/`false`/`no` =
`host`) is honoured while `ZAKURO_SHARE_RUNTIME` is unset. `ZC_SHARE_WORKER_IMAGE`
overrides the image (a `name@sha256:...` value pins a digest). On the container backend
`uv` and the zakuro directory stop being prerequisites (the image carries
both) and a reachable Docker daemon becomes one (`docker_missing`). The
agent supervises those containers the way it supervises process groups:
liveness is the worker process *inside* the container (`.State.Running`
would stay true after it died), a crash removes the container so it stops
publishing the worker's port, stopping one is SIGTERM then SIGKILL to the
container, and after an agent restart a container is re-adopted only when
it is still running and still the same `.State.StartedAt` recorded in
`children.json`.
At agent start, right after adoption, the agent also sweeps orphans: every
container labelled `zakuro.share=1` that it did not just re-adopt (a
reinstall, a lost `children.json`) is removed with `docker rm -f` and logged
as `removed orphaned share container <name> (<id>)`. It runs once, never per
tick, is skipped when Docker is unreachable, and never touches unlabelled
containers. Stopping the agent (`SIGTERM`) terminates its workers; a
restart that doesn't go through that path (an upgrade, a crash) leaves the
containers running for the next start to re-adopt.
The zakuro worker directory itself is **not** fixed at startup like the
settings above: only the *process-environment* value of `ZAKURO_WORKER_DIR`
is fixed for the agent's lifetime (carried into the LaunchAgent as listed
above, same as the others). Which directory that setting -- together with
everything else in the lookup -- resolves to is re-checked fresh on every
reconcile tick (a cheap file check), in order: that `ZAKURO_WORKER_DIR`, then
the same key read live from `<zc dir>/env`, then `~/.zakuro/zak-zakuro`
(`$ZAKURO_HOME/zak-zakuro`), then the legacy candidates (`../zak-zakuro` next
to the cwd, `/opt/code/ZAK/zak-zakuro`, `$HOME/zak-zakuro`). A fresh clone or
an edited `<zc dir>/env` therefore clears `zakuro_dir_missing`, and a newly
spawned worker picks up the new directory as its cwd, without restarting the
agent.
## The broker's port
The broker prefers 9000. If that is held by a zakuro broker the agent didn't
start, sharing is blocked with `unmanaged_broker` and the port is left alone,
whatever the route. If it is held by anything else, where the agent looks
next depends on how this Mac reaches the mesh:
- **A host VPN, or no mesh route:** the agent falls back to the first free
port in 9001-9010 (the same range zc clients scan for a local broker -- see
`zc://localhost`'s resolution), and finally to an OS-assigned port if the
whole range is taken. An OS-assigned port is outside the 9000-9010 scan, so
a zc client looking for a local broker on its own won't find it there --
only the agent itself, via `children.json`, knows where it is. Only when
nothing at all is free does the agent report `port_in_use`.
- **The zakuro-wg container (the proxy route):** the container relays only
9000-9010 from the mesh to this Mac, so the broker takes the first free
port in 9001-9010 and nothing else. There is no OS-assigned fallback, since
no peer could reach it. When all of 9000-9010 are taken the agent reports
`broker_port_unrelayable`.
The Summary v1 shape carries no broker port (`this_mac.broker` is only the
state label `running`/`starting`/.../`unmanaged`/`error`); the chosen port is
recorded in `children.json` instead, so a restarted agent finds and re-adopts
the same broker.
## agent.json
`<zc dir>/agent/agent.json` (`~/.zakuro/agent/agent.json`), mode 0600:
```json
{"v": 1, "port": 4720, "token": "<43 chars>", "pid": 12345, "version": "0.0.44", "rev": 7}
```
- Written by the agent at every start and by `zc agent install`, which mints a
new `token`. Always **replaced atomically**: written to
`agent.tmp.<pid>` in the same directory, then renamed over
`agent.json`. A reader sees the old file or the new one, never half of
either, and must watch the **directory** (the rename gives the file a new
inode).
- `rev` is bumped on every rewrite, so a watcher can tell "rewritten" from
"unchanged" without comparing tokens. A file from a zc before `rev` existed
has none; read it as 0.
- The desktop app watches this file and republishes `port` and `token` into
the App Group (`398BFF43SU.ai.zakuro.shared`), then reloads the widget
timelines (ADR ZC-0019 §7). The agent never writes the App Group itself.
The menu-bar app does this today (`AgentFileWatcher`, `EndpointPublisher` in
ZakuroAgentKit): a token re-mint reaches the widget within about 200 ms.
## The app file
`<zc dir>/agent/app.json`, next to `agent.json`, is written by the desktop
app (never by the agent) so the agent can report which app runs beside it:
```json
{"v": 1, "app": "desktop", "app_version": "0.3.1", "pid": 4242}
```
- `v`: 1. Any other value is ignored.
- `app`: `"desktop"`, the only app that writes it today. Any other value is
ignored.
- `app_version`: the app's version string (trimmed, at most 64 characters
are used).
- `pid` (optional): the app's process. When set and that process is gone,
the app counts as not running. Without it, the app counts as running
while the file exists, so an app that omits it must delete the file when
it quits.
- Write it atomically too (temp file + rename), mode 0600 or 0644.
The agent reads it on every presence report. Missing, unreadable or invalid
means no app: `app` and `app_version` are `null`.
## Presence
Every broker (the agent's or `zc up`'s) reports presence to the hub on its
existing poll: the `POST /api/broker/node/register` call it already makes
about once a minute carries an optional `presence` object (ADR ZC-0019 §6):
```json
"presence": {
"node_key_fp": "73c8ca26f49870c5",
"agent_version": "0.0.44",
"app_version": "0.3.1",
"app": "desktop",
"os": "macos",
"arch": "aarch64"
}
```
- `node_key_fp`: the node's fingerprint: the first 8 bytes of SHA-256 of the
raw 32-byte Ed25519 node public key (the `node_pubkey` sent in the same
body, base64-decoded), as 16 lowercase hex characters. The same id as
`zc://node-<fp>` and a `zakuro://` link's `node` claim. The hub recomputes
it from `node_pubkey` and drops a presence whose fingerprint differs.
- `agent_version`: this zc's version.
- `app_version`, `app`: from [the app file](#the-app-file); both `null` when
no app runs beside the agent.
- `os`: `macos` | `linux`. `arch`: Rust's `std::env::consts::ARCH`
(`aarch64`, `x86_64`, ...).
- Additive: a hub that does not know `presence` ignores it.
## v2
Same guards as v1: loopback bind, `Authorization: Bearer <token>`, 403 on any
`Origin` or an unexpected `Host`, the same error envelope and codes, and the
guards run before routing. v2 adds one status:
| 501 | `not_implemented` | the route is part of the v2 contract but its feature has not shipped; the envelope carries `until`, the issue it ships in: `{"error":{"code":"not_implemented","message":"…","until":"zakuro-ai/zc#514"}}` |
| `GET /v2/summary` | 200 | [summary v2](#summary-v2) |
| `GET /v2/jobs?state=live\|done&source=&squad=&since=` | 200 | `{"jobs": [...]}`, live first, then finished, newest first (below) |
| `GET /v2/events` | 200 | Server-Sent Events (below) |
| `GET /v2/offers` | 200 | the environment catalogue for this node, each offer with `fits` (below) |
| `PUT /v2/offers/{template_id}` | 200 | subscribe this node to an environment, reprice it, or unsubscribe (below) |
| `GET /v2/logs`, `GET /v2/logs/{name}?tail=N` | 200 | admin accounts only: list and tail this node's logs (below) |
| `GET /v2/policy`, `PUT /v2/policy` | 501 until zc#514 | effective `policy.toml` (ZC-0017) |
| `GET /v2/ledger?by=day\|product\|node&from=&to=` | 501 until zc#516 | ledger breakdowns; the totals are already in summary v2's `ledger` |
| `GET /v2/sandbox` | 501 until zc#510 | backend, size, use, image cache, health (ZC-0018) |
| `POST /v2/sandbox/resize` | 501 until zc#513 | apply a pending resize |
| `GET /v2/squads`, `POST /v2/squads/join`, `POST /v2/squads/{id}/leave` | 501 until zc#517 | squads |
| `GET /v2/envs`, `POST /v2/envs`, `POST /v2/envs/{id}/connect`, `DELETE /v2/envs/{id}` | 501 until zc#519 | environments |
| `POST /v2/handoff`, `POST /v2/handoff/{jti}/confirm` | 200 | `zakuro://` deep links (ZC-0020), [below](#handoff) |
### Jobs
A job, today, is one **busy span of one of this node's workers**: it starts
on the reconcile tick (every 2 s) a worker goes from no request in flight to
at least one, and finishes on the tick it goes back to none or disappears.
```json
{"id": "j42", "state": "live", "source": null, "squad": null, "worker": "jeans-mbp-w0",
"started_at": "2026-09-13T01:41:50Z", "finished_at": null, "requests": 3}
```
- `requests`: requests served in the span (at least 1 once finished).
- `source` and `squad` are `null` until the broker attributes requests
(zc#514) and squads exist (zc#517). `?source=` already accepts the ADR's
values (`spaces`, `env_guest`, `hub_serving`, `atelier`, `peer`, `test`;
anything else is a 400), so it matches nothing yet.
- `?state=` other than `live`/`done`, or a `since` that is not RFC 3339, is a
400 `invalid_input`. `since` keeps jobs that started or finished at or
after it.
- The last 200 finished jobs are kept in `<zc dir>/agent/jobs.json`. A job
live when the agent stops is not carried over.
`zc jobs [--state live|done] [--json]` lists them; `zc jobs --live` prints the
running ones, then streams every start and finish from `/v2/events`,
reconnecting with `Last-Event-ID` (and re-reading `agent.json`) when the
agent restarts.
### Environment offers
The provider catalogue: every environment the hub supports, and which of them
this node hosts. A subscription is a hub deployment of the template on this
node with `min_workers=0`, so the environment starts on demand, not at
subscribe time. Prices are yen per **hour** here (the hub stores per
second). The agent calls the hub with the account key from
`~/.zakuro/credentials` and adds this node's `node_pubkey` itself.
`GET /v2/offers` returns the hub's `GET /api/provide/offers` body as it
arrived, plus two fields per offer:
```json
{
"node": "<node_pubkey>",
"categories": ["Machine learning & AI", "Developer tools"],
"offers": [{
"template": {"id": "pytorch", "name": "PyTorch", "category": "Machine learning & AI",
"publisher": "PyTorch", "verified": true, "icon_url": null,
"image": "pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime",
"kind": "service", "gpu_required": true, "min_vram_gb": 8},
"default_price_per_hour": 7.2, "price_basis": "mesh", "hosts": 3,
"subscribed": false, "price_mode": null, "price_per_hour": null,
"deployment_id": null, "state": null,
"fits": false, "fit_reason": "needs 8 GB VRAM"
}]
}
```
- `fits`: `true` / `false` from this machine's hardware, `null` when the
hardware is unknown (the GPU probe gave no answer). It is never guessed.
`fit_reason` is `"needs a GPU"`, `"needs <n> GB VRAM"` or `null`.
- Only NVIDIA (CUDA) cards count as GPUs, since environments run under
`docker --gpus`; Apple unified memory is not VRAM. `min_vram_gb` is per
card, so the largest card is compared (with 5% slack for what drivers
report).
`PUT /v2/offers/{template_id}` body (strict, other fields are a 400):
```json
{"subscribed": true, "price": "default"}
```
`price` is `"default"` (follow the market price) or a number of yen per
hour, e.g. `{"subscribed": true, "price": 4.5}`; `{"subscribed": false}`
unsubscribes. Whether the value is acceptable (> 0, a known template) is the
hub's call (422 / 404). The answer is the hub's offer object for that
template, with `fits` / `fit_reason`.
| 400 | `invalid_input` | the body is not `{"subscribed": bool, "price"?: "default" \| number}` |
| 409 | `not_logged_in` | no credentials in `~/.zakuro/credentials`, or the hub rejected the key (401) |
| 502 | `hub_unreachable` | the request never reached the hub |
| 4xx | hub's `code`, else `hub_error` | the hub refused (403 not your node, 404 unknown template or node, 422 bad price): the hub's status, with its `detail` as `message` |
### Events
`GET /v2/events` is `text/event-stream`. Each message:
```
id: 17
event: job.finished
data: {"id":17,"type":"job.finished","at":"2026-09-13T01:42:05Z","data":{...}}
```
| `summary.changed` | the full summary v2. Sent when anything in it but its timestamps (`as_of`, `hub.last_ok`, `ledger.as_of`) changed: after a reconcile tick, a hub poll or a write |
| `job.started`, `job.finished` | the job |
| `problem.raised` | the problem, as in `problems[]` |
| `problem.cleared` | `{"code": "..."}` |
| `policy.changed`, `sandbox.state`, `squad.changed`, `env.state` | reserved; sent once those features ship |
| `resync` | `{"type":"resync","id":N}`: re-fetch `/v2/summary` |
- Ids increase by one per event within one agent run, starting at 1.
- Reconnect with `Last-Event-ID: <last id seen>` to get what was missed from
a ring of the last 256 events. Too far behind, or an id this run never
issued (the agent restarted), gets one `resync` instead. A client that falls
behind the live buffer also gets a `resync`.
- A `: keep-alive` comment every 15 s.
### Handoff
`POST /v2/handoff` with `{"link": "zakuro://…"}` verifies a link and says
what it would change. It changes nothing. Only
`POST /v2/handoff/{jti}/confirm` (no body) runs it: the app calls it from
its confirmation sheet, `zc link` after a terminal prompt.
The closed set: `open?view=<screen>` and `auth/callback?code=&state=` carry
no token; `squad/join`, `env/launch`, `env/connect` and `share/budget`
carry `?t=<jwt>`, a hub-signed EdDSA token (zak-marketplace
`services/action_tokens.py`). The agent checks, in order:
- the token is a three-part JWS with `alg: EdDSA` (anything else, `none`
included, is `unsigned`);
- its `kid` names a trusted action key, and the signature verifies;
- `act` is the link's action, `exp` has not passed (30 s leeway), and the
token lives at most 10 minutes;
- `sub` is the signed-in account's `zakuro_user_id`, as the hub's provider
summary reports it (`account_unknown` until the hub has answered);
- `node`, when set, is this node's fingerprint, and a `share/budget`
token's `args.node_pubkey` is this node's key;
- the `jti` has not been used. Used ids are kept in
`<zc dir>/agent/handoff_seen.json` until they expire.
Trusted keys are the active `ZAKURO_ENV` profile's action roots
(`deeplink::profile_roots`: staging trusts stg.hub's key, kid
`bde74a18996820b2`; prod has none yet, so prod refuses every signed link),
picked by the hub the node is signed in to, or `ZAKURO_ACTION_PUBKEYS` (comma-separated base64 32-byte
Ed25519 public keys, the hub's `GET /api/broker/action/pubkey` `keys[].pubkey`)
in their place. `zc doctor` prints which.
`POST /v2/handoff` answers the sheet:
```json
{"act": "share/budget", "jti": "5f0c…", "sub": "1234567890", "node": "0123456789abcdef",
"exp": 1800000590, "title": "Review a budget change", "summary": "Opens Budget & price …",
"details": [{"label": "Price", "value": "¥120/h"}, {"label": "Node", "value": "this node"}],
"view": "budget", "available": true, "until": null,
"prefill": {"price_per_hour": 120}, "args": {...}}
```
`jti` is `null` for the token-less links: there is nothing to confirm with
the agent, the app acts on its own sheet. `available: false` (with `until`)
marks an action this zc cannot run yet: `squad/join` (zc#517),
`env/launch` and `env/connect` (zc#519), `auth/callback` (the hub has no
PKCE endpoint; `zc login` signs in with a device code, which needs no
callback). Confirming one answers 501 `not_implemented` with `until` and
`view`, and leaves the link unused.
`confirm` answers `{"status": "done", "act", "jti", "view", "prefill"}`.
`share/budget` runs locally: it opens Budget & price with `prefill`, and
nothing is saved until the owner saves there.
| 400 | `invalid_link` | not a `zakuro://` link of the closed set, or a missing or repeated parameter |
| 403 | `unsigned`, `unknown_key`, `bad_signature`, `invalid_token`, `wrong_node` | as above |
| 404 | `not_found` | confirm for an id that was not verified by this agent run (open the link again) |
| 409 | `wrong_account`, `account_unknown` | the token is for another account, or the account is not known yet |
| 410 | `expired`, `already_used` | |
| 500 | `storage` | the used-link file (`agent/handoff_seen.json`) cannot be read or written, so the link is refused rather than risk a replay; a corrupt file resets by itself 11 minutes after its last change |
| 501 | `not_implemented` | confirm for an action this zc cannot run yet |
| 503 | `no_action_key` | no trusted action key for the profile, or `ZAKURO_ACTION_PUBKEYS` does not parse |
### Summary v2
[`agent-api/summary.v2.json`](agent-api/summary.v2.json) is the contract
(zc's tests serialize to it). `summary_version: 2`; an app refuses another
major version with "Update zc".
- Shared with v1, same rules: `agent_version`, `as_of`, `env`, `hub`,
`problems`, `account`, `prices`, `mesh`, `links`, `history`, `network`.
- `nodes[]`: this node first (`this_node: true`, always present, even before
the hub answers), then the account's other devices in the hub's order.
`freshness`/`last_seen_at` come from the hub (`null` for this node until it
is listed). `backend` (`host` | `container`) is only known for this node.
`budget` is `null` until zc#513. `local` (only on this node) is what the
agent supervises: `sharing`, `broker`, `workers`, `requests` (v1's
`this_mac`).
- `jobs`: `live[]` ([jobs](#jobs)) and `done_24h`.
- `ledger`: `null` until the hub's `GET /api/provide/earnings` answers once
(polled at most once a minute; the last good value is kept on failure).
`unit` is `jpy`: amounts are yen (ADR 0027).
`days` is earned per day over the last 7 days, oldest first, today last
(the hub's `week`), and `prev_month_earned` last month's total (`null`
when the hub does not send it); both additive (zc#509).
`today.earned`, `month.earned`, `month.spent` are the hub's figures;
`today.spent` is `null` (the hub does not break it out), and `by_source` is
`null` until transactions carry a source (zc#516). `tz` is the zone
today and this month start in.
- `squads`, `sandbox`, `policy`: `null` until zc#517, zc#510, zc#514. `null`
means "not available in this zc", never "none".
## Linux: `zc agent install`
`zc agent install` writes a systemd **user** unit,
`~/.config/systemd/user/zakuro-agent.service` (`$XDG_CONFIG_HOME` when set),
then `systemctl --user daemon-reload`, `enable` and `restart`, and waits up
to 10 s for the agent to answer. It re-mints the token like the macOS path.
The unit runs `<zc> agent run` with `Restart=always`, `TimeoutStopSec=60`,
`KillMode=process` (the agent stops its own children, and re-adopts the ones
still running after a crash), the carried settings above, and appends to
`agent.log`. `zc agent uninstall` drains sharing, then `disable --now`,
removes the unit and reloads. `~/.zakuro/agent/` is kept.
A user unit stops when the user's last session ends unless lingering is on:
`zc agent install` prints `loginctl enable-linger <user>` when it is not.
`systemctl --user` needs a user session (`XDG_RUNTIME_DIR`); over plain
`su`/`lxc exec` there is none, and install says so.