Metadata-Version: 2.4
Name: cowboy-sdk
Version: 0.2.1
Summary: Python SDK for Cowboy
Author-email: Cowboy <nathan@cowboy.inc>
License-Expression: MIT
Project-URL: Repository, https://github.com/cowboyinc/python-sdk
Project-URL: Issues, https://github.com/cowboyinc/python-sdk/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.0
Requires-Dist: eth-account<0.20,>=0.10
Requires-Dist: cbor2<6,>=5.4
Requires-Dist: blake3<2,>=0.3
Requires-Dist: cryptography<49,>=42
Requires-Dist: idna<4,>=3.4
Requires-Dist: cowboy-protocol-py==0.13.0
Provides-Extra: ras
Requires-Dist: cryptography<49,>=42; extra == "ras"
Provides-Extra: watchtower
Requires-Dist: cryptography<49,>=42; extra == "watchtower"
Requires-Dist: PyNaCl<2,>=1.5; extra == "watchtower"
Provides-Extra: dev
Requires-Dist: PyNaCl<2,>=1.5; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-asyncio; extra == "dev"
Requires-Dist: python-dotenv; extra == "dev"
Requires-Dist: responses; extra == "dev"
Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "dev"
Requires-Dist: ruff==0.15.8; extra == "dev"
Requires-Dist: mypy==2.3.1; extra == "dev"
Requires-Dist: pygments>=2.20.0; extra == "dev"
Requires-Dist: unasync<1,>=0.6; extra == "dev"
Requires-Dist: cryptography<49,>=42; extra == "dev"
Requires-Dist: PyYAML<7,>=6; extra == "dev"
Dynamic: license-file

# cowboy-sdk

