Skip to content
Merged
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
5 changes: 5 additions & 0 deletions claude-agent-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ Once Casey is running, there are several ways to interact:

**Assistant Panel** — Click _Add Agent_ in the top-right corner of Slack, select Casey from the list, then pick a suggested prompt or type a message.

**Stop button** — While Casey is thinking, click the stop button on its loading indicator. Casey interrupts the run, confirms the stop in the thread, and posts no reply. The stop applies to the whole thread, so it also ends runs for other people's messages there.

Casey will add a :white_check_mark: reaction when it believes an issue has been resolved, and occasionally adds a contextual emoji reaction to keep things friendly.

### Linting
Expand Down Expand Up @@ -326,6 +328,7 @@ Every incoming request is routed to a "listener". This directory groups each lis

**`/listeners/events`** — Handles incoming events:

- `agent_session_stopped.py` — Stops the thread's runs when the stop button is pressed.
- `app_home_opened.py` — Publishes the App Home view with category buttons.
- `app_mentioned.py` — Responds to `@Casey` mentions in channels.
- `message.py` — Responds to direct messages from users.
Expand Down Expand Up @@ -354,6 +357,8 @@ The `tools` directory contains five IT support tools defined using the `@tool` d

The `store.py` file implements a thread-safe in-memory session ID store, keyed by channel, thread, and user, so each person in a thread has their own conversation. The Claude Agent SDK manages conversation history server-side via sessions, so only session IDs need to be tracked locally for resuming conversations.

The `runs.py` file tracks each in-flight run by channel and thread with an `asyncio.Event`, which the stop button sets to interrupt the Claude Agent SDK client. A stop ends only the runs for messages from before it, so a message sent after the stop still gets an answer.

## Troubleshooting

### MCP Server connection error: `HTTP error 400 (Bad Request)`
Expand Down
42 changes: 34 additions & 8 deletions claude-agent-sdk/agent/casey.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import asyncio
import logging

from claude_agent_sdk import (
AssistantMessage,
ClaudeAgentOptions,
Expand All @@ -20,6 +23,8 @@
trigger_password_reset_tool,
)

logger = logging.getLogger(__name__)

CASEY_SYSTEM_PROMPT = """\
You are Casey, an IT helpdesk agent for a company. You help employees troubleshoot \
technical issues, answer IT questions, and manage support requests through Slack.
Expand Down Expand Up @@ -129,17 +134,22 @@ async def run_casey_agent(
text: str,
session_id: str | None = None,
deps: CaseyDeps | None = None,
stopped: asyncio.Event | None = None,
) -> tuple[str, str | None]:
"""Run the Casey agent with the given text and optional session for context.

Args:
text: The user's message text.
session_id: Optional session ID to resume a previous conversation.
deps: Optional dependencies for tools that need Slack API access.
stopped: Optional event that interrupts the run once it's set.

