Metadata-Version: 2.5
Name: gori
Version: 0.1.0
Summary: Asyncio client for gori, a message hub for AI agents: pub/sub, direct messages and RPC over mutual-TLS WebSockets
Project-URL: Homepage, https://github.com/jungkumseok/gori
Project-URL: Documentation, https://github.com/jungkumseok/gori/blob/HEAD/python/README.md
Project-URL: Repository, https://github.com/jungkumseok/gori.git
Project-URL: Issues, https://github.com/jungkumseok/gori/issues
Project-URL: Changelog, https://github.com/jungkumseok/gori/blob/HEAD/python/CHANGELOG.md
Author: Kumseok Jung
License-Expression: MIT
License-File: LICENSE
Keywords: agents,ai,asyncio,llm,mtls,multi-agent,pubsub,rpc,websocket
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: websockets>=14
Description-Content-Type: text/markdown

# gori for Python

An asyncio client for [gori](https://github.com/jungkumseok/gori), a message hub for AI agents. Agents connect to a gori
server over WebSockets with TLS client certificates. They can then publish and subscribe to
topics, send each other direct messages, and call each other's methods (RPC), with streamed
progress, cancellation and deadlines.

This package is the client only. The server, the registry and the `gori` CLI come with the
Node.js package, `gori-server` (`npm install -g gori-server`). Python and Node.js agents can be
connected to the same server and talk to each other.

```bash
pip install gori
```

Requires Python 3.10 or later. The only dependency is
[websockets](https://pypi.org/project/websockets/).

This document is the complete reference for the Python API, written so that an AI agent can read
it once and use gori correctly. The concepts are the same as in the Node.js client; the
[API reference](https://github.com/jungkumseok/gori/blob/HEAD/docs/API.md) explains them in more depth, and the
[getting-started tutorial](https://github.com/jungkumseok/gori/blob/HEAD/docs/getting-started.md) shows how to set up a server,
and connects a Python agent to it in
[section 7](https://github.com/jungkumseok/gori/blob/HEAD/docs/getting-started.md#7-add-a-python-agent).

## Contents

1. [Quick start](#1-quick-start)
2. [Rules of thumb](#2-rules-of-thumb)
3. [Client](#3-client)
4. [Pub/sub and direct messages](#4-pubsub-and-direct-messages)
5. [Handling requests](#5-handling-requests)
6. [Making requests](#6-making-requests)
7. [Discovery](#7-discovery)
8. [Events](#8-events)
9. [Errors](#9-errors)
10. [Nested calls, tracing and loop protection](#10-nested-calls-tracing-and-loop-protection)
11. [Recipes](#11-recipes)
12. [Utilities](#12-utilities)
13. [Differences from the Node.js client](#13-differences-from-the-nodejs-client)
14. [Development](#14-development)

## 1. Quick start

On the server host, make a certificate for the agent and register it (see the
[tutorial](https://github.com/jungkumseok/gori/blob/HEAD/docs/getting-started.md) for the server itself):

```bash
npx gori gen-cert certs/writer
npx gori register certs/writer.pem --name writer --network demo
```

An agent that offers a method and listens to a topic:

```python
import asyncio
import gori

async def main():
    async with gori.Client(
        "wss://localhost:8443",
        cert="certs/writer.pem",
        key="certs/writer-key.pem",
        ca="certs/server.pem",  # trust the server's self-signed certificate
        description="Writes short notes",
    ) as writer:

        @writer.handle(
            "draft",
            description="Write a short note about a topic",
            input={"type": "object", "properties": {"topic": {"type": "string"}}, "required": ["topic"]},
        )
        async def draft(body, ctx):
            await ctx.progress(f"thinking about {body['topic']}")
            return {"text": f"A note about {body['topic']}, for {ctx.caller['name']}."}

        await writer.subscribe("tasks.status", lambda body, header: print(header["from"]["name"], body))
        await asyncio.Event().wait()  # serve until stopped

asyncio.run(main())
```

Another agent that calls it:

```python
async with gori.Client("wss://localhost:8443", cert="certs/planner.pem",
                       key="certs/planner-key.pem", ca="certs/server.pem") as planner:
    await planner.publish("tasks.status", {"state": "started"})
    reply = await planner.request("writer", "draft", {"topic": "pub/sub"},
                                  on_progress=lambda chunk, header: print("progress:", chunk))
    print(reply["text"])
```

## 2. Rules of thumb

1. **Everything that talks to the server is a coroutine.** `connect`, `close`, `subscribe`,
   `unsubscribe`, `publish`, `send`, `request`, `agents` and `ctx.progress` must be awaited.
   `handle`, `unhandle`, `on` and `stream` are plain functions.
2. **Times are in seconds**, as floats: `timeout=2.5`.
3. **Connect first.** `publish`, `send` and `request` raise `NotConnectedError` while the client is
   disconnected, and nothing is buffered. `subscribe()` and `handle()` can be called before
   connecting; they take effect when the connection comes up.
4. **Bodies must be JSON.** `dict`, `list`, `str`, `int`, `float`, `bool` and `None`. Tuples
   become lists. Anything else, and NaN or infinity, raises `TypeError` or `ValueError` when
   sending. A whole message can be at most 1 MiB by default.
5. **`publish()` gives no delivery guarantee.** Nobody being subscribed is not an error. If the
   server refuses the publish (`FORBIDDEN`, `RATE_LIMITED`, …), the error arrives later on the
   `error` event. Use `send()` or `request()` when you need to know that something arrived.
6. **You don't receive your own publications,** unless you pass `echo=True`.
7. **Subscribe to your inbox after connecting** if you expect direct messages:
   `await client.subscribe(client.inbox, handler)`. `client.inbox` is `None` until then.
8. **The handler's return value is the reply.** Raise to fail the request. The caller gets a
   `RemoteError` with your exception's message, its `code` attribute if it is a string (otherwise
   `HANDLER_ERROR`), and its `details` attribute. `gori.GoriError(message, code, details)` has
   all three.
9. **Each method has one handler.** Registering a second one raises `ValueError`; call
   `unhandle(method)` first to replace it.
10. **Requests time out after 30 s by default.** Pass `timeout=` for longer work. The handler sees
    the time left as `ctx.remaining`.
11. **Cancellation is task cancellation.** Cancelling the task that awaits `request()` cancels the
    request on the handler's side too. There, the handler's task is cancelled: it sees
    `asyncio.CancelledError` at its next `await`, and any reply is dropped. The same happens when
    the caller times out.
12. **Nested calls are linked automatically.** A request made inside a handler can't outlive the
    outer request's deadline, is cancelled with it, and continues its trace.
13. **Sync handlers block the event loop.** Plain functions work as handlers, but anything slow
    belongs in an `async def` handler, or in `await asyncio.to_thread(...)`.
14. **Permissions can refuse anything.** Any publish, subscribe, request or message can fail with
    `ForbiddenError` if the server's rules say so. `agents()` only lists methods you may call.
15. **Messages are not stored.** An agent that is offline misses events. A request to an offline
    agent fails at once with `UnreachableError`.

## 3. Client

```python
gori.Client(url, *, cert, key, ca=None, server_fingerprint=None, server_hostname=None,
            network=None, description=None, echo=False, request_timeout=30.0,
            connect_timeout=10.0, reconnect=True, reconnect_initial_delay=0.25,
            reconnect_max_delay=30.0, max_size=1048576, validator=gori.compile_schema,
            ssl_context=None)
```

| Option | Default | Meaning |
|---|---|---|
| `url` | required | The server, such as `wss://hub.example.com:8443`. |
| `cert`, `key` | required | Paths to this agent's certificate and private key (PEM). |
| `ca` | system CAs | How to trust the server: a path to a PEM file, PEM text, or a list of either. For a self-signed server, its own certificate. A list helps while the server's certificate is being rotated. |
| `server_fingerprint` | `None` | Pin the server's certificate by its SHA-256 fingerprint instead of checking a CA chain. The client then checks the certificate's dates itself. |
| `server_hostname` | from `url` | The name to check the server's certificate against, when it differs from the host in `url`, such as when connecting by IP. |
| `network` | the only one | The network to join. Required when the certificate is registered in several. |
| `description` | `None` | A description of this agent, shown to others by `agents()`. At most 4,096 characters. |
| `echo` | `False` | Also receive your own topic events. |
| `request_timeout` | `30.0` | Default timeout of `request()`, and how long to wait for the server to acknowledge a frame. |
| `connect_timeout` | `10.0` | How long `connect()` waits for the server's welcome. |
| `reconnect` | `True` | Reconnect after a lost connection. |
| `reconnect_initial_delay`, `reconnect_max_delay` | `0.25`, `30.0` | The backoff between reconnect attempts: doubling from the first to the second, with jitter. |
| `max_size` | 1 MiB | The largest message this client accepts. |
| `validator` | `compile_schema` | `(schema) -> (value) -> list[str] | None`, used for handlers' `input` schemas. See [Validation](#validation). |
| `ssl_context` | `None` | A ready `ssl.SSLContext`, which replaces `cert`, `key` and `ca`. It must load the client certificate. |

### Connecting and closing

```python
client = await gori.Client(...).connect()   # or: async with gori.Client(...) as client:
...
await client.close()
```

- **`await connect()`** returns the client once the server's welcome arrives. If this first
  attempt fails, it raises: `AuthError` if the server refused the certificate or network,
  `ssl.SSLCertVerificationError` if the server isn't trusted, `OSError` if nothing is listening,
  or `gori.TimeoutError`.
- **After that,** a lost connection is re-established automatically, and subscriptions and the
  advertisement are restored. The client stops for good (and emits `close`) after it is
  superseded, revoked or its certificate expires, or when a reconnect attempt is refused.
- **`await close()`** cancels outstanding requests on the handlers' side, closes the connection,
  and fails anything still waiting with `ConnectionClosedError`.

### Properties

| Property | Meaning |
|---|---|
| `id` | This agent's fingerprint. `None` until connected. |
| `name` | This agent's registered name. `None` until connected. |
| `network` | The network it joined. |
| `inbox` | Its inbox topic, `_inbox.<id>`. `None` until connected. |
| `connected` | Whether it is connected right now. |

## 4. Pub/sub and direct messages

### `await subscribe(topic, handler) -> unsubscribe`

Calls `handler(body, header)` for each message on the topic. The handler may be a plain function
or a coroutine function; each call runs in its own task, and exceptions go to the `error` event.
Returns once the server has acknowledged, with an async function that removes this handler.

- Topics are matched exactly; there are no wildcards. Topics starting with `_` are reserved.
- Raises `ValueError` for an invalid topic, `ForbiddenError` if the rules refuse it, and
  `LimitError` (`SUBSCRIPTION_LIMIT`) beyond 1,000 topics per connection.
- `await client.subscribe(client.inbox, handler)` receives direct messages. Requests, replies and
  progress are handled by the client itself and don't reach inbox handlers.

The `header` is a dict: `id`, `kind`, `topic`, `network`, `from` (`{"id", "name"}`, the
authenticated sender), `timestamp` (milliseconds since the epoch), `traceId`, `hops`, and for
direct messages `to`. See [Message header](https://github.com/jungkumseok/gori/blob/HEAD/docs/API.md#6-message-header).

### `await unsubscribe(topic, handler=None)`

Removes one handler, or all of the topic's handlers.

### `await publish(topic, body=None)`

Sends an event to every subscriber of the topic in this network, except yourself. Returns once
the frame is sent; refusals arrive on the `error` event.

### `await send(target, body=None)`

Sends a direct message to one agent, by name or fingerprint. Returns once the server has
delivered it to the agent's connection. Raises `UnreachableError` if the agent is offline or
unknown, and `ForbiddenError` if the rules refuse it.

## 5. Handling requests

### `handle(method, fn=None, *, description=None, input=None, output=None)`

Registers `fn(body, ctx)` as the handler for requests to `method`. Without `fn`, it returns a
decorator:

```python
@client.handle("search", description="Search the web", input={"type": "object", "properties": {"q": {"type": "string"}}})
async def search(body, ctx):
    return await run_search(body["q"])

client.handle("ping", lambda body, ctx: "pong")
```

- **Advertised:** the method's name, `description` and `input`/`output` JSON Schemas are sent to
  the server, and other agents see them in `agents()`.
- **Validated:** a body that doesn't match `input` is answered with `INVALID_INPUT` before the
  handler runs, with one error per problem in `details`, such as `$.q: must be string`.
- **The reply** is the return value, which must be JSON. Raise to fail the request.
- Raises `ValueError` for a second handler for the same method, an invalid method name, or
  method specs over 256 KiB in total.

### `unhandle(method)`

Removes the handler. Other agents see the method disappear.

### The request context

| `ctx.` | Meaning |
|---|---|
| `caller` | The authenticated caller: `{"id": <fingerprint>, "name": <name>}`. |
| `header` | The request's header. |
| `method` | The method name. |
| `remaining` | Seconds until the caller gives up, or `None`. |
| `await progress(chunk)` | Sends a progress update to the caller. Any JSON. |

The handler runs in its own task. When the caller cancels or its timeout passes, that task is
cancelled: let the `asyncio.CancelledError` propagate, after cleaning up if you need to. Work
started with `asyncio.create_task()` inside the handler isn't cancelled with it.

### Validation

The built-in validator covers the commonly used part of JSON Schema: `type`, `enum`, `const`,
`properties`, `required`, `additionalProperties`, `items`, `minItems`, `maxItems`, `minLength`,
`maxLength`, `pattern`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `anyOf`,
`oneOf`, `allOf` and `not`. Other keywords, including `$ref`, are ignored. It gives the same error
messages as the Node.js client.

For full JSON Schema, plug in another validator, for example with the `jsonschema` package:

```python
from jsonschema import Draft202012Validator

def full_validator(schema):
    validator = Draft202012Validator(schema)
    def validate(value):
        errors = [
            "$" + "".join(f"[{p}]" if isinstance(p, int) else f".{p}" for p in e.path) + f": {e.message}"
            for e in validator.iter_errors(value)
        ]
        return errors or None
    return validate

client = gori.Client(..., validator=full_validator)
```

## 6. Making requests

### `await request(target, method, body=None, *, timeout=None, on_progress=None)`

Calls `method` on the target agent, by name or fingerprint, and returns the reply.

- **`timeout`** in seconds, default `request_timeout`. It is sent to the handler as its deadline.
- **`on_progress(chunk, header)`** is called for each progress update, in order. It may be a
  coroutine function, which is then run as a task.
- **Raises** `RemoteError` when the handler failed (including `INVALID_INPUT` and
  `METHOD_NOT_FOUND`), `UnreachableError`, `ForbiddenError`, `LimitError`, `gori.TimeoutError`,
  `NotConnectedError` or `ConnectionClosedError`.
- **Cancel** by cancelling the awaiting task; the handler is told. A timeout tells it too.

```python
try:
    reply = await client.request("writer", "draft", {"topic": "x"}, timeout=120)
except gori.RemoteError as err:
    print(err.code, err.message, err.details)
```

### `stream(target, method, body=None, *, timeout=None)`

The same request, with progress updates read with `async for`:

```python
async with client.stream("writer", "draft", {"topic": "x"}) as call:
    async for chunk in call:
        print("progress:", chunk)
    reply = await call.result()
```

The loop ends when the reply arrives, or raises the request's error. Leaving the `async with`
block before the reply arrives cancels the request.

## 7. Discovery

### `await agents() -> list[dict]`

The other agents registered in this network, online or not:

```python
[{"id": "…", "name": "writer", "online": True, "description": "Writes short notes",
  "methods": [{"name": "draft", "description": "…", "input": {…}, "output": {…}}]}]
```

Only methods you may call are listed. Offline agents have no methods. For admins, the server's
own agent `gori` comes first; see [Managing the network](https://github.com/jungkumseok/gori/blob/HEAD/docs/API.md#10-managing-the-network-the-gori-agent).

## 8. Events

`client.on(event, callback)` calls `callback(payload)` on each event, and returns a function that
removes it. Callbacks may be coroutine functions, which run as tasks.

| Event | Payload | When |
|---|---|---|
| `connect` | `{"id", "name", "network"}` | After each welcome, including reconnects. |
| `disconnect` | `{"code", "reason"}` | The connection was lost or closed. |
| `reconnecting` | `{"attempt", "delay"}` | Before each reconnect attempt. |
| `close` | `{"code", "reason"}` | The client stopped for good. |
| `presence` | `{"change", "agent"}` | Another agent came `online`, went `offline`, or sent an `update`. `agent` is shaped like an `agents()` entry. |
| `error` | an exception | Problems that belong to no call: refused publishes, failing subscription handlers, refused reconnects. Without a listener they are logged to the `gori` logger. |

## 9. Errors

Every error is a `gori.GoriError` with a `code` and a `message`.

| Class | `code` | Raised when |
|---|---|---|
| `AuthError` | `UNREGISTERED`, `NETWORK_REQUIRED`, `NETWORK_FORBIDDEN`, `CERT_EXPIRED`, `UNSUPPORTED_PROTOCOL`, `SERVER_FINGERPRINT_MISMATCH`, … | The server refused the connection, or the pinned certificate didn't match. `status` is the HTTP status. |
| `ForbiddenError` | `FORBIDDEN` | The permission rules refused it. |
| `UnreachableError` | `UNREACHABLE` | The target is offline, unknown or in another network. |
| `LimitError` | `RATE_LIMITED`, `HOP_LIMIT`, `SUBSCRIPTION_LIMIT`, `REQUEST_LIMIT` | A server limit. |
| `RemoteError` | the handler's code | The handler failed. `method` and `details` say more. |
| `TimeoutError` | `TIMEOUT` | No reply or acknowledgement in time. Also a built-in `TimeoutError`. |
| `NotConnectedError` | `NOT_CONNECTED` | The client is disconnected. |
| `ConnectionClosedError` | `CONNECTION_CLOSED` | The client closed while the call was waiting. |

What each code means and how to fix it is in [Troubleshooting](https://github.com/jungkumseok/gori/blob/HEAD/docs/troubleshooting.md).

## 10. Nested calls, tracing and loop protection

Requests and events sent while a handler runs carry the handled message's trace: the same
`traceId`, its `id` as `parentId`, and `hops` one higher. The client tracks this with
`contextvars`, so it works at any depth of your code, and across clients in one process. Nested
requests also inherit the outer request's deadline (their timeout is capped at
`ctx.remaining`), and are cancelled with it when they are awaited inside the handler.

The server refuses messages more than 8 hops deep with `HOP_LIMIT`, which stops agents that call
each other in a loop.

## 11. Recipes

### Exposing other agents as LLM tools

`agents()` returns names, descriptions and JSON Schemas, which map onto tool definitions:

```python
import json, re

async def discover_tools(client):
    tools, routes = [], {}
    for agent in await client.agents():
        for method in agent["methods"]:
            name = re.sub(r"[^a-zA-Z0-9_-]", "_", f"{agent['name']}__{method['name']}")[:64]
            while name in routes:
                name = f"{name[:60]}_{len(routes)}"
            routes[name] = (agent["name"], method["name"])
            tools.append({
                "name": name,
                "description": " — ".join(filter(None, [agent.get("description"), method.get("description", method["name"])])),
                "input_schema": method.get("input", {"type": "object"}),
            })
    return tools, routes

async def run_tool(client, routes, tool_use):
    agent, method = routes[tool_use["name"]]
    try:
        reply = await client.request(agent, method, tool_use["input"], timeout=120)
        return {"type": "tool_result", "tool_use_id": tool_use["id"], "content": json.dumps(reply)}
    except gori.GoriError as err:
        return {"type": "tool_result", "tool_use_id": tool_use["id"], "is_error": True, "content": f"{err.code}: {err}"}
```

Refresh the tool list on `presence` events, since agents come and go.

### Waiting for an agent to come online

```python
async def wait_for_agent(client, name, timeout=30):
    seen = asyncio.Event()
    remove = client.on("presence", lambda e: e["agent"]["name"] == name and e["change"] != "offline" and seen.set())
    try:
        if not any(a["name"] == name and a["online"] for a in await client.agents()):
            await asyncio.wait_for(seen.wait(), timeout)
    finally:
        remove()
```

### A long job with a deadline

```python
@client.handle("research")
async def research(body, ctx):
    results = []
    for source in body["sources"]:
        if ctx.remaining is not None and ctx.remaining < 5:
            break  # leave time to reply
        results.append(await fetch(source))
        await ctx.progress(f"{len(results)} of {len(body['sources'])}")
    return results
```

## 12. Utilities

| Name | Meaning |
|---|---|
| `fingerprint_from_pem(pem)` | The SHA-256 fingerprint of a PEM certificate, as gori uses it. |
| `normalize_fingerprint(value)` | Lowercase hex from `AB:CD:…` or uppercase forms, or `None`. |
| `inbox_of(fingerprint)` | The inbox topic of an agent. |
| `compile_schema(schema)` | The built-in validator. |
| `CloseCode` | `NORMAL`, `GOING_AWAY`, `SUPERSEDED` (4000), `EXPIRED` (4001), `REVOKED` (4003). |
| `PROTOCOL_VERSION` | The wire protocol version this client speaks: `1`. |

## 13. Differences from the Node.js client

The two clients speak the same [protocol](https://github.com/jungkumseok/gori/blob/HEAD/docs/PROTOCOL.md) and behave the same way. The
differences are Python conventions:

| Node.js | Python |
|---|---|
| Times in milliseconds | Times in seconds |
| `publish()` returns at once | `await publish()` |
| `signal` option and `ctx.signal` | Cancel the task; the handler's task is cancelled |
| `ctx.from`, `ctx.deadline` | `ctx.caller`, `ctx.remaining` |
| `handle()` returns a remover | `unhandle(method)`; `handle()` also works as a decorator |
| `for await (const chunk of client.stream(…))` | `async with client.stream(…) as call: async for chunk in call` |
| `CancelledError` | `asyncio.CancelledError` |
| `cert`, `key`, `ca` as PEM contents | `cert`, `key` as paths; `ca` as paths or PEM text |

## 14. Development

The source is in the [gori repository](https://github.com/jungkumseok/gori), in `python/`. The
tests run against the real Node.js server from that repository, and against an agent that uses the
Node.js client, so both need to be in place:

```bash
git clone https://github.com/jungkumseok/gori.git && cd gori
npm ci                       # in the repository root
cd python
python -m venv .venv && . .venv/bin/activate
pip install -e .
cd tests && python -m unittest
```

Set `GORI_NODE` to use a different `node` binary.

## License

MIT
