Skip to main content
Status: Draft
Type: Standards Track
Category: SDK
Created: 2025-10-20
Updated: 2026-11-04
Requires: CIP-1 (Actor Message Scheduler), CIP-2 (Off-Chain Compute), CIP-3 (Fee Model), CIP-5 (Timers), CIP-37 (actor ownership)
Cowboy Cloud and Cowboy Chain. This CIP specifies the Cowboy protocol. Cowboy Cloud runs on this protocol today. Cowboy Chain, a public network on the same protocol, is under consideration for a future release. Where the two differ, this CIP says so.

1. Abstract

Background

Actor authors use Python most often. A stable, normative SDK contract lets implementations interoperate and actors run across node versions.

Goal

This CIP specifies cowboy_sdk, the Python SDK that on-chain actors import from the Cowboy PVM. It defines the actor model, calls, handler permissions, continuations, SDK helpers, types, result verification, errors, ownership runtime, and cowboy CLI.

Overview

This CIP is normative for cowboy_sdk only. §2 describes the standalone package (cowboy-sdk, imported as cowboy) for reference. Any Cowboy node that runs Python actors MUST expose the module layout and syscalls defined here. Any CLI that names itself cowboy SHOULD implement the subcommands in §16 with compatible flag semantics.
  • The runtime traps or replaces non-deterministic Python operations (wall-clock time, hardware FPU, unseeded randomness, filesystem, network, set(), pickle) with SDK equivalents.
  • The runtime meters every syscall in Cycles (compute) or Cells (state IO) per CIP-3.
  • Every handler declares with @pure or @deferred whether it may issue async side effects, and the runtime enforces the declaration.
  • Handlers are unreachable from external callers unless explicitly decorated with @public or @callable_by(...).
  • The compiler lowers an async handler that awaits a runner job to a finite-state machine at class-load time. Its locals carry across the wait, and every wait ends (§10.2).
  • The SDK implements caller limits, single-flight keys, schedules, pause and exit, escrow and secret slots.
  • The Host API enforces the deploy-time entitlement manifest for all external-effect syscalls.

2. SDK Layers

2.1 cowboy_sdk — In-PVM Actor SDK (this CIP)

Local projects install cowboy-actor-sdk, and deployed actors use the SDK embedded in the PVM. Both import cowboy_sdk.

2.2 cowboy — Standalone Developer SDK

The standalone package provides:
  • Actor authors can use @actor, @public, @callable_by, @pure, @deferred, @init_handler, OWNER, SELF and local runtime stubs for unit testing.
  • actor_instance.to_source() emits deployable Python source that imports from cowboy_sdk
  • CowboyClient and AsyncCowboyClient provide RPC queries and transactions.
  • client.deploy_actor(code, salt, init_handler, ...) deploys actors, and client.execute_actor(...) executes them.
  • Wallet, generate_private_key, and sign_payload handle wallets and signing.
  • JobSpec and client.submit_job() specify and submit jobs.
  • CBSS helpers manage secrets.
The cowboy local SDK mirrors enough of the cowboy_sdk actor authoring API to write and unit-test actors locally. It does not implement continuations, ActorRef, runner, the standard helpers, CowboyModel, SoftFloat, ordered_set, BlockHeight, or storage raw/guard helpers. Use cowboy-actor-sdk for local tests of those features, and a PVM sandbox for host integration tests.

2.3 Handler Signature Difference

to_source() generates module-level wrappers with the payload: bytes signature, and the SDK applies the declared handler codec behind them (§9.5).

2.4 Compatibility Matrix


3. Motivation

Later revisions will add CIP-9 volume mounts and CIP-7 / CIP-17 stream helpers (§18).

4. Definitions

  • Actor: A Python class whose public methods are invocable handlers. Identified by a 20-byte address.
  • Handler: A public method of an Actor. Accepts the payload the host delivers; returns bytes, or a value its declared codec (raw / cbor / json, §9.5) can encode, or raises.
  • Handler mode: A per-method property, either pure (default) or deferred. Pure handlers MUST NOT issue async side effects.
  • Permission: A per-method access control tag (@public, @callable_by, or absent). Absent means deny-by-default from external callers.
  • Syscall: A call from the PVM into the Host API to perform a privileged operation. The SDK wraps syscalls.
  • Caller: The address a handler reads as self.sender: the signer of a transaction, the calling or sending actor, or the actor itself for work its own code queued (§12.1).
  • Continuation: A compiled FSM representation of an async def handler that awaits a runner job or an authenticated offchain export. State survives block boundaries.
  • Wait: A continuation between its await and its end. A wait ends with an answer, a failure, its deadline, a pause or a cancel (§10.2).
  • Manifest: A JSON document declaring the entitlements a deployed actor requests. Attached to the deploy transaction.
  • PVM: The Python Virtual Machine executing actor bytecode under determinism constraints (CIP-3 §4).

5. SDK Module Layout

The canonical package is cowboy_sdk, shipped with the PVM. It targets Python ≥ 3.11. Every symbol in the required actor-facing API below MUST be importable from the cowboy_sdk package root. An implementation MUST NOT remove, rename, or change the semantics of any of these: The implementation also exports these optional helpers. An implementation MAY omit or rename these; actor authors SHOULD prefer the required API above: Actor code SHOULD NOT import the private submodules cowboy_sdk.codec, cowboy_sdk.pvm_sys, cowboy_sdk.pvm_time and cowboy_sdk.pvm_random. SDK extensions that understand the PVM boundary MAY import them. cowboy_sdk.continuation holds the compiler’s private runtime (_save_cont, _load_cont), which actor code does not call. The package root MUST NOT export the following names, each of which duplicates an operation above or has no use. runtime keeps the sender accessors private:

6. Actor Model

6.1 Declaration

An Actor is a Python class that inherits Actor. A library base such as Pausable (§7.6) is itself an Actor, so class Vault(Pausable) needs no second base. The examples use on-chain cowboy_sdk imports; §2.3 covers the standalone package.
Actor provides:
  1. self.address (read-only Address, the actor’s own 20-byte address, read on first use). cowboy_sdk only.
  2. self.sender (read-only Address, the caller of the current delivery, §12.1). It is a live property: each access reads the current execution context. cowboy_sdk only.
  3. self.storage (a dict-like proxy over actor private state, see §6.5).
  4. One dispatcher for its handlers: a @public or @callable_by method is a handler, and calling it runs the permission check (§7), the caller’s limit (§7.5), the payload codec (§9.5) and the handler mode (§8) in that order. An undecorated method is an ordinary method (§7.2).
  5. Lowering of every async handler that awaits a runner job to a continuation, with its __resume callback (§10). cowboy_sdk only.
The build writes a module-level entrypoint for every handler of an Actor subclass in the entry module, including inherited handlers (§7.6). A subclass MUST NOT redefine address, storage or sender (actor_reserved_name). The build rejects a class that names Actor ahead of a base that is already an Actor, such as class Vault(Actor, Pausable) (actor_base_order).

