Chio/Docs
LOGIN · JOIN

ReferenceSDKs

Swift / iOS SDK

Run agents on a computer from Swift, and embed the mobile kernel in an iOS application.

The Chio package carries the Computer API from the Quickstart and the embedded mobile kernel: local evaluation, receipt signing, capability and passport verification, and App Attest. It builds for macOS and iOS with Swift 5.9 or newer.

Install

Package.swiftswift
dependencies: [
    .package(url: "https://github.com/backbay-labs/chio-swift", from: "0.1.0"),
],
targets: [
    .executableTarget(name: "Pricing", dependencies: [.product(name: "Chio", package: "chio-swift")]),
]

In Xcode, add the same URL under Package Dependencies and link the Chio product to your target.

Computer

Computer is the API the Quickstart uses. A computer is a versioned environment where authority, resources, and work live. You open one, fork it, grant an agent part of the fork, run work, read the signed receipts, and apply the changes you keep. Your kernel enforces every grant and signs every decision.

Calls that reach the kernel are async throws. grant, reissue, and describe are synchronous. Event streams are AsyncThrowingStreams read with for try await. Composition uses & for parallel and | for sequence; Swift's precedence binds & tighter, as in Python and Rust.

This program is Quickstart part 1 in one file. It runs inside the computer that chio new quickstart creates.

main.swiftswift
import Chio

let project = try await Computer.open("quickstart")
let fixer = try await project.agent("fixer")
let fork = try await project.fork()
let authority = try fork.grant(
    to: fixer,
    resources: ["/workspace": [.read, .write], "/models/default": [.invoke]],
    budget: .usd(2),
    expiresIn: .minutes(20)
)

let run = try await fixer.run("fix issue #412", on: fork, authority: authority)
for try await event in run.events() {
    print(event.summary)
}

let refusals = try await project.history.receipts(outcome: .deny)
print(refusals[0].describe())
Output
00:00  admitted   fixer runs "fix issue #412" on fork 51c07ae
00:03  read       /workspace/src/pricing.py
00:05  read       /workspace/tests/test_pricing.py
00:09  refused    read /secrets/.env: outside the grant
00:12  invoke     /models/default, USD 0.21
00:41  write      /workspace/src/pricing.py
00:56  test       pytest -k issue_412: passed
spent  USD 0.48 of 2.00

receipt    rcpt-01a8…9c04
request    fixer read /secrets/.env
verdict    deny: outside the grant
grant      cap-01a8…31f2
policy     sha256 3c7b…8010
signed     your kernel 4f1c…a2e9, signature verifies

The examples below continue from it: project is the quickstart computer, fixer is its agent, and fork and authority are the fork and grant above. The service examples use the pricing service from Quickstart part 2, and the partner examples use the partner card, treaty, and reviews mailbox from part 3.

Computer.open

static func open(_ name: String) async throws -> Computer

Opens a computer your operator identity owns and returns its handle. The handle reads the computer's current revision; nothing is copied.

swift
import Chio

let project = try await Computer.open("quickstart")
print(project.describe())
Output
computer   quickstart
owner      did:chio:z6Mkf3…Qp9 (you)
revision   main @ 7c2e1d0
resources  /workspace         git, 14 files
           /models/default    model route, metered in USD
           /secrets           3 files

Computer.connect

static func connect(_ name: String) async throws -> Partner

Resolves a paired partner by the name you gave its card, and authenticates its kernel before returning.

swift
let partner = try await Computer.connect("partner")
print(partner.describe())
Output
partner    partner, did:chio:z6MkpA7…c2T
operator   Halden, halden.example
kernel     9b07…d31c, pinned from its card
transport  iroh, authenticated at handshake

Computer.partners

static func partners() async throws -> [Partner]

Lists every partner you have paired with, each with its pinned kernel key and the treaty in force.

swift
for partner in try await Computer.partners() {
    print(partner.summary)
}
Output
partner    did:chio:z6MkpA7…c2T   Halden   kernel 9b07…d31c   treaty trt-01aa…4c19

Computer.agent

func agent(_ name: String) async throws -> Agent

Returns the agent with this name, issuing it an identity from your kernel the first time. An agent holds no authority until you grant it some.

swift
let fixer = try await project.agent("fixer")
print(fixer.describe())
Output
agent      fixer, did:chio:z6MkrT2…8wd
issued by  your kernel 4f1c…a2e9
grants     none

Computer.agents

func agents(_ role: String, count: Int, reads: Mailbox? = nil) async throws -> [Agent]

Starts several agents of one role, numbered from 1, optionally reading a shared mailbox.

swift
let reviewers = try await project.agents("review", count: 2, reads: reviews)
for reviewer in reviewers {
    print(reviewer.summary)
}
Output
reviewer-1   did:chio:z6MkvR1…3mc   reads reviews
reviewer-2   did:chio:z6MkvR2…9tf   reads reviews

