From 15e5c9a96bcdbc13812161ae796e0b7514e5713a Mon Sep 17 00:00:00 2001 From: Eden Zimbelman Date: Wed, 2 Dec 2026 18:03:55 -0800 Subject: [PATCH] feat: read images, PDFs, and text files shared with the agent Co-Authored-By: Claude --- AGENTS.md | 2 +- claude-agent-sdk/AGENTS.md | 2 +- claude-agent-sdk/README.md | 1 + claude-agent-sdk/agent/agent.py | 46 ++++- claude-agent-sdk/agent/files.py | 125 ++++++++++++++ claude-agent-sdk/agent/sessions.py | 12 +- claude-agent-sdk/agent/turns.py | 49 ++++-- claude-agent-sdk/app_oauth.py | 1 + .../listeners/events/app_mentioned.py | 7 +- claude-agent-sdk/listeners/events/message.py | 5 +- claude-agent-sdk/manifest.json | 1 + claude-agent-sdk/tests/conftest.py | 12 +- .../tests/test_agent_session_stopped.py | 10 +- claude-agent-sdk/tests/test_app_mentioned.py | 48 +++++- .../tests/test_approval_buttons.py | 2 +- claude-agent-sdk/tests/test_files.py | 157 ++++++++++++++++++ claude-agent-sdk/tests/test_message.py | 36 +++- claude-agent-sdk/tests/test_runs.py | 36 ++++ openai-agents-sdk/AGENTS.md | 2 +- openai-agents-sdk/README.md | 1 + openai-agents-sdk/agent/agent.py | 33 +++- openai-agents-sdk/agent/files.py | 125 ++++++++++++++ openai-agents-sdk/agent/sessions.py | 12 +- openai-agents-sdk/agent/turns.py | 49 ++++-- openai-agents-sdk/app_oauth.py | 1 + .../listeners/events/app_mentioned.py | 7 +- openai-agents-sdk/listeners/events/message.py | 5 +- openai-agents-sdk/manifest.json | 1 + openai-agents-sdk/tests/conftest.py | 12 +- .../tests/test_agent_session_stopped.py | 10 +- openai-agents-sdk/tests/test_app_mentioned.py | 48 +++++- .../tests/test_approval_buttons.py | 2 +- openai-agents-sdk/tests/test_files.py | 157 ++++++++++++++++++ openai-agents-sdk/tests/test_message.py | 36 +++- openai-agents-sdk/tests/test_runs.py | 38 +++++ pydantic-ai/AGENTS.md | 2 +- pydantic-ai/README.md | 1 + pydantic-ai/agent/agent.py | 27 ++- pydantic-ai/agent/files.py | 125 ++++++++++++++ pydantic-ai/agent/sessions.py | 12 +- pydantic-ai/agent/turns.py | 49 ++++-- pydantic-ai/app_oauth.py | 1 + pydantic-ai/listeners/events/app_mentioned.py | 7 +- pydantic-ai/listeners/events/message.py | 5 +- pydantic-ai/manifest.json | 1 + pydantic-ai/tests/conftest.py | 12 +- .../tests/test_agent_session_stopped.py | 10 +- pydantic-ai/tests/test_app_mentioned.py | 48 +++++- pydantic-ai/tests/test_approval_buttons.py | 2 +- pydantic-ai/tests/test_files.py | 157 ++++++++++++++++++ pydantic-ai/tests/test_message.py | 36 +++- pydantic-ai/tests/test_runs.py | 33 +++- 52 files changed, 1499 insertions(+), 120 deletions(-) create mode 100644 claude-agent-sdk/agent/files.py create mode 100644 claude-agent-sdk/tests/test_files.py create mode 100644 openai-agents-sdk/agent/files.py create mode 100644 openai-agents-sdk/tests/test_files.py create mode 100644 pydantic-ai/agent/files.py create mode 100644 pydantic-ai/tests/test_files.py diff --git a/AGENTS.md b/AGENTS.md index a4b211f..0d5aadd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,7 +63,7 @@ The flow: a mention or direct message outside a code channel runs a small routin Implementations share structure, not code, so these parts are kept the same by copying them and changing them everywhere at once: - **The seam between `listeners/` and `agent/`.** Listeners import only from the `agent` package, never from the agent framework, so `listeners/` is the same in every implementation. `agent/__init__.py` provides `answer_request`, `find_session`, `run_turn`, `resume_turn`, `stop_turn`, and `end_session`. -- **Framework-free files.** `agent/turns.py`, `agent/context.py`, `agent/approvals.py`, `agent/sessions.py`, `agent/workspace.py`, `agent/outcome.py`, and `agent/prompts.py` don't import the agent framework. The framework lives in `agent/agent.py`, `agent/guardrails.py`, and `agent/tools/`, and the Claude Agent SDK adds `agent/runtime.py` for the deps its tools can't be passed. `turns.py` calls only `run_request(prompt, deps)`, which returns the reply text, and `start_run(history, text, deps)` and `resume_run(paused, approved, deps)`, which return the `RunOutcome` in `agent/outcome.py`. The paused run is a handle `turns.py` passes back without looking inside, so each framework's way of pausing fits behind it. +- **Framework-free files.** `agent/turns.py`, `agent/context.py`, `agent/files.py`, `agent/approvals.py`, `agent/sessions.py`, `agent/workspace.py`, `agent/outcome.py`, and `agent/prompts.py` don't import the agent framework. The framework lives in `agent/agent.py`, `agent/guardrails.py`, and `agent/tools/`, and the Claude Agent SDK adds `agent/runtime.py` for the deps its tools can't be passed. `turns.py` calls only `run_request(prompt, deps, media)`, which returns the reply text, and `start_run(history, text, deps, media)` and `resume_run(paused, approved, deps)`, which return the `RunOutcome` in `agent/outcome.py`. `media` holds the images and PDFs shared with the messages, as `SharedMedia` from `agent/files.py`, and each framework gives them to its model in its own way. The paused run is a handle `turns.py` passes back without looking inside, so each framework's way of pausing fits behind it. - **What the framework side keeps true.** `turns.py` relies on these, so every implementation keeps them: `create_code_channel` sets `deps.code_channel_id`, and `archive_channel` sets `session.archived`. Every code channel tool skips its call once `session.stopped` is set. `turns.py` can drop a paused run without resuming it, since the session's history then shows its pending command as not run: the history already records it that way, or the next run answers it that way before anything else. Beyond that, `turns.py` only checks whether `history` is empty, to know a turn is the first. - **Prompts.** `agent/prompts.py` is the same word for word in every implementation. - **Tools.** Every implementation offers the same tools with the same names, arguments, and descriptions, written with its framework's tool decorator. File tools stay inside the clone and can't write into `.git`. diff --git a/claude-agent-sdk/AGENTS.md b/claude-agent-sdk/AGENTS.md index 7874366..4d2b313 100644 --- a/claude-agent-sdk/AGENTS.md +++ b/claude-agent-sdk/AGENTS.md @@ -16,7 +16,7 @@ Slack skills are pre-installed in `.agents/skills` (and `.claude/skills` for Cla **Deps** reach the tools and hooks through `current_deps` in `agent/runtime.py`, a `ContextVar`, since the SDK calls a tool with only its arguments. `_run` in `agent/agent.py` sets it before the client starts, so the tasks the client starts see it. -**Runs** use a `ClaudeSDKClient` per run from async Bolt listeners, which runs the Claude Code CLI bundled with the SDK. Coding turns allow `MAX_TURNS` model calls, and a turn that uses them all (`error_max_turns`) ends with a message, keeping its history. A `PostToolUse` hook returns `continue_: False` to end the run early once there's nothing left to do: after `create_code_channel` succeeds for the routing agent, and after `archive_channel` for the coding agent. A result with `is_error` raises, so the turn posts a warning. +**Runs** use a `ClaudeSDKClient` per run from async Bolt listeners, which runs the Claude Code CLI bundled with the SDK. Coding turns allow `MAX_TURNS` model calls, and a turn that uses them all (`error_max_turns`) ends with a message, keeping its history. A `PostToolUse` hook returns `continue_: False` to end the run early once there's nothing left to do: after `create_code_channel` succeeds for the routing agent, and after `archive_channel` for the coding agent. A result with `is_error` raises, so the turn posts a warning. A run with shared images or PDFs sends its prompt as a user message whose content has an `image` or `document` block for each, before the text. **Turns** go through `agent/turns.py`, which doesn't import the SDK. A turn that raises posts a warning and moves the session back to `active`, keeping the history from the last finished turn. Model-written replies use `markdown_text`, since the model writes standard markdown. diff --git a/claude-agent-sdk/README.md b/claude-agent-sdk/README.md index 7401e27..95d4a1f 100644 --- a/claude-agent-sdk/README.md +++ b/claude-agent-sdk/README.md @@ -46,6 +46,7 @@ Each code channel method is a tool the model calls when it decides to, in [`agen - **Archiving from Slack.** On `channel_archive` or `group_archive`, the app forgets the session and deletes its working directory, the same cleanup `archive_channel` does when the agent wraps up. - **Picking up code channels.** A message, mention, or slash command in a code channel the app has no state for, whether the seeded request in a channel the agent just created, one started from Slack's UI, or one forgotten after a restart, is recognized with `conversations.info` (`properties.record_channel.record_type == "agent_channel"`) and picked up as a session. Other channels are looked up once and remembered. - **The conversation comes along.** A new session reads the thread or direct message its channel was started from (`properties.agent_session.origin_link`) and gives it to the agent's first turn, so a request like "fix this" keeps its context. +- **Shared files.** Files shared with a request or in a code channel are downloaded with the bot token, which needs `files:read` and goes only to `files.slack.com`. Images and PDFs go to the model as they are, and text files go into the prompt. The agent is told about any other file, or one over 5 MB, that it couldn't read. - **One turn at a time.** Messages that arrive while the agent works wait, and go into its next turn together, each labeled with who sent it. The stop button drops them along with the turn. - **Creating a channel is the agent's call.** The prompt in [`agent/prompts.py`](./agent/prompts.py) follows Slack's guidance: create a channel for multi-step work like changing code or running tests, and reply in place for anything that fits in one message. - **Idempotent creation.** `create_code_channel` takes only a title. Its `session_id` comes from the triggering message, so a repeated call or a retried event reuses the same channel. The first turn only ever starts from the seeded mention, so it runs once. diff --git a/claude-agent-sdk/agent/agent.py b/claude-agent-sdk/agent/agent.py index c2cea4f..875f5a0 100644 --- a/claude-agent-sdk/agent/agent.py +++ b/claude-agent-sdk/agent/agent.py @@ -6,6 +6,8 @@ `RunOutcome`. """ +import base64 +from collections.abc import AsyncIterator, Sequence from dataclasses import dataclass from claude_agent_sdk import ( @@ -19,6 +21,7 @@ create_sdk_mcp_server, ) +from agent.files import SharedMedia from agent.guardrails import answer_unanswered, gate_tool_calls from agent.outcome import RunOutcome from agent.prompts import REQUEST_PROMPT, SYSTEM_PROMPT @@ -139,10 +142,39 @@ def _options( ) +def _media_block(file: SharedMedia) -> dict: + """The block that gives the model a shared image or PDF as it is.""" + source = { + "type": "base64", + "media_type": file.media_type, + "data": base64.b64encode(file.data).decode(), + } + if file.media_type == "application/pdf": + return {"type": "document", "source": source, "title": file.name} + return {"type": "image", "source": source} + + +async def _user_message(text: str, media: Sequence[SharedMedia]) -> AsyncIterator[dict]: + """A run's prompt as a user message, with the shared images and PDFs before the text.""" + yield { + "type": "user", + "message": { + "role": "user", + "content": [*map(_media_block, media), {"type": "text", "text": text}], + }, + "parent_tool_use_id": None, + } + + +def _prompted(text: str, media: Sequence[SharedMedia]) -> str | AsyncIterator[dict]: + """A run's prompt: the text alone, or a user message with the shared images and PDFs.""" + return _user_message(text, media) if media else text + + async def _run( options: ClaudeAgentOptions, deps: AgentDeps | RequestDeps, - prompt: str | None, + prompt: str | AsyncIterator[dict] | None, ) -> ResultMessage: """Run the agent once and return its result. @@ -204,20 +236,24 @@ def _settle(history: list, result: ResultMessage) -> RunOutcome: return RunOutcome(final_output=result.result, history=history) -async def run_request(prompt: str, deps: RequestDeps) -> str | None: +async def run_request( + prompt: str, deps: RequestDeps, media: Sequence[SharedMedia] = () +) -> str | None: """Reply to a request outside a code channel, or create one for it via the tool.""" - result = await _run(_request_options(), deps, prompt) + result = await _run(_request_options(), deps, _prompted(prompt, media)) if result.is_error: raise RuntimeError("; ".join(result.errors or []) or result.result) return result.result -async def start_run(history: list, text: str, deps: AgentDeps) -> RunOutcome: +async def start_run( + history: list, text: str, deps: AgentDeps, media: Sequence[SharedMedia] = () +) -> RunOutcome: """Start an agent turn. May complete, or pause awaiting command approval.""" # A paused run that was stopped or replaced left its command waiting. waiting = history[-1].deferred_tool_use if history else None options = _options(history, unanswered=waiting.id if waiting else None) - result = await _run(options, deps, text) + result = await _run(options, deps, _prompted(text, media)) return _settle(history, result) diff --git a/claude-agent-sdk/agent/files.py b/claude-agent-sdk/agent/files.py new file mode 100644 index 0000000..da2983e --- /dev/null +++ b/claude-agent-sdk/agent/files.py @@ -0,0 +1,125 @@ +"""Files shared with a message, downloaded from Slack so the agent can read them. + +Images and PDFs go to the model as they are, and text files go in the prompt. +Any other file is named in the prompt as not read, with the reason. +""" + +import logging +from collections.abc import Sequence +from dataclasses import dataclass, field +from urllib.parse import urlparse + +import aiohttp + +from agent.workspace import clip + +logger = logging.getLogger(__name__) + +# Slack serves the files it hosts from here, and the bot token goes nowhere else. +SLACK_FILE_HOST = "files.slack.com" + +# Well under the models' limits for one image or PDF, which count the base64 encoding. +MAX_FILE_BYTES = 5 * 1024 * 1024 + +# About 25,000 tokens of a text file. Clipping keeps most of the end, where a log's errors usually are. +MAX_TEXT_CHARS = 100_000 + +TOO_LARGE = f"it's over {MAX_FILE_BYTES // 1024 // 1024} MB" + +# Slack redirects a download it won't serve to the token, most often one without the `files:read` scope. +REDIRECTED = "Slack redirected the download, which usually means the app needs reinstalling for the files:read scope" + +MEDIA_TYPES = ("application/pdf", "image/gif", "image/jpeg", "image/png", "image/webp") + + +class Unreadable(Exception): + """A reason a shared file wasn't read, told to the model.""" + + +@dataclass +class SharedMedia: + """An image or PDF shared with a message, for the model to read as it is.""" + + name: str + # One of `MEDIA_TYPES`. + media_type: str + data: bytes + + +@dataclass +class SharedFiles: + """What the agent reads from a message's files. + + `text` holds each text file and a note for each file that wasn't read, for + the prompt. `media` holds the images and PDFs to send with it. + """ + + text: str = "" + media: list[SharedMedia] = field(default_factory=list) + + +async def _download(token: str | None, file: dict) -> bytes: + """Download a file Slack hosts, sending the bot token only to Slack's file host. + + A redirect isn't followed, since it could lead anywhere with the token. + """ + if file.get("mode") == "external" or file.get("is_external"): + raise Unreadable("it's hosted outside Slack") + if (file.get("size") or 0) > MAX_FILE_BYTES: + raise Unreadable(TOO_LARGE) + url = file.get("url_private") + if not url: + raise Unreadable("Slack didn't include a link to download it") + parsed = urlparse(url) + if parsed.scheme != "https" or parsed.hostname != SLACK_FILE_HOST: + raise Unreadable("it isn't on Slack's file host") + async with ( + aiohttp.ClientSession() as http, + http.get( + url, headers={"Authorization": f"Bearer {token}"}, allow_redirects=False + ) as response, + ): + if 300 <= response.status < 400: + raise Unreadable(REDIRECTED) + if response.status != 200: + raise Unreadable(f"downloading it returned HTTP {response.status}") + data = await response.read() + if len(data) > MAX_FILE_BYTES: + raise Unreadable(TOO_LARGE) + return data + + +def _decoded(data: bytes) -> str | None: + """A file's bytes as text, or None for a file that isn't text.""" + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + return None + return None if "\0" in text else text + + +async def read_files(token: str | None, files: Sequence[dict]) -> SharedFiles: + """Read the files shared with a message. The bot token needs the `files:read` scope.""" + parts: list[str] = [] + media: list[SharedMedia] = [] + for file in files: + name = file.get("name") or file.get("id") or "a file" + try: + data = await _download(token, file) + if file.get("mimetype") in MEDIA_TYPES: + media.append( + SharedMedia(name=name, media_type=file["mimetype"], data=data) + ) + continue + text = _decoded(data) + if text is None: + raise Unreadable( + "only PNG, JPEG, GIF, and WebP images, PDFs, and text files can be read" + ) + parts.append(f'\n{clip(text, MAX_TEXT_CHARS)}\n') + except Unreadable as e: + parts.append(f"({name} wasn't read: {e})") + except Exception: + logger.warning("Couldn't read %s", name, exc_info=True) + parts.append(f"({name} wasn't read: it couldn't be downloaded)") + return SharedFiles(text="\n\n".join(parts), media=media) diff --git a/claude-agent-sdk/agent/sessions.py b/claude-agent-sdk/agent/sessions.py index 48205ac..0ca55b3 100644 --- a/claude-agent-sdk/agent/sessions.py +++ b/claude-agent-sdk/agent/sessions.py @@ -17,6 +17,14 @@ from slack_sdk.web.async_client import AsyncWebClient +@dataclass +class InboxMessage: + """A message waiting for the next turn: its text, starting with who sent it, and the files shared with it.""" + + text: str + files: list[dict] = field(default_factory=list) + + @dataclass class CodeChannelSession: """Per-code-channel working state.""" @@ -33,8 +41,8 @@ class CodeChannelSession: base_commit: str | None = None plan_canvas_id: str | None = None history: list = field(default_factory=list) - # Messages waiting for the next turn, each starting with who sent it. - inbox: list[str] = field(default_factory=list) + # Messages waiting for the next turn. + inbox: list[InboxMessage] = field(default_factory=list) # Set by the native stop button, or when the session is discarded. Checked # before posting and before every tool call so a stopped session goes quiet; # cleared when the user starts a new turn. diff --git a/claude-agent-sdk/agent/turns.py b/claude-agent-sdk/agent/turns.py index 35b2559..22b5912 100644 --- a/claude-agent-sdk/agent/turns.py +++ b/claude-agent-sdk/agent/turns.py @@ -8,7 +8,7 @@ """ import logging -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Sequence from functools import partial from slack_sdk.errors import SlackApiError @@ -23,8 +23,15 @@ from agent.agent import resume_run, run_request, start_run from agent.approvals import PendingApproval, pending_store from agent.context import origin_context, recent_context, thread_context +from agent.files import SharedMedia, read_files from agent.outcome import RunOutcome -from agent.sessions import AgentDeps, CodeChannelSession, RequestDeps, session_store +from agent.sessions import ( + AgentDeps, + CodeChannelSession, + InboxMessage, + RequestDeps, + session_store, +) from agent.workspace import clip logger = logging.getLogger(__name__) @@ -180,6 +187,19 @@ async def _run(deps: AgentDeps, run: Callable[[], Awaitable[RunOutcome]]) -> boo return False +async def _start_turn( + deps: AgentDeps, history: list, origin: str, messages: list[InboxMessage] +) -> RunOutcome: + """Start a turn with the messages waiting for it, after reading the files shared with them.""" + texts = [origin] if origin else [] + media: list[SharedMedia] = [] + for message in messages: + shared = await read_files(deps.client.token, message.files) + texts.append("\n\n".join(filter(None, [message.text, shared.text]))) + media.extend(shared.media) + return await start_run(history, "\n\n".join(texts), deps, media) + + async def _run_inbox(client: AsyncWebClient, session: CodeChannelSession) -> None: """Run turns until the inbox is empty or a turn pauses on an approval.""" while session.inbox and not session.archived: @@ -187,16 +207,18 @@ async def _run_inbox(client: AsyncWebClient, session: CodeChannelSession) -> Non # the session back up. session.stopped = False messages, session.inbox = session.inbox, [] - text = "\n\n".join(messages) + origin = "" if session.origin_context and not session.history: - text = ( + origin = ( "This code channel was started from this conversation:\n" - f"{session.origin_context}\n\n{text}" + f"{session.origin_context}" ) session.origin_context = None deps = AgentDeps(client=client, session=session) - paused = await _run(deps, partial(start_run, session.history, text, deps)) + paused = await _run( + deps, partial(_start_turn, deps, session.history, origin, messages) + ) if paused: return @@ -210,12 +232,14 @@ async def answer_request( text: str, user_id: str, in_dm: bool, + files: Sequence[dict] = (), ) -> None: """Reply to a mention or direct message outside a code channel, or create one for it. A mention in a channel is answered in its thread. A direct message is answered where it was sent. The agent gets the conversation before the request, from - the thread or from the direct message, so it can follow along. + the thread or from the direct message, so it can follow along, and the files + shared with the request. """ reply_ts = thread_ts or (None if in_dm else message_ts) if not text: @@ -235,7 +259,8 @@ async def answer_request( earlier = await recent_context(client, channel_id, before_ts=message_ts) else: earlier = "" - prompt = f"<@{user_id}>: {text}" + shared = await read_files(client.token, files) + prompt = "\n\n".join(filter(None, [f"<@{user_id}>: {text}", shared.text])) if earlier: prompt = f"Earlier in this conversation:\n{earlier}\n\n{prompt}" @@ -245,7 +270,7 @@ async def answer_request( message_ts=message_ts, thread_ts=reply_ts, ) - reply = await run_request(prompt, deps) + reply = await run_request(prompt, deps, shared.media) # When the agent created a code channel, the work continues there. if deps.code_channel_id is None: await client.chat_postMessage( @@ -313,14 +338,16 @@ async def run_turn( session: CodeChannelSession, text: str, user_id: str, + files: Sequence[dict] = (), ) -> None: """Run a message or slash command in a code channel as a turn and post the outcome. Mentions, plain messages, and slash commands all funnel through here. A message that arrives while a turn runs waits in the session's inbox, and - everything waiting runs together as the next turn. + everything waiting runs together as the next turn. The files shared with + each message are read when its turn starts. """ - session.inbox.append(f"<@{user_id}>: {text}") + session.inbox.append(InboxMessage(text=f"<@{user_id}>: {text}", files=list(files))) if session.turn_lock.locked(): # The running turn takes this message when it finishes. return diff --git a/claude-agent-sdk/app_oauth.py b/claude-agent-sdk/app_oauth.py index 569e5c3..dcb7159 100644 --- a/claude-agent-sdk/app_oauth.py +++ b/claude-agent-sdk/app_oauth.py @@ -52,6 +52,7 @@ async def failure(args: AsyncFailureArgs) -> BoltResponse: "channels:read", "chat:write", "code_channels:manage", + "files:read", "groups:history", "groups:read", "im:history", diff --git a/claude-agent-sdk/listeners/events/app_mentioned.py b/claude-agent-sdk/listeners/events/app_mentioned.py index 48b8295..d9a48ab 100644 --- a/claude-agent-sdk/listeners/events/app_mentioned.py +++ b/claude-agent-sdk/listeners/events/app_mentioned.py @@ -24,7 +24,11 @@ async def handle_app_mentioned( session = await find_session(client, channel_id) if session is not None: await run_turn( - client=client, session=session, text=text, user_id=context.user_id + client=client, + session=session, + text=text, + user_id=context.user_id, + files=files, ) return @@ -36,4 +40,5 @@ async def handle_app_mentioned( text=text, user_id=context.user_id, in_dm=False, + files=files, ) diff --git a/claude-agent-sdk/listeners/events/message.py b/claude-agent-sdk/listeners/events/message.py index f3f7618..735a70f 100644 --- a/claude-agent-sdk/listeners/events/message.py +++ b/claude-agent-sdk/listeners/events/message.py @@ -33,6 +33,7 @@ async def handle_message( text=text.replace(mention, "").strip(), user_id=context.user_id, in_dm=True, + files=files, ) return @@ -42,4 +43,6 @@ async def handle_message( session = await find_session(client, channel_id) if session is None: return - await run_turn(client=client, session=session, text=text, user_id=context.user_id) + await run_turn( + client=client, session=session, text=text, user_id=context.user_id, files=files + ) diff --git a/claude-agent-sdk/manifest.json b/claude-agent-sdk/manifest.json index 56ca23a..f423aff 100644 --- a/claude-agent-sdk/manifest.json +++ b/claude-agent-sdk/manifest.json @@ -45,6 +45,7 @@ "channels:read", "chat:write", "code_channels:manage", + "files:read", "groups:history", "groups:read", "im:history", diff --git a/claude-agent-sdk/tests/conftest.py b/claude-agent-sdk/tests/conftest.py index 71ee6dc..f790a61 100644 --- a/claude-agent-sdk/tests/conftest.py +++ b/claude-agent-sdk/tests/conftest.py @@ -1,4 +1,4 @@ -from unittest.mock import Mock +from unittest.mock import AsyncMock, MagicMock, Mock import pytest from slack_bolt.context.async_context import AsyncBoltContext @@ -24,6 +24,7 @@ def forget_sessions(): def client() -> Mock: """A Slack client whose methods match the real one's, so a wrong call fails.""" client = Mock(AsyncWebClient) + client.token = "xoxb-example" client.chat_postMessage.return_value = {"ts": "8.8"} return client @@ -53,3 +54,12 @@ def code_channel_info(origin_channel_id: str = "C_ORIGIN", origin_ts: str = "1.1 } } } + + +def file_download(body: bytes, status: int = 200) -> MagicMock: + """A response to downloading a file from Slack, for patching `aiohttp.ClientSession.get`.""" + response = MagicMock() + response.status = status + response.read = AsyncMock(return_value=body) + response.__aenter__.return_value = response + return response diff --git a/claude-agent-sdk/tests/test_agent_session_stopped.py b/claude-agent-sdk/tests/test_agent_session_stopped.py index 14008c6..49e3300 100644 --- a/claude-agent-sdk/tests/test_agent_session_stopped.py +++ b/claude-agent-sdk/tests/test_agent_session_stopped.py @@ -2,7 +2,7 @@ from agent.approvals import PendingApproval, pending_store from agent.outcome import RunOutcome -from agent.sessions import CodeChannelSession, session_store +from agent.sessions import CodeChannelSession, InboxMessage, session_store from listeners.events.agent_session_stopped import handle_agent_session_stopped from listeners.events.message import handle_message @@ -21,7 +21,9 @@ async def send(self, client, context, text: str): ) async def test_stop_confirms_and_leaves_processing(self, client, context): - session = CodeChannelSession(channel_id="C_CODE", inbox=["<@U1>: queued"]) + session = CodeChannelSession( + channel_id="C_CODE", inbox=[InboxMessage(text="<@U1>: queued")] + ) session_store.put(session) await self.stop(client, context) @@ -57,7 +59,7 @@ async def test_stop_drops_the_pending_approval_and_its_buttons( async def test_stopped_turn_posts_nothing_more(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) - async def stop_mid_run(_history, _text, _deps): + async def stop_mid_run(_history, _text, _deps, _media): await self.stop(client, context) return RunOutcome(final_output="Done.", history=[]) @@ -79,7 +81,7 @@ async def test_a_message_after_the_stop_picks_back_up(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) texts = [] - async def run(_history, text, _deps): + async def run(_history, text, _deps, _media): texts.append(text) if len(texts) == 1: await self.stop(client, context) diff --git a/claude-agent-sdk/tests/test_app_mentioned.py b/claude-agent-sdk/tests/test_app_mentioned.py index d11711a..f9d85e0 100644 --- a/claude-agent-sdk/tests/test_app_mentioned.py +++ b/claude-agent-sdk/tests/test_app_mentioned.py @@ -1,10 +1,12 @@ +import base64 from unittest.mock import patch +from agent.files import SharedMedia from agent.outcome import RunOutcome from agent.sessions import CodeChannelSession, session_store from agent.tools import create_code_channel from listeners.events.app_mentioned import handle_app_mentioned -from tests.conftest import code_channel_info +from tests.conftest import code_channel_info, file_download from tests.test_tools import invoke @@ -33,7 +35,7 @@ async def test_mention_answered_in_place_opens_no_channel(self, client, context) _, start_run = await self.mention_in_origin( client, context, - lambda _prompt, _deps: "It's a billing service.", + lambda _prompt, _deps, _media: "It's a billing service.", text="what does billing do?", ) @@ -56,7 +58,7 @@ async def test_mention_in_a_thread_gets_the_thread_so_far(self, client, context) run_request, _ = await self.mention_in_origin( client, context, - lambda _p, _d: "On it.", + lambda _p, _d, _m: "On it.", text="can you fix this?", thread_ts="0.5", ) @@ -69,7 +71,7 @@ async def test_mention_in_a_thread_gets_the_thread_so_far(self, client, context) async def test_creating_a_channel_leaves_the_first_turn_to_the_seeded_mention( self, client, context ): - async def create(_prompt, deps): + async def create(_prompt, deps, _media): await invoke(create_code_channel, deps, title="Fix login test") _, start_run = await self.mention_in_origin(client, context, create) @@ -89,7 +91,7 @@ async def create(_prompt, deps): ] async def test_creating_a_channel_twice_points_to_it_once(self, client, context): - async def create_twice(_prompt, deps): + async def create_twice(_prompt, deps, _media): await invoke(create_code_channel, deps, title="Fix login test") await invoke(create_code_channel, deps, title="Fix the login test") @@ -122,7 +124,41 @@ async def test_mention_with_only_a_file_names_it(self, client, context): client, context, "", files=[{"id": "F123", "name": "trace.png"}] ) - assert start_run.call_args.args[1] == "<@U123>: (attachment: trace.png)" + assert start_run.call_args.args[1] == ( + "<@U123>: (attachment: trace.png)\n\n" + "(trace.png wasn't read: Slack didn't include a link to download it)" + ) + + async def test_mention_outside_a_code_channel_gives_the_request_its_files( + self, client, context + ): + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) + file = { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + + with patch("aiohttp.ClientSession.get", return_value=file_download(png)): + run_request, _ = await self.mention_in_origin( + client, + context, + lambda _p, _d, _m: "A null pointer.", + text="why does this fail?", + files=[file], + ) + + assert ( + run_request.call_args.args[0] + == "<@U123>: why does this fail?\n(attachment: trace.png)" + ) + assert run_request.call_args.args[2] == [ + SharedMedia(name="trace.png", media_type="image/png", data=png) + ] async def test_failed_turn_in_a_code_channel_warns_top_level(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) diff --git a/claude-agent-sdk/tests/test_approval_buttons.py b/claude-agent-sdk/tests/test_approval_buttons.py index 8df956f..d113ba7 100644 --- a/claude-agent-sdk/tests/test_approval_buttons.py +++ b/claude-agent-sdk/tests/test_approval_buttons.py @@ -104,7 +104,7 @@ async def resumed(_paused, _approved, _deps): ) return RunOutcome(final_output="Tests pass.", history=HISTORY) - async def start(_history, text, _deps): + async def start(_history, text, _deps, _media): texts.append(text) return RunOutcome(final_output="Linted.", history=HISTORY) diff --git a/claude-agent-sdk/tests/test_files.py b/claude-agent-sdk/tests/test_files.py new file mode 100644 index 0000000..c9f181a --- /dev/null +++ b/claude-agent-sdk/tests/test_files.py @@ -0,0 +1,157 @@ +import base64 +from unittest.mock import patch + +from agent.files import MAX_FILE_BYTES, SharedFiles, SharedMedia, read_files +from tests.conftest import file_download + + +class TestReadFiles: + async def test_image_goes_to_the_model_with_the_token_sent_only_to_slack(self): + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) + + with patch("aiohttp.ClientSession.get", return_value=file_download(png)) as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared == SharedFiles( + media=[SharedMedia(name="trace.png", media_type="image/png", data=png)] + ) + assert get.call_args.args == ( + "https://files.slack.com/files-pri/T123-F123/trace.png", + ) + assert get.call_args.kwargs == { + "headers": {"Authorization": "Bearer xoxb-example"}, + "allow_redirects": False, + } + + async def test_text_file_goes_in_the_prompt(self): + with patch( + "aiohttp.ClientSession.get", + return_value=file_download(b"FAIL tests/test_login.py\n"), + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "build.log", + "mimetype": "text/plain", + "size": 25, + "url_private": "https://files.slack.com/files-pri/T123-F123/build.log", + } + ], + ) + + assert shared == SharedFiles( + text='\nFAIL tests/test_login.py\n\n' + ) + + async def test_file_hosted_outside_slack_is_not_downloaded(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "design.pdf", + "mimetype": "application/pdf", + "mode": "external", + "is_external": True, + "url_private": "https://example.com/design.pdf", + } + ], + ) + + assert shared.text == "(design.pdf wasn't read: it's hosted outside Slack)" + get.assert_not_called() + + async def test_link_to_another_host_does_not_get_the_token(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "url_private": "https://files.slack.com.example.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared.text == "(trace.png wasn't read: it isn't on Slack's file host)" + get.assert_not_called() + + async def test_file_over_the_size_limit_is_not_downloaded(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "recording.png", + "mimetype": "image/png", + "size": MAX_FILE_BYTES + 1, + "url_private": "https://files.slack.com/files-pri/T123-F123/recording.png", + } + ], + ) + + assert shared.text == "(recording.png wasn't read: it's over 5 MB)" + get.assert_not_called() + + async def test_redirected_download_is_not_followed(self): + with patch( + "aiohttp.ClientSession.get", return_value=file_download(b"", status=302) + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared.text == ( + "(trace.png wasn't read: Slack redirected the download, which usually " + "means the app needs reinstalling for the files:read scope)" + ) + + async def test_file_that_is_not_text_is_named_as_not_read(self): + with patch( + "aiohttp.ClientSession.get", + return_value=file_download(bytes([0x50, 0x4B, 0x03, 0x04, 0xFF, 0x00])), + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "build.zip", + "mimetype": "application/zip", + "size": 6, + "url_private": "https://files.slack.com/files-pri/T123-F123/build.zip", + } + ], + ) + + assert shared == SharedFiles( + text="(build.zip wasn't read: only PNG, JPEG, GIF, and WebP images, PDFs, and text files can be read)" + ) diff --git a/claude-agent-sdk/tests/test_message.py b/claude-agent-sdk/tests/test_message.py index db2fdd9..0ed75a9 100644 --- a/claude-agent-sdk/tests/test_message.py +++ b/claude-agent-sdk/tests/test_message.py @@ -1,9 +1,11 @@ +import base64 from unittest.mock import patch +from agent.files import SharedMedia from agent.outcome import RunOutcome from agent.sessions import CodeChannelSession, session_store from listeners.events.message import handle_message -from tests.conftest import code_channel_info +from tests.conftest import code_channel_info, file_download class TestMessage: @@ -40,22 +42,39 @@ async def test_message_with_a_mention_is_left_to_app_mention(self, client, conte async def test_file_shared_in_a_code_channel_runs_a_turn(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) - with patch( - "agent.turns.start_run", return_value=RunOutcome(history=[]) - ) as start_run: + with ( + patch("aiohttp.ClientSession.get", return_value=file_download(png)), + patch( + "agent.turns.start_run", return_value=RunOutcome(history=[]) + ) as start_run, + ): await self.send( client, context, "why does this fail?", subtype="file_share", - files=[{"id": "F123", "name": "trace.png"}], + files=[ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], ) assert ( start_run.call_args.args[1] == "<@U123>: why does this fail?\n(attachment: trace.png)" ) + assert start_run.call_args.args[3] == [ + SharedMedia(name="trace.png", media_type="image/png", data=png) + ] async def test_file_shared_without_text_names_it(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) @@ -71,7 +90,10 @@ async def test_file_shared_without_text_names_it(self, client, context): files=[{"id": "F123", "name": "trace.png"}], ) - assert start_run.call_args.args[1] == "<@U123>: (attachment: trace.png)" + assert start_run.call_args.args[1] == ( + "<@U123>: (attachment: trace.png)\n\n" + "(trace.png wasn't read: Slack didn't include a link to download it)" + ) async def test_edited_message_runs_no_turn(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) @@ -100,7 +122,7 @@ async def test_messages_during_a_turn_run_together_next(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) texts = [] - async def run(_history, text, _deps): + async def run(_history, text, _deps, _media): texts.append(text) if len(texts) == 1: # Two people follow up while the first turn is still running. diff --git a/claude-agent-sdk/tests/test_runs.py b/claude-agent-sdk/tests/test_runs.py index 27348f4..88deb91 100644 --- a/claude-agent-sdk/tests/test_runs.py +++ b/claude-agent-sdk/tests/test_runs.py @@ -1,10 +1,12 @@ """Real agent runs with a scripted model, covering the seams where the turn code meets the SDK.""" +import base64 from pathlib import Path from unittest.mock import patch import agent.agent as agents_module from agent.agent import resume_run, run_request, start_run +from agent.files import SharedMedia from agent.sessions import AgentDeps, CodeChannelSession, RequestDeps from tests.fake_model import FakeModel, call, say @@ -147,6 +149,40 @@ async def test_creating_a_channel_ends_the_request(self, client): assert deps.code_channel_id == "C_NEW" assert len(model.inputs) == 1 + async def test_shared_images_and_pdfs_reach_the_model(self, client, tmp_path): + session = CodeChannelSession(channel_id="C_CODE", workdir=str(tmp_path)) + deps = AgentDeps(client=client, session=session) + png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + pdf = "JVBERi0xLjQKMSAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAyIDAgUj4+ZW5kb2JqCjIgMCBvYmo8PC9UeXBlL1BhZ2VzL0tpZHNbMyAwIFJdL0NvdW50IDE+PmVuZG9iagozIDAgb2JqPDwvVHlwZS9QYWdlL1BhcmVudCAyIDAgUi9NZWRpYUJveFswIDAgNzIgNzJdPj5lbmRvYmoKdHJhaWxlcjw8L1Jvb3QgMSAwIFI+PgolJUVPRgo=" + media = [ + SharedMedia( + name="trace.png", media_type="image/png", data=base64.b64decode(png) + ), + SharedMedia( + name="design.pdf", + media_type="application/pdf", + data=base64.b64decode(pdf), + ), + ] + + async with FakeModel(lambda _n: say("A failing test.")) as model: + outcome = await start_run([], "<@U123>: why does this fail?", deps, media) + + assert outcome.final_output == "A failing test." + blocks = [ + block + for message in model.inputs[0] + if isinstance(message["content"], list) + for block in message["content"] + ] + assert any(b["type"] == "image" and b["source"]["data"] == png for b in blocks) + assert any( + b["type"] == "document" and b["source"]["data"] == pdf for b in blocks + ) + assert any( + b["type"] == "text" and "why does this fail?" in b["text"] for b in blocks + ) + async def test_file_tools_work_without_approval(self, client, tmp_path): session = CodeChannelSession(channel_id="C_CODE", workdir=str(tmp_path)) deps = AgentDeps(client=client, session=session) diff --git a/openai-agents-sdk/AGENTS.md b/openai-agents-sdk/AGENTS.md index 79fb208..5916760 100644 --- a/openai-agents-sdk/AGENTS.md +++ b/openai-agents-sdk/AGENTS.md @@ -20,7 +20,7 @@ Slack skills are pre-installed in `.agents/skills` (and `.claude/skills` for Cla **Stopping** sets `session.stopped`, and so does archiving the channel from Slack. Every code channel tool lists the `session_stopped` tool input guardrail (`agent/guardrails.py`), which skips the call and tells the model to wrap up, and the turn posts nothing when it finishes. -**Conversation history** comes from `result.to_input_list()` and is stored on the `CodeChannelSession` (`agent/sessions.py`), keyed by code channel. Follow-up turns pass `session.history + [{"role": "user", "content": text}]`. +**Conversation history** comes from `result.to_input_list()` and is stored on the `CodeChannelSession` (`agent/sessions.py`), keyed by code channel. Follow-up turns pass `session.history + [{"role": "user", "content": text}]`. Shared images and PDFs make that message's content a list, with an `input_image` or `input_file` data URL for each before the `input_text`. **Command approvals.** `run_command_needs_approval` in `agent/guardrails.py` wraps `command_needs_approval()` from `agent/approvals.py` in the SDK's `needs_approval` hook for `run_command`. A paused run is a `PausedRun` (the `RunState` and its `ToolApprovalItem`), parked in `pending_store` with the ts of its Approve/Deny message, so a click only resumes the run its buttons were posted for. A newer message in the channel retires a pending approval, so a late click can't resume an older run over it. diff --git a/openai-agents-sdk/README.md b/openai-agents-sdk/README.md index a1b6e41..172ca06 100644 --- a/openai-agents-sdk/README.md +++ b/openai-agents-sdk/README.md @@ -46,6 +46,7 @@ Each code channel method is a tool the model calls when it decides to, in [`agen - **Archiving from Slack.** On `channel_archive` or `group_archive`, the app forgets the session and deletes its working directory, the same cleanup `archive_channel` does when the agent wraps up. - **Picking up code channels.** A message, mention, or slash command in a code channel the app has no state for, whether the seeded request in a channel the agent just created, one started from Slack's UI, or one forgotten after a restart, is recognized with `conversations.info` (`properties.record_channel.record_type == "agent_channel"`) and picked up as a session. Other channels are looked up once and remembered. - **The conversation comes along.** A new session reads the thread or direct message its channel was started from (`properties.agent_session.origin_link`) and gives it to the agent's first turn, so a request like "fix this" keeps its context. +- **Shared files.** Files shared with a request or in a code channel are downloaded with the bot token, which needs `files:read` and goes only to `files.slack.com`. Images and PDFs go to the model as they are, and text files go into the prompt. The agent is told about any other file, or one over 5 MB, that it couldn't read. - **One turn at a time.** Messages that arrive while the agent works wait, and go into its next turn together, each labeled with who sent it. The stop button drops them along with the turn. - **Creating a channel is the agent's call.** The prompt in [`agent/prompts.py`](./agent/prompts.py) follows Slack's guidance: create a channel for multi-step work like changing code or running tests, and reply in place for anything that fits in one message. - **Idempotent creation.** `create_code_channel` takes only a title. Its `session_id` comes from the triggering message, so a repeated call or a retried event reuses the same channel. The first turn only ever starts from the seeded mention, so it runs once. diff --git a/openai-agents-sdk/agent/agent.py b/openai-agents-sdk/agent/agent.py index 80db649..f6dbf4e 100644 --- a/openai-agents-sdk/agent/agent.py +++ b/openai-agents-sdk/agent/agent.py @@ -6,7 +6,9 @@ `RunOutcome`. """ +import base64 import json +from collections.abc import Sequence from dataclasses import dataclass from agents import ( @@ -22,6 +24,7 @@ ToolsToFinalOutputResult, ) +from agent.files import SharedMedia from agent.outcome import RunOutcome from agent.prompts import REQUEST_PROMPT, SYSTEM_PROMPT from agent.sessions import AgentDeps, RequestDeps @@ -155,17 +158,39 @@ def _out_of_turns(_data: RunErrorHandlerInput) -> RunErrorHandlerResult: ) -async def run_request(prompt: str, deps: RequestDeps) -> str | None: +def _media_input(file: SharedMedia) -> dict: + """The input that gives the model a shared image or PDF as it is.""" + data = f"data:{file.media_type};base64,{base64.b64encode(file.data).decode()}" + if file.media_type == "application/pdf": + return {"type": "input_file", "file_data": data, "filename": file.name} + return {"type": "input_image", "image_url": data, "detail": "auto"} + + +def _user_message(text: str, media: Sequence[SharedMedia]) -> dict: + """The user message for a run: the text, with any shared images and PDFs before it.""" + if not media: + return {"role": "user", "content": text} + content = [*map(_media_input, media), {"type": "input_text", "text": text}] + return {"role": "user", "content": content} + + +async def run_request( + prompt: str, deps: RequestDeps, media: Sequence[SharedMedia] = () +) -> str | None: """Reply to a request outside a code channel, or create one for it via the tool.""" - result = await Runner.run(request_agent, input=prompt, context=deps) + result = await Runner.run( + request_agent, input=[_user_message(prompt, media)], context=deps + ) return result.final_output -async def start_run(history: list, text: str, deps: AgentDeps) -> RunOutcome: +async def start_run( + history: list, text: str, deps: AgentDeps, media: Sequence[SharedMedia] = () +) -> RunOutcome: """Start an agent turn. May complete, or pause awaiting command approval.""" result = await Runner.run( agent, - input=history + [{"role": "user", "content": text}], + input=history + [_user_message(text, media)], context=deps, max_turns=MAX_TURNS, error_handlers={"max_turns": _out_of_turns}, diff --git a/openai-agents-sdk/agent/files.py b/openai-agents-sdk/agent/files.py new file mode 100644 index 0000000..da2983e --- /dev/null +++ b/openai-agents-sdk/agent/files.py @@ -0,0 +1,125 @@ +"""Files shared with a message, downloaded from Slack so the agent can read them. + +Images and PDFs go to the model as they are, and text files go in the prompt. +Any other file is named in the prompt as not read, with the reason. +""" + +import logging +from collections.abc import Sequence +from dataclasses import dataclass, field +from urllib.parse import urlparse + +import aiohttp + +from agent.workspace import clip + +logger = logging.getLogger(__name__) + +# Slack serves the files it hosts from here, and the bot token goes nowhere else. +SLACK_FILE_HOST = "files.slack.com" + +# Well under the models' limits for one image or PDF, which count the base64 encoding. +MAX_FILE_BYTES = 5 * 1024 * 1024 + +# About 25,000 tokens of a text file. Clipping keeps most of the end, where a log's errors usually are. +MAX_TEXT_CHARS = 100_000 + +TOO_LARGE = f"it's over {MAX_FILE_BYTES // 1024 // 1024} MB" + +# Slack redirects a download it won't serve to the token, most often one without the `files:read` scope. +REDIRECTED = "Slack redirected the download, which usually means the app needs reinstalling for the files:read scope" + +MEDIA_TYPES = ("application/pdf", "image/gif", "image/jpeg", "image/png", "image/webp") + + +class Unreadable(Exception): + """A reason a shared file wasn't read, told to the model.""" + + +@dataclass +class SharedMedia: + """An image or PDF shared with a message, for the model to read as it is.""" + + name: str + # One of `MEDIA_TYPES`. + media_type: str + data: bytes + + +@dataclass +class SharedFiles: + """What the agent reads from a message's files. + + `text` holds each text file and a note for each file that wasn't read, for + the prompt. `media` holds the images and PDFs to send with it. + """ + + text: str = "" + media: list[SharedMedia] = field(default_factory=list) + + +async def _download(token: str | None, file: dict) -> bytes: + """Download a file Slack hosts, sending the bot token only to Slack's file host. + + A redirect isn't followed, since it could lead anywhere with the token. + """ + if file.get("mode") == "external" or file.get("is_external"): + raise Unreadable("it's hosted outside Slack") + if (file.get("size") or 0) > MAX_FILE_BYTES: + raise Unreadable(TOO_LARGE) + url = file.get("url_private") + if not url: + raise Unreadable("Slack didn't include a link to download it") + parsed = urlparse(url) + if parsed.scheme != "https" or parsed.hostname != SLACK_FILE_HOST: + raise Unreadable("it isn't on Slack's file host") + async with ( + aiohttp.ClientSession() as http, + http.get( + url, headers={"Authorization": f"Bearer {token}"}, allow_redirects=False + ) as response, + ): + if 300 <= response.status < 400: + raise Unreadable(REDIRECTED) + if response.status != 200: + raise Unreadable(f"downloading it returned HTTP {response.status}") + data = await response.read() + if len(data) > MAX_FILE_BYTES: + raise Unreadable(TOO_LARGE) + return data + + +def _decoded(data: bytes) -> str | None: + """A file's bytes as text, or None for a file that isn't text.""" + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + return None + return None if "\0" in text else text + + +async def read_files(token: str | None, files: Sequence[dict]) -> SharedFiles: + """Read the files shared with a message. The bot token needs the `files:read` scope.""" + parts: list[str] = [] + media: list[SharedMedia] = [] + for file in files: + name = file.get("name") or file.get("id") or "a file" + try: + data = await _download(token, file) + if file.get("mimetype") in MEDIA_TYPES: + media.append( + SharedMedia(name=name, media_type=file["mimetype"], data=data) + ) + continue + text = _decoded(data) + if text is None: + raise Unreadable( + "only PNG, JPEG, GIF, and WebP images, PDFs, and text files can be read" + ) + parts.append(f'\n{clip(text, MAX_TEXT_CHARS)}\n') + except Unreadable as e: + parts.append(f"({name} wasn't read: {e})") + except Exception: + logger.warning("Couldn't read %s", name, exc_info=True) + parts.append(f"({name} wasn't read: it couldn't be downloaded)") + return SharedFiles(text="\n\n".join(parts), media=media) diff --git a/openai-agents-sdk/agent/sessions.py b/openai-agents-sdk/agent/sessions.py index 48205ac..0ca55b3 100644 --- a/openai-agents-sdk/agent/sessions.py +++ b/openai-agents-sdk/agent/sessions.py @@ -17,6 +17,14 @@ from slack_sdk.web.async_client import AsyncWebClient +@dataclass +class InboxMessage: + """A message waiting for the next turn: its text, starting with who sent it, and the files shared with it.""" + + text: str + files: list[dict] = field(default_factory=list) + + @dataclass class CodeChannelSession: """Per-code-channel working state.""" @@ -33,8 +41,8 @@ class CodeChannelSession: base_commit: str | None = None plan_canvas_id: str | None = None history: list = field(default_factory=list) - # Messages waiting for the next turn, each starting with who sent it. - inbox: list[str] = field(default_factory=list) + # Messages waiting for the next turn. + inbox: list[InboxMessage] = field(default_factory=list) # Set by the native stop button, or when the session is discarded. Checked # before posting and before every tool call so a stopped session goes quiet; # cleared when the user starts a new turn. diff --git a/openai-agents-sdk/agent/turns.py b/openai-agents-sdk/agent/turns.py index 35b2559..22b5912 100644 --- a/openai-agents-sdk/agent/turns.py +++ b/openai-agents-sdk/agent/turns.py @@ -8,7 +8,7 @@ """ import logging -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Sequence from functools import partial from slack_sdk.errors import SlackApiError @@ -23,8 +23,15 @@ from agent.agent import resume_run, run_request, start_run from agent.approvals import PendingApproval, pending_store from agent.context import origin_context, recent_context, thread_context +from agent.files import SharedMedia, read_files from agent.outcome import RunOutcome -from agent.sessions import AgentDeps, CodeChannelSession, RequestDeps, session_store +from agent.sessions import ( + AgentDeps, + CodeChannelSession, + InboxMessage, + RequestDeps, + session_store, +) from agent.workspace import clip logger = logging.getLogger(__name__) @@ -180,6 +187,19 @@ async def _run(deps: AgentDeps, run: Callable[[], Awaitable[RunOutcome]]) -> boo return False +async def _start_turn( + deps: AgentDeps, history: list, origin: str, messages: list[InboxMessage] +) -> RunOutcome: + """Start a turn with the messages waiting for it, after reading the files shared with them.""" + texts = [origin] if origin else [] + media: list[SharedMedia] = [] + for message in messages: + shared = await read_files(deps.client.token, message.files) + texts.append("\n\n".join(filter(None, [message.text, shared.text]))) + media.extend(shared.media) + return await start_run(history, "\n\n".join(texts), deps, media) + + async def _run_inbox(client: AsyncWebClient, session: CodeChannelSession) -> None: """Run turns until the inbox is empty or a turn pauses on an approval.""" while session.inbox and not session.archived: @@ -187,16 +207,18 @@ async def _run_inbox(client: AsyncWebClient, session: CodeChannelSession) -> Non # the session back up. session.stopped = False messages, session.inbox = session.inbox, [] - text = "\n\n".join(messages) + origin = "" if session.origin_context and not session.history: - text = ( + origin = ( "This code channel was started from this conversation:\n" - f"{session.origin_context}\n\n{text}" + f"{session.origin_context}" ) session.origin_context = None deps = AgentDeps(client=client, session=session) - paused = await _run(deps, partial(start_run, session.history, text, deps)) + paused = await _run( + deps, partial(_start_turn, deps, session.history, origin, messages) + ) if paused: return @@ -210,12 +232,14 @@ async def answer_request( text: str, user_id: str, in_dm: bool, + files: Sequence[dict] = (), ) -> None: """Reply to a mention or direct message outside a code channel, or create one for it. A mention in a channel is answered in its thread. A direct message is answered where it was sent. The agent gets the conversation before the request, from - the thread or from the direct message, so it can follow along. + the thread or from the direct message, so it can follow along, and the files + shared with the request. """ reply_ts = thread_ts or (None if in_dm else message_ts) if not text: @@ -235,7 +259,8 @@ async def answer_request( earlier = await recent_context(client, channel_id, before_ts=message_ts) else: earlier = "" - prompt = f"<@{user_id}>: {text}" + shared = await read_files(client.token, files) + prompt = "\n\n".join(filter(None, [f"<@{user_id}>: {text}", shared.text])) if earlier: prompt = f"Earlier in this conversation:\n{earlier}\n\n{prompt}" @@ -245,7 +270,7 @@ async def answer_request( message_ts=message_ts, thread_ts=reply_ts, ) - reply = await run_request(prompt, deps) + reply = await run_request(prompt, deps, shared.media) # When the agent created a code channel, the work continues there. if deps.code_channel_id is None: await client.chat_postMessage( @@ -313,14 +338,16 @@ async def run_turn( session: CodeChannelSession, text: str, user_id: str, + files: Sequence[dict] = (), ) -> None: """Run a message or slash command in a code channel as a turn and post the outcome. Mentions, plain messages, and slash commands all funnel through here. A message that arrives while a turn runs waits in the session's inbox, and - everything waiting runs together as the next turn. + everything waiting runs together as the next turn. The files shared with + each message are read when its turn starts. """ - session.inbox.append(f"<@{user_id}>: {text}") + session.inbox.append(InboxMessage(text=f"<@{user_id}>: {text}", files=list(files))) if session.turn_lock.locked(): # The running turn takes this message when it finishes. return diff --git a/openai-agents-sdk/app_oauth.py b/openai-agents-sdk/app_oauth.py index 569e5c3..dcb7159 100644 --- a/openai-agents-sdk/app_oauth.py +++ b/openai-agents-sdk/app_oauth.py @@ -52,6 +52,7 @@ async def failure(args: AsyncFailureArgs) -> BoltResponse: "channels:read", "chat:write", "code_channels:manage", + "files:read", "groups:history", "groups:read", "im:history", diff --git a/openai-agents-sdk/listeners/events/app_mentioned.py b/openai-agents-sdk/listeners/events/app_mentioned.py index 48b8295..d9a48ab 100644 --- a/openai-agents-sdk/listeners/events/app_mentioned.py +++ b/openai-agents-sdk/listeners/events/app_mentioned.py @@ -24,7 +24,11 @@ async def handle_app_mentioned( session = await find_session(client, channel_id) if session is not None: await run_turn( - client=client, session=session, text=text, user_id=context.user_id + client=client, + session=session, + text=text, + user_id=context.user_id, + files=files, ) return @@ -36,4 +40,5 @@ async def handle_app_mentioned( text=text, user_id=context.user_id, in_dm=False, + files=files, ) diff --git a/openai-agents-sdk/listeners/events/message.py b/openai-agents-sdk/listeners/events/message.py index f3f7618..735a70f 100644 --- a/openai-agents-sdk/listeners/events/message.py +++ b/openai-agents-sdk/listeners/events/message.py @@ -33,6 +33,7 @@ async def handle_message( text=text.replace(mention, "").strip(), user_id=context.user_id, in_dm=True, + files=files, ) return @@ -42,4 +43,6 @@ async def handle_message( session = await find_session(client, channel_id) if session is None: return - await run_turn(client=client, session=session, text=text, user_id=context.user_id) + await run_turn( + client=client, session=session, text=text, user_id=context.user_id, files=files + ) diff --git a/openai-agents-sdk/manifest.json b/openai-agents-sdk/manifest.json index 4347a19..0b8ad7d 100644 --- a/openai-agents-sdk/manifest.json +++ b/openai-agents-sdk/manifest.json @@ -45,6 +45,7 @@ "channels:read", "chat:write", "code_channels:manage", + "files:read", "groups:history", "groups:read", "im:history", diff --git a/openai-agents-sdk/tests/conftest.py b/openai-agents-sdk/tests/conftest.py index f8b4fed..d90b5db 100644 --- a/openai-agents-sdk/tests/conftest.py +++ b/openai-agents-sdk/tests/conftest.py @@ -1,4 +1,4 @@ -from unittest.mock import Mock +from unittest.mock import AsyncMock, MagicMock, Mock import pytest from agents import set_tracing_disabled @@ -28,6 +28,7 @@ def forget_sessions(): def client() -> Mock: """A Slack client whose methods match the real one's, so a wrong call fails.""" client = Mock(AsyncWebClient) + client.token = "xoxb-example" client.chat_postMessage.return_value = {"ts": "8.8"} return client @@ -57,3 +58,12 @@ def code_channel_info(origin_channel_id: str = "C_ORIGIN", origin_ts: str = "1.1 } } } + + +def file_download(body: bytes, status: int = 200) -> MagicMock: + """A response to downloading a file from Slack, for patching `aiohttp.ClientSession.get`.""" + response = MagicMock() + response.status = status + response.read = AsyncMock(return_value=body) + response.__aenter__.return_value = response + return response diff --git a/openai-agents-sdk/tests/test_agent_session_stopped.py b/openai-agents-sdk/tests/test_agent_session_stopped.py index 14008c6..49e3300 100644 --- a/openai-agents-sdk/tests/test_agent_session_stopped.py +++ b/openai-agents-sdk/tests/test_agent_session_stopped.py @@ -2,7 +2,7 @@ from agent.approvals import PendingApproval, pending_store from agent.outcome import RunOutcome -from agent.sessions import CodeChannelSession, session_store +from agent.sessions import CodeChannelSession, InboxMessage, session_store from listeners.events.agent_session_stopped import handle_agent_session_stopped from listeners.events.message import handle_message @@ -21,7 +21,9 @@ async def send(self, client, context, text: str): ) async def test_stop_confirms_and_leaves_processing(self, client, context): - session = CodeChannelSession(channel_id="C_CODE", inbox=["<@U1>: queued"]) + session = CodeChannelSession( + channel_id="C_CODE", inbox=[InboxMessage(text="<@U1>: queued")] + ) session_store.put(session) await self.stop(client, context) @@ -57,7 +59,7 @@ async def test_stop_drops_the_pending_approval_and_its_buttons( async def test_stopped_turn_posts_nothing_more(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) - async def stop_mid_run(_history, _text, _deps): + async def stop_mid_run(_history, _text, _deps, _media): await self.stop(client, context) return RunOutcome(final_output="Done.", history=[]) @@ -79,7 +81,7 @@ async def test_a_message_after_the_stop_picks_back_up(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) texts = [] - async def run(_history, text, _deps): + async def run(_history, text, _deps, _media): texts.append(text) if len(texts) == 1: await self.stop(client, context) diff --git a/openai-agents-sdk/tests/test_app_mentioned.py b/openai-agents-sdk/tests/test_app_mentioned.py index d11711a..f9d85e0 100644 --- a/openai-agents-sdk/tests/test_app_mentioned.py +++ b/openai-agents-sdk/tests/test_app_mentioned.py @@ -1,10 +1,12 @@ +import base64 from unittest.mock import patch +from agent.files import SharedMedia from agent.outcome import RunOutcome from agent.sessions import CodeChannelSession, session_store from agent.tools import create_code_channel from listeners.events.app_mentioned import handle_app_mentioned -from tests.conftest import code_channel_info +from tests.conftest import code_channel_info, file_download from tests.test_tools import invoke @@ -33,7 +35,7 @@ async def test_mention_answered_in_place_opens_no_channel(self, client, context) _, start_run = await self.mention_in_origin( client, context, - lambda _prompt, _deps: "It's a billing service.", + lambda _prompt, _deps, _media: "It's a billing service.", text="what does billing do?", ) @@ -56,7 +58,7 @@ async def test_mention_in_a_thread_gets_the_thread_so_far(self, client, context) run_request, _ = await self.mention_in_origin( client, context, - lambda _p, _d: "On it.", + lambda _p, _d, _m: "On it.", text="can you fix this?", thread_ts="0.5", ) @@ -69,7 +71,7 @@ async def test_mention_in_a_thread_gets_the_thread_so_far(self, client, context) async def test_creating_a_channel_leaves_the_first_turn_to_the_seeded_mention( self, client, context ): - async def create(_prompt, deps): + async def create(_prompt, deps, _media): await invoke(create_code_channel, deps, title="Fix login test") _, start_run = await self.mention_in_origin(client, context, create) @@ -89,7 +91,7 @@ async def create(_prompt, deps): ] async def test_creating_a_channel_twice_points_to_it_once(self, client, context): - async def create_twice(_prompt, deps): + async def create_twice(_prompt, deps, _media): await invoke(create_code_channel, deps, title="Fix login test") await invoke(create_code_channel, deps, title="Fix the login test") @@ -122,7 +124,41 @@ async def test_mention_with_only_a_file_names_it(self, client, context): client, context, "", files=[{"id": "F123", "name": "trace.png"}] ) - assert start_run.call_args.args[1] == "<@U123>: (attachment: trace.png)" + assert start_run.call_args.args[1] == ( + "<@U123>: (attachment: trace.png)\n\n" + "(trace.png wasn't read: Slack didn't include a link to download it)" + ) + + async def test_mention_outside_a_code_channel_gives_the_request_its_files( + self, client, context + ): + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) + file = { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + + with patch("aiohttp.ClientSession.get", return_value=file_download(png)): + run_request, _ = await self.mention_in_origin( + client, + context, + lambda _p, _d, _m: "A null pointer.", + text="why does this fail?", + files=[file], + ) + + assert ( + run_request.call_args.args[0] + == "<@U123>: why does this fail?\n(attachment: trace.png)" + ) + assert run_request.call_args.args[2] == [ + SharedMedia(name="trace.png", media_type="image/png", data=png) + ] async def test_failed_turn_in_a_code_channel_warns_top_level(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) diff --git a/openai-agents-sdk/tests/test_approval_buttons.py b/openai-agents-sdk/tests/test_approval_buttons.py index 8df956f..d113ba7 100644 --- a/openai-agents-sdk/tests/test_approval_buttons.py +++ b/openai-agents-sdk/tests/test_approval_buttons.py @@ -104,7 +104,7 @@ async def resumed(_paused, _approved, _deps): ) return RunOutcome(final_output="Tests pass.", history=HISTORY) - async def start(_history, text, _deps): + async def start(_history, text, _deps, _media): texts.append(text) return RunOutcome(final_output="Linted.", history=HISTORY) diff --git a/openai-agents-sdk/tests/test_files.py b/openai-agents-sdk/tests/test_files.py new file mode 100644 index 0000000..c9f181a --- /dev/null +++ b/openai-agents-sdk/tests/test_files.py @@ -0,0 +1,157 @@ +import base64 +from unittest.mock import patch + +from agent.files import MAX_FILE_BYTES, SharedFiles, SharedMedia, read_files +from tests.conftest import file_download + + +class TestReadFiles: + async def test_image_goes_to_the_model_with_the_token_sent_only_to_slack(self): + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) + + with patch("aiohttp.ClientSession.get", return_value=file_download(png)) as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared == SharedFiles( + media=[SharedMedia(name="trace.png", media_type="image/png", data=png)] + ) + assert get.call_args.args == ( + "https://files.slack.com/files-pri/T123-F123/trace.png", + ) + assert get.call_args.kwargs == { + "headers": {"Authorization": "Bearer xoxb-example"}, + "allow_redirects": False, + } + + async def test_text_file_goes_in_the_prompt(self): + with patch( + "aiohttp.ClientSession.get", + return_value=file_download(b"FAIL tests/test_login.py\n"), + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "build.log", + "mimetype": "text/plain", + "size": 25, + "url_private": "https://files.slack.com/files-pri/T123-F123/build.log", + } + ], + ) + + assert shared == SharedFiles( + text='\nFAIL tests/test_login.py\n\n' + ) + + async def test_file_hosted_outside_slack_is_not_downloaded(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "design.pdf", + "mimetype": "application/pdf", + "mode": "external", + "is_external": True, + "url_private": "https://example.com/design.pdf", + } + ], + ) + + assert shared.text == "(design.pdf wasn't read: it's hosted outside Slack)" + get.assert_not_called() + + async def test_link_to_another_host_does_not_get_the_token(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "url_private": "https://files.slack.com.example.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared.text == "(trace.png wasn't read: it isn't on Slack's file host)" + get.assert_not_called() + + async def test_file_over_the_size_limit_is_not_downloaded(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "recording.png", + "mimetype": "image/png", + "size": MAX_FILE_BYTES + 1, + "url_private": "https://files.slack.com/files-pri/T123-F123/recording.png", + } + ], + ) + + assert shared.text == "(recording.png wasn't read: it's over 5 MB)" + get.assert_not_called() + + async def test_redirected_download_is_not_followed(self): + with patch( + "aiohttp.ClientSession.get", return_value=file_download(b"", status=302) + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared.text == ( + "(trace.png wasn't read: Slack redirected the download, which usually " + "means the app needs reinstalling for the files:read scope)" + ) + + async def test_file_that_is_not_text_is_named_as_not_read(self): + with patch( + "aiohttp.ClientSession.get", + return_value=file_download(bytes([0x50, 0x4B, 0x03, 0x04, 0xFF, 0x00])), + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "build.zip", + "mimetype": "application/zip", + "size": 6, + "url_private": "https://files.slack.com/files-pri/T123-F123/build.zip", + } + ], + ) + + assert shared == SharedFiles( + text="(build.zip wasn't read: only PNG, JPEG, GIF, and WebP images, PDFs, and text files can be read)" + ) diff --git a/openai-agents-sdk/tests/test_message.py b/openai-agents-sdk/tests/test_message.py index db2fdd9..0ed75a9 100644 --- a/openai-agents-sdk/tests/test_message.py +++ b/openai-agents-sdk/tests/test_message.py @@ -1,9 +1,11 @@ +import base64 from unittest.mock import patch +from agent.files import SharedMedia from agent.outcome import RunOutcome from agent.sessions import CodeChannelSession, session_store from listeners.events.message import handle_message -from tests.conftest import code_channel_info +from tests.conftest import code_channel_info, file_download class TestMessage: @@ -40,22 +42,39 @@ async def test_message_with_a_mention_is_left_to_app_mention(self, client, conte async def test_file_shared_in_a_code_channel_runs_a_turn(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) - with patch( - "agent.turns.start_run", return_value=RunOutcome(history=[]) - ) as start_run: + with ( + patch("aiohttp.ClientSession.get", return_value=file_download(png)), + patch( + "agent.turns.start_run", return_value=RunOutcome(history=[]) + ) as start_run, + ): await self.send( client, context, "why does this fail?", subtype="file_share", - files=[{"id": "F123", "name": "trace.png"}], + files=[ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], ) assert ( start_run.call_args.args[1] == "<@U123>: why does this fail?\n(attachment: trace.png)" ) + assert start_run.call_args.args[3] == [ + SharedMedia(name="trace.png", media_type="image/png", data=png) + ] async def test_file_shared_without_text_names_it(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) @@ -71,7 +90,10 @@ async def test_file_shared_without_text_names_it(self, client, context): files=[{"id": "F123", "name": "trace.png"}], ) - assert start_run.call_args.args[1] == "<@U123>: (attachment: trace.png)" + assert start_run.call_args.args[1] == ( + "<@U123>: (attachment: trace.png)\n\n" + "(trace.png wasn't read: Slack didn't include a link to download it)" + ) async def test_edited_message_runs_no_turn(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) @@ -100,7 +122,7 @@ async def test_messages_during_a_turn_run_together_next(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) texts = [] - async def run(_history, text, _deps): + async def run(_history, text, _deps, _media): texts.append(text) if len(texts) == 1: # Two people follow up while the first turn is still running. diff --git a/openai-agents-sdk/tests/test_runs.py b/openai-agents-sdk/tests/test_runs.py index 8988930..8824c27 100644 --- a/openai-agents-sdk/tests/test_runs.py +++ b/openai-agents-sdk/tests/test_runs.py @@ -1,10 +1,12 @@ """Real agent runs with a scripted model, covering the seams where the turn code meets the SDK.""" +import base64 from pathlib import Path from unittest.mock import patch import agent.agent as agents_module from agent.agent import resume_run, run_request, start_run +from agent.files import SharedMedia from agent.sessions import AgentDeps, CodeChannelSession, RequestDeps from tests.fake_model import FakeModel, call, say @@ -134,6 +136,42 @@ async def test_creating_a_channel_ends_the_request(self, client): assert deps.code_channel_id == "C_NEW" assert len(model.inputs) == 1 + async def test_shared_images_and_pdfs_reach_the_model(self, client, tmp_path): + session = CodeChannelSession(channel_id="C_CODE", workdir=str(tmp_path)) + deps = AgentDeps(client=client, session=session) + png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + pdf = "JVBERi0xLjQKMSAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAyIDAgUj4+ZW5kb2JqCjIgMCBvYmo8PC9UeXBlL1BhZ2VzL0tpZHNbMyAwIFJdL0NvdW50IDE+PmVuZG9iagozIDAgb2JqPDwvVHlwZS9QYWdlL1BhcmVudCAyIDAgUi9NZWRpYUJveFswIDAgNzIgNzJdPj5lbmRvYmoKdHJhaWxlcjw8L1Jvb3QgMSAwIFI+PgolJUVPRgo=" + media = [ + SharedMedia( + name="trace.png", media_type="image/png", data=base64.b64decode(png) + ), + SharedMedia( + name="design.pdf", + media_type="application/pdf", + data=base64.b64decode(pdf), + ), + ] + replaced, model = coding_agent(lambda _n: say("A failing test.")) + + with replaced: + outcome = await start_run([], "<@U123>: why does this fail?", deps, media) + + assert outcome.final_output == "A failing test." + + assert model.inputs[0][-1]["content"] == [ + { + "type": "input_image", + "image_url": f"data:image/png;base64,{png}", + "detail": "auto", + }, + { + "type": "input_file", + "file_data": f"data:application/pdf;base64,{pdf}", + "filename": "design.pdf", + }, + {"type": "input_text", "text": "<@U123>: why does this fail?"}, + ] + async def test_file_tools_work_without_approval(self, client, tmp_path): session = CodeChannelSession(channel_id="C_CODE", workdir=str(tmp_path)) deps = AgentDeps(client=client, session=session) diff --git a/pydantic-ai/AGENTS.md b/pydantic-ai/AGENTS.md index 392b9ec..da64db3 100644 --- a/pydantic-ai/AGENTS.md +++ b/pydantic-ai/AGENTS.md @@ -22,7 +22,7 @@ Slack skills are pre-installed in `.agents/skills` (and `.claude/skills` for Cla **Stopping** sets `session.stopped`, and so does archiving the channel from Slack. The `guardrails` capability (`agent/guardrails.py`) skips every tool call once it's set, with `SkipToolExecution`, and tells the model to wrap up. `archive_channel` is an output function, so a hook on the output does the same for it. The turn posts nothing when it finishes. -**Conversation history** is the run's `all_messages()`, a `list[ModelMessage]` stored on the `CodeChannelSession` (`agent/sessions.py`), keyed by code channel. Follow-up turns pass it as `message_history` with the new text as the prompt. +**Conversation history** is the run's `all_messages()`, a `list[ModelMessage]` stored on the `CodeChannelSession` (`agent/sessions.py`), keyed by code channel. Follow-up turns pass it as `message_history` with the new text as the prompt. Shared images and PDFs go before the text in the prompt, as `BinaryContent`. **Command approvals.** `run_command_needs_approval` in `agent/guardrails.py` is a `before_tool_execute` hook for `run_command` that raises `ApprovalRequired` when `command_needs_approval()` from `agent/approvals.py` says so. That ends the run with `DeferredToolRequests` as its output. A paused run is a `PausedRun` (the messages, the requests, and the usage so far), parked in `pending_store` with the ts of its Approve/Deny message, so a click only resumes the run its buttons were posted for. Resuming passes `deferred_tool_results` with `True` or a `ToolDenied`, and the usage, so the turn keeps counting toward `MAX_TURNS`. Every pending call needs an answer, so if one step asked for more than one command, the others are answered as not run and the model can ask again. A newer message in the channel retires a pending approval, so a late click can't resume an older run over it. diff --git a/pydantic-ai/README.md b/pydantic-ai/README.md index d4a31b5..9e49d9c 100644 --- a/pydantic-ai/README.md +++ b/pydantic-ai/README.md @@ -46,6 +46,7 @@ Each code channel method is a tool the model calls when it decides to, in [`agen - **Archiving from Slack.** On `channel_archive` or `group_archive`, the app forgets the session and deletes its working directory, the same cleanup `archive_channel` does when the agent wraps up. - **Picking up code channels.** A message, mention, or slash command in a code channel the app has no state for, whether the seeded request in a channel the agent just created, one started from Slack's UI, or one forgotten after a restart, is recognized with `conversations.info` (`properties.record_channel.record_type == "agent_channel"`) and picked up as a session. Other channels are looked up once and remembered. - **The conversation comes along.** A new session reads the thread or direct message its channel was started from (`properties.agent_session.origin_link`) and gives it to the agent's first turn, so a request like "fix this" keeps its context. +- **Shared files.** Files shared with a request or in a code channel are downloaded with the bot token, which needs `files:read` and goes only to `files.slack.com`. Images and PDFs go to the model as they are, and text files go into the prompt. The agent is told about any other file, or one over 5 MB, that it couldn't read. - **One turn at a time.** Messages that arrive while the agent works wait, and go into its next turn together, each labeled with who sent it. The stop button drops them along with the turn. - **Creating a channel is the agent's call.** The prompt in [`agent/prompts.py`](./agent/prompts.py) follows Slack's guidance: create a channel for multi-step work like changing code or running tests, and reply in place for anything that fits in one message. - **Idempotent creation.** `create_code_channel` takes only a title. Its `session_id` comes from the triggering message, so a repeated call or a retried event reuses the same channel. The first turn only ever starts from the seeded mention, so it runs once. diff --git a/pydantic-ai/agent/agent.py b/pydantic-ai/agent/agent.py index 927edba..ba92f31 100644 --- a/pydantic-ai/agent/agent.py +++ b/pydantic-ai/agent/agent.py @@ -7,10 +7,12 @@ """ import os +from collections.abc import Sequence from dataclasses import dataclass from pydantic_ai import ( Agent, + BinaryContent, DeferredToolRequests, ToolDenied, ToolOutput, @@ -29,6 +31,7 @@ from pydantic_ai.models.openai import OpenAICompaction from pydantic_ai.usage import RunUsage +from agent.files import SharedMedia from agent.guardrails import guardrails from agent.outcome import RunOutcome from agent.prompts import REQUEST_PROMPT, SYSTEM_PROMPT @@ -196,16 +199,32 @@ async def _run(deps: AgentDeps, **run_args) -> RunOutcome: return _settle(run.result, deps) -async def run_request(prompt: str, deps: RequestDeps) -> str | None: +def _user_prompt(text: str, media: Sequence[SharedMedia]) -> str | list: + """A run's prompt: the text alone, or the shared images and PDFs before it.""" + if not media: + return text + return [ + *(BinaryContent(data=file.data, media_type=file.media_type) for file in media), + text, + ] + + +async def run_request( + prompt: str, deps: RequestDeps, media: Sequence[SharedMedia] = () +) -> str | None: """Reply to a request outside a code channel, or create one for it via the tool.""" - result = await request_agent.run(prompt, deps=deps) + result = await request_agent.run(_user_prompt(prompt, media), deps=deps) # Once the channel exists, the output is the tool's result, not a reply. return None if deps.code_channel_id else result.output -async def start_run(history: list, text: str, deps: AgentDeps) -> RunOutcome: +async def start_run( + history: list, text: str, deps: AgentDeps, media: Sequence[SharedMedia] = () +) -> RunOutcome: """Start an agent turn. May complete, or pause awaiting command approval.""" - return await _run(deps, user_prompt=text, message_history=history) + return await _run( + deps, user_prompt=_user_prompt(text, media), message_history=history + ) async def resume_run(paused: PausedRun, approved: bool, deps: AgentDeps) -> RunOutcome: diff --git a/pydantic-ai/agent/files.py b/pydantic-ai/agent/files.py new file mode 100644 index 0000000..da2983e --- /dev/null +++ b/pydantic-ai/agent/files.py @@ -0,0 +1,125 @@ +"""Files shared with a message, downloaded from Slack so the agent can read them. + +Images and PDFs go to the model as they are, and text files go in the prompt. +Any other file is named in the prompt as not read, with the reason. +""" + +import logging +from collections.abc import Sequence +from dataclasses import dataclass, field +from urllib.parse import urlparse + +import aiohttp + +from agent.workspace import clip + +logger = logging.getLogger(__name__) + +# Slack serves the files it hosts from here, and the bot token goes nowhere else. +SLACK_FILE_HOST = "files.slack.com" + +# Well under the models' limits for one image or PDF, which count the base64 encoding. +MAX_FILE_BYTES = 5 * 1024 * 1024 + +# About 25,000 tokens of a text file. Clipping keeps most of the end, where a log's errors usually are. +MAX_TEXT_CHARS = 100_000 + +TOO_LARGE = f"it's over {MAX_FILE_BYTES // 1024 // 1024} MB" + +# Slack redirects a download it won't serve to the token, most often one without the `files:read` scope. +REDIRECTED = "Slack redirected the download, which usually means the app needs reinstalling for the files:read scope" + +MEDIA_TYPES = ("application/pdf", "image/gif", "image/jpeg", "image/png", "image/webp") + + +class Unreadable(Exception): + """A reason a shared file wasn't read, told to the model.""" + + +@dataclass +class SharedMedia: + """An image or PDF shared with a message, for the model to read as it is.""" + + name: str + # One of `MEDIA_TYPES`. + media_type: str + data: bytes + + +@dataclass +class SharedFiles: + """What the agent reads from a message's files. + + `text` holds each text file and a note for each file that wasn't read, for + the prompt. `media` holds the images and PDFs to send with it. + """ + + text: str = "" + media: list[SharedMedia] = field(default_factory=list) + + +async def _download(token: str | None, file: dict) -> bytes: + """Download a file Slack hosts, sending the bot token only to Slack's file host. + + A redirect isn't followed, since it could lead anywhere with the token. + """ + if file.get("mode") == "external" or file.get("is_external"): + raise Unreadable("it's hosted outside Slack") + if (file.get("size") or 0) > MAX_FILE_BYTES: + raise Unreadable(TOO_LARGE) + url = file.get("url_private") + if not url: + raise Unreadable("Slack didn't include a link to download it") + parsed = urlparse(url) + if parsed.scheme != "https" or parsed.hostname != SLACK_FILE_HOST: + raise Unreadable("it isn't on Slack's file host") + async with ( + aiohttp.ClientSession() as http, + http.get( + url, headers={"Authorization": f"Bearer {token}"}, allow_redirects=False + ) as response, + ): + if 300 <= response.status < 400: + raise Unreadable(REDIRECTED) + if response.status != 200: + raise Unreadable(f"downloading it returned HTTP {response.status}") + data = await response.read() + if len(data) > MAX_FILE_BYTES: + raise Unreadable(TOO_LARGE) + return data + + +def _decoded(data: bytes) -> str | None: + """A file's bytes as text, or None for a file that isn't text.""" + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + return None + return None if "\0" in text else text + + +async def read_files(token: str | None, files: Sequence[dict]) -> SharedFiles: + """Read the files shared with a message. The bot token needs the `files:read` scope.""" + parts: list[str] = [] + media: list[SharedMedia] = [] + for file in files: + name = file.get("name") or file.get("id") or "a file" + try: + data = await _download(token, file) + if file.get("mimetype") in MEDIA_TYPES: + media.append( + SharedMedia(name=name, media_type=file["mimetype"], data=data) + ) + continue + text = _decoded(data) + if text is None: + raise Unreadable( + "only PNG, JPEG, GIF, and WebP images, PDFs, and text files can be read" + ) + parts.append(f'\n{clip(text, MAX_TEXT_CHARS)}\n') + except Unreadable as e: + parts.append(f"({name} wasn't read: {e})") + except Exception: + logger.warning("Couldn't read %s", name, exc_info=True) + parts.append(f"({name} wasn't read: it couldn't be downloaded)") + return SharedFiles(text="\n\n".join(parts), media=media) diff --git a/pydantic-ai/agent/sessions.py b/pydantic-ai/agent/sessions.py index 48205ac..0ca55b3 100644 --- a/pydantic-ai/agent/sessions.py +++ b/pydantic-ai/agent/sessions.py @@ -17,6 +17,14 @@ from slack_sdk.web.async_client import AsyncWebClient +@dataclass +class InboxMessage: + """A message waiting for the next turn: its text, starting with who sent it, and the files shared with it.""" + + text: str + files: list[dict] = field(default_factory=list) + + @dataclass class CodeChannelSession: """Per-code-channel working state.""" @@ -33,8 +41,8 @@ class CodeChannelSession: base_commit: str | None = None plan_canvas_id: str | None = None history: list = field(default_factory=list) - # Messages waiting for the next turn, each starting with who sent it. - inbox: list[str] = field(default_factory=list) + # Messages waiting for the next turn. + inbox: list[InboxMessage] = field(default_factory=list) # Set by the native stop button, or when the session is discarded. Checked # before posting and before every tool call so a stopped session goes quiet; # cleared when the user starts a new turn. diff --git a/pydantic-ai/agent/turns.py b/pydantic-ai/agent/turns.py index 35b2559..22b5912 100644 --- a/pydantic-ai/agent/turns.py +++ b/pydantic-ai/agent/turns.py @@ -8,7 +8,7 @@ """ import logging -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Sequence from functools import partial from slack_sdk.errors import SlackApiError @@ -23,8 +23,15 @@ from agent.agent import resume_run, run_request, start_run from agent.approvals import PendingApproval, pending_store from agent.context import origin_context, recent_context, thread_context +from agent.files import SharedMedia, read_files from agent.outcome import RunOutcome -from agent.sessions import AgentDeps, CodeChannelSession, RequestDeps, session_store +from agent.sessions import ( + AgentDeps, + CodeChannelSession, + InboxMessage, + RequestDeps, + session_store, +) from agent.workspace import clip logger = logging.getLogger(__name__) @@ -180,6 +187,19 @@ async def _run(deps: AgentDeps, run: Callable[[], Awaitable[RunOutcome]]) -> boo return False +async def _start_turn( + deps: AgentDeps, history: list, origin: str, messages: list[InboxMessage] +) -> RunOutcome: + """Start a turn with the messages waiting for it, after reading the files shared with them.""" + texts = [origin] if origin else [] + media: list[SharedMedia] = [] + for message in messages: + shared = await read_files(deps.client.token, message.files) + texts.append("\n\n".join(filter(None, [message.text, shared.text]))) + media.extend(shared.media) + return await start_run(history, "\n\n".join(texts), deps, media) + + async def _run_inbox(client: AsyncWebClient, session: CodeChannelSession) -> None: """Run turns until the inbox is empty or a turn pauses on an approval.""" while session.inbox and not session.archived: @@ -187,16 +207,18 @@ async def _run_inbox(client: AsyncWebClient, session: CodeChannelSession) -> Non # the session back up. session.stopped = False messages, session.inbox = session.inbox, [] - text = "\n\n".join(messages) + origin = "" if session.origin_context and not session.history: - text = ( + origin = ( "This code channel was started from this conversation:\n" - f"{session.origin_context}\n\n{text}" + f"{session.origin_context}" ) session.origin_context = None deps = AgentDeps(client=client, session=session) - paused = await _run(deps, partial(start_run, session.history, text, deps)) + paused = await _run( + deps, partial(_start_turn, deps, session.history, origin, messages) + ) if paused: return @@ -210,12 +232,14 @@ async def answer_request( text: str, user_id: str, in_dm: bool, + files: Sequence[dict] = (), ) -> None: """Reply to a mention or direct message outside a code channel, or create one for it. A mention in a channel is answered in its thread. A direct message is answered where it was sent. The agent gets the conversation before the request, from - the thread or from the direct message, so it can follow along. + the thread or from the direct message, so it can follow along, and the files + shared with the request. """ reply_ts = thread_ts or (None if in_dm else message_ts) if not text: @@ -235,7 +259,8 @@ async def answer_request( earlier = await recent_context(client, channel_id, before_ts=message_ts) else: earlier = "" - prompt = f"<@{user_id}>: {text}" + shared = await read_files(client.token, files) + prompt = "\n\n".join(filter(None, [f"<@{user_id}>: {text}", shared.text])) if earlier: prompt = f"Earlier in this conversation:\n{earlier}\n\n{prompt}" @@ -245,7 +270,7 @@ async def answer_request( message_ts=message_ts, thread_ts=reply_ts, ) - reply = await run_request(prompt, deps) + reply = await run_request(prompt, deps, shared.media) # When the agent created a code channel, the work continues there. if deps.code_channel_id is None: await client.chat_postMessage( @@ -313,14 +338,16 @@ async def run_turn( session: CodeChannelSession, text: str, user_id: str, + files: Sequence[dict] = (), ) -> None: """Run a message or slash command in a code channel as a turn and post the outcome. Mentions, plain messages, and slash commands all funnel through here. A message that arrives while a turn runs waits in the session's inbox, and - everything waiting runs together as the next turn. + everything waiting runs together as the next turn. The files shared with + each message are read when its turn starts. """ - session.inbox.append(f"<@{user_id}>: {text}") + session.inbox.append(InboxMessage(text=f"<@{user_id}>: {text}", files=list(files))) if session.turn_lock.locked(): # The running turn takes this message when it finishes. return diff --git a/pydantic-ai/app_oauth.py b/pydantic-ai/app_oauth.py index 569e5c3..dcb7159 100644 --- a/pydantic-ai/app_oauth.py +++ b/pydantic-ai/app_oauth.py @@ -52,6 +52,7 @@ async def failure(args: AsyncFailureArgs) -> BoltResponse: "channels:read", "chat:write", "code_channels:manage", + "files:read", "groups:history", "groups:read", "im:history", diff --git a/pydantic-ai/listeners/events/app_mentioned.py b/pydantic-ai/listeners/events/app_mentioned.py index 48b8295..d9a48ab 100644 --- a/pydantic-ai/listeners/events/app_mentioned.py +++ b/pydantic-ai/listeners/events/app_mentioned.py @@ -24,7 +24,11 @@ async def handle_app_mentioned( session = await find_session(client, channel_id) if session is not None: await run_turn( - client=client, session=session, text=text, user_id=context.user_id + client=client, + session=session, + text=text, + user_id=context.user_id, + files=files, ) return @@ -36,4 +40,5 @@ async def handle_app_mentioned( text=text, user_id=context.user_id, in_dm=False, + files=files, ) diff --git a/pydantic-ai/listeners/events/message.py b/pydantic-ai/listeners/events/message.py index f3f7618..735a70f 100644 --- a/pydantic-ai/listeners/events/message.py +++ b/pydantic-ai/listeners/events/message.py @@ -33,6 +33,7 @@ async def handle_message( text=text.replace(mention, "").strip(), user_id=context.user_id, in_dm=True, + files=files, ) return @@ -42,4 +43,6 @@ async def handle_message( session = await find_session(client, channel_id) if session is None: return - await run_turn(client=client, session=session, text=text, user_id=context.user_id) + await run_turn( + client=client, session=session, text=text, user_id=context.user_id, files=files + ) diff --git a/pydantic-ai/manifest.json b/pydantic-ai/manifest.json index 553c370..4775f99 100644 --- a/pydantic-ai/manifest.json +++ b/pydantic-ai/manifest.json @@ -45,6 +45,7 @@ "channels:read", "chat:write", "code_channels:manage", + "files:read", "groups:history", "groups:read", "im:history", diff --git a/pydantic-ai/tests/conftest.py b/pydantic-ai/tests/conftest.py index 1eefc26..28d687f 100644 --- a/pydantic-ai/tests/conftest.py +++ b/pydantic-ai/tests/conftest.py @@ -1,4 +1,4 @@ -from unittest.mock import Mock +from unittest.mock import AsyncMock, MagicMock, Mock import pytest from pydantic_ai import models @@ -28,6 +28,7 @@ def forget_sessions(): def client() -> Mock: """A Slack client whose methods match the real one's, so a wrong call fails.""" client = Mock(AsyncWebClient) + client.token = "xoxb-example" client.chat_postMessage.return_value = {"ts": "8.8"} return client @@ -57,3 +58,12 @@ def code_channel_info(origin_channel_id: str = "C_ORIGIN", origin_ts: str = "1.1 } } } + + +def file_download(body: bytes, status: int = 200) -> MagicMock: + """A response to downloading a file from Slack, for patching `aiohttp.ClientSession.get`.""" + response = MagicMock() + response.status = status + response.read = AsyncMock(return_value=body) + response.__aenter__.return_value = response + return response diff --git a/pydantic-ai/tests/test_agent_session_stopped.py b/pydantic-ai/tests/test_agent_session_stopped.py index 14008c6..49e3300 100644 --- a/pydantic-ai/tests/test_agent_session_stopped.py +++ b/pydantic-ai/tests/test_agent_session_stopped.py @@ -2,7 +2,7 @@ from agent.approvals import PendingApproval, pending_store from agent.outcome import RunOutcome -from agent.sessions import CodeChannelSession, session_store +from agent.sessions import CodeChannelSession, InboxMessage, session_store from listeners.events.agent_session_stopped import handle_agent_session_stopped from listeners.events.message import handle_message @@ -21,7 +21,9 @@ async def send(self, client, context, text: str): ) async def test_stop_confirms_and_leaves_processing(self, client, context): - session = CodeChannelSession(channel_id="C_CODE", inbox=["<@U1>: queued"]) + session = CodeChannelSession( + channel_id="C_CODE", inbox=[InboxMessage(text="<@U1>: queued")] + ) session_store.put(session) await self.stop(client, context) @@ -57,7 +59,7 @@ async def test_stop_drops_the_pending_approval_and_its_buttons( async def test_stopped_turn_posts_nothing_more(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) - async def stop_mid_run(_history, _text, _deps): + async def stop_mid_run(_history, _text, _deps, _media): await self.stop(client, context) return RunOutcome(final_output="Done.", history=[]) @@ -79,7 +81,7 @@ async def test_a_message_after_the_stop_picks_back_up(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) texts = [] - async def run(_history, text, _deps): + async def run(_history, text, _deps, _media): texts.append(text) if len(texts) == 1: await self.stop(client, context) diff --git a/pydantic-ai/tests/test_app_mentioned.py b/pydantic-ai/tests/test_app_mentioned.py index d11711a..f9d85e0 100644 --- a/pydantic-ai/tests/test_app_mentioned.py +++ b/pydantic-ai/tests/test_app_mentioned.py @@ -1,10 +1,12 @@ +import base64 from unittest.mock import patch +from agent.files import SharedMedia from agent.outcome import RunOutcome from agent.sessions import CodeChannelSession, session_store from agent.tools import create_code_channel from listeners.events.app_mentioned import handle_app_mentioned -from tests.conftest import code_channel_info +from tests.conftest import code_channel_info, file_download from tests.test_tools import invoke @@ -33,7 +35,7 @@ async def test_mention_answered_in_place_opens_no_channel(self, client, context) _, start_run = await self.mention_in_origin( client, context, - lambda _prompt, _deps: "It's a billing service.", + lambda _prompt, _deps, _media: "It's a billing service.", text="what does billing do?", ) @@ -56,7 +58,7 @@ async def test_mention_in_a_thread_gets_the_thread_so_far(self, client, context) run_request, _ = await self.mention_in_origin( client, context, - lambda _p, _d: "On it.", + lambda _p, _d, _m: "On it.", text="can you fix this?", thread_ts="0.5", ) @@ -69,7 +71,7 @@ async def test_mention_in_a_thread_gets_the_thread_so_far(self, client, context) async def test_creating_a_channel_leaves_the_first_turn_to_the_seeded_mention( self, client, context ): - async def create(_prompt, deps): + async def create(_prompt, deps, _media): await invoke(create_code_channel, deps, title="Fix login test") _, start_run = await self.mention_in_origin(client, context, create) @@ -89,7 +91,7 @@ async def create(_prompt, deps): ] async def test_creating_a_channel_twice_points_to_it_once(self, client, context): - async def create_twice(_prompt, deps): + async def create_twice(_prompt, deps, _media): await invoke(create_code_channel, deps, title="Fix login test") await invoke(create_code_channel, deps, title="Fix the login test") @@ -122,7 +124,41 @@ async def test_mention_with_only_a_file_names_it(self, client, context): client, context, "", files=[{"id": "F123", "name": "trace.png"}] ) - assert start_run.call_args.args[1] == "<@U123>: (attachment: trace.png)" + assert start_run.call_args.args[1] == ( + "<@U123>: (attachment: trace.png)\n\n" + "(trace.png wasn't read: Slack didn't include a link to download it)" + ) + + async def test_mention_outside_a_code_channel_gives_the_request_its_files( + self, client, context + ): + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) + file = { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + + with patch("aiohttp.ClientSession.get", return_value=file_download(png)): + run_request, _ = await self.mention_in_origin( + client, + context, + lambda _p, _d, _m: "A null pointer.", + text="why does this fail?", + files=[file], + ) + + assert ( + run_request.call_args.args[0] + == "<@U123>: why does this fail?\n(attachment: trace.png)" + ) + assert run_request.call_args.args[2] == [ + SharedMedia(name="trace.png", media_type="image/png", data=png) + ] async def test_failed_turn_in_a_code_channel_warns_top_level(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) diff --git a/pydantic-ai/tests/test_approval_buttons.py b/pydantic-ai/tests/test_approval_buttons.py index 8df956f..d113ba7 100644 --- a/pydantic-ai/tests/test_approval_buttons.py +++ b/pydantic-ai/tests/test_approval_buttons.py @@ -104,7 +104,7 @@ async def resumed(_paused, _approved, _deps): ) return RunOutcome(final_output="Tests pass.", history=HISTORY) - async def start(_history, text, _deps): + async def start(_history, text, _deps, _media): texts.append(text) return RunOutcome(final_output="Linted.", history=HISTORY) diff --git a/pydantic-ai/tests/test_files.py b/pydantic-ai/tests/test_files.py new file mode 100644 index 0000000..c9f181a --- /dev/null +++ b/pydantic-ai/tests/test_files.py @@ -0,0 +1,157 @@ +import base64 +from unittest.mock import patch + +from agent.files import MAX_FILE_BYTES, SharedFiles, SharedMedia, read_files +from tests.conftest import file_download + + +class TestReadFiles: + async def test_image_goes_to_the_model_with_the_token_sent_only_to_slack(self): + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) + + with patch("aiohttp.ClientSession.get", return_value=file_download(png)) as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared == SharedFiles( + media=[SharedMedia(name="trace.png", media_type="image/png", data=png)] + ) + assert get.call_args.args == ( + "https://files.slack.com/files-pri/T123-F123/trace.png", + ) + assert get.call_args.kwargs == { + "headers": {"Authorization": "Bearer xoxb-example"}, + "allow_redirects": False, + } + + async def test_text_file_goes_in_the_prompt(self): + with patch( + "aiohttp.ClientSession.get", + return_value=file_download(b"FAIL tests/test_login.py\n"), + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "build.log", + "mimetype": "text/plain", + "size": 25, + "url_private": "https://files.slack.com/files-pri/T123-F123/build.log", + } + ], + ) + + assert shared == SharedFiles( + text='\nFAIL tests/test_login.py\n\n' + ) + + async def test_file_hosted_outside_slack_is_not_downloaded(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "design.pdf", + "mimetype": "application/pdf", + "mode": "external", + "is_external": True, + "url_private": "https://example.com/design.pdf", + } + ], + ) + + assert shared.text == "(design.pdf wasn't read: it's hosted outside Slack)" + get.assert_not_called() + + async def test_link_to_another_host_does_not_get_the_token(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "url_private": "https://files.slack.com.example.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared.text == "(trace.png wasn't read: it isn't on Slack's file host)" + get.assert_not_called() + + async def test_file_over_the_size_limit_is_not_downloaded(self): + with patch("aiohttp.ClientSession.get") as get: + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "recording.png", + "mimetype": "image/png", + "size": MAX_FILE_BYTES + 1, + "url_private": "https://files.slack.com/files-pri/T123-F123/recording.png", + } + ], + ) + + assert shared.text == "(recording.png wasn't read: it's over 5 MB)" + get.assert_not_called() + + async def test_redirected_download_is_not_followed(self): + with patch( + "aiohttp.ClientSession.get", return_value=file_download(b"", status=302) + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], + ) + + assert shared.text == ( + "(trace.png wasn't read: Slack redirected the download, which usually " + "means the app needs reinstalling for the files:read scope)" + ) + + async def test_file_that_is_not_text_is_named_as_not_read(self): + with patch( + "aiohttp.ClientSession.get", + return_value=file_download(bytes([0x50, 0x4B, 0x03, 0x04, 0xFF, 0x00])), + ): + shared = await read_files( + "xoxb-example", + [ + { + "id": "F123", + "name": "build.zip", + "mimetype": "application/zip", + "size": 6, + "url_private": "https://files.slack.com/files-pri/T123-F123/build.zip", + } + ], + ) + + assert shared == SharedFiles( + text="(build.zip wasn't read: only PNG, JPEG, GIF, and WebP images, PDFs, and text files can be read)" + ) diff --git a/pydantic-ai/tests/test_message.py b/pydantic-ai/tests/test_message.py index db2fdd9..0ed75a9 100644 --- a/pydantic-ai/tests/test_message.py +++ b/pydantic-ai/tests/test_message.py @@ -1,9 +1,11 @@ +import base64 from unittest.mock import patch +from agent.files import SharedMedia from agent.outcome import RunOutcome from agent.sessions import CodeChannelSession, session_store from listeners.events.message import handle_message -from tests.conftest import code_channel_info +from tests.conftest import code_channel_info, file_download class TestMessage: @@ -40,22 +42,39 @@ async def test_message_with_a_mention_is_left_to_app_mention(self, client, conte async def test_file_shared_in_a_code_channel_runs_a_turn(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) + png = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + ) - with patch( - "agent.turns.start_run", return_value=RunOutcome(history=[]) - ) as start_run: + with ( + patch("aiohttp.ClientSession.get", return_value=file_download(png)), + patch( + "agent.turns.start_run", return_value=RunOutcome(history=[]) + ) as start_run, + ): await self.send( client, context, "why does this fail?", subtype="file_share", - files=[{"id": "F123", "name": "trace.png"}], + files=[ + { + "id": "F123", + "name": "trace.png", + "mimetype": "image/png", + "size": 69, + "url_private": "https://files.slack.com/files-pri/T123-F123/trace.png", + } + ], ) assert ( start_run.call_args.args[1] == "<@U123>: why does this fail?\n(attachment: trace.png)" ) + assert start_run.call_args.args[3] == [ + SharedMedia(name="trace.png", media_type="image/png", data=png) + ] async def test_file_shared_without_text_names_it(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) @@ -71,7 +90,10 @@ async def test_file_shared_without_text_names_it(self, client, context): files=[{"id": "F123", "name": "trace.png"}], ) - assert start_run.call_args.args[1] == "<@U123>: (attachment: trace.png)" + assert start_run.call_args.args[1] == ( + "<@U123>: (attachment: trace.png)\n\n" + "(trace.png wasn't read: Slack didn't include a link to download it)" + ) async def test_edited_message_runs_no_turn(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) @@ -100,7 +122,7 @@ async def test_messages_during_a_turn_run_together_next(self, client, context): session_store.put(CodeChannelSession(channel_id="C_CODE")) texts = [] - async def run(_history, text, _deps): + async def run(_history, text, _deps, _media): texts.append(text) if len(texts) == 1: # Two people follow up while the first turn is still running. diff --git a/pydantic-ai/tests/test_runs.py b/pydantic-ai/tests/test_runs.py index 711c36e..9897cea 100644 --- a/pydantic-ai/tests/test_runs.py +++ b/pydantic-ai/tests/test_runs.py @@ -1,12 +1,14 @@ """Real agent runs with a scripted model, covering the seams where the turn code meets Pydantic AI.""" +import base64 from pathlib import Path from unittest.mock import patch -from pydantic_ai.messages import ModelResponse, ToolReturnPart +from pydantic_ai.messages import BinaryContent, ModelResponse, ToolReturnPart import agent.agent as agents_module from agent.agent import resume_run, run_request, start_run +from agent.files import SharedMedia from agent.sessions import AgentDeps, CodeChannelSession, RequestDeps from tests.fake_model import FakeModel, call, say @@ -192,6 +194,35 @@ async def test_creating_a_channel_ends_the_request(self, client): assert reply is None assert len(model.inputs) == 1 + async def test_shared_images_and_pdfs_reach_the_model(self, client, tmp_path): + session = CodeChannelSession(channel_id="C_CODE", workdir=str(tmp_path)) + deps = AgentDeps(client=client, session=session) + png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC" + pdf = "JVBERi0xLjQKMSAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAyIDAgUj4+ZW5kb2JqCjIgMCBvYmo8PC9UeXBlL1BhZ2VzL0tpZHNbMyAwIFJdL0NvdW50IDE+PmVuZG9iagozIDAgb2JqPDwvVHlwZS9QYWdlL1BhcmVudCAyIDAgUi9NZWRpYUJveFswIDAgNzIgNzJdPj5lbmRvYmoKdHJhaWxlcjw8L1Jvb3QgMSAwIFI+PgolJUVPRgo=" + media = [ + SharedMedia( + name="trace.png", media_type="image/png", data=base64.b64decode(png) + ), + SharedMedia( + name="design.pdf", + media_type="application/pdf", + data=base64.b64decode(pdf), + ), + ] + replaced, model = coding_agent(lambda _n: say("A failing test.")) + + with replaced: + outcome = await start_run([], "<@U123>: why does this fail?", deps, media) + + assert outcome.final_output == "A failing test." + + prompt = model.inputs[0][-1].parts[-1].content + assert prompt == [ + BinaryContent(data=base64.b64decode(png), media_type="image/png"), + BinaryContent(data=base64.b64decode(pdf), media_type="application/pdf"), + "<@U123>: why does this fail?", + ] + async def test_file_tools_work_without_approval(self, client, tmp_path): session = CodeChannelSession(channel_id="C_CODE", workdir=str(tmp_path)) deps = AgentDeps(client=client, session=session)