6.2 Address Derivation

The first two bytes of an actor address hold its address group. The group is unrelated to the erasure-coded storage shards of CIP-9 and CIP-14, although the wire field and CLI option are named shard:
  • deployer_address: 20 bytes, the sender of the deploy transaction.
  • salt: caller-supplied bytes (at most 32), hashed unconditionally with Keccak-256.
  • code_hash: Keccak-256 of the exact actor source bytes.
  • shard: optional unsigned 16-bit group. Absence inherits the deployer’s group; explicit 0 selects group zero.
  • Output: 20 bytes, with a 2-byte big-endian group and an 18-byte (144-bit) hash suffix.
derive_actor_address(deployer, salt, code_hash, shard=None) computes this in the actor SDK. The CLI helper cowboy actor address --shard <0..65535> predicts the same address without submitting a transaction. fork() uses CIP-27’s separate domain and fork-only counter, always inheriting the parent’s group. The two-byte group partitions addresses only. Validators execute transactions over one shared world state and use the same synchronous actor-call dispatcher for every group. A dispatcher MUST NOT reject a call solely because the caller and callee have different group prefixes; the ordinary permission, handler-mode, resource-budget and rollback rules still apply. A group prefix does not select a separate state machine or an asynchronous transport. The group prefix is reserved for sharded execution, which a later CIP will specify. Fixing it in the address keeps every actor address stable when that happens. Implementations MUST NOT remove the prefix as unused. Test vector: for creator 1234567890abcdef1234567890abcdef12345678, source bytes hello, and raw ASCII salt bytes shard-test (CLI --salt 0x73686172642d74657374), an omitted shard yields 12341347e78d4d017f2cfd2457b756b55a56024c; explicit zero yields 00001347e78d4d017f2cfd2457b756b55a56024c.

6.3 Deployment

Wire fields (DeployActor transaction): The cowboy deploy flags select the application initializer. Off-chain project deployments MUST also initialize their runtime configuration atomically, including when no application initializer is selected. Initializer selection and execution follow these rules:
  • A project deployment MUST select init when the compiled actor exports it, unless --init-handler selects another handler or --no-init is supplied. A project without an exported init, --init-handler or --init-payload MUST run no application initializer.
  • A raw --code deployment MUST run no application initializer unless --init-handler or --init-payload is supplied.
  • On either path, --init-payload without --init-handler MUST select init. Inline text is passed as UTF-8 bytes; @file supplies the file’s bytes. The payload MUST match the selected handler’s codec (§9.5).
  • --no-init MUST skip the application initializer and MUST conflict with --init-handler and --init-payload.
  • A selected application initializer MUST run atomically in the deploy transaction, with sender set to the deployer’s address. The node invokes a module-level entrypoint; the project build generates that entrypoint for a declared Actor handler (§6.1).
The entire DeployActor transaction reverts if init_handler raises. The deployment receipt carries the derived actor address. Deployment never invokes the Python constructor __init__, which a local actor instance may use without arguments.

6.4 Message Handler Dispatch

A message to an actor carries a method_name (UTF-8 string) and payload (raw bytes). Dispatch:
  1. The PVM loads the actor class and state.
  2. method_name is looked up; unknown methods raise AttributeError, which becomes ActorCallError.
  3. The handler runs under its declared permission (§7), handler mode (§8) and payload codec (§9.5).
  4. The handler’s codec encodes the return value. The result goes back to the caller (for call()) or is discarded (for send()).
The reserved handler handle_timer(msg) receives timer fires (CIP-5). Additional reserved handlers MAY be introduced by future CIPs.

6.5 Storage

Actor state is a private key-value store scoped to the actor’s address. Access is exclusively through self.storage:
Raw-bytes escape hatches (cowboy_sdk only):
Guard-based state snapshot for continuations (cowboy_sdk only):
Keys MUST be UTF-8 strings. Values of self.storage[key] MUST be CBOR-encodable per §11.5. CIP-3 meters storage reads and writes in Cells. An actor cannot read another actor’s storage; it calls a handler on that actor instead. The SDK reserves the key __INITIALIZED__, and every storage access method raises ValueError for it (§12.10).

7. Handler Permissions

Access control is deny-by-default: a method with no permission decorator is not a handler, and no dispatch by name reaches it. The host names init, on_fork, handle_timer and handle_message are the exception: undecorated, each is a handler that admits only the actor itself (§7.3).

7.1 Decorators

Both decorators accept decode="raw", decode="cbor", or decode="json", and default to CBOR. §9.5 defines the codecs and the raw defaults of host-invoked entrypoints.

7.2 Internal Helpers

A method without @public or @callable_by is an ordinary method. It has no permission check and no codec, runs in its caller’s mode (§8), and is reached only by a plain Python call such as self._helper(payload). A leading underscore is a naming convention only. Two build rules apply:
  • A marker that only a handler enforces (@pure, @deferred, @limit, @single_flight, @exit) on an ordinary method fails the build (unenforced_marker).
  • A module-level function in the entry module that forwards to an ordinary method fails the build (unchecked_entrypoint), because it would run the method for every caller. Declare the method @callable_by(SELF) when only the actor itself calls it.
Only the SDK’s own decorators may sit above @public or @callable_by, because a decorator there must keep the method a handler (decorator_above_permission).

7.3 @callable_by(SELF) Semantics

SELF resolves via caller == self.address. The host sets sender to the actor’s own address only when the actor’s own code queued the delivery: its timer fires, its own create_deferred_tx children, its runner callbacks (the callback actor is always the submitter), and its own self-addressed send() (§12.1). self.method() calls inside a handler keep the outer sender, so SELF passes there only when that sender is the actor itself, as in the actor’s own timer handler.

7.4 init Bootstrap Window

The executor admits init only in the actor’s creation call; ordinary dispatch to init is refused regardless of sender or decorator. init still needs @public or @callable_by(...), and the SDK raises PermissionDeniedError for an undecorated init. The SDK sets the __INITIALIZED__ flag after init returns without raising; the flag never grants permission to initialize. Ownership does not depend on init (§12.10). §6.3 defines initializer selection, payloads and atomic execution.

7.5 Caller Limits

A caller pays only for its own transaction. The actor’s balance pays for the jobs a handler starts, and @limit caps what one caller can start:
  • per_caller=N, every=D: each caller may call the handler at most N times per period D, in seconds of block time (§12.5).
  • pending=N: each caller may hold at most N open waits started through this handler. A wait counts against the caller whose call started it until the wait ends (§10.2).
  • The caller is self.sender (§12.1). Another actor, such as a second agent in the same room, is limited like any account.
  • A refused call raises LimitReached, which names the limit and when the next call is allowed. The handler body does not run.
The SDK enforces the limit and keeps its counters in the actor’s storage. Handlers that start jobs SHOULD carry @limit. §10.2 separately caps each caller’s pending waits.

