Metadata-Version: 2.4
Name: peaq-os-cli
Version: 0.0.8
Summary: Python CLI for peaqOS, the operating system for the machine economy — on-chain identity, credit rating, and omnichain infrastructure for robots and machines.
Author-email: peaqOS <info@peaq.xyz>
License: Apache-2.0
Project-URL: Homepage, https://www.peaq.xyz
Project-URL: Documentation, https://docs.peaq.xyz
Project-URL: Repository, https://github.com/peaqnetwork/peaq-os-cli-py
Project-URL: Issues, https://github.com/peaqnetwork/peaq-os-cli-py/issues
Keywords: peaq,peaqos,peaq-os,machine-economy,depin,robotics,ai-agents,blockchain,omnichain,peaqid,did,machine-nft,machine-tokenization,machine-credit-rating,mcr,cli,python
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: peaq_os_sdk[x402]>=0.6.0
Requires-Dist: click>=8.1
Requires-Dist: python-dotenv>=1.0
Requires-Dist: cryptography>=41.0
Requires-Dist: Pillow>=10.0
Requires-Dist: eth-account<1.0,>=0.10
Requires-Dist: PyYAML>=6.0
Provides-Extra: ows
Requires-Dist: open-wallet-standard>=1.3.2; extra == "ows"
Provides-Extra: s3
Requires-Dist: boto3>=1.28; extra == "s3"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: types-PyYAML; extra == "dev"

# peaq-os-cli

Python CLI for peaqOS. Describes install and the console entry point.

## Install

```bash
python3 -m venv .peaq-os-cli
source .peaq-os-cli/bin/activate
pip install -e ".[dev]"
```

## Run Tests
```
pytest
```

## Quality Gates
```
ruff check src tests
black --check src tests
mypy src
pytest -q --cov=src/peaq_os_cli --cov-fail-under=90
flake8 src tests
```

### Running integration tests

| Gate | Scope | Cost |
| --- | --- | --- |
| `PEAQOS_CLI_INTEGRATION=1` | CLI suites, local mock faucet | No chain, no funds |
| `PEAQOS_TOKENOMICS_INTEGRATION=1` | Live agung activation and machine management | **Activation spends real PEAQ irreversibly** |

The second matches the SDK's own gate name deliberately: enabling the CLI's
integration tests must not also start spending.

Under that gate, the machine-management suite **submits nothing by default**. A
write invoked without `--yes` against non-TTY stdin renders its full preview —
real preflight, real chain reads, real SDK-supplied contract and method — and
only then refuses for want of consent, so the read half of every write is
covered for free. Three further opt-ins widen it:

| Variable | Unlocks | Cost |
| --- | --- | --- |
| `PEAQOS_TKN2_MACHINE_ID` | Anything machine-scoped | None |
| `PEAQOS_TKN2_LIFECYCLE_WRITES=1` | `suspend` → rerun → `resume` | Gas only, no bond |
| `PEAQOS_TKN2_DESTINATION_RPC_URL` + `PEAQOS_TKN2_DESTINATION_DEPLOYMENT_ID` | `relocation status` across deployments | None |

Never aim the destination at peaq mainnet. These suites are testnet-only, and a
cross-deployment read is still a read against whatever it targets.

**Known limits, deliberately visible.** Six integration paths cannot run yet
for want of fixtures neither this repository nor the SDK provides: existing-machine
subscription activation, USDT subscription on either rail, controller-funded
subscription, ERC-721 transfer, DID array replacement, and a renewal reconciled
after its allowance is consumed to zero. Each is a **skipped test with its
reason attached** rather than an absent one, so `pytest -m integration -rs`
lists them.

Agung's PriceOracle also has no committed PEAQ price, so every subscription
quote reverts `PriceNotAvailable()` today. The suite asserts the CLI presents
that as a stable `error_code` rather than a traceback, and starts skipping with
"a price is now committed" once that changes.

## Console usage

The `peaqos` script invokes the Click root group in `peaq_os_cli.main`.

```bash
peaqos --help
peaqos --version
```

Authoritative option text for any subcommand is always available via built-in help:

```bash
peaqos <command> -h
peaqos qualify event -h
peaqos qualify mcr -h
peaqos monetize provision run -h
peaqos stream grant -h
peaqos stream consume -h
peaqos stream distribute -h
peaqos stream pay -h
peaqos stream payproof -h
```

## Commands

### `peaqos init`

Interactive wizard that writes a `.env` file in the current working directory.

```bash
peaqos init                    # interactive (network, key, URLs, contract addresses)
peaqos init --non-interactive  # read all values from environment variables
peaqos init --force            # overwrite existing .env without confirmation
```

**Example (interactive):**

```
Network (mainnet, testnet) [mainnet]: mainnet
Private key source (paste, generate, wallet): generate
  Address:  0xAbCd...1234
  Key:      0xdeadbeef...
IMPORTANT: Save this private key securely. It will not be shown again.
RPC URL [https://peaq.api.onfinality.io/public]:
MCR API URL [https://mcr.peaq.xyz]:
Gas Station URL [https://depinstation.peaq.xyz]:
Event Registry address: 0xEe6f...78aB
  Config: .env written to /home/operator/project/.env

  Running whoami to verify...
  Address :  0xAbCd...1234
  Network :  mainnet
  RPC URL :  https://peaq.api.onfinality.io/public
  Chain ID:  3338
  MCR API :  https://mcr.peaq.xyz

  Contracts:
    IdentityRegistry:  0x9075...0B6A
    IdentityStaking :  0x7d39...9B8E
    EventRegistry   :  0xEe6f...78aB
    MachineNFT      :  0xaF13...Bd61
    DID Registry    :  0x0000...0800
    Batch Precompile:  0x0000...0805
```

### `peaqos whoami`

Show the active wallet address, network, chain ID, and all contract addresses.

```bash
peaqos whoami
```

**Example:**

```
  Address :  0xAbCd...1234
  Network :  mainnet
  RPC URL :  https://peaq.api.onfinality.io/public
  Chain ID:  3338
  MCR API :  https://mcr.peaq.xyz

  Contracts:
    IdentityRegistry:  0x9075...0B6A
    IdentityStaking :  0x7d39...9B8E
    EventRegistry   :  0xEe6f...78aB
    MachineNFT      :  0xaF13...Bd61
    DID Registry    :  0x0000...0800
    Batch Precompile:  0x0000...0805
```

### `peaqos wallet`

Manage OWS (Open Wallet Standard) wallets in the local encrypted vault (`~/.ows/`).
Requires the optional OWS dependency: `pip install peaq-os-cli[ows]`.

```
peaqos wallet create <name> [--words 12|24] [--json]
peaqos wallet import <name> (--mnemonic | --private-key-file <path>) [--index <n>] [--json]
peaqos wallet list [--json]
peaqos wallet show <name-or-id> [--json]
peaqos wallet export <name-or-id>
peaqos wallet delete <name-or-id>
peaqos wallet use <name-or-id>
```

**`wallet create`** — Generate a new mnemonic-backed wallet. Displays addresses for all supported chains (peaq, Base, Ethereum, Solana, Bitcoin, Cosmos, etc.). The mnemonic is never shown; use `wallet export` to retrieve it.

```bash
peaqos wallet create my-machine
peaqos wallet create my-machine --words 24   # 24-word mnemonic
peaqos wallet create my-machine --json       # JSON output
```

**`wallet import`** — Import an existing wallet from a BIP-39 mnemonic (hidden prompt) or a private key file.

```bash
peaqos wallet import recovered --mnemonic
peaqos wallet import from-file --private-key-file ./operator.key
```

**`wallet list`** — List all wallets in the vault. Shows Name, ID, peaq Address, Key Type, and Created date.

```bash
peaqos wallet list
peaqos wallet list --json   # full WalletInfo array
```

**`wallet show`** — Display full wallet details with addresses for every supported chain family.

```bash
peaqos wallet show operator
peaqos wallet show operator --json
```

**`wallet export`** — Export the recovery phrase or private key (requires confirmation).

```bash
peaqos wallet export my-machine
```

**`wallet delete`** — Securely delete a wallet from the vault (requires confirmation).

```bash
peaqos wallet delete my-machine
```

**`wallet use`** — Set a wallet as the active default by writing `PEAQOS_OWS_WALLET` to `.env`. Subsequent commands use this wallet via `load_client()`.

```bash
peaqos wallet use operator
```

**Migration from raw keys:**

```bash
peaqos wallet import my-operator --private-key-file ./operator.key
peaqos wallet use my-operator
peaqos whoami   # address matches the original key
```

### `peaqos activate`

Onboard a machine in **one atomic transaction**.
`MachineStateAndSync.activateMachine` mints the ERC-721, stores the DID
document, activates the subscription and registers the home chain in a single
call — replacing the old register → mint → DID-write sequence.

The bond is always **quoted in PEAQ**. `--payment` chooses what settles it.

The transaction sender becomes the machine's **owner and bond payer**. There is
no recipient parameter, and no operator-sponsored variant.

**Two modes:**

* **Self-owned** — no `--for`. Your configured signer owns the machine, pays
  the bond, and is its DID controller.
* **Machine-owned / operator-controlled** — `--for <machine-address>
  --machine-key <path>` together. The **machine** signs, owns the NFT, and pays
  gas and the bond; your operator address is recorded as DID controller. Both
  flags are required together; supplying one alone exits `1`.

Before any spend the CLI shows the bond, the voucher credit applied, and the
net PEAQ, then asks. In machine-key mode it also states the changed rights:

| Who | Can | Cannot |
| --- | --- | --- |
| Machine wallet (owner) | Transfer the NFT; rotate or clear the controller | — |
| Operator (controller) | Lifecycle, subscription, relocation and DID actions | Transfer the NFT; rotate or clear the controller |

```bash
# Self-owned
peaqos activate \
  --machine-type Sensor \
  --credential-subject-hex 0xdeadbeef \
  --manufacturer 0x3333333333333333333333333333333333333333 \
  --tier entry \
  --did-document ./did.json

# Machine-owned, operator-controlled
peaqos activate ... --for 0xMachine --machine-key ./machine.key

# Preview the cost without submitting anything
peaqos activate ... --dry-run

# Scripted: --yes is the only non-interactive consent
peaqos activate ... --json --yes

# Settle the PEAQ bond in USDT, accepting 0.5% conversion movement
peaqos activate ... --payment usdt --slippage-bps 50
```

**Flags:**

| Flag | Purpose |
| --- | --- |
| `--machine-type` | Identity domain. Half of what fixes the permanent machine ID. |
| `--credential-subject-hex` | `0x`-prefixed identity-anchor bytes. The other half. |
| `--manufacturer` | Manufacturer address. **Recorded on-chain, never verified by the contract.** |
| `--tier` | `entry` \| `basic` \| `pro`. |
| `--did-document` | Path to a UTF-8 JSON DID document (schema below). |
| `--for` | Machine EOA address. Switches to machine-owned mode; requires `--machine-key`. |
| `--machine-key` | File holding the machine's `0x`-prefixed hex private key. |
| `--payment` | `peaq` (default) \| `usdt`. Which asset settles the PEAQ-quoted bond. |
| `--slippage-bps` | Accepted conversion movement, `0`..`10000`. **Required for `usdt`, rejected for `peaq`.** |
| `--skip-funding` | Skip balance check, 2FA and gas-station funding. |
| `--dry-run` | Preview and stop. Submits nothing. |
| `--json` | One JSON object on stdout. **Never implies consent.** |
| `--yes` / `-y` | Accept the displayed terms. The only non-interactive consent. |

`--machine-type` and `--credential-subject-hex` alone determine the machine ID
(`uint256(keccak256(abi.encode(machineType, credentialSubject)))`). Neither can
be changed after activation, and the same pair can never be onboarded twice.

**Paying in USDT.** The bond, the voucher credit and the net amount stay in
PEAQ; only settlement differs. The CLI shows the USDT token, the quote, the
accepted slippage and the resulting **maximum USDT**, then submits that exact
maximum — it never widens a bound you approved. The allowance goes to
`SubscriptionTokenProvisionPool`, which performs the conversion, rather than to
`MachineSubscription`.

On this rail no PEAQ leaves your wallet, so the funding check accounts for gas
alone. A bond covered entirely by voucher credit converts nothing, transfers
nothing, emits no `PaidWithUsdt`, and reports `0` paid — which is what
happened, not a missing value.

Private keys **must** come from a file. Inline key flags are intentionally
unsupported — a file keeps the key out of shell history and `ps` output.

**Removed flags.** `--doc-url`, `--data-api` and `--visibility` wrote DID
attributes *after* registration. Tokenomics 2.0 records the DID document
atomically during activation, so there is no post-registration write to target.
Passing any of them exits `1` with migration guidance; move documentation and
API URLs into the `serviceEndpoints` array of `--did-document`.

