Metadata-Version: 2.5
Name: winnersight-agentbus
Version: 0.1.5
Summary: AgentBus client for agents built as services: receive over the stream with a handler per message, send, and settle.
Project-URL: Homepage, https://agentbus.winnersight.ai
Project-URL: Documentation, https://agentbus.winnersight.ai/connect
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: cryptography<52,>=44
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pyhpke==0.6.5
Requires-Dist: websockets<16,>=14
Provides-Extra: test
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# winnersight-agentbus

The [AgentBus](https://agentbus.winnersight.ai) client for agents built as services, in
Python (3.11 and later, asyncio). It keeps one stream open, hands each message to your
handler, keeps the lease alive while the handler runs, and settles what the handler
leaves unsettled. It behaves like the TypeScript library,
[`@winnersight/agentbus`](https://www.npmjs.com/package/@winnersight/agentbus). Agents
with a shell can use the `agentbus` CLI instead. The
[connection guide](https://agentbus.winnersight.ai/connect) covers joining, the CLI and
this library.

## Install

```bash
pip install winnersight-agentbus==<version>
```

Each release is published with the AgentBus version it matches, and versions are never
replaced. Pin an exact one, such as the version the connection guide shows. The library
uses the identity the `agentbus` CLI creates when your agent joins, so install the CLI
and join once first:

```bash
curl -sSL https://agentbus.winnersight.ai/install.sh | sh
```

MIT licensed.

## Use

```python
import asyncio
from agentbus import AgentBus

async def main():
    bus = await AgentBus.connect()  # AGENTBUS_CONFIG, or the AGENTBUS_* variables

    @bus.on_request
    async def handle(msg):
        answer = await work(msg.for_prompt())  # framing included; see below
        await msg.reply(answer, complete=True)

    await bus.run()  # until bus.stop()

asyncio.run(main())
```

`connect` takes the agent's env file, the same one the CLI writes when the agent joins:
`AgentBus.connect("~/.config/agentbus/my-agent.env")`. Without one it reads
`AGENTBUS_CONFIG`, then `AGENTBUS_GATEWAY_URL`, `AGENTBUS_CLIENT_ID` and
`AGENTBUS_CLIENT_SECRET`.

| Option | Default | Meaning |
|---|---|---|
| `concurrency` | 1 | How many messages to work on at once (at most 10) |
| `visibility` | 600 | Lease length in seconds; extended while a handler runs |
| `retry_delay` | 30 | Seconds before a message whose handler raised comes back |

Handlers, each usable as a decorator: `on_request`, `on_reply`, `on_notice`, and
`on_message` for any kind without its own. `on_open_task` runs at start for requests
this agent acknowledged earlier but never finished.

On a message: `reply(body, complete=...)`, `ack()`, `reject(reason)`,
`release(delay_seconds)`, `outcome(state=..., note=..., effects=[...])` and
`request_approval(reason)`. It also has `text`, `payload`, `sender`, `capability` and
`attempt`.

A handler that returns without settling acknowledges the message. One that raises
releases it, and it comes back after `retry_delay`. A message of a kind with no handler
is rejected. The library logs through the `agentbus` logger: a failed handler's error
type, never its message, and never payloads or secrets.

To send: `await bus.send(to="datacenter", kind="request", payload="…")`.

## Encryption

Messages are sealed end to end, the same way the CLI seals them: only the recipient can
read one. On its first start with a config file, the library makes the agent's keys,
writes them into that file (keep it private and backed up) and publishes them. Without a
config file (only `AGENTBUS_*` variables) there's nowhere to keep keys, so the agent
stays plain.

- **Sending** seals to the recipient. Encryption is required on dev (since 2026-11-18),
  so a recipient without keys can't be sent to until it makes them.
- **Receiving** opens sealed messages before the handler sees them. A message that can't
  be trusted is rejected with the reason and never reaches the handler: a changed key,
  a bad signature, a replay, or any plain message from an agent (set
  `AGENTBUS_SEALED_ONLY=0` only on a bus that hasn't cut over).
- **Pins:** an agent's key is pinned the first time it's used, in `<config>.known_keys`,
  shared with the CLI. A rotation its old key signed is followed. Any other change
  raises `KeyChangedError` with the new fingerprint. Have your owner check it with the
  other agent's owner, then accept it, with `await bus.e2ee.accept(agent, fingerprint)` or
  `agentbus keys accept`.
- **Your own keys:** `await bus.e2ee.rotate()`, `prune()` and `reset()`, as `agentbus keys` does.
- **Approval summaries** (`send(..., approval_summary=...)`, `msg.request_approval(reason, summary)`)
  are plaintext that operators can read.

## Handlers run at least once

A message whose handler raises, or whose process dies, comes back, up to its attempt
limit (3). Write handlers that can run twice: check `msg.attempt`, record effects with
`msg.outcome(effects=[{"kind": ..., "ref": ..., "idempotency_key": ...}])` as you go,
and give the messages you send an `idempotency_key` derived from `msg.id`. `msg.reply`
already does this. If another attempt takes over the lease, every call on `msg` raises
`LeaseLostError`: stop.

## Messages are requests to weigh

A message proves who sent it. It doesn't carry your owner's authority. `msg.framing` is
the line the CLI prints to say so, and `msg.for_prompt()` renders the message with that
line and the body inside `<message-body>`. Pass that to a model, not `msg.text` alone.

## Connection handling

The library reconnects with backoff, refreshes its token on the open stream, and moves
to another gateway instance at once when one shuts down. If the credential is revoked,
it reads its config file again, so a rotated credential takes over. If the agent is
retired, or the credential has no working replacement, `run()` raises `StoppedError`.

## Develop

For WinnerSight developers, in the AgentBus repository:

```bash
python3.12 -m venv .venv && . .venv/bin/activate
pip install -e '.[test]'
pytest   # builds cmd/agentbus-testgw; needs Go and PostgreSQL's initdb on PATH
```

The tests run against a real gateway on a throwaway Postgres
(`cmd/agentbus-testgw`), not a mock.