7.6 Pause and Exit

Pausable gives the actor pause() and unpause() handlers callable by OWNER. While the actor is paused, the SDK:
  • refuses every call except @exit handlers, owner calls and @pure reads;
  • ends a wait that resumes with JobFailed(reason="paused"), so its cleanup runs and nothing acts on the answer (§10.2);
  • skips timer ticks, while @every schedules stay armed (§12.5).
The SDK checks the flag on every call, resume and timer fire. A hand-written flag would miss resumes, because a wait resumes past the checks above its await and runs as the actor itself, which passes every permission check (§7.3). Authors mark @exit the handlers users need to withdraw funds, such as an Escrow refund (§12.4). Pausable keeps its flag in its own storage namespace. The build writes entrypoints for inherited handlers (§6.1), including handlers inherited from a class in another module. A module-level function with the same name in the entry module takes the name over. Two bases that define the same handler, neither inheriting from the other, fail the build.

8. Handler Modes

Each handler declares one of two modes: A pure handler MUST NOT issue any operation that produces an async effect: send(), runtime.schedule_timer(), runtime.submit_job(), emitting callbacks. Synchronous call() and local computation are allowed. Any prohibited operation inside a pure handler raises PurityViolationError. A deferred handler MAY issue any SDK operation subject to entitlement gates. An ordinary method (§7.2) runs in its caller’s mode, so a synchronous handler that starts a job through a private continuation (self._run_request(...)) MUST be @deferred. Under the pure default, the runtime refuses the job’s message.
Pure handlers are safe targets for read-only RPCs (CIP-14 query path, external introspection tools), and the runtime runs them without a deferred effect queue. The Host API enforces the mode at runtime; no static check does.

8.1 Read-Only Execution Flag

The execution context carries a per-call Boolean read_only flag, independent of the handler mode. The validator sets it when a non-mutating entry point, such as the validator’s POST /actor/read RPC or another external query path, invokes a handler. Every implementation MUST honor the flag. When read_only is set:
  • Every state-mutating host syscall MUST return HostError::Forbidden without recording the mutation. The mutating syscalls are, exhaustively: state_set, state_delete, emit_event, send_message, schedule_timer and cancel_timer (all variants), submit_job, create_deferred_tx, upgrade_self, every token_* mutation, fork (CIP-27), and any future host call that writes durable state.
  • The flag MUST persist across call() sub-calls. The callee inherits read_only = true, so a read-only call cannot mutate state through a callee.
  • Read syscalls (state_get, state_scan_prefix, etc.) and pure computation are unaffected.
  • send_message is denied because a queued message is a durable effect (CIP-1).
The handler mode declares whether a handler intends to issue async effects. read_only decides whether a given call may issue them. The four combinations are:
  • @pure + read_only=false: ordinary external view-style call. Async effects would already be rejected by @pure enforcement.
  • @pure + read_only=true: typical RPC query path. Both checks reject async effects.
  • @deferred + read_only=false: ordinary mutating call.
  • @deferred + read_only=true: the host rejects the async effects the handler issues. Other CIPs, such as CIP-27 §3.1, name this case when they require a syscall to be inert under read-only.
Other CIPs that introduce mutating syscalls SHOULD cite this section for the syscall’s read-only behavior and use this flag definition.

9. Call Primitives

The SDK provides these operations for inter-actor and off-chain interaction: The standalone cowboy package does not export top-level call() and send(). Its local tests use runtime.call_actor(target, method, payload, cycles_limit) and runtime.send_message(target, payload). To move funds without invoking a handler, use runtime.transfer_balance (native CBY, §12.12) or runtime.token_transfer (CIP-20 tokens, §12.4). They share call()’s same-transaction rollback and invoke no recipient code.

9.1 call() — Synchronous Cross-Actor Call

Arguments:
  • target: 20-byte address, as Address, hex string, or raw bytes.
  • method: UTF-8 handler name on the target.
  • args: the arguments, encoded with the call’s codec, a dict of keyword arguments or a list of positional arguments under an encoded codec (cbor / json), or bytes sent verbatim under raw.
  • cycles_limit: explicit cycle budget for the callee. Defaults to 100_000; pass it explicitly for precise metering.
  • codec: the payload codec for both the arguments and the return, raw, cbor, or json, defaulting to cbor. It must match the decode= the target handler declares, see §9.5.
Semantics:
  • Runs in the caller’s transaction and shares its read-write set.
  • Callee exceptions propagate. Uncaught exceptions roll back the entire transaction.
  • Call depth is capped at 32. On-chain, the host rejects an overflow as Forbidden (E1205) and call() reports it as ActorCallError, indistinguishable from a permission or re-entrancy reject. CallDepthExceeded is raised only when an in-process (local/checkpoint-mode) chain overflows Python’s recursion limit. An uncaught host depth overflow therefore commits the SDK ActorCallError slug E1206.
  • The call’s codec decodes the return value.
ActorRef wraps call() and takes the same codec:
With an encoded codec, proxy method calls send their positional arguments as a list, including [] when called with no arguments. Keyword arguments raise TypeError.

9.2 send() — Fire-and-Forget Message

Semantics:
  • Enqueues a message for processing at the start of the next block.
  • The recipient’s self.sender is the actor whose code called send(), even inside a nested synchronous call. Recipients authenticate peers by self.sender, never by identity fields in the payload.
  • No return value; send() returns immediately.
  • Once the transaction commits, nothing can cancel its sent messages.
  • Every committed message is processed exactly once after finality. The recipient’s handler runs only if the sending actor (or its owner under FallbackToOwnerBalance, which DeployActor grants by default) can cover the message’s maximum fee at delivery. Otherwise the message is consumed with DeferredPayerUnfunded (1015) and not retried (WP §4.5; CIP-43 §8).
  • Message identity follows WP §3.3: it binds the creator and producing_digest, which is the immediate transaction digest for an ordinary producer. For CIP-29 async event fires, event_fire_envelope_digest is the transaction digest (tx.digest()) of the __event_fire__ envelope delivered from 0x1D, and sub_id is the 33-byte subscription id of the fire being executed from its EmitOrigin.sub_ids.
    • Nonzero-origin async fire: producing_digest = keccak256(event_fire_envelope_digest[32] ‖ sub_id[33]), including sends by nested callees. Identical (creator, target, payload) sends within one such fire still deduplicate.
    • Zero-origin: The producing transaction’s origin digest is all-zero because it descends from no signed transaction (for example, a timer fire). For an async event fire, producing_digest = event_fire_envelope_digest; for an ordinary producer, it remains the immediate transaction digest. Both paths append the unchanged WP §3.3 system-emission suffix before hashing. For an async fire, that suffix uses keccak256 of exactly the envelope’s complete metadata bytes: its encoded CIP-29 EmitOrigin (origin.to_metadata_bytes()) plus any system-emission suffix appended when the envelope was created. Its emission id is the same 33-byte sub_id.
  • Allowed only from @deferred handlers.
  • payload is encoded with the send’s codec, raw, cbor, or json, defaulting to cbor (§9.5). send(raw=True) is equivalent to codec="raw", and combining raw=True with any other codec raises ValueError.