**DID document schema.** Exactly three root fields, all required. Unknown
fields, duplicate JSON keys, and a root `id` or `controller` are rejected —
`id` is computed on-chain, and `controller` is set by the CLI from the mode.

```json
{
  "verificationMethods": [
    {
      "id": "#key-1",
      "methodType": "Ed25519VerificationKey2020",
      "controller": "0x1111111111111111111111111111111111111111",
      "publicKeyMultibase": "z6MkiExamplePublicKey"
    }
  ],
  "authentication": [0],
  "serviceEndpoints": [
    {
      "id": "#telemetry",
      "serviceType": "TelemetryService",
      "serviceEndpoint": "https://machine.example/telemetry"
    }
  ]
}
```

Each `authentication` entry is an index into `verificationMethods`. The CLI
bounds-checks them because **nothing on-chain does**: `MachineRegistry` stores
them unchecked at mint, so an out-of-range index would be recorded permanently.

**Environment:**

| Variable | Purpose |
| --- | --- |
| `PEAQOS_PRIVATE_KEY` | Operator key. In machine-key mode this signs nothing; it supplies the controller address. |
| `PEAQOS_RPC_URL` | RPC endpoint. Must match the deployment's chain. |
| `PEAQOS_NETWORK` | `mainnet` or `testnet`. |
| `PEAQOS_GAS_STATION_URL` | Gas-station base URL for the funding steps. |
| `TOKENOMICS_DEPLOYMENT_ID` | Deployment record, e.g. `agung-2026-08-28`. |

**No Tokenomics contract addresses are configured.** `TOKENOMICS_DEPLOYMENT_ID`
selects a record from the SDK's approved snapshot; the five addresses travel
with it and are verified against `InfoDesk.peer(role)` on-chain before any
write. `peaqos whoami` shows which ones resolved.

The six legacy `*_ADDRESS` variables are still required, because the SDK client
still takes them. They are unused by activation.

**Exit codes and `error_code`.** Four exit codes, per the CLI-wide convention.
The specific condition rides on `error_code`, which is stable, appears in
`--json`, and is bracketed in human output.

| Exit | Meaning | `error_code` |
| --- | --- | --- |
| `0` | Activated, already active, or a confirmed management write | `ACTIVATED`, `ALREADY_ACTIVE`, `CONFIRMED`, `ALREADY_CONFIRMED` |
| `1` | Bad input, declined, or non-interactive without `--yes` | `INVALID_INPUT`, `DEPRECATED_FLAG`, `MACHINE_KEY_MISMATCH`, `DECLINED`, `NOT_INTERACTIVE`, `MACHINE_ID_MISMATCH`, `CANCELLED_BEFORE_SUBMIT`, `SPONSORED_UNSUPPORTED`, `INVALID_TIER`, `LEGACY_REGISTRATION_UNSUPPORTED`, `RELOCATION_UNAVAILABLE`, `AUTHENTICATION_REWRITE_REQUIRED` |
| `2` | RPC / on-chain failure, or a submitted transaction still pending | `ORACLE_UNPRICED`, `NOT_FULL_MODE`, `INSUFFICIENT_PEAQ`, `QUOTE_MOVED`, `APPROVAL_FAILED`, `ALLOWANCE_INSUFFICIENT`, `ALREADY_ACTIVATED_RACE`, `TX_REVERTED`, `EVENT_MISMATCH`, `STATE_MISMATCH`, `STATE_CONFLICT`, `MACHINE_NOT_FOUND`, `RPC_FAILED`, `PENDING`, `ALREADY_ACTIVATED`, `ALREADY_TERMINATED`, `NOT_ACTIVATED`, `NOT_ACTIVE`, `NOT_SUSPENDED`, `TECHNICALLY_PAUSED`, `MACHINE_RELOCATING`, `NOT_MACHINE_OWNER`, `NOT_OWNER_OR_CONTROLLER`, `ERC721_INCORRECT_OWNER`, `ERC721_INSUFFICIENT_APPROVAL`, `ERC721_INVALID_APPROVER`, `ERC721_INVALID_OPERATOR`, `PROVISION_POOL_NOT_CONFIGURED`, `SLIPPAGE_EXCEEDED`, `MAX_USDT_EXCEEDED`, `INSUFFICIENT_RESERVE`, `INSUFFICIENT_USDT_RECEIVED` |
| `3` | Missing or invalid configuration | `ADDRESSES_UNSET`, `DEPLOYMENT_UNKNOWN`, `TOKENOMICS_NOT_CONFIGURED`, `ADDRESS_OVERRIDE_MISMATCH`, `CHAIN_MISMATCH`, `CONTRACT_NOT_DEPLOYED`, `PEER_MISMATCH`, `SIGNER_UNAVAILABLE` |

Two are worth telling apart, because they look alike and resolve differently:

* `ADDRESSES_UNSET` — the network is supported but its Tokenomics contracts are
  not deployed yet. Nothing is wrong with your configuration.
* `ORACLE_UNPRICED` — the contracts *are* deployed and reachable, but no PEAQ
  price is committed, so the bond cannot be quoted. A chain-side condition;
  nothing local will fix it.

**Pending transactions.** A submitted transaction whose receipt does not arrive
is reported as `PENDING` at exit `2` with its hash — **not** as a failure. It
may still mine, and nothing local can recall it. Re-run the same command: the
CLI reconciles the recorded hash before considering another write, and a hash
with no receipt blocks resubmission regardless of its age. Never submit a second
activation for the same machine.

**Example — `--json` on success:**

```json
{
  "status": "activated",
  "mode": "self-owned",
  "deployment_id": "agung-2026-08-28",
  "chain_id": "9990",
  "machine_id": "57896044618658097711785492504343953926634992332820282019728792003956564819975",
  "tier": "entry",
  "owner": "0xDC5b20847F43d67928F49Cd4f85D696b5A7617B5",
  "controller": "0xDC5b20847F43d67928F49Cd4f85D696b5A7617B5",
  "bond_amount": "400000000000000000",
  "voucher_credit": "0",
  "net_peaq_amount": "400000000000000000",
  "transaction_hash": "0xabab...",
  "is_homed_locally": true
}
```

Machine IDs and every unbounded chain integer are **decimal strings**, never
JSON numbers: a `uint256` exceeds what most parsers hold as a number. Progress,
the preview and prompts go to stderr, so stdout carries only this object.

**`peaqos.log`.** Every submitted transaction is appended as one JSONL line —
flushed *before* the receipt wait, which is what makes recovery possible — with
mode `0600`. Never delete it while a transaction is outstanding; the hash is the
only way to reconcile it.

```jsonl
{"step":"activate_machine","phase":"activation","status":"pending","tx_hash":"0xabab...","machine_id":"578960...","sender_nonce":7,"deployment_id":"agung-2026-08-28","chain_id":9990,"ts":"..."}
```


### `peaqos machine`

Everything after onboarding: lifecycle, subscription payments, ERC-721
ownership, DID updates, and cross-deployment relocation evidence.

```text
peaqos machine status MACHINE_ID
peaqos machine suspend MACHINE_ID
peaqos machine resume MACHINE_ID

peaqos machine subscription activate MACHINE_ID --tier TIER --payment RAIL [--slippage-bps N]
peaqos machine subscription renew MACHINE_ID --payment RAIL [--slippage-bps N]

peaqos machine approve MACHINE_ID OPERATOR
peaqos machine approve-all OPERATOR --allow|--revoke
peaqos machine transfer MACHINE_ID TO [--unsafe] [--data-hex HEX]

peaqos machine did set-controller MACHINE_ID CONTROLLER
peaqos machine did clear-controller MACHINE_ID
peaqos machine did set-verification-methods MACHINE_ID --file PATH
peaqos machine did set-authentication MACHINE_ID [--index N]... | --clear
peaqos machine did set-services MACHINE_ID --file PATH

peaqos machine relocation status MACHINE_ID \
  --destination-rpc-url URL --destination-deployment-id ID
```

Every write accepts `--yes` and `--json`. Every read accepts `--json`.

**Machine IDs are full-width `uint256`.** Pass them as canonical unsigned
decimal — no `0x`, no leading zeros, no exponents. They come back as decimal
**strings** in `--json`, because a JSON number cannot carry a `uint256` without
rounding it.

#### What every write does, in order

1. Validate your input locally. Nothing reaches the chain until it passes.
2. Reconcile the journal. A previously submitted transaction for the same
   action and machine is settled first — and blocks, rather than being
   repeated.
3. Ask the SDK for a preview. The chain, target contract, method signature,
   current state and intended effect all come from there; the CLI infers none
   of them.
4. Show that preview, plus what this specific action risks, and ask.
5. Submit once, recording the hash **before** waiting for a receipt.

`--json` changes output only. **It never confirms a write.** For scripts,
`--yes` is the only non-interactive consent; without it, a non-TTY stdin fails
before anything is approved or submitted. Previews and prompts go to stderr, so
stdout carries exactly one JSON object.

#### Reruns never resubmit

Submitted hashes are appended to `./peaqos.log` (mode `0600`) before the
receipt wait, which is the only way a timeout stays recoverable. Re-running the
same command reconciles that record instead of sending a second transaction:

* **still pending** — reports the prior hash and exits `2`. Age, mempool
  visibility and account nonce are *not* treated as evidence it was dropped.
* **confirmed** — reports the reconciled result and exits `0`.
* **failed or conflicting** — reports every disagreement and exits `2`. Nothing
  is retried automatically, ever.

A pending write blocks by *action and machine*, not by its details. A pending
transfer blocks another transfer regardless of recipient or safe/unsafe mode; a
pending renewal blocks another even if a fresh quote differs.

DID arrays and transfer data are stored as **hashes**, never contents. So a
rerun must supply the same `--file` or `--data-hex`: if the rebuilt input does
not match the recorded hash, the CLI says so and stops rather than reconciling
the wrong payload.

#### The parts with teeth

**`approve-all` is not scoped to one machine.** It grants the operator every
MachineRegistry machine the signer owns, including ones onboarded later. The
preview says so in those words.

**`transfer` is safe by default.** `safeTransferFrom` asks a contract recipient
whether it can receive an ERC-721 and reverts if it cannot. `--unsafe` selects
`transferFrom`, which does not — an incompatible contract recipient strands the
NFT permanently. `--data-hex` selects the four-argument safe overload and is
rejected with `--unsafe`, which has no such overload. The sender is read from
SDK machine state, never typed. **Transfer does not rotate the DID controller**;
the retained controller is shown before and after.

**Clearing a controller is its own command.** `set-controller` refuses the zero
address and `clear-controller` takes no address, so a typo truncated to zero
cannot revoke permissions while you believed you were granting them. Clearing
states that the controller loses its owner-or-controller rights.

**DID setters replace whole arrays.** The file or index list you pass is the
complete new state; anything currently stored and absent from it is removed.
Authentication indices point into the verification-method array *by position*,
so reordering or shrinking it changes what they refer to. `--index` and
`--clear` are mutually exclusive and one is required — clearing is a deliberate
change, never a default.

**Subscription rails.** `--payment peaq` passes back the previewed net PEAQ;
`--payment usdt` requires `--slippage-bps` (`0`..`10000`) and passes back the
previewed maximum USDT, unchanged. Renewal takes **no `--tier`** — the contract
renews at the stored tier — and extends from the current period end, not from
now. Points and credits accrue to the machine's **owner** even when a
controller pays, and output keeps owner and caller/payer as separate fields.

**Relocation is read-only.** `relocation status` distinguishes `pending`,
`arrived`, `completed` and `cancelled`, and never calls destination arrival
alone a completion. It takes no raw EVM, protocol or LayerZero chain IDs; the
SDK derives them from each deployment. Initiation and cancellation are absent
until the protocol publishes a fee quote.

```bash
# Read the full management state
peaqos machine status 42 --json

# Take a machine out of service, then restore it
peaqos machine suspend 42 --yes
peaqos machine resume 42 --yes

# Renew at the stored tier, paying in USDT with 0.5% accepted movement
peaqos machine subscription renew 42 --payment usdt --slippage-bps 50 --yes

# Hand ownership over safely, then let the new owner set their own controller
peaqos machine transfer 42 0xRecipient --yes
```

