Skip to content
Open
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
8 changes: 7 additions & 1 deletion claude_agent_sdk_plugin/agent_chat/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,14 @@ async def send_message(self, message: str) -> str:
elif isinstance(response, AssistantMessage):
reply_id = response.uuid
elif isinstance(response, ResultMessage):
if response.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = response.result or "; ".join(
response.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
self.reply_id = reply_id
return response.result or "\n".join(response.errors or [])
return response.result or ""

raise RuntimeError("Claude Code ended the turn without a result")

Expand Down
7 changes: 7 additions & 0 deletions claude_agent_sdk_plugin/fork_session/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
)
from temporalio import workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.exceptions import ApplicationError


@dataclass
Expand Down Expand Up @@ -95,6 +96,12 @@ async def ask(self, prompt: str, fork_from: str | None = None) -> Branch:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return Branch(
message.session_id, prompt, message.result or ""
)
Expand Down
7 changes: 7 additions & 0 deletions claude_agent_sdk_plugin/hooks/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
)
from temporalio import activity, workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.exceptions import ApplicationError


# @@@SNIPSTART python-claude-agent-sdk-hooks-callback
Expand Down Expand Up @@ -108,6 +109,12 @@ async def ask(self, prompt: str) -> str:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return message.result or ""

raise RuntimeError("Claude Code ended the turn without a result")
Expand Down
7 changes: 7 additions & 0 deletions claude_agent_sdk_plugin/human_in_the_loop/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
)
from temporalio import workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.exceptions import ApplicationError


@dataclass
Expand Down Expand Up @@ -85,6 +86,12 @@ async def ask(self, prompt: str) -> str:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return message.result or ""

raise RuntimeError("Claude Code ended the turn without a result")
Expand Down
7 changes: 7 additions & 0 deletions claude_agent_sdk_plugin/multi_agent/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
)
from temporalio import workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.exceptions import ApplicationError

COORDINATOR = "coordinator"

Expand Down Expand Up @@ -108,6 +109,12 @@ async def ask(self, prompt: str) -> Briefing:
elif isinstance(message, AssistantMessage):
self.record(message)
elif isinstance(message, ResultMessage):
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return Briefing(
message.result or "", self.messages_by_agent
)
Expand Down
33 changes: 29 additions & 4 deletions claude_agent_sdk_plugin/offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,30 @@
import threading
import uuid
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Union

# Outlives the Worker, so a restarted Worker finds the sessions it can resume.
OFFLINE_CONFIG_DIR = os.path.join(tempfile.gettempdir(), "claude-agent-sdk-samples")

Answer = Union[str, list[str], dict[str, Any], Callable[[dict[str, Any]], Any]]

@dataclass(frozen=True)
class ApiError:
"""An error response from the Anthropic API, such as a rejected API key."""

status: int
type: str
message: str

def body(self) -> bytes:
error = {"type": self.type, "message": self.message}
return json.dumps({"type": "error", "error": error}).encode()


Answer = Union[
str, list[str], dict[str, Any], ApiError, Callable[[dict[str, Any]], Any]
]


def tool_use(id: str, name: str, **tool_input: Any) -> dict[str, Any]:
Expand Down Expand Up @@ -47,10 +64,16 @@ def _handler(self) -> type[BaseHTTPRequestHandler]:
class Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
data = stream(api.answer(body), body.get("model", "claude"))
answer = api.answer(body)
if isinstance(answer, ApiError):
status, content_type = answer.status, "application/json"
data = answer.body()
else:
status, content_type = 200, "text/event-stream"
data = stream(answer, body.get("model", "claude"))
with contextlib.suppress(OSError):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
Expand All @@ -69,6 +92,8 @@ def scripted_api(answers: Mapping[str, Answer]) -> Iterator[ScriptedApi]:
"ANTHROPIC_API_KEY": "offline",
"ANTHROPIC_BASE_URL": api.url,
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
# The scripted API answers at once, so an error it returns is final.
"CLAUDE_CODE_MAX_RETRIES": "0",
"CLAUDE_CONFIG_DIR": OFFLINE_CONFIG_DIR,
}
inherited = [
Expand Down
7 changes: 7 additions & 0 deletions claude_agent_sdk_plugin/open_telemetry/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
)
from temporalio import workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.exceptions import ApplicationError

# The text Claude Code sends itself to continue an interrupted turn.
CONTINUE = "Continue from where you left off."
Expand Down Expand Up @@ -59,6 +60,12 @@ async def ask(self, prompt: str) -> str:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return message.result or ""

raise RuntimeError("Claude Code ended the turn without a result")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
)
from temporalio import workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.exceptions import ApplicationError

# Where the Worker's connector puts the plugin, in Claude Code's sandbox. The
# path is recorded in history, as part of the connect Activity's input.
Expand Down Expand Up @@ -70,7 +71,13 @@ async def ask(self, prompt: str) -> str:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
return message.result or "\n".join(message.errors or [])
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return message.result or ""

raise RuntimeError("Claude Code ended the turn without a result")

Expand Down
7 changes: 7 additions & 0 deletions claude_agent_sdk_plugin/streaming/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from temporalio import workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.contrib.workflow_streams import WorkflowStream
from temporalio.exceptions import ApplicationError

# The text Claude Code sends itself to continue an interrupted turn.
CONTINUE = "Continue from where you left off."
Expand Down Expand Up @@ -76,6 +77,12 @@ async def ask(self, prompt: str) -> str:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return message.result or ""

