# Python SDK

The package provides synchronous and asynchronous clients. It requires Python 3.9+ and uses httpx for HTTP requests.

## Installation

```bash
pip install getstack
```

## Quick Start

Sign in once on your development machine:

```bash
npx @getstackrun/cli auth login
```

```python
from getstack import Stack

stack = Stack()
agents = stack.agents.list()

# Open a Mission for one agent and issue its Passport in one call.
started = stack.missions.start(
    agent_id="agt_support",
    mission={"intent_summary": "Post the daily support update", "intent_services": ["slack"]},
)
token = started["passport"]["token"]

# Completing the Mission revokes its Passports.
stack.missions.complete(started["mission_id"])
```

Stack() creates an API client and can use the local OAuth profile written by the CLI. A fleet worker uses Stack(agent_id=agent_id) to sign requests with its locally stored key. AsyncStack exposes the same methods with await.

## Fleet setup

Connect the service first and name an enrolled provisioner in the policy. wait_for_approval opens the returned approval URL and waits for the operator's decision. create_worker returns Stack(agent_id=agent_id), or AsyncStack for the async example. Enrollment stores the worker's key locally and needs no separate operator approval.

```python
from getstack.errors import StackError

def setup_fleet(*, operator, provisioner, policy, policy_key, worker_name,
                enrollment_key, create_worker, wait_for_approval):
    try:
        activated = operator.fleets.activate(policy, idempotency_key=policy_key)
    except StackError as error:
        approval = error.details
        if (error.code != "GOVERNANCE_APPROVAL_REQUIRED"
                or not approval.get("approval_id") or not approval.get("approval_url")):
            raise
        wait_for_approval(approval)
        activated = operator.fleets.activate(policy, idempotency_key=policy_key,
            governance_approval_id=approval["approval_id"])
    enrolled = provisioner.fleets.enroll_local(activated["id"],
        name=worker_name, idempotency_key=enrollment_key)
    worker = create_worker(enrolled["agent_id"])
    session = worker.fleets.session()
    return {"policy_id": activated["id"], "agent_id": enrolled["agent_id"],
            "worker": worker, "session": session}
```

```python
from getstack.errors import StackError

async def setup_fleet(*, operator, provisioner, policy, policy_key, worker_name,
                      enrollment_key, create_worker, wait_for_approval):
    try:
        activated = await operator.fleets.activate(policy, idempotency_key=policy_key)
    except StackError as error:
        approval = error.details
        if (error.code != "GOVERNANCE_APPROVAL_REQUIRED"
                or not approval.get("approval_id") or not approval.get("approval_url")):
            raise
        await wait_for_approval(approval)
        activated = await operator.fleets.activate(policy, idempotency_key=policy_key,
            governance_approval_id=approval["approval_id"])
    enrolled = await provisioner.fleets.enroll_local(activated["id"],
        name=worker_name, idempotency_key=enrollment_key)
    worker = create_worker(enrolled["agent_id"])
    session = await worker.fleets.session()
    return {"policy_id": activated["id"], "agent_id": enrolled["agent_id"],
            "worker": worker, "session": session}
```

## Fleet Mission workflow

```python
import hashlib
import json
from getstack.errors import StackError

def run_fleet_mission_example(stack, request, provider_url="https://slack.com/api/chat.postMessage"):
    started = stack.missions.start(request)
    repeated = stack.missions.start(request)
    assert repeated["mission_id"] == started["mission_id"]
    operation_id = hashlib.sha256(json.dumps([started["mission_id"], "support-update"]).encode()).hexdigest()
    response = stack.proxy.request("slack", provider_url, "POST",
        body={"channel": "C123", "text": "Support update"},
        passport_token=started["passport"]["token"], authority_request_id=operation_id)
    assert response.status == 200
    try:
        stack.proxy.request("slack", provider_url, "POST", body={"channel": "OTHER", "text": "Support update"},
            passport_token=started["passport"]["token"], authority_request_id=operation_id + "_denied")
    except StackError as error:
        assert error.status_code == 403
    else:
        raise AssertionError("Expected channel restriction")
    before = stack.missions.get(started["mission_id"])
    renewed = stack.missions.renew(started["mission_id"])
    after = stack.missions.get(renewed["mission_id"])
    assert renewed["mission_id"] == started["mission_id"]
    assert after["fleet"]["limits"] == before["fleet"]["limits"]
    assert after["fleet"]["usage"] == before["fleet"]["usage"]
    completed = stack.missions.complete(started["mission_id"], output={"done": True})
    assert completed["terminal_state"] == "completed_successful"
    stopped = stack.missions.start({**request, "idempotency_key": request["idempotency_key"] + "-stop"})
    stack.missions.revoke(stopped["mission_id"], reason="operator_initiated_clean")
    try:
        stack.missions.renew(stopped["mission_id"])
    except StackError:
        pass
    else:
        raise AssertionError("Expected revoked Mission")
    return {"mission_id": started["mission_id"], "operation_id": operation_id, "completed": True, "revoked": True}
```