Exit codes and `error_code` values are the ones documented under
[`peaqos activate`](#peaqos-activate) — one taxonomy for both.

### `peaqos stream publish`

Chunk, encrypt, and sign data for the peaqOS stream pipeline. Takes raw data
(local file or URL), splits it into fixed-size chunks using the SDK's
`build_chunk_chain`, encrypts each chunk with a unique XChaCha20-Poly1305 key
wrapped for owner/operator/machine recipients, signs the chain with an
Ed25519 key, and writes output files to a local directory.

Optionally upload encrypted blobs and chunk envelopes to S3-compatible storage
with `--s3`. Local output is always written; S3 upload is additive.

```bash
peaqos stream publish \
  --input ./sensor-data.bin \
  --output-dir ./chunks/ \
  --owner-public-key <x25519-hex> \
  --operator-public-key <x25519-hex> \
  --machine-public-key <x25519-hex> \
  --signing-key-file ./ed25519.key \
  --machine-did did:peaq:0x... \
  --machine-key-id did:peaq:0x...#keys-1

# URL input (downloaded automatically)
peaqos stream publish \
  --input https://example.com/data.bin \
  --output-dir ./chunks/ \
  ...

# Custom chunk size and JSON output
peaqos stream publish \
  --input ./data.bin \
  --output-dir ./chunks/ \
  --chunk-size 1024 \
  --json \
  ...

# S3 upload (requires optional boto3 extra — see below)
peaqos stream publish \
  --input ./data.bin \
  --output-dir ./chunks/ \
  --s3 s3://my-bucket/data-stream/ \
  ...

# MinIO or other S3-compatible endpoint
peaqos stream publish \
  --input ./data.bin \
  --output-dir ./chunks/ \
  --s3 s3://peaq-stream/chunks/ \
  --s3-endpoint http://localhost:9000 \
  --s3-region us-east-1 \
  ...
```

#### Flags

| Flag | Required | Default | Description |
|------|----------|---------|-------------|
| `--input` | Yes | — | File path or URL to the source data. |
| `--output-dir` | Yes | — | Directory to write chunk files. Created if missing. |
| `--owner-public-key` | Yes | — | Owner X25519 public key (hex). |
| `--operator-public-key` | Yes | — | Operator X25519 public key (hex). |
| `--machine-public-key` | Yes | — | Machine X25519 public key (hex). |
| `--signing-key-file` | Yes | — | Path to Ed25519 private key file (hex). |
| `--machine-did` | Yes | — | Machine DID (e.g. `did:peaq:<address>`). |
| `--machine-key-id` | Yes | — | DID key reference (e.g. `did:peaq:<address>#keys-1`). |
| `--chunk-size` | No | 262144 | Bytes per chunk (256 KB default). |
| `--json` | No | — | Output manifest as JSON to stdout. |
| `--s3` | No | — | S3 bucket path (e.g. `s3://my-bucket/prefix/`). Enables upload. |
| `--s3-region` | No | from env | Region for the S3-compatible service. |
| `--s3-endpoint` | No | from env | Custom S3-compatible endpoint URL (MinIO, R2, etc.). |

#### S3 upload (optional)

S3 support requires the optional `boto3` dependency:

```bash
pip install peaq-os-cli[s3]
```

When `--s3` is used, the command uploads each `chunk-{n}.bin`, rewrites each
`chunk-{n}.json` with an updated `storageRef`, uploads the envelopes and
`manifest.json`, and adds `s3Bucket` / `s3Prefix` to the manifest. Upload
progress is printed to stderr (suppressed by global `--quiet`). Partial upload
failures are not cleaned up — re-run the command to retry idempotently.

**Credentials and endpoint configuration**

| Variable | Description |
|----------|-------------|
| `PEAQOS_S3_ACCESS_KEY_ID` | Access key ID for the S3-compatible service. |
| `PEAQOS_S3_SECRET_ACCESS_KEY` | Secret access key. |
| `PEAQOS_S3_REGION` | Default region (overridden by `--s3-region`). |
| `PEAQOS_S3_ENDPOINT` | Default custom endpoint URL (overridden by `--s3-endpoint`). |

When `PEAQOS_S3_*` credentials are not set, the CLI falls back to the standard
`boto3` credential chain (shared credentials file, instance profiles, etc.).

#### Output

Creates `chunk-{n}.json` (envelope), `chunk-{n}.bin` (encrypted data), and
`manifest.json` in the output directory. Without `--s3`, each chunk's
`storageRef` is `null`.

**Example (human output):**

```
Chunking 1048576 bytes into 4 chunks...

Published 4 chunks to ./chunks/

  Schema:       peaq.stream.chunks.v1
  Source Hash:  0xabc123...
  Chunk Size:   262144 bytes
  Machine DID:  did:peaq:0xAbc...

  Files:
    chunk-0.json  chunk-0.bin
    chunk-1.json  chunk-1.bin
    chunk-2.json  chunk-2.bin
    chunk-3.json  chunk-3.bin
    manifest.json
```

**Example (human output with `--s3`):**

```
Chunking 1048576 bytes into 4 chunks...
Uploading chunk-0.bin to S3...
Uploading chunk-0.json to S3...
...

Published 4 chunks to ./chunks/
Uploaded 4 chunks to s3://my-bucket/data-stream/

  Schema:       peaq.stream.chunks.v1
  Source Hash:  0xabc123...
  Chunk Size:   262144 bytes
  Machine DID:  did:peaq:0xAbc...
  S3 Bucket:    my-bucket
  S3 Prefix:    data-stream/

  Files (local + S3):
    chunk-0.json  chunk-0.bin  → s3://my-bucket/data-stream/chunk-0.bin
    chunk-1.json  chunk-1.bin  → s3://my-bucket/data-stream/chunk-1.bin
    chunk-2.json  chunk-2.bin  → s3://my-bucket/data-stream/chunk-2.bin
    chunk-3.json  chunk-3.bin  → s3://my-bucket/data-stream/chunk-3.bin
    manifest.json              → s3://my-bucket/data-stream/manifest.json
```

With `--json` and `--s3`, stdout includes `s3Bucket`, `s3Prefix`, and a
`chunks` array with per-chunk `storageRef` values.

### `peaqos show machine`

Display the full on-chain profile for a single machine DID — identity,
DID attributes, MCR snapshot, and recent event summary.

```bash
peaqos show machine did:peaq:0x<40-hex>
peaqos show machine did:peaq:0x<40-hex> --json   # raw JSON to stdout
```

Example output:

```
  Machine: did:peaq:0x9a5F1E244c15e491Ae571c5bF77fDD836ddc37C5

    Machine ID:  45
    Operator  :  did:peaq:0x9Eea...641C

    DID Attributes:
      documentation_url:  https://example.com/docs
      data_visibility  :  public

    MCR Snapshot:
      Rating     :  B
      Score      :  31 / 100
      Bond Status:  bonded

    Recent Events:
      Total            :  10
      Last Event       :  2026-04-20T14:30:00Z
      Last Origin Value:  123
      Last Currency    :  HKD
      Last Subunit     :  100
      Last Status      :  ok
      Last USD Value   :  0.13
```

When the most recent event is a revenue event, the block surfaces the
PRO-336 / PRO-334 FX fields. `Last USD Value` is rendered as USD
dollars (Decimal-quantised to 2 places — `usd_value=13` → `0.13`,
`usd_value=150` → `1.50`). When `amount_status` is
`"unsupported_currency"` or `"fx_unavailable"`, the `Last USD Value`
row shows `—` (em-dash) so the CLI never displays a misleading USD
number for a row whose FX state the server flagged as unreliable:

```
    Recent Events:
      Total            :  10
      Last Event       :  2026-04-20T14:30:00Z
      Last Origin Value:  100
      Last Currency    :  XYZ
      Last Status      :  unsupported_currency
      Last USD Value   :  —
```

Activity events (eventType=1) omit all five FX lines.

### `peaqos show operator machines`

List every machine managed by a given operator DID in a tabular summary
(`peaqID`, `Machine ID`, `MCR`, `Rating`).

```bash
peaqos show operator machines did:peaq:0x<40-hex>
peaqos show operator machines did:peaq:0x<40-hex> --json   # raw JSON to stdout
```

Example output:

```
  Operator: did:peaq:0x9Eeab1aCcb1A701aEfAB00F3b8a275a39646641C
  Machines: 3

peaqID                                              Machine ID   MCR   Rating
────────────────────────────────────────────────────────────────────────────
did:peaq:0x9a5F...37C5                              45           31    B
did:peaq:0xAb3D...12F0                              46           75    A
did:peaq:0xC12E...99B1                              47           55    BB
```

### `peaqos qualify event`

Submit one machine event on-chain via the Event Registry (`submitEvent`).

#### Prerequisites

Configure `.env` in the CLI directory (or export the same variables): private key, RPC URL, and contract addresses. See `peaq_os_cli.config.load_client`.

#### Required flags

| Flag | Meaning |
|------|---------|
| `--machine-id` | Positive integer machine identity. |
| `--type` | `revenue` or `activity`. |
| `--value` | Non-negative integer **as ISO 4217 subunit** per PRO-334. **BREAKING**: pre-PRO-334 callers passed whole-currency amounts; the wire is now subunit. Example: `HK$1.23 → --value=123 --currency HKD`; `¥100 → --value=100 --currency JPY` (JPY has no minor unit). Partner is responsible for the conversion. |
| `--ts` | Event time: Unix seconds (digits only) or ISO 8601 with timezone (`Z` or `+hh:mm`). |

Use a timestamp **on or before** the chain's block time. If `--ts` is ahead of the network clock, the contract can revert with `FutureTimestamp`.

#### Common options

| Flag | Meaning |
|------|---------|
| `--trust` | `self` (default), `onchain`, or `hardware`. |
| `--source-chain` | `same`, `peaq`, or `base` (maps to a chain id for the SDK). |
| `--source-tx` | 32-byte tx hash (hex, `0x` optional). **Required** when `--trust` is `onchain`. |
| `--raw-data` | File path; file bytes are hashed and stored as the event data hash. |
| `--metadata` | File path; bytes are sent as on-chain metadata. |
| `--currency` | Per PRO-336 §6 — currency code for revenue events (e.g. `USD`, `HKD`, 3-10 uppercase alphanumeric chars). Activity events take `""`. **Omit** to use the SDK's smart default (`"USD"` for revenue, `""` for activity). |

#### Examples

```bash
# Revenue event (self-reported trust, default source chain)
peaqos qualify event --machine-id 42 --type revenue --value 100 --ts 1735000000
```

```
Event submitted.
  Machine ID:  42
  Type:        revenue
  Value:       100
  Trust:       self-reported
  Tx:          0x3f4a8c1e2d9b7f05a6c3e8d1f4b2a7c9e0d5f3b1a8e2c6d9f7b4a1e3c5d8f2b4
  Data Hash:   0xa1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890a1b2c3d4e5f67890
```

```bash
# Activity with ISO timestamp
peaqos qualify event --machine-id 42 --type activity --value 0 --ts "2026-04-22T12:00:00Z"

# On-chain-verified event with a source tx hash
peaqos qualify event --machine-id 42 --type revenue --value 200 --ts 1735000000 \
  --trust onchain \
  --source-tx 0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab

# Attach a payload file (raw data is hashed on submit)
peaqos qualify event --machine-id 42 --type activity --value 0 --ts 1735000000 \
  --raw-data ./sensor.bin
```

### `peaqos qualify mcr`

Look up a machine's **Machine Credit Rating (MCR)** from the MCR HTTP API.

#### Usage

```text
peaqos qualify mcr <DID> [--json]
```

- **`DID`** — Must match `did:peaq:0x` plus exactly 40 hex characters (checksum casing is allowed).
- **`--json`** — Print **only** JSON to stdout (pretty-printed, indent 2). No banner or prose. Useful for scripts.

In `--json` mode the object includes the SDK field **`mcr`** (rating label, e.g. `Provisioned`, `BBB`) and a duplicate key **`mcr_rating`** with the same string for tools that expect a `*_rating` field.

#### Examples

```bash
# Human-readable block (rating, score, bond, events, trend, last updated)
peaqos qualify mcr did:peaq:0x9a5F1E244c15e491Ae571c5bF77fDD836ddc37C5
```

```
MCR for did:peaq:0x9a5F1E244c15e491Ae571c5bF77fDD836ddc37C5

  Rating:          A
  Score:           82 / 100
  Bond Status:     bonded

  Events:
    Total:         150
    Revenue:       120
    Activity:      30

  30-Day Revenue:  +12.5%
  Last Updated:    2026-04-20T14:30:00Z
  FX Degraded:     no
```

`FX Degraded: yes` (PRO-336 §S6 / PRO-331) means at least one event in the
scoring set used a degraded FX source (`stale_latest` /
`default_usd_fx_outage`). Use it to distinguish a conservative score caused
by FX outage from an empty-data machine when gating UI / alerts on data
quality.

```bash
# Machine-readable JSON for jq / scripts
peaqos qualify mcr did:peaq:0x9a5F1E244c15e491Ae571c5bF77fDD836ddc37C5 --json
```

```json
{
  "did": "did:peaq:0x9a5F1E244c15e491Ae571c5bF77fDD836ddc37C5",
  "mcr": "A",
  "mcr_rating": "A",
  "mcr_score": 82,
  "bond_status": "bonded",
  "event_count": 150,
  "revenue_event_count": 120,
  "activity_event_count": 30,
  "revenue_trend": "+12.5%",
  "last_updated": 1745152200
}
```

#### Typical failures

| Situation | Exit | What you see |
|-----------|------|----------------|
| Bad or empty DID | `1` | Validation message |
| No MCR row for that DID (HTTP 404) | `2` | `Machine not found` |
| API unavailable (HTTP 503) | `2` | `MCR API unavailable` |
| Other HTTP / RPC issues | `2` | Wrapped SDK or network message |

### `peaqos monetize`

Manage a machine's **Tokenomics 2.0 monetisation** decision in the MCR. `status` is a public read; `opt-in` and `opt-out` are signed, off-chain decisions. The CLI delegates compatibility checks, EIP-191 signing, retry, HTTP, and response validation to the SDK.

#### Usage

```text
peaqos monetize status  KEY [--timeout-seconds SECONDS] [--max-unavailable-retries INTEGER] [--unavailable-retry-delay-seconds SECONDS] [--json]
peaqos monetize opt-in  KEY [--timeout-seconds SECONDS] [--max-unavailable-retries INTEGER] [--unavailable-retry-delay-seconds SECONDS] [--yes] [--json]
peaqos monetize opt-out KEY [--timeout-seconds SECONDS] [--max-unavailable-retries INTEGER] [--unavailable-retry-delay-seconds SECONDS] [--yes] [--json]
```

`KEY` is either a canonical decimal machine ID in `0..2^256-1`, or `did:peaq:<canonical-decimal-machine-id>`. A leading zero (except the value `0`), sign, whitespace, fraction, exponent, hexadecimal value, address-based DID, or value at least `2^256` is rejected locally before SDK I/O. The decimal DID suffix is already the machine ID; the CLI performs no legacy DID lookup.

| Option | Default | Behaviour |
| --- | --- | --- |
| `--timeout-seconds` | `30.0` | Positive, finite end-to-end deadline for each SDK call. Confirmation time is outside it. |
| `--max-unavailable-retries` | `2` | Non-negative retries for the write after `MACHINE_UNAVAILABLE`; SDK reads are not retried. |
| `--unavailable-retry-delay-seconds` | `1.0` | Positive, finite pause before each SDK write retry. |
| `--yes` / `-y` | off | The only non-interactive confirmation for `opt-in` and `opt-out`. |
| `--json` | off | Emit one state object on stdout. It changes output only and never confirms a write. |

Every command requires `TOKENOMICS_DEPLOYMENT_ID`. The SDK resolves the MCR URL, chain ID, Machine Registry, and API version from that approved deployment and the live compatibility signal. `status` requires no signer; writes also require `PEAQOS_PRIVATE_KEY`, whose recovered address must be the machine owner or controller.

Legacy `PEAQOS_MCR_API_URL`, `IDENTITY_REGISTRY_ADDRESS`, and `PEAQOS_RPC_URL` values are not read by these monetisation commands. An explicitly supplied legacy `--api-url` is rejected with exit `3` and is intentionally hidden from help.

Before a write, the CLI reads the current state. An already-satisfied state returns successfully without a prompt, signature, or PUT. Otherwise it shows the deployment, decimal machine ID, current and requested states, and signing address. Without `--yes`, stdin must be a TTY and the operator must confirm that the decision is stored off-chain in the MCR with that signing address as authorizer. Non-TTY input or a declined prompt exits `1` without a PUT.

Opt-in eligibility, including bond and lifecycle state, is enforced by the MCR. Opt-out is not locally blocked by those conditions; even a `MACHINE_UNAVAILABLE` result from its initial idempotency read can proceed to a confirmed opt-out.

#### Examples

```bash
# Turn monetisation on (prompts on interactive stdin)
peaqos monetize opt-in did:peaq:42

# Turn it off from a script after reviewing the decision
peaqos monetize opt-out 42 --yes

# Read the current state (public, no signing key)
peaqos monetize status 42
```

```
  Monetization status

    Deployment:  agung-2026-08-28
    Machine ID:  42
    Status:      OPTED_IN
    Signer:      0x7099...79C8
    Updated At:  2026-07-13T12:00:04Z
```

```bash
# Machine-readable JSON for jq / scripts
peaqos monetize status 42 --json
```

```json
{
  "machine_id": "42",
  "status": "OPTED_IN",
  "signer": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
  "updated_at": 1783944004
}
```

A `PENDING` state renders `Signer` and `Updated At` as `—` (and as `null` in JSON). `machine_id` is always a decimal string in JSON, including values above JavaScript's safe-integer range.

Tokenomics 2.0 state normally starts at `PENDING`; Tokenomics 1.0 decisions, IDs, and signatures are not translated or imported.

#### Typical failures

| Situation | Exit | What you see |
|-----------|------|----------------|
| Invalid or noncanonical `KEY` or option value | `1` | Validation message before SDK I/O |
| Declined prompt or non-TTY write without `--yes` | `1` | No write was sent |
| Missing/unknown `TOKENOMICS_DEPLOYMENT_ID` or incompatible MCR API | `3` | Deployment or compatibility guidance |
| Explicit legacy `--api-url` | `3` | Use `TOKENOMICS_DEPLOYMENT_ID`; raw URL overrides are unsupported |
| Signing key is not owner or controller (`UNAUTHORIZED_SIGNER`) | `2` | Owner/controller authorization guidance |
| Ineligible opt-in (`MACHINE_NOT_BONDED` / `MACHINE_DEACTIVATED`) | `2` | Server code and remediation |
| Network failure, timeout, cancellation, bad response, or API rejection | `2` | Stable mapped error; server code when available |

A timeout or network failure during a PUT is ambiguous: the MCR may have applied it. The CLI reports that the state is unknown and instructs you to rerun the same command. That rerun performs the GET first and sends no second PUT when the requested state is already present.

### `peaqos monetize provision`

Provision an **opted-in** machine as a compute provider node from a
schema-driven manifest. These commands are thin wrappers over the SDK's manifest
runner: the SDK fetches and validates the manifest, runs every command through
its executor, redacts secrets, and decides success. The CLI adds argument
parsing, interactive prompts, terminal rendering, and the resume state file — it
never runs a provisioning command itself.

Success means **verification probes pass**, not that install commands exited
zero. The manifest is provider-agnostic: all provider specifics (commands,
prompts, captures, probes, commission field) live in the manifest, never here.

#### Usage

```text
peaqos monetize provision run       <provider> --machine <key> [--mode manual|auto] [--grant-sudo]
                                               [--inputs <file>] [--manifest-repo <url>] [--manifest-version <v>]
                                               [--state-file <path>] [--resume] [--yes]
peaqos monetize provision preflight <provider> [--machine <key>] [--mode manual|auto] [--grant-sudo]
                                               [--inputs <file>] [--manifest-repo <url>] [--manifest-version <v>]
peaqos monetize provision verify    <provider> [--state-file <path>] [--machine <key>] [--inputs <file>]
                                               [--mode manual|auto] [--grant-sudo]
                                               [--manifest-repo <url>] [--manifest-version <v>] [--json]
```

- **`<provider>`** — Manifest provider key, e.g. `akash`. Lowercase letters, digits, and single hyphens; the slug is interpolated into the manifest URL, so anything else is rejected.
- **`--machine`** — Required on `run`: a canonical decimal Tokenomics machine ID or `did:peaq:<canonical-decimal-machine-id>`. It drives the deployment-bound monetisation pre-check. This key contains no payout address, so `run` also requires `PEAQOS_MACHINE_WALLET_ADDRESS` for the manifest's `context.machine_wallet_address`; the CLI never substitutes the signing key. On `preflight` and `verify`, `--machine` remains an optional provisioning-context value and does not perform the monetisation pre-check.
- **`--mode`** — `manual` (default) confirms each command step; `auto` runs unattended and **requires `--grant-sudo`**. The exact command is always shown before it runs.
- **`--grant-sudo`** — Allow `sudo: required` commands to elevate, scoped to the manifest's `allowedCommands`. `sudo: optional` commands always run unprivileged.
- **`--inputs`** — YAML or JSON file of manifest input values. Any required input still missing is prompted; **secret inputs are read hidden** and never echoed, logged, or persisted.
- **`--state-file`** — Resume/idempotency state, default `./peaqos-provision-state.json`. Written atomically (`0600`) after each completed step and at owner-action pauses.
- **`--resume`** — Continue an interrupted run. The persisted non-secret inputs are restored, so the original `--inputs` file is not needed (secrets are re-prompted, since they are never persisted); an explicit `--inputs` value still wins. Applied only after the state file's provider, machine wallet, manifest digest, resolved inputs, and schema version all match this invocation; any mismatch exits `1` rather than skipping steps done under different values.
- **`--yes` / `-y`** — Auto-confirm command steps. **Owner-action steps still pause** — funding, DNS, and signing handoffs are never auto-confirmed.

`run` requires `PEAQOS_MANIFEST_REPO_URL` (or `--manifest-repo`), `TOKENOMICS_DEPLOYMENT_ID` for the public monetisation pre-check, and `PEAQOS_MACHINE_WALLET_ADDRESS` for provider payout context. The pre-check does not use `PEAQOS_MCR_API_URL`, `IDENTITY_REGISTRY_ADDRESS`, `PEAQOS_RPC_URL`, or a signing key.

#### What `run` does

```text
[1/6] Monetisation status   deployment-bound SDK GET; anything but OPTED_IN stops here
[2/6] Manifest              fetched and pinned by sha256 over the source bytes
[3/6] Inputs                merged, prompted, validated; pin written to the state file
[4/6] Pre-flight            a blocking failure aborts before any phase runs
[5/6] Provisioning          steps run, state checkpointed after each one
[6/6] Verification          the node is live only when every success probe passes
```

#### Examples

```bash
# Full manual run (confirms each command; owner actions always pause)
export PEAQOS_MACHINE_WALLET_ADDRESS=0x9a5F1E244c15e491Ae571c5bF77fDD836ddc37C5
peaqos monetize provision run akash \
  --machine did:peaq:42 \
  --inputs ./akash-inputs.yaml
```

```
  Provider node provisioned.
    Provider:         akash
    Version:          0.3.0
    Probes:           4/4 passed
    providerAddress:  akash1abc…xyz
```

```bash
# Dry gate before committing to a run
peaqos monetize provision preflight akash --inputs ./akash-inputs.yaml

# Unattended run within the manifest's sudo allowlist
peaqos monetize provision run akash \
  --machine 42 \
  --inputs ./akash-inputs.yaml --mode auto --grant-sudo --yes

# Continue after an interruption (persisted inputs are restored; secrets are re-prompted)
peaqos monetize provision run akash \
  --machine did:peaq:42 --resume

# Re-check an already-provisioned node against the pinned manifest
peaqos monetize provision verify akash --json | jq '.[] | select(.passed == false)'
```

`verify` refetches the **pinned** manifest, recomputes its digest, and rebuilds
probe context from the persisted inputs, captures, and wallet. It never resolves
`latest` silently, and a capture a probe needs but the state file cannot supply
is an error — captures come from provisioning, so they are never prompted or
rendered empty.

#### Typical failures

| Situation | Exit | What you see |
|-----------|------|----------------|
| Machine not opted in (`PENDING` / `OPTED_OUT`) | `2` | `Machine … is not opted in … Run 'peaqos monetize opt-in …' first` (no manifest fetched) |
| Bad `<provider>` slug, bad `--machine`, `--mode auto` without `--grant-sudo` | `1` | Names the problem and the fix |
| Missing `PEAQOS_MACHINE_WALLET_ADDRESS` on `run` | `1` | Requests the provider payout wallet override |
| Manifest fetch / schema failure (incl. non-`compute` category) | `2` | Names the URL or the offending schema path |
| Input fails the manifest's validation | `1` | Names the input key and constraint |
| Blocking pre-flight check | `2` | Lists the failing checks with remediation (nothing is provisioned) |
| Step failure | `2` | Names `phase/step` and hints `--resume` |
| `--resume` binding mismatch | `1` | Names the differing field; start a fresh run |
| Resume needs an unrestorable secret capture | `2` | Names the capture; start a fresh run |
| Verification probes failed | `2` | Lists the failed probes (the node is **not** reported live) |
| `verify` digest mismatch / stale override | `2` | `manifest changed since provisioning`, or requires a fresh `run` |
| Missing `PEAQOS_MANIFEST_REPO_URL` or `TOKENOMICS_DEPLOYMENT_ID` | `3` | Missing-var message |

### `peaqos scale agent pair`

Pair an AI agent to an activated machine via the challenge-sign flow.
Requests a pairing challenge, collects the agent's EIP-191 signature, and
creates the pairing with the signed proof. The one-time `pairing_token` is
printed on success. Subsequent commands (such as `peaqos scale search`)
use that token via `--pairing-token-file`.

Requires an activated machine and a platform API key
(`PEAQOS_ORCH_API_KEY`). The token is rendered to stdout exactly once
and is never written to `peaqos.log` or `--verbose` output.

```bash
# Interactive: prompts for the EIP-191 signature
peaqos scale agent pair \
  --machine-id mach_1 \
  --agent-address 0xAgent...0101 \
  --agent-provider teneo \
  --agent-role machine-market-buyer

# Non-interactive: reads signature from file, skips confirmation
peaqos scale agent pair \
  --machine-id mach_1 \
  --agent-address 0xAgent...0101 \
  --agent-provider teneo \
  --agent-role machine-market-buyer \
  --agent-signature-file sig.txt \
  --per-tx-limit 5 --daily-limit 20 --currency USD \
  --allowed-skills pyth-price-feed,walrus-store \
  --yes

# JSON output (requires --agent-signature-file)
peaqos scale agent pair \
  --machine-id mach_1 \
  --agent-address 0xAgent...0101 \
  --agent-provider teneo \
  --agent-role machine-market-buyer \
  --agent-signature-file sig.txt \
  --json
```
### `peaqos scale machine onboard`

Onboard a machine into the Machine Market. Four-step wizard: request an
identity challenge, sign it (via key file, OWS wallet, or manual paste),
register the machine with identity proof, and activate it.

The CLI verifies that the signer address matches one of the DID
controller addresses returned by the challenge endpoint before
proceeding to registration.

**Signing modes** (checked in order):

1. `--identity-signature-file` — read a pre-signed EIP-191 signature from file.
2. `--identity-key-file` — read a private key from file and sign the challenge.
3. OWS wallet (`PEAQOS_OWS_WALLET` set) — sign via the active wallet.
   The key is exported from the vault for the duration of signing only.
4. None of the above — display the challenge and prompt for a pasted signature.

A raw `PEAQOS_PRIVATE_KEY` client does **not** auto-sign; it always falls
through to mode 4 (manual prompt). Only `--identity-signature-file`,
`--identity-key-file`, or an active OWS wallet avoid the prompt.

```bash
# Sign with a DID controller key file (non-interactive)
peaqos scale machine onboard \
  --identity-ref peaqos:machine:my-bot \
  --display-name "My Edge Node" \
  --owner-id operator-42 \
  --machine-type edge-node \
  --runtime-profile linux-docker \
  --identity-key-file ./controller.key \
  --capabilities price-feed,qvac \
  --skill-keys pyth-price-feed \
  --labels env=production,region=eu \
  --yes

# Auto-sign via OWS wallet (PEAQOS_OWS_WALLET must be set)
peaqos scale machine onboard \
  --identity-ref did:peaq:0xAbCd...1234 \
  --display-name "My Edge Node" \
  --owner-id operator-42 \
  --machine-type edge-node \
  --runtime-profile linux-docker \
  --yes

# Pre-signed signature from file
peaqos scale machine onboard \
  --identity-ref peaqos:machine:my-bot \
  --display-name "My Edge Node" \
  --owner-id operator-42 \
  --machine-type edge-node \
  --runtime-profile linux-docker \
  --identity-signature-file sig.txt \
  --yes

# Interactive: prompts for a pasted EIP-191 signature
peaqos scale machine onboard \
  --identity-ref did:peaq:0xAbCd...1234 \
  --display-name "My Edge Node" \
  --owner-id operator-42 \
  --machine-type edge-node \
  --runtime-profile linux-docker

# JSON output (requires a non-interactive signing method)
peaqos scale machine onboard \
  --identity-ref peaqos:machine:my-bot \
  --display-name "My Edge Node" \
  --owner-id operator-42 \
  --machine-type edge-node \
  --runtime-profile linux-docker \
  --identity-key-file ./controller.key \
  --json
```

#### Flags

| Flag | Required | Description |
|------|----------|-------------|
| `--identity-ref` | Yes | Machine identity reference (`did:peaq:0x...` or `peaqos:machine:<id>`). |
| `--display-name` | Yes | Human-readable machine name. |
| `--owner-id` | Yes | Operator/owner identifier. |
| `--machine-type` | Yes | Machine type (e.g. `edge-node`, `robot`). |
| `--runtime-profile` | Yes | Runtime profile (e.g. `linux-docker`). |
| `--capabilities` | No | Machine capabilities (comma-separated). |
| `--skill-keys` | No | Skill keys the machine supports (comma-separated). |
| `--labels` | No | Machine labels (`key=value`, comma-separated). |
| `--identity-signature-file` | No | Path to file containing a pre-signed EIP-191 signature. |
| `--identity-key-file` | No | Path to file containing the DID controller private key for signing. Mutually exclusive with `--identity-signature-file`. |
| `--skip-activate` | No | Register in `draft` status without activating. |
| `-y`, `--yes` | No | Skip confirmation prompt. |
| `--json` | No | Output raw JSON. Requires a non-interactive signing method (`--identity-signature-file`, `--identity-key-file`, or OWS wallet). |

#### Example output

```
[1/4] Requesting identity challenge...
[2/4] Signing identity challenge...
      Signed with key from ./controller.key
      Signer: 0x1111...1111
[3/4] Registering machine...
[4/4] Activating machine...

Machine onboarded successfully (active).

  Machine ID:  mach_abc123
  Identity:    did:peaq:0xAbCd...1234
  Status:      active
  Name:        My Edge Node

  Next: peaqos scale agent pair --machine-id mach_abc123
```

### `peaqos scale machine status`

Display details of a single machine.

```bash
peaqos scale machine status mach_abc123
peaqos scale machine status mach_abc123 --json
```

#### Example output

```
Machine mach_abc123

  Display name:  My Edge Node
  Status:        active
  Identity:      peaqos:machine:my-bot
  Owner:         operator-42
  Type:          edge-node
  Runtime:       linux-docker
  Capabilities:  price-feed, qvac
  Skills:        pyth-price-feed
  Created:       2026-05-16T12:00:00Z
```

### `peaqos scale machine list`

List all machines registered on the orchestration service.

```bash
peaqos scale machine list
peaqos scale machine list --json
```

#### Example output

```
Machines

  ID                     Name                      Status   Identity               Type
  ─────────────────────────────────────────────────────────────────────────────────────────
  mach_abc123            My Edge Node              active   peaqos:machine:my-bot  edge-node
  mach_def456            Test Machine              draft    did:peaq:0xAbCd...1e8f robot

2 machines found.
```

### `peaqos scale search`

Search for services matching a task in the Machine Market. The agent
describes what it needs (service type, capabilities, budget) and gets
back a ranked list of matching quotes.

Requires an active machine and a valid agent pairing token
(`--pairing-token-file`).

```bash
peaqos scale search \
  --machine-id mach_1 \
  --service-type oracle.price-feed \
  --pairing-token-file ./token.txt

peaqos scale search \
  --machine-id mach_1 \
  --service-type oracle.price-feed \
  --pairing-token-file ./token.txt \
  --json   # raw JSON to stdout
```

#### Flags

| Flag | Required | Description |
| `--machine-id` | Yes | Machine performing the search. |
| `--service-type` | Yes | Service type (e.g. `oracle.price-feed`). |
| `--pairing-token-file` | Yes | Path to file containing the agent pairing token. |
| `--agent-pairing-id` | No | Agent pairing ID. |
| `--operation` | No | Desired operation (e.g. `get-latest-price`). |
| `--capabilities` | No | Required capabilities (comma-separated). |
| `--region` | No | Preferred region. |
| `--max-results` | No | Max quotes to return. |
| `--budget-amount` | No | Budget amount. |
| `--budget-max` | No | Maximum budget amount. |
| `--budget-currency` | No | Budget currency (e.g. `USD`). |
| `--native-only` | No | Require native execution (no external handoff). |
| `--allow-handoff` | No | Allow external handoff. |
| `--provider-credentials` | No | Path to JSON file with provider credentials. |
| `--json` | No | Output raw JSON to stdout. |

#### Example output

```
Searching for "oracle.price-feed" services...

Found 2 matching services.

#  Skill Key         Provider   Score  Execution    Integration
────────────────────────────────────────────────────────────────
1  pyth-price-feed   pyth       0.95   native       native
2  dia-price-feed    dia        0.72   ext-handoff  partner-required

Search ID: msearch_449650d9b2be

Use: peaqos scale order <service-id> to place an order (when available).
```

When no quotes are returned:

```
Searching for "compute.marketplace" services...

No matching services found.

Search ID: msearch_abc123

Try broadening your search: remove --native-only, increase --budget-amount, or try a different --service-type.
```

#### Environment

Orchestration-specific variables (in `.env` or environment):

| Variable | Purpose |
|----------|---------|
| `PEAQOS_ORCHESTRATION_URL` | Base URL of the Machine Markets API. |
| `PEAQOS_ORCH_API_KEY` | Platform API key (deployment-level auth). |
| `PEAQOS_ORDER_STEP_DELAY_SEC` | Optional seconds to pause between order placement steps. |

The orchestration URL and API key can also be passed as CLI flags
(`--orchestration-url`, `--orch-api-key`).

### `peaqos scale order <service-uuid>`

Place a market order end-to-end: create the order, handle payment when
required, then execute. The service UUID is the first argument (from a
prior `peaqos scale search` quote). Registered subcommands
(`status`, `list`, `received`, `dispute`) take precedence over service IDs.

Requires an active machine, agent pairing ID, and pairing token
(`--pairing-token-file`). Progress steps are written to `stderr`; the
final summary or `--json` payload goes to `stdout`.

**Payment flows** (chosen from the service quote):

| Pattern | Steps | When |
| ------- | ----- | ---- |
| No payment | `[1/2]` create → execute | `paymentStatus` is `not-required` (e.g. native Pyth) |
| Wallet payment | `[1/5]` create → payment intent → send payment → proof → execute | EVM USDC, Solana USDT, etc. |
| Escrow | Same as wallet, but step 4 calls escrow lock instead of payment proof | External handoff with on-chain escrow |
| x402 | `[1/6]` create → payment intent → sign → proof → execute → confirm | Agentic Market providers (paid HTTP, e.g. Wolfram Alpha over USDC) |

For the **x402** rail the CLI signs the provider's payment challenge locally with
the active wallet (`client.account` — the OWS wallet when `PEAQOS_OWS_WALLET` is
set, otherwise the local key) and hands the signed `PAYMENT-SIGNATURE` header to
peaqOS, which pays the provider during execute. There is **no separate on-chain
transfer** and no "paste the transaction hash" prompt. After order creation, you
confirm once before payment intent, signing, proof submission, and execution;
delivery is then confirmed automatically (step 6). If execution fails after proof is
recorded, the error reports the current payment status so you can verify whether
the authorization is held.

**Payment transfer modes** (step 3 when wallet payment is required; the x402 rail signs instead of transferring):

| Mode | How |
| ---- | --- |
| **OWS** | `PEAQOS_OWS_WALLET` set — CLI signs and sends the ERC-20 transfer via the OWS vault; tx hash captured automatically. Passphrase from `OWS_PASSPHRASE` or an interactive prompt. |
| **Manual** | No OWS wallet — CLI prints amount, chain, token, and payee; operator completes the transfer and pastes the tx hash at the `>` prompt. |
| **Pre-supplied** | `--payment-tx-hash` (+ `--payment-chain`, `--payment-token`) — skips step 3; proof submitted with the given hash/signature. |

Use `--skip-payment` only when payment was already completed externally;
combine with `--payment-tx-hash` to record proof without re-sending funds.

#### Flags

| Flag / argument | Required | Description |
| --------------- | -------- | ----------- |
| `<service-uuid>` | Yes | Service ID from search results. |
| `--machine-id` | Yes | Machine placing the order. |
| `--agent-pairing-id` | Yes | Agent pairing ID (from `peaqos scale agent pair`). |
| `--pairing-token-file` | Yes | Path to agent pairing token file. |
| `--search-id` | No | Search ID from a prior `peaqos scale search`. |
| `--quote-id` | No | Quote ID from search results. |
| `--operation` | No | Requested operation (e.g. `get-latest-price`). |
| `--budget-amount` | No | Budget amount. |
| `--budget-currency` | No | Budget currency (e.g. `USD`). |
| `--input` | No | JSON file with operation input. |
| `--provider-credentials` | No | JSON file with provider credentials (never logged). |
| `--payment-tx-hash` | No | Pre-completed payment tx hash (EVM) or signature (Solana). |
| `--payment-chain` | No | Chain for proof (e.g. `base`, `solana`, `peaq`). Required with `--payment-tx-hash`. |
| `--payment-token` | No | Token for proof (e.g. `USDC`, `USDT`). Required with `--payment-tx-hash`. |
| `--skip-payment` | No | Skip the on-chain payment step (use with `--payment-tx-hash` when proof is supplied separately). |
| `-y`, `--yes` | No | Skip confirmation prompts. |
| `--json` | No | Output JSON to stdout (implies `--yes`). Contains `order`, `execution`, and `payment` when a payment record exists. |

Set `PEAQOS_ORDER_STEP_DELAY_SEC` to a non-negative number of seconds to pause
between placement steps for demos or eventually consistent order state. When the
variable is unset, no delay is applied.

#### Examples

**No-payment service** (native execution, two steps):

```bash
peaqos scale order svc_pyth_btc_usd \
  --machine-id mach_1 \
  --agent-pairing-id pair_67c50f8fdd3c \
  --pairing-token-file ./token.txt \
  --search-id msearch_449650d9b2be \
  --quote-id quote_abc123 \
  --operation get-latest-price \
  --yes
```

```
[1/2] Creating order...
[2/2] Executing order...

Order executed.

  Order ID:      ord_e89c70259bdb
  Service:       BTC/USD (pyth-price-feed)
  Status:        delivered
  Payment:       not_required

  Confirm delivery: peaqos scale order received ord_e89c70259bdb
```

**Manual wallet payment** (operator sends USDC, pastes hash):

```bash
peaqos scale order svc_dia_eth_usd \
  --machine-id mach_1 \
  --agent-pairing-id pair_67c50f8fdd3c \
  --pairing-token-file ./token.txt \
  --yes
# Step 3 prompts: paste 0x... tx hash after transferring off-wallet
```

**OWS auto-payment** (`PEAQOS_OWS_WALLET` in `.env`):

```bash
export PEAQOS_OWS_WALLET=agent
export OWS_PASSPHRASE='...'   # optional; otherwise prompted once
peaqos scale order svc_dia_eth_usd \
  --machine-id mach_1 \
  --agent-pairing-id pair_67c50f8fdd3c \
  --pairing-token-file ./token.txt \
  --yes
```

```
[3/5] Sending payment...
      Signing transfer via OWS (wallet=agent, chain=base)
      0x3333...3333 → 0x4444...4444  1.00 USDC
      Tx: 0x602d...5584
```

**Pre-supplied payment** (skip transfer step):

```bash
peaqos scale order svc_dia_eth_usd \
  --machine-id mach_1 \
  --agent-pairing-id pair_67c50f8fdd3c \
  --pairing-token-file ./token.txt \
  --payment-tx-hash 0x602d5584... \
  --payment-chain base \
  --payment-token USDC \
  --yes
```

**x402 paid provider** (local signing, no on-chain transfer):

```bash
peaqos scale order "agentic-market:...:query:92c9d0a2" \
  --machine-id mach_1 \
  --agent-pairing-id pair_67c50f8fdd3c \
  --pairing-token-file ./token.txt \
  --input query.json
```

```
[1/6] Creating order...

Order summary:

  Order ID:  ord_3ba63e8494a8
  Service:   wolfram-alpha
  Status:    created
  Payment:   payment_pending
Proceed with payment and order execution? [y/N]: y
[2/6] Creating payment intent...
Payment required (x402).

  Amount:    $0.02
  Chain:     eip155:8453
  Token:     USDC (0x8335...2913)
  Pay from:  0x9fbd...4913
  Pay to:    0x6302...Ad57

  The agent wallet will sign the x402 authorization next.
[3/6] Signing x402 payment...
[4/6] Recording payment proof...
[5/6] Executing order...
[6/6] Confirming delivery...

Order executed.

  Order ID:      ord_3ba63e8494a8
  Service:       Wolfram Alpha
  Status:        delivered
  Payment:       paid (x402)

  Result: x^3/3 + C
```

**External handoff** (escrow + handoff URL):

```
Order placed (external handoff).

  Order ID:      ord_63ab7e934300
  Service:       Aethir GPU Cloud
  Status:        handoff
  Handoff:       Open Aethir Cloud → https://app.aethir.com/

  After using the external service:
    peaqos scale order received ord_63ab7e934300
```

**JSON output** (scripting):

```bash
peaqos scale order svc_pyth_btc_usd \
  --machine-id mach_1 \
  --agent-pairing-id pair_67c50f8fdd3c \
  --pairing-token-file ./token.txt \
  --yes --json
```

```json
{
  "order": { "id": "ord_e89c70259bdb", "status": "delivered", "...": "..." },
  "execution": {
    "status_code": 200,
    "run": { "...": "..." },
    "outcome": { "...": "..." }
  }
}
```

When the order requires payment, the response also includes `"payment": { "status": "held", ... }`.

On partial failure after create, the error includes the order ID, current
payment status, and a hint to run `peaqos scale order status <id>`.

### `peaqos scale order status <order-id>`

Check order and payment state.

```bash
peaqos scale order status ord_e89c70259bdb
peaqos scale order status ord_e89c70259bdb --json
```

#### Example output

```
Order ord_e89c70259bdb

  Service:        BTC/USD (pyth-price-feed)
  Status:         delivered
  Execution:      native
  Created:        2026-05-16T12:00:00Z

  Payment:
    Status:       not_required
    Rail:         —
    Amount:       —

  Next: peaqos scale order received ord_e89c70259bdb
```

`--json` returns `{ "order": { ... }, "payment": { ... } }`.

### `peaqos scale order list`

List market orders for a machine (`GET /market/orders`). Supports
page-by-page listing with `--limit` and `--cursor`, or fetching every
order in one shot when using `--json` without `--limit`.

**Flags:**

| Flag | Description |
|------|-------------|
| `--machine-id` | **Required.** Machine whose orders to list. |
| `--limit` | Page size (1–500). Omitted → server default (100). |
| `--cursor` | Opaque cursor from a previous response (next page). |
| `--json` | Machine-readable output (see below). |

**Human output** (default) returns one page. When the API includes a
`next_cursor`, a copy-paste hint is printed after the table. Cursors are
shown verbatim in the hint and are never written to logs (even with
`--verbose`).

```bash
peaqos scale order list --machine-id mach_prod_smoke_mcr_1
peaqos scale order list --machine-id mach_prod_smoke_mcr_1 --limit 10
peaqos scale order list --machine-id mach_prod_smoke_mcr_1 \
  --limit 10 --cursor eyJ2IjoxLCJvZmZzZXQiOjJ9
```

#### Example output (human)

```
Orders for mach_prod_smoke_mcr_1

  ID                     Service                   Status      Execution   Created
  ─────────────────────────────────────────────────────────────────────────────────
  ord_e89c70259bdb       BTC/USD (pyth-price-feed) confirmed   native      2026-05-16T12:25:00Z
  ord_63ab7e934300       Aethir GPU Cloud          disputed    ext-handoff 2026-05-16T13:00:00Z

2 orders shown.

Next page: peaqos scale order list --machine-id mach_prod_smoke_mcr_1 --cursor eyJ2IjoxLCJvZmZzZXQiOjJ9
```

When there is no next page, only the count line is shown (no `Next page:` line).

**JSON output:**

| Invocation | Shape |
|------------|--------|
| `--json` (no `--limit`) | Root **array** of all orders across pages (auto-paginated). |
| `--json --limit N` | Single page: `{ "items": [...], "next_cursor": "..." \| null }`. |

```bash
# All orders (pipe-friendly for jq)
peaqos scale order list --machine-id mach_1 --json | jq '.[] | .id'

# Manual paging
peaqos scale order list --machine-id mach_1 --json --limit 5
```

```json
[
  { "id": "ord_e89c70259bdb", "status": "delivered", "...": "..." },
  { "id": "ord_63ab7e934300", "status": "handoff", "...": "..." }
]
```

```json
{
  "items": [{ "id": "ord_e89c70259bdb", "...": "..." }],
  "next_cursor": "eyJ2IjoxLCJvZmZzZXQiOjJ9"
}
```

Invalid `--limit` (0, negative, or above 500) exits with code `1` and:
`Limit must be between 1 and 500.`

### `peaqos scale order received <order-id>`

Confirm delivery and release escrowed funds. The order must be in
`delivered` status (native execution or after external handoff).

```bash
peaqos scale order received ord_e89c70259bdb \
  --pairing-token-file ./token.txt

peaqos scale order received ord_e89c70259bdb \
  --pairing-token-file ./token.txt \
  --json
```

#### Example output

```
Delivery confirmed.

  Order ID:  ord_e89c70259bdb
  Status:    confirmed
  Payment:   release_pending
```

### `peaqos scale order dispute <order-id>`

Raise a dispute and freeze escrowed payment. Requires `--reason` and the
pairing token. Prompts for confirmation unless `--yes` or `--json`.

```bash
peaqos scale order dispute ord_63ab7e934300 \
  --reason "Service unavailable after payment" \
  --pairing-token-file ./token.txt \
  --yes

# Optional evidence JSON file
peaqos scale order dispute ord_63ab7e934300 \
  --reason "Incorrect deliverable" \
  --evidence ./evidence.json \
  --pairing-token-file ./token.txt \
  --json
```

#### Example output

```
Dispute raised.

  Order ID:  ord_63ab7e934300
  Status:    disputed
  Payment:   frozen
  Reason:    Service unavailable after payment
```

#### Integration tests

Order lifecycle integration tests live at
`tests/integration/commands/scale/test_order_integration.py`. Enable with
`PEAQOS_CLI_ORCH_INTEGRATION=1` and the `PEAQOS_INTEGRATION_*` variables
documented in that file.

### `peaqos stream grant`

Grant a buyer decryption access to a published chunk chain. Reads chunk
envelope files from a publish output directory, unwraps the owner's per-chunk
keys, re-wraps them for the buyer, and writes `peaq.stream.buyer-access.v1`
files. Chunk envelope files are never modified — only new buyer access files
are produced.

**Prerequisites:**

* A publish output directory containing `chunk-*.json` envelope files (from
  `peaqos stream publish`). The encrypted `chunk-*.bin` blobs and
  `manifest.json` are not read by this command.
* Owner X25519 private key file (the key used when the chain was published).
* Buyer X25519 public key (hex) and buyer recipient ID (e.g.
  `did:peaq:<buyer-address>`).

Progress and the human summary are written to `stderr`; `--json` writes only
the summary object to `stdout`.

**Key file format:** `--owner-private-key-file` expects an X25519 private key
as a single line of hex — exactly 64 hex characters, with an optional `0x`
prefix. This is **not** the secp256k1 `0x`-prefixed 64-hex format used by
`read_key_file` in Utilities below.

#### Flags

| Flag | Required | Default | Description |
| ---- | -------- | ------- | ----------- |
| `--chunk-dir` | Yes | — | Directory containing published chunk envelope files (`chunk-*.json`). |
| `--buyer-public-key` | Yes | — | Buyer's X25519 public key (hex). |
| `--buyer-id` | Yes | — | Buyer recipient ID (e.g. `did:peaq:<buyer-address>`). |
| `--owner-private-key-file` | Yes | — | Path to file containing the owner's X25519 private key (hex). |
| `--output-dir` | Yes | — | Directory to write buyer access files (created if missing). |
| `--max-file-size` | No | `512000` | Maximum buyer access file size in bytes (500 KB). |
| `--json` | No | — | Output summary JSON to stdout (no other stdout output). |

#### Output files

Buyer access files use schema `peaq.stream.buyer-access.v1`. Files are named
`<buyerPublicKeyHex>-<n>.json` with a 1-based index (e.g.
`a1b2c3d4...-1.json`, `a1b2c3d4...-2.json`). Entries are batched up to
`--max-file-size` (default 500 KB). A single oversized entry gets its own
file; entries are never split across files.

#### Examples

```bash
peaqos stream grant \
  --chunk-dir ./publish-output \
  --buyer-public-key a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456 \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --owner-private-key-file ./owner-x25519.key \
  --output-dir ./access
```

Progress and summary on `stderr`:

```
Granting access to 4 chunks for buyer did:peaq:0xBuyer00000000000000000000000000000001...

Wrote 1 buyer access file to ./access

  Schema:       peaq.stream.buyer-access.v1
  Buyer ID:     did:peaq:0xBuyer00000000000000000000000000000001
  Chunks:       4
  Files:        1

    a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456-1.json  (12.3 KB)
```

```bash
# Smaller batch size → more access files
peaqos stream grant \
  --chunk-dir ./publish-output \
  --buyer-public-key a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456 \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --owner-private-key-file ./owner-x25519.key \
  --output-dir ./access \
  --max-file-size 1024

# JSON summary to stdout (stderr empty)
peaqos stream grant \
  --chunk-dir ./publish-output \
  --buyer-public-key a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456 \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --owner-private-key-file ./owner-x25519.key \
  --output-dir ./access \
  --json
```

```json
{
  "schemaVersion": "peaq.stream.buyer-access.v1",
  "buyerId": "did:peaq:0xBuyer00000000000000000000000000000001",
  "chunkCount": 4,
  "fileCount": 1,
  "outputDir": "./access",
  "files": [
    {
      "name": "a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456-1.json",
      "sizeBytes": 12634
    }
  ]
}
```

#### Common errors

| Condition | Exit code | Message |
| --------- | --------- | ------- |
| Wrong owner private key (`key_commitment` mismatch) | `2` | `Key commitment verification failed — wrong owner key?` |
| No `chunk-*.json` files in `--chunk-dir` | `1` | `No chunk files found in {path}` |
| Gap or duplicate chunk indices | `1` | `Missing chunk at index {n}` / `Duplicate chunk at index {n}` |
| Invalid buyer public key hex | `1` | Validation error before SDK call |
| Empty `--buyer-id` | `1` | `--buyer-id must not be empty.` |
| Output directory not writable | `1` | `Cannot write to: {path}` |

### `peaqos stream consume`

Decrypt a purchased chunk chain and reassemble the original data. Verifies the
chain integrity, decrypts each chunk using the buyer's wrapped key, and writes
the reassembled original data to an output file.

Supports two input modes:

* **Local directories** — provide `--chunk-dir`, `--access-dir`, and
  `--data-dir` pointing to directories already on disk.
* **Remote download** — provide `--download-url` pointing to an HTTP/HTTPS
  release package. The package is downloaded to a work directory first, then
  the existing verify → decrypt → reassemble pipeline runs on the downloaded
  files. The work directory is deleted after successful reassembly unless
  `--keep-files` is set.

**Prerequisites:**

* Buyer X25519 private key file (the key whose public key was used in grant).
* For **local mode**: chunk directory (`chunk-*.json` envelopes, optionally
  `manifest.json` from `peaqos stream publish`), encrypted data directory
  (`chunk-*.bin` blobs), and buyer access directory (`*.json` files from
  `peaqos stream grant`).
* For **remote mode**: an HTTP/HTTPS URL to a **self-contained release
  package** that bundles everything the pipeline needs — chunk envelopes
  (`chunk-*.json`), encrypted data blobs (`chunk-*.bin`), and buyer access
  files (`*.json`) — exposed either as a `manifest.json` listing those files or
  as a ZIP archive containing them. This is a self-hosted bundle, distinct from
  the SDK `S3DeliveryChannel` pre-signed URL, which delivers only the buyer
  access files (the ciphertext stays referenced by each chunk's `storage_ref`).
  Manifest file names are restricted to flat `*.json` / `*.bin` names. A query
  token on the URL (for a self-hosted endpoint that authorises that way) is
  preserved when fetching each file — but note an S3 **pre-signed
  single-object** URL cannot address the manifest's sub-paths (SigV4 signs the
  object path, so a changed path returns 403). A pre-signed URL pointing at a
  single **ZIP** object still works: the manifest probe returns 403/404 and the
  command falls back to fetching the signed object as a ZIP.

> **Roundtrip note (acceptance-criterion deviation).** `--download-url` does
> **not** consume the URL produced by `peaqos stream distribute` /
> `S3DeliveryChannel` directly. That pre-signed URL delivers only the first
> buyer-access file; the chunk envelopes are not delivered and the ciphertext
> stays referenced by each chunk's `storage_ref`, and the SDK ships no
> buyer-side S3 receiver. A complete distribute → consume roundtrip therefore
> requires SDK/orchestration support (an S3 delivery receiver plus a descriptor
> enumerating every access file, chunk-envelope location, and a `storage_ref`
> resolver) that does not exist yet. Until then, point `--download-url` at a
> self-contained bundle as described above.

Progress and the human summary are written to `stderr`; `--json` writes only
the summary object to `stdout`.

#### Flags

| Flag | Required | Default | Description |
| ---- | -------- | ------- | ----------- |
| `--chunk-dir` | Yes (local mode) | — | Directory containing chunk envelope files (`chunk-*.json`). Not used with `--download-url`. |
| `--access-dir` | Yes (local mode) | — | Directory containing buyer access files (`*.json`). Not used with `--download-url`. |
| `--data-dir` | Yes (local mode) | — | Directory containing encrypted data blobs (`chunk-*.bin`). Not used with `--download-url`. |
| `--buyer-private-key-file` | Yes | — | Path to file containing buyer's X25519 private key (hex). |
| `--buyer-id` | Yes | — | Buyer recipient ID matching the access files. |
| `--output` | Yes | — | Output file path for the reassembled data. |
| `--skip-verify` | No | `False` | Skip chain verification (not recommended, debugging only). |
| `--json` | No | `False` | Output summary JSON to stdout (no other stdout output). |
| `--download-url` | No | — | HTTP/HTTPS URL to a release package. Mutually exclusive with `--chunk-dir`, `--access-dir`, `--data-dir`. |
| `--work-dir` | No | temp dir | Working directory for downloaded files. Cleaned up after success unless `--keep-files`. Ignored when `--download-url` is absent. |
| `--keep-files` | No | `False` | Keep the work directory after successful reassembly. Ignored when `--download-url` is absent. |

#### Examples

```bash
# Local mode — directories already on disk
peaqos stream consume \
  --chunk-dir ./chunks \
  --access-dir ./access \
  --data-dir ./chunks \
  --buyer-private-key-file ./buyer-x25519.key \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --output ./recovered-data.bin

# Remote download — fetch a self-contained release bundle
peaqos stream consume \
  --download-url "https://bundles.example.com/releases/ord-001/" \
  --buyer-private-key-file ./buyer-x25519.key \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --output ./recovered-data.bin

# Remote download — keep the downloaded files for inspection
peaqos stream consume \
  --download-url "https://bundles.example.com/releases/ord-001/" \
  --work-dir ./downloaded \
  --keep-files \
  --buyer-private-key-file ./buyer-x25519.key \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --output ./recovered-data.bin

# Skip verification (debugging only)
peaqos stream consume \
  --chunk-dir ./chunks \
  --access-dir ./access \
  --data-dir ./chunks \
  --buyer-private-key-file ./buyer-x25519.key \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --output ./recovered-data.bin \
  --skip-verify

# JSON summary to stdout
peaqos stream consume \
  --chunk-dir ./chunks \
  --access-dir ./access \
  --data-dir ./chunks \
  --buyer-private-key-file ./buyer-x25519.key \
  --buyer-id did:peaq:0xBuyer00000000000000000000000000000001 \
  --output ./recovered-data.bin \
  --json
```

Human output on `stderr`:

```
Downloading release package from https://bundles.example.com/releases/ord-001/...
Downloading chunk-0.json...
Downloading chunk-0.bin...
Downloading chunk-1.json...
Downloading chunk-1.bin...
Downloading buyer-access-abc123.json...
Verifying chain... ✓ 4 chunks valid.
Decrypting chunk 0/4...
Decrypting chunk 1/4...
Decrypting chunk 2/4...
Decrypting chunk 3/4...

Reassembled 1048576 bytes to ./recovered-data.bin

  Source Hash:  0xabc123...
  Chunks:       4
  Buyer ID:     did:peaq:0xBuyer00000000000000000000000000000001
```

JSON output:

```json
{
  "output": "./recovered-data.bin",
  "totalBytes": 1048576,
  "chunkCount": 4,
  "sourceHash": "0xabc123...",
  "buyerId": "did:peaq:0xBuyer00000000000000000000000000000001",
  "verified": true
}
```

#### Download behaviour

When `--download-url` is provided, the command:

1. Creates the work directory (`--work-dir` if given, otherwise a temp dir).
2. Downloads land in a command-owned, uniquely named `peaqos-package-*`
   subdirectory of the work directory, so a pre-existing `--work-dir`'s files
   (including any prior `peaqos-package-*` kept via `--keep-files`) are never
   touched.
3. Fetches `manifest.json` from the URL path (a query token is preserved). If
   the manifest contains a `"files"` list, each file is downloaded individually
   with per-file progress on `stderr` (suppressed under `--quiet`). The manifest
   itself is persisted so its `sourceHash` survives.
4. If `manifest.json` returns 404 (absent) or 403 (e.g. a pre-signed single
   object), or has no `"files"` key, the base URL is downloaded as a ZIP archive
   and extracted.
5. Downloaded files are sorted (recursively, so a ZIP wrapping the package in a
   top-level directory works) into `chunks/`, `data/`, and `access/`
   subdirectories; `manifest.json` is co-located with the chunks so its
   `sourceHash` is recovered before the pipeline runs.
6. On success, cleanup removes only what the command created: a work directory
   it created is removed entirely; otherwise only the `peaqos-package-*`
   staging subdirectory is removed, and an `--output` inside it is preserved.
   `--keep-files` skips cleanup; a cleanup failure is reported as a warning.
7. On any error, the work directory is preserved for debugging.

#### Common errors

| Condition | Exit code | Message |
| --------- | --------- | ------- |
| Chain verification failed | `2` | `Chain verification failed at chunk {n}: {reason}` |
| Missing encrypted data for a chunk | `2` | `Missing encrypted data for chunk {n}` |
| No buyer access for a chunk | `2` | `No buyer access for chunk {n} ({chunk_id})` |
| Wrong buyer private key | `2` | `Decryption failed for chunk {n} — access not granted for this buyer private key` |
| `key_commitment` mismatch | `2` | `Key commitment verification failed for chunk {n}` |
| `plaintext_hash` mismatch | `2` | `Data integrity check failed for chunk {n} — plaintext hash mismatch` |
| Download HTTP error | `2` | `Download failed: HTTP {code} from {url}` |
| Download timeout | `2` | `Download failed: connection timed out after 60s` |
| Downloaded archive not a valid ZIP | `2` | `Downloaded archive is not a valid ZIP file: {detail}` |
| No chunk files in dir | `1` | `No chunk files found in {path}` |
| No encrypted data files | `1` | `No encrypted data files found in {path}` |
| No buyer access files | `1` | `No buyer access files found in {path}` |
| `--download-url` with a dir flag | `1` | `--download-url is mutually exclusive with --chunk-dir, --access-dir, and --data-dir.` |
| Invalid `--download-url` scheme | `1` | `--download-url must start with http:// or https://.` |
| Missing `--chunk-dir` (local mode) | `1` | `--chunk-dir is required when --download-url is not provided.` |
| Empty `--buyer-id` | `1` | `--buyer-id must not be empty.` |
| Output path not writable | `1` | `Cannot write to: {path}` |

### `peaqos stream pay`

Transfer tokens on-chain to a seller and optionally submit the transaction hash as payment proof. Supports native token and ERC-20/SPL contract transfers on peaq, Base, and Solana.

When `--confirmation-url` is provided, proof is submitted immediately after the transfer. If omitted, only the transfer executes and a `peaqos stream payproof` hint is printed so proof can be submitted separately.

Progress lines are written to `stderr`; the transfer summary and `--json` payload go to `stdout`. The transaction hash is always written to `stdout` before the proof step, so it is captured even if proof submission fails.

#### Flags

| Flag | Required | Default | Description |
| ---- | -------- | ------- | ----------- |
| `--seller-address` | Yes | — | Recipient address (EVM `0x...` or Solana base58). |
| `--amount` | Yes | — | Human-readable transfer amount (e.g. `"10.5"`). |
| `--chain` | Yes | — | Target chain: `peaq`, `base`, or `solana`. |
| `--order-id` | Yes | — | Order ID for the purchase. |
| `--confirmation-url` | No | — | URL to submit payment proof after transfer. Omit to transfer only. |
| `--token-address` | No | — | ERC-20 contract (EVM) or SPL mint address (Solana). Omit for native token. |
| `--token-decimals` | No | — | Token decimal count override (for tokens not in the well-known registry). |
| `--rpc-url` | No | — | RPC endpoint. Required for `--chain base` and `--chain solana`. |
| `--private-key-file` | No | from config | Path to buyer private key file (0x-prefixed hex). Falls back to `PEAQOS_PRIVATE_KEY`. |
| `--json` | No | `False` | Output result as JSON to stdout. |

#### Examples

```bash
# Native PEAQ transfer (no proof)
peaqos stream pay \
  --seller-address 0xSeller...1234 \
  --amount 10.5 \
  --chain peaq \
  --order-id order-001

# Base EVM transfer with proof submission
peaqos stream pay \
  --seller-address 0xSeller...1234 \
  --amount 1.0 \
  --chain base \
  --order-id order-002 \
  --rpc-url https://mainnet.base.org \
  --token-address 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 \
  --confirmation-url https://api.example.com/payments/proof

# Solana SPL transfer
peaqos stream pay \
  --seller-address So111...base58 \
  --amount 5.0 \
  --chain solana \
  --order-id order-003 \
  --rpc-url https://api.mainnet-beta.solana.com \
  --token-address EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v

# JSON output with proof
peaqos stream pay \
  --seller-address 0xSeller...1234 \
  --amount 10.5 \
  --chain peaq \
  --order-id order-001 \
  --confirmation-url https://api.example.com/payments/proof \
  --json
```

**Human output (with `--confirmation-url`):**

```
Transferring 10.5 on peaq to 0xSeller...1234...

  Tx Hash:     0xabc123...
  Chain:       peaq
  Status:      submitted

  Proof:       accepted
  Order ID:    order-001
  Submitted:   2026-06-25T12:00:05Z
```

**Human output (without `--confirmation-url`):**

```
Transferring 10.5 on peaq to 0xSeller...1234...

  Tx Hash:     0xabc123...
  Chain:       peaq
  Status:      submitted

  Submit proof manually: peaqos stream payproof --tx-hash 0xabc123... --order-id order-001 --confirmation-url <url>
```

**JSON output:**

```json
{
  "txHash": "0xabc123...",
  "chain": "peaq",
  "status": "submitted",
  "payerAddress": "0xPayer...5678",
  "payeeAddress": "0xSeller...1234",
  "amount": "10.5",
  "token": "PEAQ",
  "tokenAddress": null,
  "proof": {
    "accepted": true,
    "orderId": "order-001",
    "submittedAt": "2026-06-25T12:00:05Z"
  }
}
```

`"proof"` is `null` when `--confirmation-url` is omitted.

#### Error codes

| Condition | Exit | Message |
| --------- | ---- | ------- |
| Invalid or empty `--amount` | `1` | Validation message |
| Empty `--seller-address` or `--order-id` | `1` | Validation message |
| Missing Solana dependency | `1` | Install instructions (`pip install peaq-os-sdk[solana]`) |
| Signing failure | `1` | Sanitized message (no key material) |
| Insufficient balance | `2` | `Insufficient balance for transfer` |
| Transaction reverted | `2` | `Transaction reverted: {reason}` |
| Proof HTTP failure | `2` | `Payment proof submission failed: {reason}` |
| Missing env vars / config | `3` | Actionable config message |

### `peaqos stream payproof`

Submit a payment proof for a completed on-chain transfer. Use this when the transfer was done outside of `peaqos stream pay`, or when the proof step from that command failed and needs to be retried.

Progress is written to `stderr`; the proof result and `--json` payload go to `stdout`.

#### Flags

| Flag | Required | Default | Description |
| ---- | -------- | ------- | ----------- |
| `--tx-hash` | Yes | — | EVM transaction hash (`0x...`) or Solana transaction signature. |
| `--order-id` | Yes | — | Order ID associated with the payment. |
| `--confirmation-url` | Yes | — | URL to submit the payment proof to. |
| `--chain` | Yes | — | Chain the transfer was on: `peaq`, `base`, or `solana`. |
| `--payer-address` | Yes | — | Buyer wallet address that signed the transfer. |
| `--payee-address` | Yes | — | Seller wallet address that received the transfer. |
| `--amount` | Yes | — | Human-readable amount transferred (must match the original transfer). |
| `--token` | No | — | Token symbol metadata (e.g. `USDC`). |
| `--token-address` | No | — | Token contract or SPL mint address. Omit for native transfers. |
| `--json` | No | `False` | Output result as JSON to stdout. |

#### Examples

```bash
# Submit proof for a previously completed transfer
peaqos stream payproof \
  --tx-hash 0xabc123... \
  --order-id order-001 \
  --confirmation-url https://api.example.com/payments/proof \
  --chain peaq \
  --payer-address 0xPayer...5678 \
  --payee-address 0xSeller...1234 \
  --amount 10.5

# ERC-20 transfer proof (Base USDC)
peaqos stream payproof \
  --tx-hash 0xdef456... \
  --order-id order-002 \
  --confirmation-url https://api.example.com/payments/proof \
  --chain base \
  --payer-address 0xPayer...5678 \
  --payee-address 0xSeller...1234 \
  --amount 1.0 \
  --token USDC \
  --token-address 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913

# JSON output
peaqos stream payproof \
  --tx-hash 0xabc123... \
  --order-id order-001 \
  --confirmation-url https://api.example.com/payments/proof \
  --chain peaq \
  --payer-address 0xPayer...5678 \
  --payee-address 0xSeller...1234 \
  --amount 10.5 \
  --json
```

**Human output:**

```
Submitting payment proof...

  Proof:       accepted
  Order ID:    order-001
  Submitted:   2026-06-25T12:00:05Z
```

**JSON output:**

```json
{
  "accepted": true,
  "orderId": "order-001",
  "submittedAt": "2026-06-25T12:00:05Z"
}
```

#### Error codes

| Condition | Exit | Message |
| --------- | ---- | ------- |
| Empty `--tx-hash` or `--order-id` | `1` | Validation message |
| Proof HTTP failure | `2` | `Payment proof submission failed: {reason}` |
| Missing env vars / config | `3` | Actionable config message |

### `peaqos stream distribute`

Listen for buyer payment confirmation and deliver buyer access files. After
publishing a chunk chain, the seller runs this command to wait for a buyer's
payment to be confirmed, then automatically generates buyer access files and
delivers them to S3.

The command polls `--confirmation-url` every `--poll-interval` seconds until
the endpoint reports a confirmed payment or `--timeout` seconds elapse. On
confirmation the SDK builds buyer access files (the same as `peaqos stream
grant`), uploads them to the S3 path under `{prefix}{buyer_id}/`, and returns
a pre-signed download URL.

**Prerequisites:**

* A published chunk directory containing `chunk-*.json` envelope files (from
  `peaqos stream publish`).
* Owner X25519 private key file (the same key used at publish time).
* A reachable HTTP endpoint at `--confirmation-url` that returns a JSON body
  containing at minimum `status`, `buyer_id`, and `buyer_public_key_hex`.
* AWS S3 credentials in `PEAQOS_S3_ACCESS_KEY_ID` / `PEAQOS_S3_SECRET_ACCESS_KEY`
  (or the standard `boto3` credential chain) when `--delivery s3`.
* `boto3` installed (`pip install peaq-os-cli[s3]`).

Progress lines are written to `stderr`; the human summary is written to
`stdout`. `--json` writes only the result object to `stdout`.

**Key file format:** `--owner-private-key-file` expects an X25519 private key
as a single line of hex — exactly 64 hex characters, with an optional `0x`
prefix. This is the same format accepted by `peaqos stream grant`.

#### Flags

| Flag | Required | Default | Description |
| ---- | -------- | ------- | ----------- |
| `--chunk-dir` | Yes | — | Directory containing published chunk envelope files (`chunk-*.json`). |
| `--owner-private-key-file` | Yes | — | Path to file containing the owner's X25519 private key (hex). |
| `--confirmation-url` | Yes | — | HTTP endpoint to poll for payment confirmation. |
| `--order-id` | Yes | — | Purchase order identifier (`purchaseId` in the orchestration API). |
| `--poll-interval` | No | `30` | Seconds between confirmation polls. |
| `--timeout` | No | `3600` | Max seconds to wait for confirmation before giving up. |
| `--delivery` | Yes | — | Delivery channel. Currently only `s3`. |
| `--s3` | Conditional | — | S3 bucket path (e.g. `s3://my-bucket/prefix/`). Required when `--delivery s3`. |
| `--s3-region` | No | from env | S3 region (overrides `PEAQOS_S3_REGION`). |
| `--s3-endpoint` | No | from env | Custom S3-compatible endpoint URL (MinIO, R2, etc.). |
| `--presign-expiry` | No | `3600` | Pre-signed download URL expiry in seconds. |
| `--max-file-size` | No | `512000` | Maximum buyer access file size in bytes (500 KB). |
| `--json` | No | — | Output result as JSON to stdout (no other stdout output). |

#### Examples

```bash
# Basic — poll every 30 seconds, 1-hour timeout
peaqos stream distribute \
  --chunk-dir ./publish-output \
  --owner-private-key-file ./owner-x25519.key \
  --confirmation-url https://api.example.com/orders/ord-001/status \
  --order-id ord-001 \
  --delivery s3 \
  --s3 s3://my-bucket/distributes/

# Faster polling with a shorter timeout
peaqos stream distribute \
  --chunk-dir ./publish-output \
  --owner-private-key-file ./owner-x25519.key \
  --confirmation-url https://api.example.com/orders/ord-001/status \
  --order-id ord-001 \
  --delivery s3 \
  --s3 s3://my-bucket/distributes/ \
  --poll-interval 10 \
  --timeout 300

# Longer-lived download links (24 hours)
peaqos stream distribute \
  --chunk-dir ./publish-output \
  --owner-private-key-file ./owner-x25519.key \
  --confirmation-url https://api.example.com/orders/ord-001/status \
  --order-id ord-001 \
  --delivery s3 \
  --s3 s3://my-bucket/distributes/ \
  --presign-expiry 86400

# JSON output to stdout
peaqos stream distribute \
  --chunk-dir ./publish-output \
  --owner-private-key-file ./owner-x25519.key \
  --confirmation-url https://api.example.com/orders/ord-001/status \
  --order-id ord-001 \
  --delivery s3 \
  --s3 s3://my-bucket/distributes/ \
  --json
```

Progress on `stderr`, summary on `stdout`:

```
Waiting for payment confirmation (polling every 30s)...
Payment confirmed for buyer did:peaq:0xBuyer00000000000000000000000000000001 (tx: 0xabc...)

Distributing 4 chunks to s3://my-bucket/distributes/

  Buyer ID:      did:peaq:0xBuyer00000000000000000000000000000001
  Access Files:  1
  Download URL:  https://my-bucket.s3.amazonaws.com/distributes/did:peaq:0xBuyer.../access-1.json?X-Amz-Signature=...
  Expires:       3600s
```

JSON output:

```json
{
  "order_id": "ord-001",
  "buyer_id": "did:peaq:0xBuyer00000000000000000000000000000001",
  "tx_hash": "0xabc...",
  "chunks_distributed": 4,
  "access_files_count": 1,
  "delivery": {
    "channel": "s3",
    "download_url": "https://my-bucket.s3.amazonaws.com/distributes/...?X-Amz-Signature=...",
    "delivered_at": "2026-06-25T12:00:00Z",
    "presign_expiry": 3600
  }
}
```

#### Common errors

| Condition | Exit code | Message |
| --------- | --------- | ------- |
| Payment confirmation timed out | `2` | `Payment confirmation timed out after {N}s for order {order_id}` |
| S3 upload failed | `2` | `S3 upload failed: {reason}` |
| `--delivery s3` without `--s3` | `1` | `--s3 is required when --delivery is s3` |
| `--poll-interval` not positive | `1` | `--poll-interval must be a positive integer.` |
| `--timeout` not positive | `1` | `--timeout must be a positive integer.` |
| Non-confirmed payment status from SDK | `1` | `payment.status — ... (constraint: confirmed)` |
| No `chunk-*.json` files in `--chunk-dir` | `1` | `No chunk files found in {path}` |
| Missing or unreadable owner key file | `1` | `Could not read key file: {path} (...)` |
| `boto3` not installed | `3` | `boto3 is required for S3 delivery but is not installed — install with: pip install boto3` |

## Errors

The CLI maps SDK and network exceptions to stable exit codes:

| Exit code | Meaning                                                      |
| --------- | ------------------------------------------------------------ |
| `0`       | Success                                                      |
| `1`       | User / validation error (bad input, cap, rate limit)         |
| `2`       | Network, RPC, or on-chain error (connection, HTTP, revert)   |
| `3`       | Configuration error (missing env vars, invalid private key)  |

Subcommands funnel exceptions through `peaq_os_cli.errors.handle_sdk_error`,
which raises `click.ClickException` with the mapped exit code and a
user-friendly message. Known on-chain revert reasons and Faucet API error
codes are translated by `map_revert_reason` and `map_faucet_error`.

## Output formatting

Subcommands render results through `peaq_os_cli.formatting` to keep human
output consistent across the CLI:

* `truncate_address` — shortens a hex address to `0x{first4}...{last4}`.
* `format_timestamp` — renders a Unix timestamp as ISO 8601 UTC, or `—` for
  `None`.
* `format_key_value` — aligns `key: value` pairs so the colons line up.
* `format_table` — left-aligned columnar table with a header separator.
* `print_json` — writes `json.dumps(data, indent=2)` to stdout for
  pipe-friendly output.
* `print_step` — writes `[{step}/{total}] {label}` progress lines to
  stderr, suppressed when the active Click context is quiet.

## Utilities

Input parsing and validation helpers in `peaq_os_cli.utils`:

* `parse_timestamp` — accepts pure-digit Unix seconds or ISO 8601 strings
  with an explicit UTC offset (`...Z` or `...+HH:MM`). Raises
  `click.BadParameter` on unrecognised input.
* `validate_did_format` — requires `did:peaq:0x` followed by 40 hex
  characters.
* `validate_address_format` — requires a `0x`-prefixed 40-hex-character
  address.
* `read_key_file` — reads, strips, and validates a `0x`-prefixed 64-hex
  private key file. Raises `click.ClickException` with exit code `1` on
  missing files or invalid content.