raise RuntimeError("Claude Code ended the turn without a result")
Expand Down
6 changes: 6 additions & 0 deletions claude_agent_sdk_plugin/structured_output/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ async def ask(self, prompt: str) -> SupportTicket:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
if message.structured_output is not None:
return SupportTicket.model_validate(
message.structured_output
Expand Down
9 changes: 8 additions & 1 deletion claude_agent_sdk_plugin/tools/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
)
from temporalio import activity, workflow
from temporalio.claude_agent_sdk import TemporalTransport
from temporalio.exceptions import ApplicationError


@tool(
Expand Down Expand Up @@ -97,7 +98,13 @@ async def ask(self, prompt: str) -> str:
):
prompt_id = message.uuid
elif isinstance(message, ResultMessage):
return message.result or "\n".join(message.errors or [])
if message.is_error:
# A failed turn, such as a bad API key, also ends here.
reason = message.result or "; ".join(
message.errors or []
)
raise ApplicationError(f"Claude Code failed: {reason}")
return message.result or ""

raise RuntimeError("Claude Code ended the turn without a result")

Expand Down
97 changes: 97 additions & 0 deletions tests/claude_agent_sdk_plugin/api_error_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import uuid
from typing import Any

import pytest
from temporalio.claude_agent_sdk import ClaudeAgentSDKPlugin
from temporalio.client import Client, WorkflowFailureError, WorkflowUpdateFailedError
from temporalio.exceptions import ApplicationError
from temporalio.worker import Worker

from claude_agent_sdk_plugin.agent_chat.workflow import ChatInput, ChatWorkflow
from claude_agent_sdk_plugin.fork_session.workflow import ForkSessionWorkflow
from claude_agent_sdk_plugin.hooks.workflow import HooksWorkflow
from claude_agent_sdk_plugin.human_in_the_loop.workflow import HumanInTheLoopWorkflow
from claude_agent_sdk_plugin.multi_agent.workflow import MultiAgentWorkflow
from claude_agent_sdk_plugin.offline import ApiError, scripted_api
from claude_agent_sdk_plugin.open_telemetry.workflow import OpenTelemetryWorkflow
from claude_agent_sdk_plugin.plugin_with_custom_transport.workflow import (
PluginWithCustomTransportWorkflow,
)
from claude_agent_sdk_plugin.streaming.workflow import StreamingWorkflow
from claude_agent_sdk_plugin.structured_output.workflow import TriageTicketWorkflow
from claude_agent_sdk_plugin.tools.workflow import ToolsWorkflow

# Every request gets this answer: the empty key matches any prompt.
REJECTED_KEY = {
"": ApiError(401, "authentication_error", "invalid x-api-key"),
}

WORKFLOWS: list[tuple[Any, list[Any]]] = [
(ForkSessionWorkflow, ["Plan a weekend in Lisbon", ["Redo it on a budget."]]),
(HooksWorkflow, ["Run echo hello."]),
(HumanInTheLoopWorkflow, ["Create hello.txt with a greeting."]),
(MultiAgentWorkflow, ["durable execution"]),
(OpenTelemetryWorkflow, ["How many Python files are here?"]),
(PluginWithCustomTransportWorkflow, ["Write a haiku."]),
(StreamingWorkflow, ["Count to five"]),
(ToolsWorkflow, ["Get the weather in Paris."]),
(TriageTicketWorkflow, ["The app crashes."]),
]


def assert_claude_code_failed(cause: BaseException | None) -> None:
assert isinstance(cause, ApplicationError)
prefix = "Claude Code failed: "
assert cause.message.startswith(prefix)
assert cause.message[len(prefix) :].strip(), "the failure gives no reason"


@pytest.mark.parametrize(
("workflow_class", "args"), WORKFLOWS, ids=[w.__name__ for w, _ in WORKFLOWS]
)
async def test_api_error_fails_the_workflow(
client: Client, workflow_class: Any, args: list[Any]
) -> None:
task_queue = f"claude-agent-sdk-api-error-{uuid.uuid4()}"
with scripted_api(REJECTED_KEY) as api:
async with Worker(
client,
task_queue=task_queue,
workflows=[workflow_class],
plugins=[ClaudeAgentSDKPlugin()],
):
handle = await client.start_workflow(
workflow_class.run,
args=args,
id=f"claude-agent-sdk-api-error-{uuid.uuid4()}",
task_queue=task_queue,
)
with pytest.raises(WorkflowFailureError) as failure:
await handle.result()

assert api.requests, "Claude Code never called the scripted API"
assert_claude_code_failed(failure.value.cause)


async def test_api_error_fails_the_chat_message(client: Client) -> None:
task_queue = f"claude-agent-sdk-api-error-{uuid.uuid4()}"
with scripted_api(REJECTED_KEY) as api:
async with Worker(
client,
task_queue=task_queue,
workflows=[ChatWorkflow],
plugins=[ClaudeAgentSDKPlugin()],
):
handle = await client.start_workflow(
ChatWorkflow.run,
ChatInput(),
id=f"claude-agent-sdk-api-error-{uuid.uuid4()}",
task_queue=task_queue,
)
with pytest.raises(WorkflowUpdateFailedError) as failure:
await handle.execute_update(ChatWorkflow.send_message, "I'm Ada.")
await handle.signal(ChatWorkflow.end_conversation)
await handle.result()

assert api.requests, "Claude Code never called the scripted API"
assert_claude_code_failed(failure.value.cause)
Loading