Returns:
A tuple of (response_text, new_session_id).
"""
if stopped is not None and stopped.is_set():
return "", session_id

if deps:
casey_deps_var.set(deps)

Expand Down Expand Up @@ -169,14 +179,30 @@ async def run_casey_agent(

async with ClaudeSDKClient(options) as client:
await client.query(text)

async for message in client.receive_response():
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock):
response_parts.append(block.text)
if isinstance(message, ResultMessage):
new_session_id = message.session_id
interrupt = asyncio.create_task(_interrupt_when_stopped(client, stopped))

try:
async for message in client.receive_response():
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock):
response_parts.append(block.text)
if isinstance(message, ResultMessage):
new_session_id = message.session_id
finally:
interrupt.cancel()

response_text = "\n".join(response_parts) if response_parts else ""
return response_text, new_session_id


async def _interrupt_when_stopped(
client: ClaudeSDKClient, stopped: asyncio.Event | None
) -> None:
if stopped is None:
return
await stopped.wait()
try:
await client.interrupt()
except Exception:
logger.exception("Failed to interrupt the run")
2 changes: 2 additions & 0 deletions claude-agent-sdk/listeners/events/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from slack_bolt.async_app import AsyncApp

from .agent_session_stopped import handle_agent_session_stopped
from .app_home_opened import handle_app_home_opened
from .app_mentioned import handle_app_mentioned
from .message import handle_message


def register(app: AsyncApp):
app.event("agent_session_stopped")(handle_agent_session_stopped)
app.event("app_home_opened")(handle_app_home_opened)
app.event("app_mention")(handle_app_mentioned)
app.event("message")(handle_message)
15 changes: 15 additions & 0 deletions claude-agent-sdk/listeners/events/agent_session_stopped.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from slack_sdk.web.async_client import AsyncWebClient

from thread_context import run_store


async def handle_agent_session_stopped(client: AsyncWebClient, event: dict):
run_store.stop_before(event["channel"], event["thread_ts"], event["event_ts"])
try:
await client.agents_sessions_setStatus(
channel_id=event["channel"], thread_ts=event["thread_ts"], status="active"
)
finally:
await client.chat_postMessage(
channel=event["channel"], thread_ts=event["thread_ts"], text="Stopped."
)
42 changes: 25 additions & 17 deletions claude-agent-sdk/listeners/events/app_mentioned.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
from slack_bolt.context.async_context import AsyncBoltContext
from slack_bolt.context.say.async_say import AsyncSay
from slack_bolt.context.say_stream.async_say_stream import AsyncSayStream
from slack_bolt.context.set_status.async_set_status import AsyncSetStatus
from slack_sdk.web.async_client import AsyncWebClient

from agent import CaseyDeps, run_casey_agent
from listeners.views.feedback_builder import build_feedback_blocks
from thread_context import session_store
from thread_context import run_store, session_store


async def handle_app_mentioned(
Expand All @@ -19,9 +18,11 @@ async def handle_app_mentioned(
logger: Logger,
say: AsyncSay,
say_stream: AsyncSayStream,
set_status: AsyncSetStatus,
):
"""Handle @Casey mentions in channels."""
stopped = run_store.start(
context.channel_id, event.get("thread_ts") or event["ts"], event["ts"]
)
try:
channel_id = context.channel_id
text = event.get("text", "")
Expand All @@ -45,16 +46,8 @@ async def handle_app_mentioned(
name="eyes",
)

# Set assistant thread status with loading messages
await set_status(
status="Thinking...",
loading_messages=[
"Teaching the hamsters to type faster…",
"Untangling the internet cables…",
"Consulting the office goldfish…",
"Polishing up the response just for you…",
"Convincing the AI to stop overthinking…",
],
await client.agents_sessions_setStatus(
channel_id=channel_id, thread_ts=thread_ts, status="processing"
)

# Get session ID for conversation context
Expand All @@ -72,8 +65,10 @@ async def handle_app_mentioned(
user_token=context.user_token,
)
response_text, new_session_id = await run_casey_agent(
cleaned_text, session_id=existing_session_id, deps=deps
cleaned_text, session_id=existing_session_id, deps=deps, stopped=stopped
)
if stopped.is_set():
return

# Stream response in thread with feedback buttons
streamer = await say_stream()
Expand All @@ -88,8 +83,21 @@ async def handle_app_mentioned(
)

except Exception as e:
if stopped.is_set():
return
logger.exception("Failed to handle app mention")
await say(
text=f":warning: Something went wrong! ({e})",
thread_ts=event.get("thread_ts") or event["ts"],
try:
await say(
text=f":warning: Something went wrong! ({e})",
thread_ts=event.get("thread_ts") or event["ts"],
)
finally:
await client.agents_sessions_setStatus(
channel_id=context.channel_id,
thread_ts=event.get("thread_ts") or event["ts"],
status="active",
)
finally:
run_store.finish(
context.channel_id, event.get("thread_ts") or event["ts"], stopped
)
42 changes: 25 additions & 17 deletions claude-agent-sdk/listeners/events/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
from slack_bolt.context.async_context import AsyncBoltContext
from slack_bolt.context.say.async_say import AsyncSay
from slack_bolt.context.say_stream.async_say_stream import AsyncSayStream
from slack_bolt.context.set_status.async_set_status import AsyncSetStatus
from slack_sdk.web.async_client import AsyncWebClient

from agent import CaseyDeps, run_casey_agent
from listeners.views.feedback_builder import build_feedback_blocks
from thread_context import session_store
from thread_context import run_store, session_store


async def handle_message(
Expand All @@ -18,7 +17,6 @@ async def handle_message(
logger: Logger,
say: AsyncSay,
say_stream: AsyncSayStream,
set_status: AsyncSetStatus,
):
"""Handle messages sent to Casey via DM or in threads the bot is part of."""
# Issue submissions are posted by the bot with metadata so the message
Expand Down Expand Up @@ -51,6 +49,9 @@ async def handle_message(
# Top-level channel messages are handled by app_mentioned
return

stopped = run_store.start(
context.channel_id, event.get("thread_ts") or event["ts"], event["ts"]
)
try:
channel_id = context.channel_id
text = event.get("text", "")
Expand All @@ -75,16 +76,8 @@ async def handle_message(
name="eyes",
)

# Set assistant thread status with loading messages
await set_status(
status="Thinking...",
loading_messages=[
"Teaching the hamsters to type faster…",
"Untangling the internet cables…",
"Consulting the office goldfish…",
"Polishing up the response just for you…",
"Convincing the AI to stop overthinking…",
],
await client.agents_sessions_setStatus(
channel_id=channel_id, thread_ts=thread_ts, status="processing"
)

# Run the agent with deps for tool access
Expand All @@ -97,8 +90,10 @@ async def handle_message(
user_token=context.user_token,
)
response_text, new_session_id = await run_casey_agent(
text, session_id=existing_session_id, deps=deps
text, session_id=existing_session_id, deps=deps, stopped=stopped
)
if stopped.is_set():
return

# Stream response in thread with feedback buttons
streamer = await say_stream()
Expand All @@ -111,8 +106,21 @@ async def handle_message(
session_store.set_session(channel_id, thread_ts, user_id, new_session_id)

except Exception as e:
if stopped.is_set():
return
logger.exception("Failed to handle message")
await say(
text=f":warning: Something went wrong! ({e})",
thread_ts=event.get("thread_ts") or event.get("ts"),
try:
await say(
text=f":warning: Something went wrong! ({e})",
thread_ts=event.get("thread_ts") or event.get("ts"),
)
finally:
await client.agents_sessions_setStatus(
channel_id=context.channel_id,
thread_ts=event.get("thread_ts") or event["ts"],
status="active",
)
finally:
run_store.finish(
context.channel_id, event.get("thread_ts") or event["ts"], stopped
)
1 change: 1 addition & 0 deletions claude-agent-sdk/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"event_subscriptions": {
"request_url": "https://ngrok-free.app/slack/events",
"bot_events": [
"agent_session_stopped",
"app_home_opened",
"app_mention",
"message.channels",
Expand Down
46 changes: 46 additions & 0 deletions claude-agent-sdk/tests/test_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import asyncio
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest

from agent import casey


@pytest.mark.asyncio
async def test_run_casey_agent_skips_the_run_when_already_stopped():
stopped = asyncio.Event()
stopped.set()

with patch("agent.casey.ClaudeSDKClient") as sdk_client:
result = await casey.run_casey_agent(
"hi", session_id="session-1", stopped=stopped
)

assert result == ("", "session-1")
sdk_client.assert_not_called()


@pytest.mark.asyncio
async def test_run_casey_agent_stops_watching_for_the_stop_once_the_run_finishes():
client = MagicMock(interrupt=AsyncMock(), query=AsyncMock())
client.__aenter__.return_value = client
client.receive_response.return_value.__aiter__.return_value = []
stopped = asyncio.Event()

with patch("agent.casey.ClaudeSDKClient", return_value=client):
await casey.run_casey_agent("hi", stopped=stopped)
stopped.set()
await asyncio.sleep(0)

client.interrupt.assert_not_awaited()


@pytest.mark.asyncio
async def test_interrupt_when_stopped_interrupts_the_run():
client = Mock(interrupt=AsyncMock())
stopped = asyncio.Event()
stopped.set()

await casey._interrupt_when_stopped(client, stopped)

client.interrupt.assert_awaited_once()
Loading