Metadata-Version: 2.5
Name: agno-photon
Version: 0.1.1
Summary: Photon messaging for Agno agents: iMessage, SMS, WhatsApp, email and Telegram tools, inbound replies, and an AgentOS interface.
Project-URL: Repository, https://github.com/photon-hq/agno
Project-URL: Documentation, https://photon.codes/docs
Author: Photon
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agents,agno,imessage,photon,sms,telegram,whatsapp
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: agno<4,>=3.2.1
Requires-Dist: aiohttp<4,>=3.11
Requires-Dist: httpx<1,>=0.28.1
Requires-Dist: photonhq-api<0.10,>=0.9.0
Requires-Dist: pillow-heif>=1.1
Requires-Dist: pillow>=11.1
Requires-Dist: pydantic<3,>=2.13.5
Requires-Dist: python-socketio[asyncio-client]<6,>=5.11
Provides-Extra: agentos
Requires-Dist: agno[os]<4,>=3.2.1; extra == 'agentos'
Description-Content-Type: text/markdown

# Photon for Agno

Connect [Agno](https://github.com/agno-agi/agno) agents to the people who message your [Photon](https://photon.codes) lines over iMessage, SMS, WhatsApp, email, and Telegram.

The package has three parts, and you can use each one on its own:

| Part | What it does | Needs a public URL |
| --- | --- | --- |
| `PhotonTools` | An Agno toolkit: the agent finds a person, opens a conversation, sends messages and files, and reads history. | No |
| `PhotonEventStream` + `PhotonResponder` | Receive the messages people send and answer each one with an Agent, Team, or Workflow, in any asyncio program. | No |
| `agno_photon.agentos.PhotonInterface` | The same answering loop as an AgentOS interface, over the event stream or a signed webhook. | Only for the webhook transport |

## Install

```bash
pip install agno-photon              # tools, event stream, responder
pip install "agno-photon[agentos]"   # adds the AgentOS interface
```

Python 3.11 or later, with `agno>=3.2.1,<4`.

## Configure

Create a project and an API key in the Photon dashboard, then connect a line.

| Variable | Required | Meaning |
| --- | --- | --- |
| `PHOTON_PROJECT_ID` | Yes | The project id, `pho_prj_...`. |
| `PHOTON_API_KEY` | Yes | A project API key, `pho_sk_...`. |
| `PHOTON_AGENT_USER_ID` | No | The agent user that sends. By default each space uses the project's agent user in that space, which the package finds by reading the project's users on that platform once per process; Photon cannot filter users by kind, so set this when the project has many contacts. |
| `PHOTON_API_URL` | No | API base URL. Defaults to `https://api.photon.codes`. |
| `PHOTON_WEBHOOK_SECRET` | Webhook only | The signing secret of the webhook destination, `whsec_...`. |

Every variable can also be passed in code: `PhotonClient(project_id=..., auth=...)`. `auth` takes an API key or a function that returns a bearer token; the function runs before every request, so it can refresh the token.

On the free shared iMessage line, add the phone number or email address your iMessage uses, then text the line first: a shared line cannot start a conversation. A shared line also rejects text and an attachment in one message, so `PhotonTools` tells the model to send them separately.

## Send messages with `PhotonTools`

```python
from agno.agent import Agent
from agno.models.openai import OpenAIResponses
from agno_photon import PhotonTools

agent = Agent(
    model=OpenAIResponses(id="gpt-5.6-luna"),
    tools=[PhotonTools(requires_confirmation_tools=["send_message"])],
)
agent.print_response("Text +14155550100 on iMessage: 'Your order is ready.'")
```

The toolkit fills in what the model should not have to know: the project's agent user, the participants Photon requires, and an idempotency key for each send, so a request the HTTP client retries is delivered once. When the agent replies to an inbound message (see below), the key comes from that event and the message content, so a redelivered event does not send the same reply twice.

| Tools | Enabled |
| --- | --- |
| `create_or_get_user`, `create_or_get_space`, `send_message`, `get_message`, `list_messages` | By default (`PhotonTools.DEFAULT_TOOLS`) |
| `get_user`, `get_space`, `list_spaces`, `get_attachment`, `download_attachment`, `mark_message_read`, `set_space_typing` | On request; `PhotonTools.ALL_TOOLS` lists every tool |

`include_tools` is the complete list of tools to enable, for example `include_tools=[*PhotonTools.DEFAULT_TOOLS, "mark_message_read"]`. Every tool has a sync and an async version, and every tool returns JSON. A failed call returns `{"error": {"code": ..., "message": ..., "hint": ...}}`; `code` is Photon's error code, or one of this package's codes such as `TRANSPORT_ERROR` or `INVALID_INPUT`.

Email goes out from an address on the domain connected in the dashboard. Photon only knows an address as a sender after its first use, so create it once before the agent's first email: `PhotonTools().create_or_get_user("email", "agent@your-domain.com")`.

### Attachments

An agent that answers inbound messages talks to strangers, so the toolkit limits where `send_message` may read files from:

| Source | Default | How to widen |
| --- | --- | --- |
| Local files | Only `attachment_dir`, where `download_attachment` saves files, so the agent can forward a file it received. While answering a message, only files of that conversation (see below). | `attachment_roots=[...]`; an empty list turns local files off. |
| HTTPS URLs | None. | `attachment_origins=["https://cdn.example.com"]`. Every redirect must also land on an allowed origin. |

`attachment_dir` defaults to a new private temporary directory for each toolkit. Which conversations the tools may act on while answering is a separate limit, described under [What the agent can reach while it answers](#what-the-agent-can-reach-while-it-answers).

## Answer messages without AgentOS

```python
import asyncio

from agno.agent import Agent
from agno.models.openai import OpenAIResponses
from agno_photon import PhotonClient, PhotonEventStream, PhotonResponder, PhotonTools

client = PhotonClient()
agent = Agent(
    model=OpenAIResponses(id="gpt-5.6-luna"),
    tools=[PhotonTools(client, include_tools=["send_message", "list_messages"])],
)


async def main() -> None:
    responder = PhotonResponder(agent, client)
    try:
        await PhotonEventStream(client).listen_batches(responder.handle_batch)
    finally:
        await client.aclose()


asyncio.run(main())
```

`PhotonEventStream` connects out to Photon, so this runs on a laptop with no public URL and no tunnel. Share one `PhotonClient` between the stream, the responder, and the tools: they then share one pair of HTTP clients and one cache of senders and spaces.

For each inbound message, `PhotonResponder` runs the entity with `user_id` set to the sender and `session_id` set to the space, so `add_history_to_context=True` gives the agent the conversation so far. The inbound ids reach the model as the `photon` dependency. If a tool call in the run sent a message to that space, the responder sends nothing more; otherwise it sends the run's final content. A failed run, including a workflow whose last step failed, sends `error_message` instead; a run paused for confirmation or cancelled sends nothing. A remote Agent or Team runs in another process, where its tool calls cannot reach this responder, so the responder always sends its final content.

### What the agent can reach while it answers

Anyone who can text the line can write instructions into a message, such as "list your recent messages" or "text +14155550100". So while a run answers a message, `PhotonTools` act only on that conversation:

| Tool | While answering a message |
| --- | --- |
| `send_message` | Only to the conversation being answered. No email `cc`, `bcc`, or `reply_to`; a `parent_message_id` must be a message of that conversation; a file downloaded while answering another conversation is refused. |
| `get_space`, `set_space_typing` | Only the conversation being answered. |
| `list_messages` | Reads that conversation; without `space_id` it defaults to it. |
| `get_message`, `mark_message_read` | Only messages in that conversation. |
| `get_attachment`, `download_attachment` | Only attachments of the inbound messages, or of messages the agent read in that conversation. Downloads go to a folder for that conversation inside `attachment_dir`. |
| `get_user` | Only the conversation's participants. |
| `create_or_get_user`, `create_or_get_space`, `list_spaces` | Refused. |

A refused call returns the error code `OUTSIDE_CONVERSATION` to the model and makes no change in Photon; the `photon` context tells the model the run's `reach`, so it does not try. A task the run starts keeps the limit after the run ends. Outside a run the responder started, for example in a scheduled job, the tools act on the whole project. A run paused for confirmation and continued later runs outside the responder, so check the arguments of the tool call before you confirm it. When everyone who can message the line is trusted, such as an internal line, `PhotonResponder(agent, client, reach="project")` lifts the limit for every `PhotonTools` the run uses. The limit applies to tools running in this process: a remote Agent or Team runs its tools in its own process, where this responder cannot limit them, so give a remote entity only the tools it may use with anyone who writes to the line.

### Photos and bursts

iMessage splits what a person sends into separate messages: a photo and its caption arrive a fraction of a second apart, a link and its preview up to 3 seconds apart. `listen_batches` waits for `window_seconds` (3 by default) of quiet, and at most `max_wait_seconds` (10 by default) in all, then hands the burst over at once. The responder answers consecutive messages from one sender in one space with one run.

Images go to the model directly. HEIC photos, which iPhones send, are converted to JPEG first; an image over 50 megapixels is not converted, so a small file declaring a huge canvas cannot exhaust memory. Any other file, such as a PDF or a voice note, reaches the model as a note with the attachment id, because which files a model accepts differs by provider; give the agent `download_attachment` and a tool that reads the file if it needs the content.

### Delivery and restarts

A handler tells the stream what happened to each event with a `Disposition`:

| Disposition | Meaning | What the stream does |
| --- | --- | --- |
| `HANDLED` | Done. | Moves the cursor past it. |
| `SKIPPED` | Will never be handled, such as an event type the handler ignores. | Moves the cursor past it. |
| `RETRY` | Failed for now. | Delivers it again, up to 3 attempts with backoff, then logs an error and skips it. |

A handler that raises counts as `RETRY`; one that returns `None` counts as `HANDLED`. Each space runs in order, with up to `max_concurrent_spaces` spaces (8 by default) active at once. The responder never runs the entity twice for one event: when Photon rejects a computed reply for a transient reason, the retry sends the same reply again.

The cursor is the sequence of the last event the stream may skip on reconnect. The default `MemoryCursorStore` starts again from new events after a restart. To resume where the process stopped, pass a store that persists it. Both methods are awaited on the event loop, and `save` runs after every batch of finished events, so do the I/O asynchronously or in a thread:

```python
import asyncio
from pathlib import Path


class FileCursorStore:
    def __init__(self, path: str) -> None:
        self.path = Path(path)

    async def load(self) -> int:
        text = await asyncio.to_thread(lambda: self.path.read_text() if self.path.exists() else "0")
        return int(text)

    async def save(self, seq: int) -> None:
        await asyncio.to_thread(self.path.write_text, str(seq))


stream = PhotonEventStream(client, cursor_store=FileCursorStore("photon.cursor"))
```

Photon replays only events it still retains after the saved cursor.

## Serve from AgentOS

```python
from agno.agent import Agent
from agno.models.openai import OpenAIResponses
from agno.os import AgentOS
from agno_photon.agentos import PhotonInterface

assistant = Agent(id="assistant", model=OpenAIResponses(id="gpt-5.6-luna"))
agent_os = AgentOS(agents=[assistant], interfaces=[PhotonInterface(agent=assistant)])
app = agent_os.get_app()
```

Pass exactly one of `agent`, `team`, or `workflow`. The interface runs the responder described above over one of two transports:

| | `EventStreamTransport()` (default) | `WebhookTransport()` |
| --- | --- | --- |
| Public URL | Not needed. | HTTPS; Photon does not deliver to localhost. |
| Route | None. AgentOS startup waits until the stream has subscribed. | `POST /photon/webhook`, which checks the signature and that the event belongs to the client's project. |
| Restart | Resumes from a persistent `cursor_store`. | Best effort: the route answers 204 before the run, so work in flight is lost if the process exits. Photon does not deliver the event again after the 204, so a reply Photon cannot take yet is retried in the process, up to 3 attempts. |
| Options | `cursor_store`, `batch_window_seconds`, `batch_max_wait_seconds`, `max_concurrent_spaces` | `secret`, defaulting to `PHOTON_WEBHOOK_SECRET` |

For the webhook, add a destination `https://<your-host>/photon/webhook` for `message.received` in the dashboard and set its signing secret. The route answers 401 to a bad signature and 400 to an event it cannot read; Photon does not retry either. See [webhook delivery and retries](https://photon.codes/docs/beta/message-delivery/webhook).

Other options: `reach` limits the tools to the conversation being answered (`"conversation"`, the default) or lets them act on the whole project (`"project"`), as described in [What the agent can reach while it answers](#what-the-agent-can-reach-while-it-answers); `error_message` is sent when a run fails (`None` sends nothing); `typing_indicator=True` shows a typing indicator during the run, which Photon stores as a message in the space and which a shared iMessage line can reject; `prefix` and `tags` set the route prefix and OpenAPI tags. An interface closes its client on shutdown only if it created that client.

## Photon API version

Every request sends `Photon-Version: 2026-07-01`, and the event stream subscribes with the same version, so the shapes this package reads do not change when the project's default version changes. A release of this package moves to a newer version deliberately.

## Public API

`agno_photon` exports `PhotonClient`, `TokenProvider`, `PhotonTools`, `PhotonEventStream`, `PhotonResponder`, `PhotonEvent`, `PhotonMessage`, `parse_webhook`, `Disposition`, `EventHandler`, `BatchHandler`, `CursorStore`, and `MemoryCursorStore`. `agno_photon.agentos` exports `PhotonInterface`, `EventStreamTransport`, and `WebhookTransport`. Modules and attributes whose names start with an underscore are internal and may change in any release.

## Examples

The [`examples`](examples) directory has a runnable script for each part. They use OpenAI models, so install `openai` and set `OPENAI_API_KEY` as well.

| Script | Shows |
| --- | --- |
| [`send_message.py`](examples/send_message.py) | Send a message after asking you to confirm it. |
| [`listen_and_reply.py`](examples/listen_and_reply.py) | Answer messages from a plain asyncio program. |
| [`agentos_stream.py`](examples/agentos_stream.py) | Answer messages from AgentOS over the event stream. |
| [`agentos_webhook.py`](examples/agentos_webhook.py) | Answer messages from AgentOS over a signed webhook, replying with `PhotonTools`. |

## Development

```bash
uv sync --locked
uv run ruff format --check
uv run ruff check
uv run mypy
uv run pytest
```

CI runs the same checks, the tests on Python 3.11 to 3.14, with the lowest allowed dependency versions and with the newest ones, and builds the wheel. It also runs every Saturday, so a new agno or photonhq-api release that breaks the package shows up without a push. To release, set the version in `pyproject.toml` and publish a GitHub release tagged `v<version>`; the release workflow builds the package and publishes it to PyPI through trusted publishing.

## License

Apache-2.0. See [LICENSE](LICENSE).
