Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 1 addition & 1 deletion claude-agent-sdk/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
1 change: 1 addition & 0 deletions claude-agent-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
46 changes: 41 additions & 5 deletions claude-agent-sdk/agent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
`RunOutcome`.
"""

import base64
from collections.abc import AsyncIterator, Sequence
from dataclasses import dataclass

from claude_agent_sdk import (
Expand All @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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)


Expand Down
125 changes: 125 additions & 0 deletions claude-agent-sdk/agent/files.py
Original file line number Diff line number Diff line change
@@ -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'<file name="{name}">\n{clip(text, MAX_TEXT_CHARS)}\n</file>')
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)
12 changes: 10 additions & 2 deletions claude-agent-sdk/agent/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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.
Expand Down
Loading