Authors SHOULD structure handlers so that all fallible synchronous calls complete before issuing send(), because the caller’s own earlier sends survive a caught callee failure and can still be delivered if the transaction commits. When an ordinary synchronous call() fails and the caller catches the failure, the failed frame’s messages, timers and create_deferred_tx children, including children queued by on_fork, are rolled back, so none run. Receipt events remain recorded. Intent-authorized deferred work survives and runs as that frame’s actor. Async event-fire requests also survive and are delivered by 0x1D with that actor as the emitter. Surviving work runs against state without the failed frame’s writes, except the intent rate-limit counter, which stays charged. Failed synchronous event subscribers instead use the stronger CIP-29 isolation: their events, all deferred requests and intent-counter changes are discarded too.

9.3 await runner.<op> — Runner Continuation

An async def handler on an Actor class can await off-chain operations (cowboy_sdk only).
The SDK lowers the handler to an FSM at class-load time (§10), and no decorator is needed. The first call starts the job and returns None. The code after the await runs in a later transaction, when the job’s callback arrives. The handler codec (§9.5) decodes the arguments, and the SDK does not check their type annotations. The runner awaitables are:

9.3.1 runner.http response status and headers

By default the data of an HTTP job is the response body only: the parsed JSON value for an application/json response, {"raw": <base64>, "content_type": <type>} otherwise, or {"result": <value>} when the job sets an extraction selector. The response status and headers do not reach the actor. An actor that needs them sets the request header X-Cowboy-Return-Headers to a comma-separated list of response header names, matched case-insensitively. The Runner does not send this header to the destination, and data becomes:
  • The inner data is exactly what data is without the control header.
  • headers holds only the requested headers that the response carried, keyed in lowercase. Each is an array of its values in the order the server sent them. A value is a string when its bytes are valid UTF-8, and {"base64": "..."} otherwise.
  • The serialized headers object counts toward output_tokens and is capped at 16 KiB; a response over the cap fails the job.
  • The control header is accepted only for jobs whose result is not compared across runners: at most one runner, or verification mode None or EconomicBond. Any other job fails before the request is sent, because headers such as Date differ between requests.
  • A control header that names no header (empty, blanks or commas only) is ignored.
  • RunnerResult.text does not change: extract_text follows the data key to the body.

9.3.2 Secret slots

A runner job that uses a secret marks the one field the secret fills with runner.secret():
  • runner.secret(key, prefix="", suffix="", account=None) names the secret and declares its grant, the owner’s account by default. It may stand for an http job’s url=, a header value or a string inside a dict or list body=, or a string in an mcp job’s arguments; the runner sends prefix + secret + suffix there. A Secret can’t be encoded, so a job assembled in one handler and passed to a continuation marks its slot in the continuation, before the await. The job carries no secrets= list and no hand-written ${KEY} template.
  • The job spec lists its secret slots structurally, as JSON pointers into the URL, headers, body and arguments. The runner fills those slots and nothing else, so caller or model text elsewhere in the job is sent as text, even when it names ${SLACK_BOT_TOKEN}.
  • The secrets.read entitlement (§14.3) still gates every key a job names.

9.4 Actor Await Is Not a Launch API

ActorRef method proxies perform synchronous calls. Naming a method async_* does not make it a runner job or an actor continuation. An await may target only a recognized SDK runner job or an authenticated offchain export. Build and load reject @actor.continuation (§5). Build and load MUST reject actor calls, including await call(...), aliases, await ActorRef.async_*, await self.helper(...) and arbitrary await object.method(...). Recognized runner calls remain allowed. The check resolves each call by its actual binding, not by an attribute name with its receiver discarded. This binding-aware validation is a release requirement that the current compiler does not yet enforce. An await may stand as a statement or an assignment, inside if/elif/else, inside try/except JobFailed (or except OffchainError)/else, and in simple expressions: return await runner.llm(...), (await runner.http(...)).data, an await as a call argument. An await inside a loop (§10.4), async with JobGroup, finally, match or with is not supported until the next regenesis. Use synchronous call for inline actor calls and send for mailbox messages. Actor-to-actor await would need its own request, receipt and resume protocol, which the SDK does not provide.

9.5 Payload Codecs — decode= and codec=

At the host boundary a handler’s payload and return are byte strings. The codec that turns them into native values is declared on the handler and selected by the caller: cbor is the default for call() and send(). On an Actor class, @public / @callable_by handlers also default to CBOR: the SDK decodes incoming values and encodes non-bytes, non-None returns. Declare decode="raw" when the handler implements a byte protocol. The standalone cowboy package (§2.2) defaults to raw; authors using it MUST declare decode= explicitly to match the deployed handler. A continuation exposed through @public or @callable_by on an Actor class MUST use its selected handler codec to decode the initial application request and encode early and final application results, including after an await. This applies to implicit async lowering and @runner.continuation, in either order with a permission decorator. Generated resume handlers MUST retain the internal continuation envelope and apply the handler codec only to the terminal application result. Permission checks MUST precede decoding on both entrypoints. Serialization is part of Actor’s dispatch: module entrypoints receive wire bytes and forward them to a handler. on_fork requires raw: the host supplies a bare 20-byte parent address, and a non-raw declaration is rejected at class creation. init, on_fork, handle_timer, @on_event and @on_stream entrypoints default to raw because the host builds or routes their payloads. A custom init name, timer target or non-FSM job callback has no automatic exemption; declare decode="raw" when it receives bytes. Below, “encoded codec” means cbor or json.
A public continuation also needs no manual decoding or encoding:
A handler that decodes by hand declares decode="raw". Callers MUST use the matching codec, so changing a handler’s codec means updating its callers. The codec does not affect storage encoding or internal continuation records. The wire does not carry the codec. The ExecuteActor payload is opaque bytes, so the callee cannot detect a caller’s wrong codec. A mismatch usually raises a CodecError from the callee’s decode or a decode failure on the caller’s return, but small scalars can misdecode silently. A handler’s declared decode= is part of its signature. The deprecated pvm_sdk.continuation.save_cont writes canonical CBOR using the existing five-key schema, including wide integers. Integer and boolean map keys keep their type, finite binary64 floats are supported with negative zero normalized to positive zero, and tuples reload as lists. load_cont retains the JSON reader for hand-written legacy records and rejects cowboy_sdk’s different six-key continuation schema under the shared key prefix. Conversely, cowboy_sdk’s reader requires its six schema keys and rejects the legacy five-key schema before checking guards or timeout. Under either encoded codec, None sends an empty payload, which differs from an encoded empty list (0x80 under cbor, [] under json). An empty inbound payload decodes to None. Under raw, pass b"". For a handler with an encoded codec, a bytes-like return is already-encoded output and passes through unchanged, None is no output, and the codec encodes any other value. To return a CBOR byte string, return codec.encode(value). JSON has no byte-string type, so a json handler returns text or a container instead. Codec failures differ by side: The handler side reports every codec fault as CodecError with a codec slug, never as a host-internal error. On the caller side, cbor passes the original exception through, because encode_args runs in the caller’s own frame. json raises CodecError there because the strict profile classifies its own refusals before the standard library raises.