Computer.fork

func fork(boot: Program? = nil) async throws -> Fork

Branches the computer's managed state at its current revision. Work on the fork stays there until you apply it. A fork does not reset authority, history, or spending.

swift
let fork = try await project.fork()
print(fork.describe())
Output
fork       51c07ae of quickstart, base main 7c2e1d0
writes     stay in the fork until you apply them

Fork.grant

func grant(to: Principal, resources: [String: [Right]], budget: Money? = nil, expiresIn: Expiry, under: Treaty? = nil, delegation: Delegation? = nil) throws -> Authority

Issues a capability token over part of the fork: resources and their rights, a budget charged at your door, and an expiry. to takes an agent, a partner, or a DID. delegation lets the holder delegate narrower grants onward, and under issues a grant within a treaty. Issuance completes durably before the call returns.

swift
let authority = try fork.grant(
    to: fixer,
    resources: ["/workspace": [.read, .write], "/models/default": [.invoke]],
    budget: .usd(2),
    expiresIn: .minutes(20)
)
print(authority.describe())
Output
grant      cap-01a8…31f2, signed by your kernel
to         fixer, did:chio:z6MkrT2…8wd
on         quickstart, fork 51c07ae
allows     /workspace         read, write
           /models/default    invoke
budget     USD 2.00, charged at your door
expires    in 20 minutes

Authority.reissue

func reissue(on: Fork) throws -> Authority

Issues a grant with the same terms on another fork. The original grant is unchanged.

swift
let next = try await project.fork()
let again = try authority.reissue(on: next)
print(again.describe())
Output
grant      cap-01a8…5b3e, signed by your kernel
to         fixer, did:chio:z6MkrT2…8wd
on         quickstart, fork 7d2e914
allows     /workspace         read, write
           /models/default    invoke
budget     USD 2.00, charged at your door
expires    in 20 minutes

Agent.run

func run(_ task: String, on: Fork, authority: Authority) async throws -> Run

Sends a task to an agent under a grant. Every operation the agent attempts reaches your kernel before it reaches a resource.

swift
let run = try await fixer.run("fix issue #412", on: fork, authority: authority)
print(run.describe())
Output
run        run-01a8…e7c0
agent      fixer, on fork 51c07ae
authority  cap-01a8…31f2

Run.events

func events(include: [Agent] = []) -> AsyncThrowingStream<RunEvent, Error>

Streams the run's events in order: admissions, reads, writes, model calls, tests, and refusals. A refusal is an event with a receipt, not an exception, and the run continues.

swift
for try await event in run.events() {
    print(event.summary)
}
Output
00:00  admitted   fixer runs "fix issue #412" on fork 51c07ae
00:03  read       /workspace/src/pricing.py
00:05  read       /workspace/tests/test_pricing.py
00:09  refused    read /secrets/.env: outside the grant
00:12  invoke     /models/default, USD 0.21
00:41  write      /workspace/src/pricing.py
00:56  test       pytest -k issue_412: passed
spent  USD 0.48 of 2.00

Partner.exec

func exec(_ task: String, on: Fork, authority: Authority, reportTo: Mailbox? = nil) async throws -> Run

Sends a task to a partner's agents under a grant issued within a treaty. The partner's kernel admits the work and runs it in its own process tree. run.joinTree() waits for every agent the partner delegated to.

swift
let run = try await partner.exec("fix issue #414", on: fork, authority: authority, reportTo: reviews)
for try await event in run.events() {
    print(event.summary)
}
try await run.joinTree()
Output
00:00  them  admitted   "fix issue #414" under trt-01aa…4c19
00:01  them  delegate   coordinator to fixer-1, fixer-2, tester, each narrower
00:31  them  refused    fixer-2 read /secrets/.env: outside the grant, at your door
01:47  them  sealed     fork c4e81b7 at 5b93d10
spent  USD 3.12 of 5.00 across 4 of their agents

Fork.diff

func diff() async throws -> String

Returns the changes the fork holds against its base, as a unified diff.

swift
print(try await fork.diff())
Output
src/pricing.py
@@ def discount(price, percent):
+    if not 0 <= percent <= 100:
+        raise ValueError("percent must be between 0 and 100")
     return price * (1 - percent / 100)

Computer.apply

func apply(_ changes: ChangeSet, treaty: Treaty? = nil) async throws -> Applied

Publishes the fork's exact changes if main still matches the fork's base, and returns the signed merge. Under a treaty, both kernels co-sign it.

swift
let merged = try await project.apply(fork.changes)
print(merged.describe())
Output
applied    fork 51c07ae onto quickstart main
revision   main 8d4b2e7, base 7c2e1d0
receipt    rcpt-01a8…d51e, signed by your kernel