```python
import hashlib
import json
from getstack.errors import StackError

async def run_fleet_mission_example(stack, request, provider_url="https://slack.com/api/chat.postMessage"):
    started = await stack.missions.start(request)
    repeated = await stack.missions.start(request)
    assert repeated["mission_id"] == started["mission_id"]
    operation_id = hashlib.sha256(json.dumps([started["mission_id"], "support-update"]).encode()).hexdigest()
    response = await stack.proxy.request("slack", provider_url, "POST",
        body={"channel": "C123", "text": "Support update"},
        passport_token=started["passport"]["token"], authority_request_id=operation_id)
    assert response.status == 200
    try:
        await stack.proxy.request("slack", provider_url, "POST", body={"channel": "OTHER", "text": "Support update"},
            passport_token=started["passport"]["token"], authority_request_id=operation_id + "_denied")
    except StackError as error:
        assert error.status_code == 403
    else:
        raise AssertionError("Expected channel restriction")
    before = await stack.missions.get(started["mission_id"])
    renewed = await stack.missions.renew(started["mission_id"])
    after = await stack.missions.get(renewed["mission_id"])
    assert renewed["mission_id"] == started["mission_id"]
    assert after["fleet"]["limits"] == before["fleet"]["limits"]
    assert after["fleet"]["usage"] == before["fleet"]["usage"]
    completed = await stack.missions.complete(started["mission_id"], output={"done": True})
    assert completed["terminal_state"] == "completed_successful"
    stopped = await stack.missions.start({**request, "idempotency_key": request["idempotency_key"] + "-stop"})
    await stack.missions.revoke(stopped["mission_id"], reason="operator_initiated_clean")
    try:
        await stack.missions.renew(stopped["mission_id"])
    except StackError:
        pass
    else:
        raise AssertionError("Expected revoked Mission")
    return {"mission_id": started["mission_id"], "operation_id": operation_id, "completed": True, "revoked": True}
```

stack.missions starts and manages server-side Missions. The with stack.passports.mission(agent_id, intent, services) context manager opens a Mission and its Passport in one call (POST /v1/missions/start), completes the Mission on exit and revokes it if the block raises. Pass mission_id="ms_..." to bind an existing Mission instead; the helper then leaves that Mission open.

## Services

### stack.fleets and stack.missions

```python
stack.fleets.list()
stack.fleets.list_page(page=1, limit=20)
stack.fleets.get(policy_id)
stack.fleets.membership(agent_id)
stack.fleets.members_page(policy_id, page=1, limit=20)
stack.fleets.activate(policy, idempotency_key=key, governance_approval_id=approval_id)
stack.fleets.revise(policy_id, policy, expected_revision=revision, idempotency_key=key, governance_approval_id=approval_id)
stack.fleets.members(policy_id)
stack.fleets.revoke_member(policy_id, agent_id)
stack.fleets.revoke(policy_id)
stack.fleets.enroll_local(policy_id, name=name, idempotency_key=key)
stack.fleets.enroll_workload_local(policy_id, name=name, idempotency_key=key)
stack.fleets.session(fleet_policy_id)
stack.missions.start(agent_id="agt_...", mission={"intent_summary": "...", "intent_services": [...]}, passport={...})
stack.missions.start(fleet_request)  # fleet form: dict with fleet_policy_id
stack.missions.open("summary", agent_id="agt_...", intent_services=[...], expires_in_seconds=3600)
stack.missions.renew(mission_id)
stack.missions.complete(mission_id, output={"done": True})
stack.missions.revoke(mission_id, reason="operator_initiated_clean")
```

The operator form of missions.start returns a dict with mission_id, claim_id, expires_at and passport (token, jti, expires_at). passport is optional and takes issue fields such as scopes, ttl_seconds and intent. missions.open assigns the Mission to agent_id when given. Completing or revoking a Mission revokes every Passport bound to it, for any revoke reason.

### stack.agents