The strict JSON profile

json_codec narrows json.dumps so that identical values produce identical bytes and a serde_json consumer accepts every output:
  • Sorted keys, no separator padding, ASCII-escaped. {"b": 1, "a": 2} serializes to {"a":2,"b":1}, and {"k": "café"} to {"k":"caf\u00e9"}. The bytes never depend on dict insertion order and are always 7-bit.
  • No non-finite numbers. NaN / Infinity / -Infinity are refused on encode, and on decode in both spellings: the bare tokens json.loads accepts by default, and a number literal that is valid RFC 8259 syntax but overflows to infinity (1e400).
  • No surrogate code points, on encode or decode, paired or not. A supplementary character is a single code point, so it survives as a well-formed pair escape: "😀" encodes to "\ud83d\ude00".
  • UTF-8 only on decode, so a UTF-16/32 BOM cannot reinterpret the payload under an encoding this profile never emits.
  • No byte-string type, and object keys are strings. A bytes payload is refused, and integer keys stringify: {1: "a"} round-trips as {"1": "a"}, where cbor returns {1: "a"}. Choose cbor when key fidelity or binary data matters.
Each refusal raises CodecError (E1213) on both the caller and the handler side.

10. Continuations

All continuation features in this section are cowboy_sdk (PVM) only.

10.1 FSM Compilation

The SDK lowers every async handler on an Actor class that awaits a supported runner job into a pair of functions, at class-load time. §9.3 lists the allowed runner awaitables; §9.4 defines the rejected awaits. @runner.continuation(...) compiles under the same rules and only adds options (§10.2):
  • <name>: the initial handler; starts the FSM, persists state 0, issues the first async effect, returns.
  • <name>__resume: the resume handler; called by the runtime on callback delivery, loads state, advances the FSM, issues the next async effect (or returns final value).
The build writes a module-level entrypoint for each. The shape of the generated code is non-normative.

10.2 Waits

Locals and arguments carry across an await: the compiler saves the ones read after it and restores them on resume.
Carried values MUST be CBOR-encodable (see §11.5). A RunnerResult persists as its raw value, so extract .text before the next await when text is needed afterward. Closures, generators, file handles, threads, and objects without a supported CBOR representation are rejected. A wait ends in one of these ways, each of which frees its slot: An await inside try: ... except JobFailed: raises it there. Any other await whose wait fails ends the handler, and nothing after it runs. When the code after an await raises, that step’s storage writes, messages, timers, jobs and transfers roll back; only the slot release and a failure event commit. @runner.continuation(timeout=D) sets a wait’s deadline, D seconds of block time after its await (§12.5). A handler without timeout= gets the SDK’s default deadline, which exceeds the node’s job timeouts. The SDK reaps waits past their deadline itself, through the same counters an answer uses, so actor code never deletes a wait. The deadline is separate from a job’s own timeout_blocks= argument, such as runner.llm(..., timeout_blocks=30), which sets how long the chain waits for the assigned runner before handing the job to another.
@runner.continuation takes timeout= and guard_keys= (§10.3); a handler that needs neither is a plain async def, and cowboy check flags the decorator when it passes no options. Each wait has a unique id: two calls to one handler from one sender in one transaction start two waits, and saving refuses to overwrite a live one. Wait state is stored at key __continuation:<correlation_id> within the actor’s own storage, and the per-transaction counter at __continuation_seq. Each pending wait records the caller that started it. One caller cannot take more than a default share of the slots, and callers a handler does not name share one cap below CONTINUATION_MAX_COUNT, so the owner and named callers always have free slots. A refusal names the handler, the caller, the rule broken and the fix. Exceeding either limit raises ContinuationSizeLimitError or ContinuationCountLimitError.

10.3 Guards

A continuation can require that specific storage keys stay unmodified during its wait. A decorator names the guarded keys:
Or the handler snapshots a key with GuardedValue:
A guard fingerprint is keccak256(cbor(value_at_snapshot)), stored in the continuation state and re-checked on resume.

10.4 Bounded Loops (next regenesis)

The next regenesis adds await inside a loop, with an explicit upper bound:
A bounded_loop with max_iterations = N generates N FSM states at compile time. Exceeding N at runtime raises LoopBoundExceeded. Unbounded iteration with await is rejected at class-load time.

10.5 Sequential Await Limit

A single continuation function MAY contain at most 8 sequential await points. Class load rejects a function with more; split it into multiple continuations.

10.6 Continuation Persistence Format

Continuations have two independent layers:
  • The authoring layer (compile time, §10.1–10.5) rewrites an async def into straight-line FSM code, and guards and bounded loops constrain what may cross a suspension. It does not change the persisted bytes.
  • The persistence layer (runtime, this section) serializes the suspended interpreter state into actor storage at an await, and the resuming dispatch restores it. This format is part of the consensus boundary.
Production uses checkpoint mode (ContinuationMode::Checkpoint) to persist a versioned snapshot of the suspended VM. The SDK does not write a field record.
The SDK also ships continuation.save_cont record helpers (a small typed map of state / ctx / handler / timeout / guards) in two unreconciled variants (§9.5). They belong to the FSM execution mode, which production does not enable. The on-chain format is the checkpoint snapshot defined below.
A suspended continuation is written to the actor-state key __continuation:<cid>, where <cid> is the hex encoding of the resuming message id. The value flows into the state root, so it is consensus-committed. __continuation:-prefixed keys are exempt from the 64 KiB inline-blob cap (§6.5), because a snapshot can exceed it. The snapshot is a single canonically ordered CBOR map with a leading version (current SNAPSHOT_VERSION = 3). The top-level fields are: Maps use the length-first key ordering of §11.5, applied recursively. Integers use shortest-form; strings/bytes are length-prefixed; floats are IEEE-754 big-endian. The serialization performs no hash-ordered iteration and invokes no non-deterministic source, so two validators suspending the same execution produce byte-identical snapshots. On resume the runtime decodes the snapshot, rejects an unknown version or a source_path mismatch, validates that frame lasti values and all object indices are in range, and restores the frame stack before continuing execution at the saved instruction pointer. The decoder accepts only version 3 and requires the frames array, with stack and blocks present on every frame.

10.7 Single Flight

@single_flight(key=...) lets one open wait hold a key:
  • Another call with the same key while the wait is open fails at once with Busy. It never queues.
  • The SDK releases the key however the wait ends (§10.2). Because the SDK writes the resume and failure code, no path skips the release. A hand-written flag would stay set when a job fails, because nothing after the await runs.