History.receipts

func receipts(outcome: Outcome? = nil, agent: Agent? = nil, since: Expiry? = nil) async throws -> [Receipt]

Reads signed receipts from the computer's history, filtered by outcome, agent, or time.

swift
let refusals = try await project.history.receipts(outcome: .deny)
print(refusals[0].describe())
Output
receipt    rcpt-01a8…9c04
request    fixer read /secrets/.env
verdict    deny: outside the grant
grant      cap-01a8…31f2
policy     sha256 3c7b…8010
signed     your kernel 4f1c…a2e9, signature verifies

History.export

func export(to directory: URL) async throws -> Evidence

Writes the computer's history to a directory as an evidence package. Verification checks every signature against pinned kernel keys, offline.

swift
let evidence = try await project.history.export(to: URL(filePath: "audit"))
print(try await evidence.verify())
Output
receipts   9 signed decisions from your kernel
refusals   1: fixer read /secrets/.env
spend      USD 0.48 of 2.00
verified   offline, against your kernel key 4f1c…a2e9

Policy.add

func add(_ rule: Rule) async throws -> RuleRef

Adds a named rule to the computer's policy. Policy narrows every grant on the computer, and no grant widens policy.

swift
let rule = try await project.policy.add(
    Rule("tests-are-evidence", deny: .write("/workspace/tests/**"))
)
print(rule.describe())
Output
rule       tests-are-evidence
denies     write /workspace/tests/**
policy     sha256 9a41…e6f2, narrows every grant on quickstart

Computer.service

func service(_ name: String, tools: [String: String]) async throws -> Service

Exposes project functions as named tools and publishes them over MCP and HTTP. Every caller presents a grant from your kernel.

swift
let pricing = try await project.service(
    "pricing",
    tools: ["quote": "src/pricing.py:quote", "refund": "src/pricing.py:refund"]
)
let endpoint = try await pricing.publish(protocols: [.mcp, .http])
print(endpoint.describe())
Output
service    pricing, from quickstart @ main 2f60a91
tools      quote · refund
mcp        https://127.0.0.1:9440/pricing/mcp
http       https://127.0.0.1:9440/pricing/v1, OpenAPI at /openapi.json
admits     callers that hold a grant from your kernel

Service.grant

func grant(to: String, tools: [String], limits: Rate? = nil, budget: Money? = nil, expiresIn: Expiry) throws -> Authority

Grants a caller named tools on the service, with a call rate, a budget spent at each tool's price, and an expiry.

swift
let access = try pricing.grant(
    to: "did:chio:z6MkbY4…e1R",
    tools: ["quote"],
    limits: Rate(calls: 100, per: .hours(1)),
    budget: .usd(2),
    expiresIn: .hours(24)
)
print(access.describe())
Output
grant      cap-01ab…77d1, signed by your kernel
to         did:chio:z6MkbY4…e1R
allows     pricing.quote
limits     100 calls per hour
budget     USD 2.00, USD 0.01 per call
expires    in 24 hours

Service.require

func require(approval: Approver, when condition: String) async throws -> RuleRef

Pauses each matching call until the approver signs for that exact request.

swift
let rule = try await pricing.require(approval: .you, when: "quote.percent > 50")
print(rule.describe())
Output
rule       quote.percent > 50 waits for did:chio:z6Mkf3…Qp9 (you)
binds      one signature to one request

Service.events

func events() -> AsyncThrowingStream<CallEvent, Error>

Streams calls to the service as your kernel decides them.

swift
for try await call in pricing.events() {
    print(call.summary)
}
Output
00:00  z6MkbY4  quote   sku-118 at 10%        allow     USD 0.01
00:04  z6MkbY4  refund  order-77              refused   not in the grant
00:05  z6MkQx8  quote   sku-118 at 10%        refused   no grant from your kernel
00:09  z6MkbY4  quote   sku-301 at 80%        pending   approval required
00:41  z6MkbY4  quote   sku-301 at 80%        allow     USD 0.01

Service.usage

func usage(since: Expiry) async throws -> Usage

Summarizes each caller's calls, refusals, approvals, and spend, computed from that caller's signed receipts.

swift
print(try await pricing.usage(since: .hours(1)))
Output
caller             calls   refused   approvals   spent
z6MkbY4…e1R        100     2         1           USD 1.00
z6MkQx8…7Ha        0       1         0           USD 0.00

Computer.treaty

func treaty(with partner: Partner, actions: [String], expiresIn: Expiry) async throws -> Treaty

Agrees terms with a partner: the actions you cooperate on and what each requires. Both kernels sign, and each computes the intersection of the two governance ladders, so the stricter requirement wins.

swift
let treaty = try await project.treaty(
    with: partner,
    actions: ["workspace.read", "workspace.write", "model.invoke", "merge"],
    expiresIn: .days(7)
)
print(treaty.describe())
Output
treaty           trt-01aa…4c19, signed by both kernels
participants     you · partner (did:chio:z6MkpA7…c2T)
action           you       them      admitted as
workspace.read   allow     allow     either kernel admits under its own policy
workspace.write  allow     allow     either kernel admits under its own policy
model.invoke     allow     allow     charged at your door
merge            co-sign   co-sign   both kernels sign
expires          in 7 days

Treaty.revoke

func revoke() async throws

Ends the treaty and every grant issued under it, including grants the partner's agents delegated to each other. The revocation reaches the partner's kernel over iroh, and its next call is refused.

swift
try await treaty.revoke()
for try await event in run2.events() {
    print(event.summary)
}
Output
00:00  them  admitted   "add banker's rounding as an option" under trt-01aa…4c19
00:04  you   revoked    trt-01aa…4c19, revocation root sent over iroh
00:05  them  refused    fixer-1 write /workspace/src/pricing.py: treaty revoked
00:05  them  stopped    their work closed, no effects after revocation

Computer.mailbox

func mailbox(_ name: String, partner: Partner, treaty: Treaty) async throws -> Mailbox

Opens a mailbox shared with a partner under a treaty. Each message is sent and claimed under its sender's or reader's own grant.

swift
let reviews = try await project.mailbox("reviews", partner: partner, treaty: treaty)
print(reviews.describe())
Output
mailbox    reviews, under trt-01aa…4c19
senders    partner's agents, each under its own grant
readers    your agents that hold a reads grant

firstPassing

func firstPassing(_ runs: [Run], check: String) async throws -> Run

Waits on several runs and returns the first whose sealed fork passes the check. The other runs are cancelled, and their receipts stay in history.

swift
let ours = try await fixer.run("fix issue #414", on: forkA, authority: grantA)
let theirs = try await partner.exec("fix issue #414", on: forkB, authority: grantB)
let winner = try await firstPassing([ours, theirs], check: "pytest")
print(winner.describe())
try await project.apply(winner.changes)
Output
winner     run-01ab…0c7d, partner on fork c4e81b7
check      pytest: 14 passed
others     cancelled, receipts kept in history

Program composition

static func & (lhs: Program, rhs: Program) -> Program; static func | (lhs: Program, rhs: Program) -> Program

Composes boot programs, the pinned descriptors your project exports. & runs programs at once and | runs them in sequence; Swift binds & tighter, so the expression below needs no parentheses. A fork started with a boot program runs it under the fork's grant.

swift
let boot = Programs.reproduce & Programs.survey | Programs.patch | Programs.verify
let fork = try await project.fork(boot: boot)
print(fork.describe())
Output
boot       (reproduce & survey) | patch | verify
fork       a3d90f1 of quickstart, base main 2f60a91

Money.usd

static func usd(_ amount: Decimal) -> Money

Constructs an exact dollar amount for budgets and prices. Money wraps Decimal, so cents are exact. Parameters typed Money accept the shorthand .usd(2).

swift
print(Money.usd(2))
print(Money.usd(Decimal(string: "0.01")!) * 100)
Output
USD 2.00
USD 1.00

ChioError.applyConflict

case ChioError.applyConflict(base: String, current: String); var isApplyConflict: Bool

Apply refuses to publish when main moved after the fork was taken. Nothing changes; fork again from the new main and reapply.

swift
do {
    try await project.apply(fork.changes)
} catch let conflict as ChioError where conflict.isApplyConflict {
    print(conflict.localizedDescription)
}
Output
main moved from 7c2e1d0 to 9e03a4b; fork 51c07ae was not applied

How the Computer reaches the kernel

Each grant is a chio.capability.v1 token signed by your kernel. Each operation in a run is a mediated call, and each event carries the id of a chio.receipt.v1 receipt in the store that history reads. Policy rules compile into the HushSpec policy every grant on the computer is checked against. The Computer and the Kernel maps each Computer object onto its kernel mechanism. The low-level clients below speak to the same kernel and the same records without the Computer layer.

Mobile kernel

ChioKernel embeds the portable decision core in the app process. It evaluates requests against a policy you ship with the app, signs receipts with a key held in the Secure Enclave, verifies capabilities and passports offline, and attests the device with App Attest. A receipt that fails verification throws.

Your iOS appswift
import Chio

let kernel = ChioKernel()
do {
    _ = try kernel.verifyMobileReceipt(receiptJson: "{}", evidenceJson: "{}")
} catch {
    print("rejected: \(error)")
}

An empty receipt is rejected before any signature check. App Attest needs a supported device and server-side verification of the challenge; a simulator build verifies receipts but cannot attest.

Read more in Portable Kernel.