```python
stack.agents.register("name", description="optional")
stack.agents.list()
stack.agents.get("agt_...")
stack.agents.update("agt_...", status="suspended")
stack.agents.delete("agt_...")
```

### stack.passports

```python
mission = stack.missions.open("Post the daily support update",
                              agent_id="agt_...", intent_services=["slack"])
passport = stack.passports.issue(
    agent_id="agt_...",
    mission_ids=[mission["mission_id"]],
    authority_binding_ids=["abn_..."],
)
print(passport.token)
```

mission_ids is required and holds exactly one live Mission ID; the SDK raises ValueError otherwise. The Mission must be assigned to the agent or unassigned. The Passport never outlives its Mission, and refresh and delegation fail once the Mission is completed, revoked or expired.

The issue helper attaches active bindings and the Passport receives opaque authority references. Authority management and the native receiver protocol use the [Authority REST API](/docs/api/authority). The async client accepts the same `authority_binding_ids` argument.

### stack.skills

```python
# Publishing
stack.skills.publish(
    name="my-skill",
    description="...",
    input_schema={...},
    output_schema={...},
    execution_mode="sealed",
)

# Browsing
skills = stack.skills.browse(query="financial analysis", tags="finance")

# Invoking
result = stack.skills.invoke(
    "skl_...",
    agent_id="agt_...",
    input={"data": "..."},
)

# Polling
completed = stack.skills.poll(result.id, timeout_seconds=60)

# Requests
stack.skills.post_request(description="I need...", tags=["finance"])
stack.skills.suggest_composition("sreq_...")
```

### stack.identity

```python
providers = stack.identity.list_providers()
# Start a provider shown as available for this deployment.
provider_key = providers[0].key
session = stack.identity.initiate_verification(provider_key)
stack.identity.complete_verification(provider_key, session.session_ref)
claims = stack.identity.list_claims()
stack.identity.revoke_claim("clm_...")
stack.identity.replace_service_requirement(service_id, requirement_or_none)
```

## Authentication Methods

```python
# Local OAuth profile created by the CLI
stack = Stack()

# Existing dashboard session
stack = Stack.from_session(session_token)
```

### stack.dropoffs / stack.proxy / stack.scan / stack.delivery_methods / stack.security_events

```python
# Drop-offs
dof = stack.dropoffs.create(from_agent_id="agt_a", to_agent_id="agt_b", schema={...})  # a list names a group: ["agt_b", "agt_c"]
# Each agent passes the Passport from its own stack.missions.start(...).
stack.dropoffs.deposit(dof["id"], data={...}, agent_id="agt_a", passport_token=producer_token)
stack.dropoffs.collect(dof["id"], agent_id="agt_b", passport_token=consumer_token)

# Proxy
resp = stack.proxy.request(service="slack", method="POST",
                           url="https://slack.com/api/chat.postMessage",
                           body={"channel": "C0123", "text": "hi"},
                           passport_token=passport.token,
                           on_operation_id=save_operation_id,
                           connection="work")  # only when the agent may use several Slack connections
operation = stack.proxy.get_operation(resp.operation_id,
                                      passport_token=passport.token,
                                      include_response=True)

# Content scan — run prompt-injection detector on retrieved content
result = stack.scan.scan(
    content=email_body,
    context="email",
    source=sender_address,
)
if result["verdict"] == "critical":
    raise RuntimeError(f"Indirect injection caught: {result['match']['pattern_id']}")
stack.scan.usage()  # monthly quota

# Delivery methods (email, SMS or webhook; each is verified before it delivers)
dest = stack.delivery_methods.add("webhook", "https://…")
stack.delivery_methods.send_verification_code(dest["id"])
stack.delivery_methods.verify(dest["id"], code="123456")
stack.delivery_methods.test(dest["id"])

# Security events
events = stack.security_events.list(limit=50)
```

A notification rule routes events to verified delivery methods. The Python client has no helper for creating one; send `POST /v1/notifications/channels` with `destination_ids`, `events` and an optional `min_severity`. See [Notifications API](/docs/api/notifications).