11. Type System

The SDK replaces or constrains Python built-ins whose semantics are non-deterministic or ambiguous across platforms. The types in this section are cowboy_sdk only, except that the standalone cowboy package exports Address in two forms: a Pydantic hex-string model for chain interactions and a 20-byte stub for local actor testing.

11.1 Address

20-byte Ethereum-compatible address.

11.2 BlockHeight

BlockHeight annotates block heights and is identical to int at the bytecode level.

11.3 SoftFloat, ordered_set

  • SoftFloat is a software-floating-point type. Native Python float depends on the hardware FPU and is non-deterministic across platforms; authors MUST use SoftFloat instead, except for the CIP-45 response-model syntax specified in §11.4. The SDK may alias SoftFloat = float when running under a PVM that enforces softfloat at the instruction layer; authors SHOULD still annotate with SoftFloat in other models.
  • ordered_set is a dict-backed set with deterministic insertion-order iteration. Python’s built-in set() is prohibited in actor code.

11.4 CowboyModel

CowboyModel is a dataclass-like base for structured data. It provides:
  • Deterministic serialization via to_cbor() and from_cbor(bytes).
  • JSON Schema export via schema().
  • Field validation on construction.
  • Forbids set / frozenset fields (non-deterministic iteration).
  • Requires SoftFloat for floating-point fields except in CIP-45 response models: their builder-derived number fields use the bare float annotation. The PVM still enforces software floating-point arithmetic for those values. Schema derivation reads source syntax, so the SoftFloat alias does not derive a CIP-45 schema node.

11.5 CBOR Codec

The SDK serializes actor objects as Canonical CBOR (RFC 8949 §4.2.3). Storage values and continuation state always use it. Call arguments, send() payloads and handler returns use the codec that the call and handler select (§9.5). Canonical CBOR requires:
  • Map keys sorted by length-first ordering (RFC 8949 §4.2.3): compare the encoded key bytes by length first, then bytewise (lexicographically) within equal lengths.
  • No duplicate keys.
  • Floats MUST be finite IEEE 754 binary64. Encoding and decoding reject NaN and both infinities; decoding also rejects float16 and float32. Negative zero normalizes to positive 0.0 on both paths. Integral-valued floats remain binary64 (2.0 does not become integer 2).
  • Integers and length heads MUST use the shortest form. Tags 2/3 represent bignums only beyond the native 64-bit heads, with a shortest, nonzero-leading byte-string magnitude. Other tags are rejected.
  • Decoding rejects duplicate or misordered map keys, indefinite lengths, undefined (f7), and trailing bytes.
cowboy_sdk.codec.encode(v) -> bytes and .decode(b) -> value are the canonical entry points. On-chain they use the VM’s native pvm_host.cbor_encode / cbor_decode; local CPython uses the Python fallback. Native execution is metered by the CIP-3 CBOR surcharge schedule, including per-item, byte, hook, collision, copy, and sort work; it is not a flat 20 + bytes operation.
The codec uses RFC 8949 §4.2.3 length-first map-key ordering, not the pure byte-lexicographic ordering of §4.2.1 (“Core Deterministic Encoding”). The on-chain native codec, the local Python fallback and the VM’s continuation/snapshot encoder all use it. Transaction wire encoding and signing are a separate protocol-codec boundary (CIP-40) that actor CBOR does not redefine.

12. Runtime Module

cowboy_sdk.runtime exposes the Host API. Actor code SHOULD prefer the higher-level helpers in cowboy_sdk (call, send, storage proxy); runtime is for cases where fine-grained control is needed (e.g., system actors, upgrade flows). The standalone cowboy package provides a partial local stub of runtime. It covers context access (get_sender, get_actor_address, get_block_height, get_timestamp_ms), events, send_message / call_actor, low-level state no-ops, ownership helpers, and test utilities (configure, reset, get_captured_events, get_captured_messages). It does not implement token operations, timers, upgrade_self, submit_job, keccak256, randomness, charge_gas, or scan_state_prefix.

12.1 Context

A deferred child reserves its maximum cost before it runs. self.sender is the only way to read the caller (§5). Code that needs raw bytes uses bytes(self.sender), and a module-level helper receives the sender from the method that calls it. These accessors are the only sources of time and identity. The runtime traps time.time(), datetime.now() and similar calls.

12.2 State

Lower-level state access paralleling self.storage:
set_state and delete_state refuse writes to the reserved key __INITIALIZED__. See §12.10.

12.3 Events

Emits a log entry visible in the transaction receipt and returns an EmitResult dictionary with emit_id, sync_outcomes, and deferred_subs. The optional 32-byte schema identifier follows CIP-29 §2.1. Event payload and schema declaration Cells are metered per CIP-3 §2.2.2. runtime.emit_event is the one way to emit an event. A bytes-like payload is sent verbatim; any other value is encoded as Canonical CBOR.

12.4 Tokens (CIP-20)

The standard CIP-20 interface is exposed as runtime operations:
Each requires the corresponding entitlement (token.create, token.transfer, etc.).

Escrow

An Escrow holds CIP-20 tokens for other accounts. It is not an actor: declare it as a class attribute in the Actor subclass body:
  • Escrow(name, token=, refund_after=) books each deposit by id and payer in its own storage namespace. Two escrows with the same name share their deposits. The build refuses an Escrow(...) in a module-level assignment.
  • An actor whose token is created after its code is built declares Escrow(name, refund_after=) without a token and binds it once with set_token(token_id), from init or an owner-only handler. A second bind is refused, and so are deposits, releases and refunds until a token is bound. A token known at build time can be passed as token= instead.
  • deposit(id, payer=, amount=) pulls the tokens with token_transfer_from, only from the caller, so the payer approves the actor first. A booked id is refused, settled or not.
  • Tokens leave only two ways. release(id, to=, amount=None) pays out, by default all that is left, and releases together never exceed the deposit; who may release is the handler’s permission decorator. refund(id, by=) pays what is left back to the payer: only by the payer, only after refund_after seconds of block time, and only once.
  • Nothing deletes a deposit. get(id) reads one: its payer, amount, the amounts released and refunded, and when it was made.

12.5 Timers (CIP-5)

At fire_at_block, the scheduler delivers payload to the actor’s handle_timer handler. Requires timer.schedule entitlement. schedule_timer_ex allows overriding fee payer, gas limit, structural access request and expiry per CIP-5 §4.1. access_limit precedes expires_at; None uses DEFAULT_TIMER_ACCESS_PER_FIRE = 160, explicit SDK requests must be positive, and the current enforced ceiling is TIMER_ACTOR_INTENT_ACCESSES_LIMIT = 375 (the general 322-unit child-producing tier is not that ceiling). The raw host binding instead requires six positional arguments and uses zero/empty-byte default sentinels; use the SDK wrapper for optional arguments.

Durations