Client SDK for the [Cowboy](https://cowboy.xyz) decentralized compute network:
query the chain, submit transactions, and call deployed actors.

Write actors with the separate [`cowboy-actor-sdk`](https://pypi.org/project/cowboy-actor-sdk/)
package (`import cowboy_sdk`); this client uses `import cowboy`.

See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for a contributor-oriented overview of the codebase internals.

## Requirements

- Python 3.10+

## Installation

```bash
pip install 'cowboy-sdk>=0.2.1'
```

This README describes the **0.2.1 client API**: typed actor calls and Safer
actors support. Actor-authoring helpers have moved out of this client; use
`cowboy-actor-sdk` to write actors.

0.2.0 was the first client release on PyPI. The same distribution name previously
carried the actor SDK, so keep the version bound when installing this client.

### Writing actors

Install the authoring SDK separately:

```bash
pip install 'cowboy-actor-sdk>=0.2.0'
```

Actors inherit from `Actor` and expose handlers with permission decorators:

```python
from cowboy_sdk import Actor, public

class Counter(Actor):
    @public
    def increment(self, amount: int) -> int:
        count = self.storage.get("count", 0) + amount
        self.storage["count"] = count
        return count
```

Build and deploy actor projects with the Cowboy CLI. See the
[actor SDK quick start](https://github.com/cowboyinc/core/blob/devnet/pvm/Lib/cowboy_sdk_readme.md)
for authoring and plain `async def` runner calls. The client then calls the
compiled actor through its `interface.json`, as shown below. The old
`cowboy.Actor` and `to_source()` authoring helpers are no longer part of this
client.

### Distributions and versions

| Distribution | Import | What it is |
| --- | --- | --- |
| `cowboy-sdk` 0.2.0 and later | `cowboy` | This client SDK, published from `cowboyinc/python-sdk`. |
| `cowboy-sdk` 0.1.0, 0.1.1 | `cowboy_sdk` | **Historical actor SDK releases** (March 2026). They are not this client and are never re-published. |
| `cowboy-actor-sdk` | `cowboy_sdk` | The actor SDK for writing on-chain actors, now published under its own name from `cowboyinc/core`. |

The two current distributions install different top-level packages, so a
project can depend on both: an actor project depends on `cowboy-actor-sdk` and,
if it also drives the chain from Python, on `cowboy-sdk>=0.2.1`. An actor project
that still requires `cowboy-sdk` for its actor code (for example
`cowboy-sdk>=0.1.2`, which older CLI scaffolds wrote; current ones write
`cowboy-actor-sdk>=0.2.0`) must switch that requirement to `cowboy-actor-sdk`: from 0.2.0 the `cowboy-sdk` name resolves to
this client. Its `import cowboy_sdk` lines stay as they are.

The protocol codec comes in through `cowboy-protocol-py`, pinned to one release;
`protocol-pin.json` records which commit and WASM that release is. See
[docs/RELEASING.md](docs/RELEASING.md).

### Migrating from `cowboy-sdk` 0.1.x

`cowboy-sdk` 0.1.x was the actor SDK, which is now distributed as
`cowboy-actor-sdk`. Actor code continues to use `import cowboy_sdk`. Starting
with 0.2.0, `cowboy-sdk` is the client SDK and uses `import cowboy`. See the
[migration guide](https://docs.cowboy.inc/developers/migrating-from-cowboy-sdk-0-1)
for migration and repair steps.

### From source

With dev dependencies:

```bash
git clone https://github.com/cowboyinc/python-sdk.git
cd python-sdk
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
```

### `set_secret` / CBSS

`ChainClient.set_secret` and `encrypt_secret_for_account` need the native
`cowboy-crypto` extension (the BLS12-381 IBE wrap). The core SDK stays
pure-Python; methods that need the extension raise a clear `ImportError` if it is
missing.

**There is no `[crypto]` extra yet.** `cowboy-crypto` is not published to any
package index, so this client does not declare it. The extra returns once
`cowboy-crypto` is published from `cowboyinc/core`. Until then the supported
installation is the native wheel, installed directly, then the SDK:

```bash
# 1. Get the cowboy-crypto wheel for your platform — from a cowboyinc/core
#    `core-extras` GitHub Actions run (Artifacts → crypto-wheels-*), or build
#    it locally:
#      maturin build --release -m path/to/core/protocol/bindings/cowboy-crypto/Cargo.toml
pip install ./cowboy_crypto-*.whl

# 2. Install the SDK (the manually-installed extension satisfies the import)
pip install 'cowboy-sdk>=0.2.1'
```

**Which wheel is canonical.** The wheel must be built from the **cowboy-protocol**
tree (`protocol/bindings/cowboy-crypto` in cowboyinc/core, revision `45eefb95` or
later) — it owns the canonical CBSS crypto (AAD layout, IBE identity, wrap-key
HKDF), so any wheel built from it matches what the chain enforces. The revision CI builds and
verifies is pinned as `COWBOY_PROTOCOL_CRYPTO_REV` in
`.github/workflows/ci.yml` (COW-2846; `MATURIN_VERSION` beside it is the
second bump point). The enforcement is the byte-parity vectors in
`tests/unit/test_set_secret.py`, which catch a wrong wheel. They `skip` when
no wheel is installed, except in CI's `native-crypto` job, which builds the
wheel from the pinned rev and runs them with `COWBOY_REQUIRE_NATIVE=1`
(missing wheel ⇒ fail, not skip; `0`/unset ⇒ skip; any other non-empty value
gates on, fail-loud by design). Still run them locally against the exact
wheel you intend to deploy.

### CBSS reshare events (schema v2)

The node-authored `cbss.reshare.requested` event is compact JSON, not actor
CBOR. Decode it with the strict, version-pinned helper:

```python
from cowboy import CBSS_RESHARE_REQUESTED_TOPIC, decode_cbss_reshare_requested_event

for event in receipt.events:
    if event.topic == CBSS_RESHARE_REQUESTED_TOPIC:
        requested = decode_cbss_reshare_requested_event(event.data)
        for member in requested.new_committee_metadata:
            connect_to = member.network_addr
```

Schema v2 carries complete connection metadata only for the five new committee
members. `old_committee_proxy_ids` and `old_signer_proxies` are proxy-ID
references and are the event-authoritative membership. Resolve their connection
metadata from the current `/cbss/proxies` registry because the node exposes no
exact-height registry read and registry snapshots are only every 100,000 blocks.
A missing ID must produce an explicit per-member resolution error rather than
being silently omitted; current registry membership must never replace the IDs
carried by the event.

The strict decoder rejects every schema version other than `2`, non-canonical
binary fields, and data over 512 KiB before JSON parsing. The largest legal
corpus is 130,974 data bytes (131,008 bytes as its `SystemBytes` page). The
durable FIFO is bounded to eight pages, 256 events, and 1 MiB. The CBSS actor log
is separately bounded and may trim old entries, so consumers should checkpoint
event height/order and must not assume indefinite log retention.

## Configuration

Copy `.env.example` to `.env` and fill in your values:

```bash
cp .env.example .env
```

| Variable | Description |
|---|---|
| `COWBOY_RPC_URL` | Node RPC URL (e.g. `http://localhost:4000`) |
| `COWBOY_KEY_FILE` | Path to PEM private key file |
| `COWBOY_BASE_URL` | Validator URL (alias for `COWBOY_RPC_URL`) |

---

## Usage

### Client

```python
from cowboy import CowboyClient

# Read-only
client = CowboyClient("http://localhost:4000")

# With signing key (required for write operations)
client = CowboyClient(
    "http://localhost:4000", private_key=open("key.pem").read(),
    expected_chain_id=42, expected_network="local",  # use your configured values
)

# Context manager — closes the HTTP connection on exit
with CowboyClient(
    "http://localhost:4000", private_key=key, expected_chain_id=42, expected_network="local"
) as client:
    height = client.get_height()
```

Signing on a custom endpoint requires both the configured `expected_chain_id`
and `expected_network`. Discovery checks those values and obtains the genesis
instance from the endpoint; applications must never compile in an instance ID.
Transaction and signed-object helpers take the validated `ChainIdentity`.
A client refuses an observed identity change; create a new client after genesis.

#### Network presets

```python
from cowboy import CowboyClient, Network

client = CowboyClient(network=Network.MESA, private_key=key)
client = CowboyClient(network=Network.LOCAL)   # http://localhost:4000

# Summit (mainnet) requires an explicit rpc_url — bare Network.SUMMIT is rejected
client = CowboyClient(network=Network.SUMMIT, rpc_url="https://rpc.summit.example.com")
```

### Async client

```python
from cowboy import AsyncCowboyClient

async with AsyncCowboyClient(
    "http://localhost:4000", private_key=key, expected_chain_id=42, expected_network="local"
) as client:
    height = await client.get_height()
    account = await client.get_account("0xABCD...")
```

All methods on `CowboyClient` have async equivalents on `AsyncCowboyClient` — just `await` them.

---

### Chain queries

```python
# Block and chain state
height = client.get_height()
block  = client.get_block("latest")       # by "latest", block hash, or height int
fee    = client.get_basefee()             # BaseFee: cycle/cell fee oracle values
ok     = client.health()                  # True if node reports healthy

# Closed v3 discovery: chain id, genesis instance, network, activation digest,
# transaction version, and supported signature modes.
info = client.get_chain_info()
identity = info.identity()               # pass this to transaction/object signing
parameters = client.get_chain_parameters()  # storage clock, activation, deployers

# Accounts
account = client.get_account("0xABCD...")  # raises AccountNotFound if absent

# Transactions
tx      = client.get_transaction("0xhash...")
receipt = client.get_transaction_receipt("0xhash...")  # raises TransactionFailed on failure
pending = client.get_mempool_transaction("0xhash...")

# Actors
info    = client.get_actor("0xABCD...")        # raises ActorNotFound if absent
code    = client.get_actor_code("0xABCD...")
logs    = client.get_actor_logs("0xABCD...")   # list[ActorEvent]
value   = client.get_actor_storage("0xABCD...", key="my_key")   # bytes | None
storage = client.get_actor_storage_all("0xABCD...")             # dict[str | bytes, bytes]

# Upgrade preflight: committed code hash + whether account libraries are pinned.
# Context only — it neither authorizes nor guards a later upgrade.
ctx     = client.get_actor_upgrade_context("0xABCD...")         # ActorUpgradeContext
```

---

### Standing workload mount policies

CIP-10 standing consent uses the canonical CN-19 workload policy exports. The
caller supplies one trusted `ChainIdentity` and the current volume owner proven
at the same finalized root as the workload, volume, pool and owner account-auth
claims. Read the
planned policy before signing it:

```python
import json
from cowboy import (
    WorkloadMountPolicyV1,
    workload_mount_policy_plan,
    workload_mount_policy_instruction,
)

# record_json is the canonical workload record as UTF-8 bytes.
# owner_auth is authenticated at that same root. For trusted-RPC workflows,
# client.get_account_auth(current_owner) reads the current endpoint form.
owner_auth_json = json.dumps(owner_auth)
policy_revision = "0" if owner_auth["kind"] == "AddressDerived" else str(owner_auth["policy_revision"])
# Epoch/revision arguments are canonical decimal u64 strings.
plan_json = workload_mount_policy_plan(
    record_json, volume_id, current_owner, "99", "4", policy_revision, trusted_identity
)
plan = json.loads(plan_json)
policy = WorkloadMountPolicyV1(json.dumps(plan["policy"]))
# After inspecting/approving the policy:
signed = policy.sign(
    owner_private_key, trusted_identity,
    current_owner=current_owner, owner_auth_json=owner_auth_json,
)
publish_json = workload_mount_policy_instruction(
    record_json, volume_id, current_owner, "99", "4",
    json.dumps(signed.signature), owner_auth_json, trusted_identity,
)
```

`workload_mount_policy_plan` and `workload_mount_policy_instruction` return the
codec's exact JSON **text**, without re-serialization. Parse `publish_json` when
passing the instruction to the transaction signer. Object preimage/hash exports
return `bytes`; `workload_mount_policy_verify` returns `{"address": ...}`. The
policy classes require the independently proven current owner and current
owner account-auth policy for signing and verification. The policy key may be
a rotated key; the account address stays the owner. Publication and release still require the node's current revision,
expiry, ownership, pool and attempt checks. Revocation uses only the outer v3
transaction signature.

The former credential-offer/owner-certificate flow and the three workload
delegation classes are removed. Ordinary CBFS delegations retain only
`MOUNT_CAPABLE_V1` and `NON_MOUNT_SERVICE_V1`.

### Native token transfers

```python
tx_hash = client.transfer(to="0xABCD...", amount=1_000_000)
```

SDK-built writes use estimate-then-sign by default: the client signs a
provisional transaction, sends that exact transaction to `POST /estimate_gas`,
re-signs the same nonce with the node's cycle/cell/access suggestions, and only
then submits. A dry run that reports `accesses_exceed_admission_ceiling` raises
`AccessLimitExceeded` before `/submit`; the SDK never clamps the estimate.
All three fee suggestions come from `GET /basefee`.

`estimate(signed_tx)` exposes the same dry run as a first-class `GasEstimate`,
including resource usage, suggested limits, status/success, per-meter fee
suggestions, and worst-case cost properties:

```python
estimate = client.estimate(signed_tx)
print(estimate.accesses_used, estimate.access_limit_suggested)
print(estimate.suggested_max_fee_per_access, estimate.total_max_cost)
```

Every typed write helper accepts `options`; explicit values override the
matching suggestions. Supplying all three limits skips `/estimate_gas`, and
supplying all three fees skips `/basefee`. The node already adds its standard
headroom; state-dependent transactions can request more without silent
clamping. Before both the provisional and final signature, the SDK fetches the
signer's current balance and rejects when the exact three-meter declared
maximum spend exceeds it. Set `max_total_cost` for a stricter caller-selected
bound:

```python
from cowboy import TransactionOptions

tx_hash = client.transfer(
    to="0xABCD...",
    amount=1_000_000,
    options=TransactionOptions(
        additional_access_headroom=8,
        max_total_cost=50_000_000,
    ),
)

# Deliberate fully explicit override: neither estimator nor fee oracle is used.
tx_hash = client.transfer(
    to="0xABCD...",
    amount=1_000_000,
    options=TransactionOptions(
        cycles_limit=200_000,
        cells_limit=20_000,
        access_limit=13,
        max_fee_per_cycle=10,
        max_fee_per_cell=10,
        max_fee_per_access=10,
    ),
)
```

`submit_raw(signed_tx)` remains an explicit low-level bypass because an already
signed transaction cannot have its limits replaced safely. Use
`submit_raw_instruction(..., options=...)` when the SDK should own
the estimate and final signature.

---

### Actors

#### Deploy

```python
from cowboy import CowboyClient

# Build the Counter project first: cowboy build counter
with open(".cowboy/build/counter/actor.py", "rb") as f:
    code = f.read()

result = client.deploy_actor(
    code=code,
    salt=b"my-salt",          # optional — affects the deterministic address
)

print(result.actor_address)    # deterministic on-chain address
print(result.deploy_tx_hash)
print(result.init_tx_hash)     # None if no init_handler
```

`deploy_actor` defaults to `owner_draw=OwnerDraw.default()` (import `OwnerDraw`
from `cowboy`). This creates a revocable `FallbackToOwnerBalance` entitlement
with **NO total cap** for the new actor. Set `owner_draw=OwnerDraw.off()` to
disable that automatic entitlement, or `OwnerDraw.capped(amount)` to limit its
total draw in nano-CBY. Native route installation remains a follow-up for this
helper; it does not expose `routes` yet.

#### Execute

```python
from cowboy.serialization import encode

tx_hash = client.execute_actor(
    actor="0xABCD...",
    handler="increment",
    payload=encode({"amount": 1}),
)
```

#### Call through the interface

`cowboy build` writes an `interface.json` next to each actor: its methods, who
may call them, and JSON Schemas for their input and output. A handle checks every
call against it before anything is sent, encodes it the way the node does, and
checks and decodes the result.

```python
from cowboy import ActorInterface, CowboyClient, PreparedCall, TransactionOptions

store = client.actor("0xABCD...", ActorInterface.from_file("store.interface.json"))

store.read.price("hat")              # /actor/read: no transaction, no fee
store.read.price(sku="hat")          # the same; the keyword is the actor's parameter name

capped = store.with_options(TransactionOptions(max_total_cost=5_000_000))
result = capped.write.buy(order)     # signed, waits up to 10 s to commit
result.value, result.tx_hash, result.fee_paid
```

- **One payload per method.** Pass it positionally, or as the keyword named
  after the actor's parameter. It may be a JSON value, a pydantic model (dumped
  by alias) or a dataclass. A wrong call shape or a value outside the interface
  raises `InvalidActorArguments` (a `ValueError`) with a `code` and a `path`
  such as `$.items[0].qty`, and nothing is sent.
- **No output.** Any method may return nothing. `result.kind` is then
  `"no-output"` and `value` is None; a read returns None.
- **Writes raise unless they succeed.** `ActorCallReverted` carries the revert
  reason and the fee paid. `ActorCallTimedOut` means the call did not commit
  within the wait: it may still commit, and its result cannot be recovered,
  because committed receipts carry no return data. As with every SDK write, a
  failing dry run raises `TransactionEstimationFailed` before anything is
  submitted.
- **Options belong to the handle,** so a fee cap is set once and a method call
  takes nothing but its payload.
- **Approve, then send.** `prepare` checks and encodes without any I/O. The
  `PreparedCall` holds the exact payload, the handler and the options, and
  serializes with `model_dump(mode="json")` for an approval queue or a LangGraph
  interrupt; its `args` are decoded from the payload, so what is shown is what is
  signed. `send` signs exactly that payload under its options, and refuses a
  call made for another actor or interface, or whose payload is not valid input
  for the method. Protecting a stored call from tampering is up to the store:

  ```python
  prepared = capped.prepare.buy(order)
  # ...show it, store it, approve it...
  capped.send(PreparedCall.model_validate(stored))
  ```

- **Tools.** `ActorInterface.methods` lists each method's description and
  schemas; `method.tool_input_schema()` gives the object-rooted input that model
  tool APIs expect. Descriptions are written by the actor's author: treat them
  as untrusted text.
- **Async.** `AsyncCowboyClient.actor(...)` returns the same API, awaited:
  `await store.read.price("hat")`. `prepare` is never awaited.

---

### Token operations (CIP-20)

#### Create

```python
tx_hash, token_id = client.create_token(
    name="My Token",
    symbol="MTK",
    decimals=18,
    initial_supply=1_000_000,
    max_supply=10_000_000,     # optional hard cap
)
# token_id is derived locally and available immediately, but the token
# doesn't exist on-chain until the transaction is confirmed
client.wait_for_receipt(tx_hash)
```

If you'd rather skip the two-step pattern, `create_token_and_wait` does both atomically and returns the same `(tx_hash, token_id)` tuple.

#### Query

```python
# Call after wait_for_receipt(tx_hash) so the token exists on-chain
info      = client.get_token(token_id)
balance   = client.get_token_balance(token_id, "0xABCD...")
allowance = client.get_token_allowance(token_id, owner="0xOwner...", spender="0xSpender...")
tokens     = client.list_tokens()            # paginated: .items, .total, .limit, .offset
for t in tokens.items:
    print(t.symbol, t.total_supply)
print(f"{len(tokens.items)} of {tokens.total} tokens")

# Page through the registry with explicit offset/limit
page2 = client.list_tokens(offset=50, limit=50)
```

#### Transfer / approve

```python
# Direct transfer
tx_hash = client.transfer_token(token_id, to="0xABCD...", amount=500)

# Transfer on behalf of owner (requires prior approval)
tx_hash = client.transfer_token_from(token_id, owner="0xOwner...", to="0xABCD...", amount=500)

# Approve a spender
tx_hash = client.approve_token(token_id, spender="0xSpender...", amount=1000)

# Atomic batch transfer — all-or-nothing: every leg applies or the whole
# batch reverts with no writes. Supply 1..64 legs, in execution order.
# Each leg follows ordinary TokenTransfer rules, including transfer hooks.
tx_hash = client.batch_transfer_tokens([
    (token_id_a, "0xAlice...", 100),
    (token_id_b, "0xBob...",   200),
])
```

#### Mint / burn

```python
tx_hash = client.mint_token(token_id, to="0xABCD...", amount=1000)
tx_hash = client.burn_token(token_id, amount=500)
```

`burn_token_from` (CIP-36 third-party burn) is **encode/submission support for a
system-only operation** — it is not callable from an external key today. The node
authorizes it solely against a token's immutable `burn_from_authority`, and
`token_create` always stores `None`, so no SDK-created token can ever grant it. The
only production token with an authority is genesis CUSD, whose authority is the
BankActor system address — an address with no keypair. Any externally signed call
therefore fails `Unauthorized` on devnet; on node main, which pins a codec predating
the opcode, the submission fails to decode instead.

#### Admin operations

```python
tx_hash = client.freeze_token(token_id, account="0xABCD...")
tx_hash = client.unfreeze_token(token_id, account="0xABCD...")
tx_hash = client.set_token_hook(token_id, hook_address="0xHook...")  # pass None to clear
tx_hash = client.transfer_token_ownership(token_id, new_owner="0xNewOwner...")
```

---

### Jobs

#### Submit

```python
from cowboy import CowboyClient, JobSpec

spec = (
    JobSpec.llm(
        model="my-model",
        prompt="What is 2+2?",
        max_tokens=256,
    )
    .with_bounds(max_wall_time=60, max_retries=1)
    .with_verification(mode="majorityvote", runners=3, threshold=2)
    .with_callback(actor="0xMyActor...", handler="on_result")
    .with_budget(max_price=1_000_000, tip=10_000, timeout_blocks=50)
)

tx_hash = client.submit_job(spec)
```

JobSpec v7 uses core's default callback budget of 1,000,000 cycles and 150,000
cells. To set a different budget, pass
`resume_budget=ResumeBudget(cycles=6_000_000, cells=5_000_000)` to
`with_callback` (`ResumeBudget` is exported from `cowboy`). Core validates the
budget when the job is built. Container jobs now accept registered resource
class names through `resource_tier` and CBSS key names through `secret_env`.
Class names contain 3–63 lowercase ASCII letters, digits or hyphens, with
alphanumeric ends and no consecutive hyphens. The base-image keys are
`"cby-runner-base"` and `"cby-runner-python"`.
Since v6, `"small"` and `"medium"` are not built-in tiers: they are literal resource
class names and work only if registered on the target chain. Omit
`resource_tier` to use core's default class (`"small-ephemeral"` at this pin).

RAS storage epochs also depend on the target chain. Use
`client.get_storage_epoch(height)` (or omit `height` for the current height)
when constructing authorization windows. It reads `/chain-info` for the chain
instance's epoch length and refuses missing or invalid values. The low-level
`storage_epoch_from_height(height, storage_epoch_blocks)` requires that length
explicitly; the old `STORAGE_EPOCH_BLOCKS` export has been removed.

Other job types:

```python
# HTTP fetch
spec = JobSpec.http_request(url="https://api.example.com/data", method="GET")

# HTTP call with a secret: secret() marks the one string a CBSS secret fills.
# The runner sends prefix + secret + suffix there and fills nothing else, so a
# "${KEY}" anywhere in the job is sent as written. Each secret's grant is added
# to the job's secrets automatically; account= defaults to the submitting account.
from cowboy import secret

spec = JobSpec.http_request(
    url="https://slack.com/api/chat.postMessage",
    method="POST",
    headers={"Authorization": secret("SLACK_BOT_TOKEN", prefix="Bearer ")},
    body={"channel": "C123", "text": "deploy finished"},
)

# Custom executor — `data` is JSON (dict / list / any JSON-serializable value), not raw bytes
spec = JobSpec.custom(job_type="my-executor", data={"seed": 42})

# Agent — open-ended LLM with tool-calling. `query` becomes the agent mode's
# single InteractiveQuery input, which is what the default Interactive profile
# takes; richer transient jobs pass profile=/inputs=/invocation=/secret_bindings=.
spec = (
    JobSpec.agent(
        model="kimi-k2",
        query="Explain the key design decisions in this codebase.",
        max_iterations=12,
        timeout_seconds=180,
    )
    .with_budget(max_price=2_000_000, timeout_blocks=100)
)
tx_hash = client.submit_job(spec)
```

The `JobSpec` builder is the recommended high-level path: it runs the shared
`cowboy-protocol` codec (compiled to WASM) **client-side** to produce the
canonical `JobSpec` bytes the node accepts — applying defaults and hashing
model/executor names into ids — so the bytes you submit are byte-identical to
what every node and runner independently derives.

#### Advanced / low-level submission (⚠️ unstable)

For tests, protocol debugging, and advanced users, you can bypass intent
normalization and submit raw bytes or instructions directly. These APIs are
**unstable** and may change without notice — prefer the `JobSpec` builder above.

```python
# Submit raw *canonical* JobSpec bytes verbatim (no client-side normalization;
# the node still applies protocol/security validation). Use blake3_id() to
# derive the canonical model_id/executor_hash a canonical spec expects.
tx_hash = client.submit_canonical_job_spec(raw_job_spec_bytes)

# Submit any pre-built low-level instruction dict verbatim.
tx_hash = client.submit_raw_instruction({"System": {"JobSubmit": {"job_spec": [...]}}})
```

#### Query / cancel

```python
job     = client.get_job(job_id)
status  = client.get_job_status(job_id)     # "pending" | "executing" | "completed" | "failed"
results = client.get_job_results(job_id)
best    = client.get_job_verified_result(job_id)

tx_hash = client.cancel_job(job_id)
```

---

### Runners

```python
runner  = client.get_runner("0xRunner...")
active  = client.get_active_runners()       # list[RunnerInfo]

# Move where the gateway proxies this runner's Target::Runner routes, without a
# deregister/re-register cycle. The node enforces sender == runner, and validates
# the URL: http is loopback-only, and private/link-local hosts are refused.
client.update_runner_endpoint(my_runner_address, "https://runner-01.example.net:8080")
client.update_runner_endpoint(my_runner_address, None)   # clear the advertisement
```

> The pinned `cowboy-protocol` binding encodes `RunnerUpdateEndpoint` (opcode 219).
> The method still probes the binding before taking a nonce and raises
> `ProtocolBindingTooOld` against an older one. See
> [docs/AUDIT_LOG.md](docs/AUDIT_LOG.md).

---

### Storage volumes (CIP-9 RAS)

RAS requests are authenticated twice: a wallet-signed `DelegationCert` binding a
`cbfs` Ed25519 key, and a per-request envelope that key signs.

```python
from cowboy import (
    EncryptionPublicKey, SigningPublicKey, MountGrant, MountPrincipal,
    generate_cbfs_keypair, mint_delegation_cert,
)

seed, cbfs_pub = generate_cbfs_keypair()
identity = client.get_chain_info().identity()
cert = mint_delegation_cert(private_key, SigningPublicKey.ed25519(cbfs_pub), identity, expires_at_ms)

# Owner: grant another wallet direct access. grantee_signing_key is the grantee's
# registered delegated key; a private volume also needs its X25519 key and the
# volume DEK sealed to it (GrantDekPackage, AAD from grant_dek_aad_bytes).
grant = MountGrant(
    MountPrincipal.account(grantee), "ReadOnly",
    grantee_signing_key=SigningPublicKey.ed25519(grantee_cbfs_pub),
    grantee_encryption_key=EncryptionPublicKey.x25519(grantee_x25519_pub),
    grantee_wrapped_dek=sealed_package,
)
grant.check_for_volume(visibility="PRIVATE", dek_version=dek_version)  # from the volume commitment
client.update_mount_allowlist(volume_id, cbfs_private_key=seed, delegation_cert=cert, add_grants=[grant])

# Grantee: open the owner's volume with its own delegated key. Any unusable grant
# is a plain 404; an unregistered or revoked delegation is a 401.
opened = grantee_client.open_volume("dataset", cbfs_private_key=grantee_seed,
                                    delegation_cert=grantee_cert, owner=owner_address)
opened.grantee_wrapped_dek   # this grantee's sealed DEK package (private volumes)
```

`EncryptionPublicKey` uses algorithm 1 and a contributory 32-byte X25519 key.
Its JSON form is a single `"0x0120…"` string containing the commonware codec bytes.
`GrantDekPackage` validates the tagged 124-byte package (version 1, algorithm 1,
DEK version, then u16-BE lengths for the recipient key, encapsulated key and
ciphertext). The HPKE info stays `cbfs/grant-volume-dek/v1`; `grant_dek_aad_bytes`
binds the version and algorithm tags plus the length-prefixed recipient key.
`OwnerWrappedDek` encodes the 62-byte owner envelope; transfers and volume reads
validate present envelopes. These helpers reject the old untagged formats.

The SDK does not perform the HPKE sealing, and does not build the
`RegisterDelegation` instruction `open_volume` depends on — see
[docs/UPSTREAM_GAPS.md](docs/UPSTREAM_GAPS.md).

---

### Faucet

```python
# Testnet only — funds the given address
result = await client.faucet("0xABCD...")
```

---

### Key management

```python
from cowboy import Wallet, CowboyClient

# Generate a new key and persist it
wallet = Wallet.create()
print(wallet.address)
wallet.export_keyfile("key.pem")           # written with mode 0600; raises if file exists
wallet.export_keyfile("key.pem", overwrite=True)  # replace an existing key file

# CowboyClient takes key file contents as a string: COWBOY PEM or raw hex
with open("key.pem") as f:
    key = f.read()

client = CowboyClient(rpc_url, private_key=key, expected_chain_id=chain_id, expected_network=network)

# Or pass a raw hex private key string directly
client = CowboyClient(rpc_url, private_key="0xdeadbeef...", expected_chain_id=chain_id, expected_network=network)

# Wallet is for direct payload signing, not required for CowboyClient
with Wallet.from_keyfile("key.pem") as wallet:
    sig = wallet.sign(some_payload)
```

---

### Error handling

```python
from cowboy import (
    CowboyError,            # base — catch all SDK errors
    APIError,               # HTTP error from the node
    RpcError,               # non-retryable transport error
    RateLimitError,         # 429 — retries exhausted
    AccountNotFound,
    ActorNotFound,
    TokenNotFound,
    JobNotFound,
    RunnerNotFound,
    NonceTooLow,            # nonce desync — surfaced, NOT auto-retried (resubmit could double-spend)
    NonceTooHigh,           # nonce desync — client invalidates cache and auto-retries once
    TransactionFailed,      # receipt.status != "Success"
    TransactionTimeout,     # receipt not mined within timeout
    InsufficientFunds,
    PermissionDeniedError,  # caller not authorised for this handler (E1230)
    JobFailureDeliveryFull, # E1624: no failure-callback slot for this job; retry later (.limit)
    BudgetExceeded,         # E1625: actor past its econ.budget this period (.cap/.spent/.amount, wei)
)

try:
    receipt = client.get_transaction_receipt(tx_hash)
except TransactionFailed as e:
    print(e.receipt.status)
    if e.error_guidance:
        print(e.error_guidance.why)
        print(e.error_guidance.suggestion)
```

`TransactionFailed` subclasses such as `JobFailureDeliveryFull` and
`BudgetExceeded` type the receipt's execution-error code. Three failure events
have decoders: `decode_deferred_tx_over_budget_event` for the payer's
`deferred_tx.over_budget` receipt event (a deferred transaction refused past
its budget), and `decode_wait_failed_event` / `decode_every_failed_event` for
the actor-log events `cowboy.wait.failed` (a wait ended without its answer)
and `cowboy.every.failed` (an `@every` tick raised).

---

## Development

```bash
python -m pip install -e ".[dev]"

# Lint and format
ruff check --fix .
ruff format .

# Type check
mypy cowboy/

# Regenerate the sync client after editing the async client (see below)
python scripts/gen_sync_client.py

# Run unit tests
pytest tests/unit/

# Build the sdist, its wheel and a direct wheel from the tracked files, and check
# that each ships only cowboy/ (see docs/RELEASING.md)
python -m pip install -r .github/requirements-publish.txt
python scripts/check_dist.py --build --out /tmp/cowboy-sdk-build

# Install them into fresh environments outside the checkout and run the unit
# suite against the installed package
python scripts/check_install.py --tests /tmp/cowboy-sdk-build/dist/*

# The protocol dependency is the pinned release (needs a token with read access
# to cowboyinc/core to check devnet); --installed checks the binding in this environment
python scripts/check_protocol_pin_durable.py
python scripts/check_protocol_pin_durable.py --installed

# Run integration tests (requires a running node and .env)
pytest tests/integration/
```

### Sync client is generated

`cowboy/async_client.py` (`AsyncCowboyClient`) is the single source of truth. The
sync `cowboy/chain_client.py` (`CowboyClient`) is generated from it with
[unasync](https://github.com/python-trio/unasync) — `async`/`await` are stripped
and a few async-only identifiers are rewritten (`asyncio.sleep` → `time.sleep`,
`httpx.AsyncClient` → `httpx.Client`, `asyncio.Lock` → `threading.Lock`).

Edit the **async** client, then regenerate:

```bash
python scripts/gen_sync_client.py          # rewrite cowboy/chain_client.py
python scripts/gen_sync_client.py --check   # verify it is up to date (CI runs this)
```

Do not edit `cowboy/chain_client.py` by hand — it carries a generated-file banner
and CI fails if it has drifted from the async source.

### Git hooks

```bash
cp scripts/pre-push.sh .git/hooks/pre-push
chmod +x .git/hooks/pre-push
```

### CIP-7 Watchtower cutover

The disposable-devnet cutover removes `cowboy.stream`, the legacy
`CbssCip7*` response models, and the sync/async `get_cbss_cip7_seal_requests`
and `get_cbss_cip7_delivery` methods. Use the Watchtower clients and
`cowboy.watchtower_codec` for CIP-7. CIP-9 volume polling and its signed proxy
authentication remain available. Deploy the coordinated node and service
revisions; this change does not provide a legacy SKM migration path.

CONSENSUS Feeds are pull-only: an actor reads them with `cowboy_sdk`'s
`@on_stream` (from `cowboy-actor-sdk`), which installs a public `read_streams`
handler any caller may invoke.