Non-GET proxy calls generate an operation ID before network I/O. Durable workers should use `on_operation_id` to persist it, then reuse `authority_request_id` only for the unchanged request. Sync and async clients both provide `get_operation()` for recovery. See [Proxy operation recovery](/docs/api/proxy#operation-recovery).

### stack.audit / stack.reviews

```python
# Tail recent entries — newest-first. Pass since (epoch ms) for
# incremental polling; pass agent_id or passport_jti to narrow.
data = stack.audit.list(limit=20, agent_id="agt_support")
for entry in data["entries"]:
    print(entry["action"], entry["outcome"])
watermark = data["max_timestamp"]

# Anchor the chain head externally to prove no row was rewritten later.
head = stack.audit.chain_head()

# Walk the chain and verify every entry's hash + link integrity.
result = stack.audit.verify_chain()
assert result["valid"], result.get("first_break")

# Checkout reviews
pending = stack.reviews.list(status="flagged")
stack.reviews.decide(checkout_id="cout_abc", decision="approved",
                    notes="notion use was ancillary")
```

Cascade revokes write one `passport.revoke` entry plus one`passport.revoke_cascade` per child — filter by`passport_jti=` to see the chain for a single passport. The Python client has no export helper; use `GET /v1/audit/export` for date-range exports.

## Agent accounts

`stack.accounts` opens an agent with its pieces at once, with no approval. Calls the account's agent makes take its Passport as `passport_token`; the operator calls without one. `monthly_budget_cents` is optional and needs controls; without it, prepaid credit is the limit. Texts and calls go to any country Twilio can reach, at cost: a destination Twilio has no price for or does not allow raises `DestinationNotAvailableError` (422, reason `no_price` or `refused_by_twilio`), and a number on the do-not-contact list raises `RecipientOptedOutError`. A call is paid for 10 minutes at a time; `max_seconds` runs from 30 to 14400, which is the default.`reply_to_message` names the received message a send, text or call answers; a policy that sets the account's recipients to `"per_mission"` requires it.

```python
account = stack.accounts.open({"name": "Support"}, idempotency_key="open-support-1")

stack.accounts.get(account["id"])
stack.accounts.list(limit=50)
stack.accounts.close(account["id"])

# Messages and sending
page = stack.accounts.messages.list(account_id, channel="email", passport_token=token)
stack.accounts.send_email(account_id, {"to": "a@example.com", "subject": "Hi", "body": "..."},
                          passport_token=token)

# Several recipients, copies and attachments. OpenMail takes one To address: the first is the To,
# further ones are delivered as Cc. An attachment is a drive file by id, or an inline file as bytes
# (at most 10 MB in all; attachments come to at most 25 MB).
stack.accounts.send_email(account_id, {
    "to": ["a@example.com", "b@example.com"],
    "cc": ["c@example.com"],
    "bcc": ["audit@example.com"],
    "subject": "Report",
    "body": "Attached.",
    "attachments": [
        {"file_id": drive_file_id},
        {"filename": "report.pdf", "content_type": "application/pdf", "content": pdf_bytes},
    ],
}, passport_token=token)

# Answer a received email in its thread, or forward it as a new email
stack.accounts.reply_email(account_id, message_id, {"body": "Thanks.", "reply_all": True}, passport_token=token)
stack.accounts.forward_email(account_id, message_id, {"to": "d@example.com", "body": "For you."}, passport_token=token)

stack.accounts.send_sms(account_id, {"to": "+14155550123", "body": "..."}, passport_token=token)

# A policy can set the account's recipients.email, sms and call to "per_mission": the send then names the
# received message it answers and goes only to who wrote it (an unknown id is a NotFoundError)
stack.accounts.send_email(account_id, {"to": "a@example.com", "subject": "Re: order", "body": "Done",
                                       "reply_to_message": "amsg_..."}, passport_token=token)

# The agent's own Telegram bot (a bot cannot message a chat first): answer a chat that wrote to it
stack.accounts.telegram.start(account_id)  # the single-use link the owner opens in Telegram to have the bot made
stack.accounts.send_telegram(account_id, {"chat_id": "42", "text": "..."}, passport_token=token)

# Your own mail domain for agent inboxes: publish the returned DNS records, then verify
domain = stack.accounts.mail_domains.connect("mail.example.com")
stack.accounts.mail_domains.verify(domain["id"])
stack.accounts.mail_domains.list()

# The do-not-contact list (list and add: owner, admin or the account's agent; remove: owner or admin): numbers that texted STOP or were added
stack.accounts.opt_outs.add("+14155550123")  # owner, admin or the account's agent
listed = stack.accounts.opt_outs.list()
stack.accounts.opt_outs.remove(listed["opt_outs"][0]["id"])  # texts and calls to it go through again

# The blocked-callers list (list and add: owner, admin or the account's agent; remove: owner or admin): an incoming call from a listed number is turned away before it rings
stack.accounts.blocked_callers.add("+14155550123")
blocked = stack.accounts.blocked_callers.list()
stack.accounts.blocked_callers.remove(blocked["blocked_callers"][0]["id"])  # its calls ring again

# Workspace, browser, purchases
run = stack.accounts.workspace.exec(account_id, "git clone https://example.com/repo.git && ls", passport_token=token)
stack.accounts.workspace.write_file(account_id, run["workspace"]["id"], "notes.txt", content_text="hello", passport_token=token)
stack.accounts.workspace.list()  # every workspace you may use, with whose it is and whether it is shared
stack.accounts.workspace.set_sharing(account_id, run["workspace"]["id"], False)  # owner or admin
stack.accounts.workspace.stop(account_id, run["workspace"]["id"])
session = stack.accounts.browser.start_session(account_id, passport_token=token)
stack.accounts.browser.navigate(account_id, session["session_id"], "https://shop.example", passport_token=token)
purchase = stack.accounts.browser.checkout(account_id, session["session_id"],
                                           {"merchant_origin": "https://shop.example",
                                            "amount_minor": 1299, "currency": "USD"},
                                           passport_token=token)
```

Other errors: `AccountPieceNotReadyError` (`piece`, `state`) and `AgentBudgetExceededError` (`remaining_cents`).

### stack.wakes and stack.calendar

```python
queue = stack.wakes.list(agent_id, status="open", passport_token=token)
stack.wakes.acknowledge(agent_id, queue["wakes"][0]["id"], passport_token=token)

stack.wakes.set_settings({"quiet_start": "22:00", "quiet_end": "07:00", "time_zone": "Europe/Stockholm",
                          "webhook_url": "https://agent.example/wake"}, agent_id)
stack.wakes.create_rule({"name": "Customer mail", "source": "email", "task": "Answer the customer."}, agent_id)
stack.wakes.create_schedule(agent_id, {"name": "Morning", "cron": "0 8 * * 1-5", "task": "Check the day."})
stack.wakes.rotate_webhook_secret(agent_id)
stack.wakes.test_webhook(agent_id)

stack.calendar.list_events(account_id, role="attendee", passport_token=token)
stack.calendar.agenda(account_id, "2026-11-01", "2026-11-30", time_zone="Europe/Stockholm")
stack.calendar.create_event(account_id, {"title": "Review", "start": "2026-11-10T10:00", "time_zone": "Europe/Stockholm",
                                         "guests": ["olivia@example.com"], "meeting": True}, passport_token=token)
stack.calendar.respond(account_id, event_id, "accept", passport_token=token)
# The agent in the room of one of its events (made with meeting=True); STACK runs no model
turn = stack.meetings.join(account_id, {"event_id": event_id}, passport_token=token)
stack.meetings.say(account_id, turn["meeting"]["id"], text="Hello.", wait_seconds=10, passport_token=token)
stack.meetings.chat(account_id, meeting_id, "A link.") ; stack.meetings.leave(account_id, meeting_id)
stack.meetings.get_voice(account_id) ; stack.meetings.set_voice(account_id, {"voice": "Claire", "language": "fr"})
# RentAHuman: the agent hires people through the customer's own account; the key stays in STACK, the agent signs the payment with its own wallet key
start = stack.rentahuman.join(account_id, country="US", accept_terms=True, passport_token=token)   # nothing is taken
stack.rentahuman.complete_join(account_id, start["join_id"], sign_rentahuman_payment(wallet_key, start), passport_token=token)
stack.rentahuman.join_with_key(account_id, wallet_key, country="US", accept_terms=True, passport_token=token)  # both steps
stack.rentahuman.fund(account_id, 2500, passport_token=token) ; stack.rentahuman.get(account_id)
# Any connected service that speaks MCP over HTTP, through the credential proxy; the answers are untrusted
stack.proxy.service_tools("rentahuman", passport_token=token)   # connection="work" picks one of several connections
stack.proxy.service_call_tool("rentahuman", "send_message", {"conversationId": cid, "content": "Thursday."}, passport_token=token)
```

A wake starts an agent with a task, with or without an agent account. An agent id addresses one agent; without one the settings and rules are your defaults; the calendar takes the account id. The agent's own calls take its Passport; settings, rules, schedules and the webhook are owner or admin only, and a webhook signing secret is returned once, never to an OAuth token. On the agent's own endpoint, `verify_wake_webhook` checks the Standard Webhooks signature and raises `WakeSignatureError` when it is stale or wrong. A wake carries facts, never what a stranger wrote; a decision wake's event names the pending item and how it ended.

Every request STACK signs to your server (a wake-up, a notification, an inbound-webhook forward, a network revocation push, the control socket) is a Standard Webhooks message. `verify_webhook` checks any of them and raises `WebhookSignatureError` with a reason; a `ReplayGuard` notices a repeated message id.

### stack.billing

```python
status = stack.billing.subscriptions()  # platform, controls, this_month
checkout = stack.billing.subscribe_platform()  # checkout_url, session_id, trial
stack.billing.subscribe_controls(governance_approval_id=None)
```

The platform and controls subscriptions are card subscriptions through Stripe Checkout, with a free trial the first time: open `checkout_url`, then read the state back with `subscriptions()`. The two writes are owner or admin actions and wait for a human approval outside a dashboard session: retry the same call with `governance_approval_id` once it is approved. A `SUBSCRIPTION_CONFLICT` (409) means it is already on or the account is one of STACK's own; `subscribe_controls` needs the platform subscription first. When the controls subscription lapses, controls switch off and the agent accounts keep running.

### Connect links and approvals

```python
link = stack.services.create_connect_link("github", scopes=None, connection_name="work")  # link_id, status, url
stack.services.rename(connection_id, "personal")  # owner or admin
stack.services.get_connect_link(link["link_id"])  # pending, connected (connection_id) or expired
stack.services.list_connect_links()  # the links still waiting, newest first
detail = stack.governance.get_approval(approval_id)  # approval, payload_hash, approval_url
```

A connect link connects a service without the credential passing through your program or a chat: open the returned `url` (the only copy) in a browser signed in to STACK. It works once, expires after 10 minutes, and any number can be open at once. An account can hold several named connections of one service: the first needs no `connection_name` (it is called `default`), a second does, on `connect`, `connect_custom` and `create_connect_link`. A call that may use more than one connection of the service passes `connection` (a name in any case, or its id) to `proxy.request`, `service_tools` and `service_call_tool`; without it the call raises `ConnectionAmbiguousError` (409), whose `connections` lists the id and name of each it may use. `get_connect_link` never returns the URL. `get_approval` only reads: a person decides an approval in the dashboard.

### Wallet key

The agent's own key is the wallet's only signer; STACK holds no key to any wallet. Create it on the agent's machine; every function raises `WalletKeyInSandboxError` inside the STACK sandbox. `wallet.pay_url` buys from an x402 seller in one call: it pays the seller's 402 from the account's wallet, through STACK's checks, and asks again;`result.response` is what was bought. Only USDC on Base with x402's exact scheme, over https; anything else raises `X402PaymentError` before STACK is asked.

```python
from getstack import WalletPaymentTarget, generate_agent_wallet_key, load_agent_wallet_key, sign_wallet_payment

key = generate_agent_wallet_key()
stored = key.export_private_key()  # "wallet-auth:...", keep it in your own secret store
wallet = {"agent_public_key": key.public_key, "per_payment_cap_usdc": 5, "daily_cap_usdc": 50}

key = load_agent_wallet_key(stored)
details = next(p for p in account["pieces"] if p["kind"] == "wallet")["details"]
target = WalletPaymentTarget(app_id=details["privy_app_id"], wallet_id=details["wallet_id"],
                             typed_data=typed_data)
stack.accounts.wallet.pay(account_id, sign_wallet_payment(key, target), passport_token=token)

# Or buy from an x402 seller in one call
result = stack.accounts.wallet.pay_url(account_id, "https://seller.example/report", key=key, max_cents=100,
                                       passport_token=token)
report = result.response.content
```

## Async client

For async applications, import `AsyncStack`. All service methods are awaitable; the service surface mirrors the sync client exactly.

```python
from getstack import AsyncStack

stack = AsyncStack()

async with stack:
    agent = await stack.agents.register("my-agent")
    mission = await stack.missions.open("...", agent_id=agent.id, intent_services=[...])
    passport = await stack.passports.issue(agent_id=agent.id, mission_ids=[mission["mission_id"]],
                                           intent="...", services=[...])
    # ...
    await stack.missions.complete(mission["mission_id"])  # also revokes the Passport
```

## Error Handling

```python
from getstack import Stack, NotFoundError, ForbiddenError

try:
    agent = stack.agents.get("agt_nonexistent")
except NotFoundError:
    print("Agent not found")
except ForbiddenError:
    print("Access denied")
```