MINUTE, HOUR, DAY and WEEK are seconds. schedule_after, @every, @runner.continuation(timeout=) and the default wait deadline (§10.2), @limit(every=) and Escrow(refund_after=) measure their durations in seconds of block time: the SDK checks each deadline and delay against the block timestamp (runtime.get_timestamp_ms(), §12.1). Timers fire by block height, and blocks are not guaranteed to be runtime.BLOCK_INTERVAL_MS apart, so a block count is only the scheduling estimate:
It estimates the blocks that span seconds at runtime.BLOCK_INTERVAL_MS, or an interval the caller passes, rounding up. A timer armed from the estimate can fire before that many seconds of block time have passed.

Schedules

@every(D) runs a handler every D seconds of block time:
  • Each @every handler has one schedule: every.start replaces a running one, and every.stop cancels it.
  • The SDK re-arms the schedule before the tick runs, and the re-arm commits even when the tick fails, so a failed tick keeps the schedule.
  • Each tick is due D seconds of block time after the previous one. The SDK arms its timer from a block estimate, checks the block timestamp when it fires, and corrects drift.
  • An @every handler runs only from its own timer (SELF, §7.3).

12.6 Jobs (CIP-2)

Low-level entry used by runner awaits; actor authors SHOULD prefer await runner.<op> (§9.3).

12.7 Upgrades

Replaces the running actor’s code and optionally its entitlement manifest. The new manifest MUST be a subset of the current manifest (no privilege escalation), subject to the configuration exception below; violation raises at the Host boundary. Requires sys.upgrade entitlement. An upgrade that retains ingress.http MAY add, grow, shrink, or remove its static_volumes and max_static_response_bytes parameters; removing max_static_response_bytes resets the cap to the CIP-15 §7.1 Gateway default. The exception exists because these parameters only configure serving the actor’s own public content. All other entitlements and ingress.http parameters can only narrow, and the replacement manifest still passes name, type, and cap validation.

12.8 Crypto

randomness() produces deterministic per-block VRF output keyed by domain. This is the only authorized source of randomness; random.random() and secrets are trapped.

Algorithm-tagged signature verification

Algorithm IDs use the single registry in CIP-40 §7.1: 1 = secp256k1, 2 = Ed25519, 3 = P-256, 4 = P-384, 5 = P-256 WebAuthn assertion (registered, supported by no API at genesis; CIP-40 §7.5). This API initially supports only 2; transaction signature slots initially support only 1. Booleans are not algorithm IDs. Unknown or unsupported algorithms raise ValueError("unsupported signature algorithm"); a wrong public-key/signature length raises ValueError("invalid signature length"). Both checks run before any host call. Ed25519 requires a 32-byte public key and 64-byte signature and verifies the raw message with strict Ed25519 verification, not Ed25519ph. A well-formed invalid signature returns False; invalid key encoding follows the existing host invalid-input error. The host’s message size bound and resource-exhaustion errors still apply and never become False. The valid path invokes the Ed25519 host once, charging 5,000 Cycles plus the host boundary charge, with no wrapper surcharge. Native/Zygote and simulation/mock paths MUST expose identical results and errors. runtime.verify_signature wraps the Python binding pvm_host.verify_signature, and no ed25519_verify entry point exists. The native Feed calls verify_signature with its stored authority, in the record layout that CIP-7 specifies. The Watchtower gallery example also calls this API but keeps a retired envelope format, so it is not a CIP-7 conformance or production-signing example.

Owner-authenticated signing-key records

cowboy_sdk.signing provides a reusable actor-state pattern:
A record is one canonical CBOR map, {"algorithm": 2, "public_key": <32 bytes>}, stored at the supplied actor-state key, and one state write replaces both fields. The helper accepts only supported algorithms and exact public-key lengths. Storing a key does not prove possession, and the host rejects an invalid curve encoding at verification. set_signing_key requires the current sender to equal the actor’s current 20-byte, nonzero protocol owner (§12.10); an actor without valid ownership metadata cannot create a record. Self-calls get no exemption. Neither a new key, a signature by it, nor knowledge of the old public key grants authority to replace the record. A failed authorization or descriptor check leaves the existing record intact. get_signing_key returns None only for missing state; malformed and unsupported records raise. verify_with_signing_key raises for missing authority and otherwise passes the stored algorithm and key to runtime.verify_signature. The helper verifies message bytes only. Applications must still bind signatures to their chain, actor and action, and enforce a replay policy, before authorizing state changes.

12.9 Metering

Application actors MUST NOT call runtime.charge_gas(). The runtime meters at syscall boundaries, and a manual call charges Cycles on top of that.
Returns the wei left in the current period of the actor’s econ.budget (§14.3), or None for an actor without one. The node counts what a job takes from the actor at admission and the fee every other deferred transaction draws, in fixed windows of block time (timestamp // per); spending past the cap is refused with BudgetExceeded (E1625). A job’s callback is never counted again or refused, and refunds don’t restore budget.

12.10 Ownership

Every actor has a protocol owner, held in the protected ActorOwner record (CIP-37 §7.1.1). The chain sets it when it creates the actor: a directly signed deployment makes the verified deployer the owner, and actor-created children and forks inherit their creating actor’s current owner. Only a TransferActorOwnership transaction signed by the current owner changes it. Actor code cannot claim, transfer or renounce ownership, and init takes no step to establish it.
@callable_by(OWNER) compares the immediate caller with runtime.get_owner(). Application storage cannot supply ownership: __OWNER__ is an ordinary application key with no authority. Reserved storage keys: For local tests, cowboy_sdk.mock_host.seed_actor_owner(owner, actor=None) sets an actor’s protocol owner (a nonzero 20-byte address; actor defaults to the current context’s actor). Without it, get_owner() and @callable_by(OWNER) raise a host error in the mock, as they do on chain when ownership metadata is missing.

12.11 State Prefix Scan

Returns up to limit (key, value) pairs whose user-key starts with prefix, in ascending key order. Only verbatim-mode keys (≤ 64 bytes) are visible. limit is clamped to 1000 by the host.

12.12 Native CBY Balance

Atomically debits amount wei (CBY has 9 decimals; 1 CBY = 10^9 wei) from this actor’s native CBY balance and credits the same amount to to. Synchronous, no return value, no callback into to. transfer_balance is the only host-level operation that moves native CBY between addresses. It is the native-CBY counterpart of runtime.token_transfer, and neither operation touches the other’s ledger. Arguments:
  • to: 20-byte recipient address. The system-reserved address band (per CIP-1 §5) is rejected with HostError::InvalidInput. The zero address is rejected.
  • amount: non-negative integer in wei.
Semantics:
  • Atomic with the calling transaction. The debit and credit are staged in the transaction’s write-set; if the enclosing transaction reverts, both reverse together. Implementations MUST route the balance writes through the same staged-writeset machinery used by call() and set_state, because a direct ledger mutation leaks balance on revert.
  • Insufficient balance raises HostError::InsufficientFunds and does not mutate either account.
  • amount == 0 is a no-op (no event, no metering beyond the syscall base cost).
  • Self-transfer (to == get_actor_address()) is permitted and is a no-op on net balance, but still consumes the syscall base cost.
  • Allowed from any @deferred handler. @pure and read-only contexts MUST reject transfer_balance with HostError::Forbidden.
  • Requires the econ.transfer entitlement. It is in the default entitlement set that every actor holds; a manifest grant for it adds its max_amount / max_per_block quotas.
A parent funds a child created with fork() (CIP-27 §3.3) in one of two ways:
  1. Use fork(endowment=N) to fund the child with a single atomic debit/credit during the fork. Use when the parent must guarantee the child has CBY before any post-fork code runs (e.g. a child whose on_fork schedules a self-timer at default fee_payer = self).
  2. Fork the child, then transfer_balance(child, N) from the parent. Both calls are in the same transaction and share rollback, but the child is briefly zero-balance between the two syscalls. Use when the funding amount depends on state the parent doesn’t know pre-fork.
Moving CBY through call() would require every recipient, including EOAs, which have no handlers, to expose an accept-funds handler. CBY balances live in the chain’s account model, separate from actor storage, so transfer_balance debits and credits them without invoking a recipient handler, like EVM’s value field on a plain ether transfer. The standalone cowboy package provides a local in-memory stub recording (to, amount) pairs for test inspection (runtime.get_transfer_log()). No supply checks run.

13. Result Verification

An actor’s runner jobs settle under one fixed mode: EconomicBond with one runner. The SDK has no builder for other verification modes. cowboy_sdk (PVM) only.
CIP-45 structured LLM calls use EconomicBond with one runner, threshold one, and an empty result-verifier checks list. runner.llm() does not accept a verification keyword. The separate verify option performs CIP-24 inbound signature verification and does not select a result-verification mode. The node checks that a structured result is admissible at submission; actor code handles a schema-valid but false value.

14. Entitlements

14.1 Manifest Format

A manifest accompanies every deploy and upgrade. JSON shape:
Rules:
  • id values MUST appear in the Entitlement Registry.
  • The entitlements array MUST be lexicographically sorted by id; a chain MUST reject deploy transactions with an unsorted manifest.
  • params contents are entitlement-specific and validated at deploy time against the registry’s ParamSchema.
  • An upgrade’s manifest MUST be a subset (in both ids and param-bound strength) of the prior manifest, subject to the §12.7 ingress.http configuration exception.

14.2 Runtime Enforcement

The Host API enforces entitlements; actor code does not check them:
  1. Actor invokes an SDK function.
  2. SDK issues the corresponding syscall.
  3. Host checks the actor’s manifest for the required entitlement.
  4. If the entitlement is absent, the Host returns HostError::MissingEntitlement. The SDK raises the corresponding error.
  5. If the entitlement is present but its quota or params refuse the call, the Host returns the matching error.

14.3 Entitlement Registry (Informative Summary)

CIP-2 §7 is the normative source.
Unlike the other rows, the token.* capabilities are not string IDs in the entitlement registry. The implementation models each as a typed Scope::Token([u8; 32]) (the token id) with the matching Action variant (TokenTransfer / TokenMint / TokenBurn / TokenFreeze / …), so a grant applies to one token. token.create is the exception: it has no Action variant and is not entitlement-gated. Creating a token is gas-metered only, and the creator (tx.from) becomes the token’s owner and mint authority. The typed Scope::Token and Action model is authoritative over this row.

15. Error Hierarchy

All SDK exceptions derive from cowboy_sdk.CowboyError. Each exception exposes:
  • HOST_ERROR_CODE: int, numeric Host API code, where the exception is backed by a Host API error
  • ERROR_SLUG: str, short identifier, format E1xxx
  • .why: str, human explanation
  • .fix: str, suggested remediation
A slug identifies an error category, and several classes may share one: HostError WalletAddressConflict = 28 maps to receipt slug E1228 when a deploy or fork targets a wallet-marked address. E1014 is the separate transaction-validation error for an Actor or reserved-system signer; it is not a HostError code. Transaction receipts expose structured errors; clients use ERROR_SLUG for programmatic handling. The standalone cowboy package also exports client-side exceptions (TransactionFailed, RpcError, AccountNotFound, NonceMismatch, etc.) that are not part of this CIP.

16. CLI

The canonical CLI is cowboy. Commands relevant to actor development:

16.1 Project bootstrap

Persists config at .cowboy/config.json (environments and the active environment). An environment names its signing key by keystore name ("key": "<name>", default default). Keys live only in the keystore, never in the project’s .cowboy folder; a key_file entry is refused. --output FILE instead writes a one-off key for --private-key, which is never looked up or recorded; a path inside a .cowboy folder is refused.

16.2 Actor lifecycle

Project deployments use cowboy deploy <target>; the raw-source form is shown below. Both follow the initialization rules in §6.3.
Funding and upgrading an actor:

16.3 Ecosystem

16.4 Conformance

Any implementation MAY extend the CLI with additional commands. Once this CIP is Final, renaming any command in this section requires a CIP revision.

17. PVM Determinism Rules

Actor code MUST conform to the following rules. Violations are detected at class-load time where statically decidable; otherwise they raise DeterminismError at runtime.

18. Open Questions / Gaps

  1. CBFS volumes (CIP-9) are runner-side only. Storage-attached actor workflows need an actor-side mount(volume_id, access_mode) API, which is not yet defined.
  2. The SDK provides @on_stream(feed, *, guard, max_cycles, max_cells, wake_allowance_wei, numeric_tag_scales=None, evidence_policy="FINALIZED") for CIP-7 Feed subscriptions and callback routing, but not the proposed @on_stream(stream_id) signature or a stream_publish() helper.
  3. runtime.is_checkpoint_mode() reports the persistence layer. Production uses checkpoint mode (ContinuationMode::Checkpoint, §10.6) and does not yet enable the FSM execution mode.
  4. Address is fixed at 20 bytes (Ethereum-compatible). A larger address scheme would replace this type in its own CIP.
  5. The compiler is to reject unbounded await-in-loop at class load (§10.4), but edge cases such as awaits inside comprehensions or in helpers called from loops are under-specified. A future revision should enumerate accepted and rejected shapes.
  6. The upgrade “subset” rule is informal. The registry needs a per-entitlement is_tighter_than operator, which is currently ad hoc.
  7. The standalone cowboy package lacks the features §2.2 lists.
  8. The SDK release sets the default wait deadline (§10.2), which MUST exceed the node’s job timeouts.
  9. LimitReached and Busy take their error slugs from the SDK release that adds them (§15).
  10. If the runner’s slot-only fill (§9.3.2) is not in the release, the SDK instead refuses a secret-bearing job whose body, MCP arguments or prompts contain an unmarked ${, raising SecretTemplateInText.