claude_sdk
robotsix_llmio.claude_sdk
Claude Agent SDK transport layer (subscription / claude login auth).
Requires the claude_sdk extra plus a logged-in claude CLI and Node.js at
runtime. The model/provider are loaded lazily via PEP 562 __getattr__ so
importing the lightweight transient helpers stays free of the SDK; a missing
extra surfaces a clear install hint when the model/provider is actually used.
ClaudeSDKActivityEvent
dataclass
One live signal from the Claude Agent SDK's streaming loop.
Mirrors what the diagnostic log line already captures — tool calls, tool results, extended-thinking, and intermediate assistant text — as structured data a caller can forward as UI feedback (e.g. into robotsix-chat's SSE channel) instead of only reading it from logs.
ClaudeSDKAPIError
Bases: RobotsixLLMIOError
A terminal Claude Agent SDK transport or process failure that survived the transient classification and retry loop.
Wraps a raw claude_agent_sdk exception (e.g. CLIConnectionError,
ProcessError) whose transient retries were exhausted — the original
is preserved as __cause__ so the transient classifier can inspect it.
All library consumers can catch this (or its base
:class:RobotsixLLMIOError) without importing claude_agent_sdk
internals.
ClaudeSDKAuthError
Bases: RobotsixLLMIOError
The claude CLI could not authenticate — the stored OAuth credential
is expired, revoked, or otherwise rejected with a 401.
Surfaced exactly like usage exhaustion and the 400: the CLI streams the
failure as assistant-visible text ("Failed to authenticate. API Error: 401
OAuth access token has expired.") inside an is_error=True
ResultMessage, which claude_agent_sdk then collapses into its
generic degenerate-success message. Left unclassified it looks transient,
so the bounded retry re-sends the identical request against the same dead
credential and the exhausted retry surfaces as an opaque transport failure —
the exact shape that made a plain expired token read as an SDK bug.
Re-running at the same tier can never help: the credential stays invalid
until a human re-authenticates. It is therefore never treated as transient
(see :func:~robotsix_llmio.claude_sdk.transient.is_claude_sdk_transient).
Because the credential is per-provider rather than per-request, callers
should treat it like usage exhaustion and fall back to a different
capability tier (e.g. via
:func:~robotsix_llmio.core.failover.acall_with_failover), which
keeps a keyed provider serving while the Claude credential is dead.
ClaudeSDKPermanentAPIError
Bases: RobotsixLLMIOError
The Anthropic API rejected the request itself with a 400 — a
malformed or out-of-range parameter, not an infrastructure hiccup.
Like usage exhaustion, the CLI surfaces this as assistant-visible text
("API Error: 400 ...") inside an is_error=True ResultMessage rather
than raising, and claude_agent_sdk then collapses that frame into its
generic degenerate-success message. Left unclassified it therefore looks
transient: the bounded retry burns every attempt re-sending the identical
(still-invalid) request, and the exhausted retry surfaces as an opaque
transport failure that callers may charitably read as "ran, changed
nothing". A 400 is deterministic — the same request always reproduces it —
so this is never treated as transient (see
:func:~robotsix_llmio.claude_sdk.transient.is_claude_sdk_transient) and
must fail loudly so the offending parameter gets fixed.
ClaudeSDKQueryTimeout
Bases: RobotsixLLMIOError
A single Claude Agent SDK query() exceeded the per-call wall-clock cap
(:data:~robotsix_llmio.core.constants.SDK_QUERY_TIMEOUT).
Unlike the turn-limit failure, a timeout is a stall (the subprocess made no
progress — often startup contention), not a non-converging loop. Re-running
usually clears it, so it is treated as transient and retried by the
bounded retry (matched by name in
:data:~robotsix_llmio.claude_sdk.transient._SDK_TRANSIENT_NAMES).
ClaudeSDKTurnLimitError
Bases: RobotsixLLMIOError
The Claude Agent SDK loop hit its turn cap (_MAX_TURNS) without
returning a final answer.
A hard failure surfaced loudly: the agent loop did not converge, and the
identical request would just loop to the cap again — so it is never treated
as transient (see
:func:~robotsix_llmio.claude_sdk.transient.is_claude_sdk_transient).
ClaudeSDKUsageExhaustedError
Bases: ProviderExhaustedError
The Claude subscription has exhausted its usage credits for the
ClaudeAgentOptions.model tier this call used.
Because every Claude tier draws on the one subscription, this is a
provider-wide exhaustion — hence the
:class:~robotsix_llmio.exceptions.ProviderExhaustedError base — and the
tier-fallback loop skips all sibling Claude levels in one step rather than
walking them one by one.
The SDK reports this as a normal-looking ResultMessage (is_error=True,
often subtype="success") carrying the assistant-visible text "You're out
of usage credits" rather than raising — so left unhandled, that text would be
returned as if it were a genuine reply. A re-run at the same tier cannot
help (the credits are exhausted until they reset), so this is never treated
as transient (see
:func:~robotsix_llmio.claude_sdk.transient.is_claude_sdk_transient) —
callers should catch it and fall back to a different capability tier
instead (e.g. via
:func:~robotsix_llmio.core.failover.acall_with_failover).
ClaudeSDKModel
Bases: Model
pydantic-ai model backed by the Claude Agent SDK (subscription auth).
sdk_model is the value passed to the SDK's model option — a Claude
Code alias ("opus", "sonnet", "haiku") or a full model id.
model_name
property
model_name
The model name reported to pydantic-ai (the SDK model id, or its override).
system
property
system
The provider/system identifier for this model (always
"anthropic").
provider
property
provider
The HTTP provider for this model (always None: the claude CLI
subprocess is the transport, not an HTTP client).
request
async
request(messages, model_settings, model_request_parameters)
Run messages through the Claude Agent SDK and return the final
:class:ModelResponse.
Rejects unsupported request parameters (function tools, non-text output modes), renders the conversation into a single prompt plus system text, and invokes the SDK to obtain the assistant's final text and usage.
ClaudeSDKProvider
Bases: LLMProvider
Builds :class:~robotsix_llmio.claude_sdk._model.ClaudeSDKModel instances,
one per model name, authenticated by your claude login subscription.
new_model
new_model(*, model=None, level=0)
Build a model, returning (model, http_client).
The http_client is always None here: the claude CLI
subprocess is the transport and there is no HTTP client to manage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | None
|
The concrete model name (e.g. |
None
|
level
|
int
|
Capability level (unused for Claude SDK — no per-level policy is applied here). Accepted for signature compatibility with the base class. |
0
|
build_agent
build_agent(
*,
level=1,
tier_config=None,
model=None,
system_prompt,
tools=None,
output_type=str,
name=None,
retries=2,
workspace_root=None,
builtin_tools=True,
web_tools=False,
images=None,
vision_api_key=None,
)
Build a ready-to-run agent for the requested capability level.
Uses the integer level (1 → cheap, 2/3 → capable, 4 → frontier)
with tier_config. When tier_config is None, a default is
built from baked module-level defaults.
When tools is non-empty, returns a :class:_SdkToolAgentHandle that
drives the SDK tool loop directly — intermediate ToolCallPart
objects are not surfaced. When tools is empty/None, delegates
to the standard pydantic-ai Agent path (unchanged).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | None
|
Optional explicit model name override (e.g.
|
None
|
workspace_root
|
str | Path | None
|
confines the agent's built-in file-mutating
tools to that directory: the SDK runs with
|
None
|
images
|
Sequence[tuple[str, bytes]] | None
|
attached |
None
|
activity_events
activity_events(on_event)
Route Claude Agent SDK activity events to on_event for this context.
Applies to any claude_sdk call made within the with block —
both the no-tools ClaudeSDKModel path and the SDK-tools
_SdkToolAgentHandle path — since both funnel through
:func:_stream_query, which reads this ambient callback when no
explicit on_event argument is given. A context variable is used
(rather than a constructor/call argument on build_agent()/run())
so a caller doesn't need to know which transport build_agent()
resolved to, and the shared LLMProvider interface stays untouched.
contextvars propagate into the asyncio.Task the streaming loop
runs in (a task copies its creator's context at creation time), so this
works across the await inside handle.run(...).
is_claude_sdk_auth_error
is_claude_sdk_auth_error(exc)
True if exc (or anything in its cause/context chain) is the dedicated
ClaudeSDKAuthError. Matched by name so this stays free of an import
cycle with the error module, walking the bounded cause/context chain like
the other helpers.
is_claude_sdk_permanent_api_error
is_claude_sdk_permanent_api_error(exc)
True if exc (or anything in its cause/context chain) is the dedicated
ClaudeSDKPermanentAPIError. Matched by name so this stays free of an
import cycle with the error module, walking the bounded cause/context chain
like the other helpers.
is_claude_sdk_session_option_error
is_claude_sdk_session_option_error(exc)
True if exc reports a session option the CLI refuses to honour.
Covers asking to resume a session the CLI does not have, asking to create
one it already has, and passing --session-id alongside
--resume/--continue without --fork-session. None of these is
flaky: the fix is always to bind a different option, never to try again.
is_claude_sdk_spawn_argv_too_long
is_claude_sdk_spawn_argv_too_long(exc)
True if exc is the CLI spawn failing with E2BIG.
The kernel refuses the execve when a single argument exceeds
MAX_ARG_STRLEN (128 KiB) or when argv plus envp together exceed
ARG_MAX (RLIMIT_STACK / 4, so 2 MiB at the usual 8 MiB stack). The
transport builds the same command from the same options on every attempt,
so the size is identical each time and no retry can clear it — observed
2026-08-13 on robotsix-chat, where four autonomous sessions each burned all
three attempts on it in a ten-second window and surfaced an opaque
server_error to the user.
Matched on the errno rather than the message so it holds under a
non-English locale, walking the bounded cause/context chain like the other
helpers.
is_claude_sdk_transient
is_claude_sdk_transient(exc)
Core transient set OR a Claude Agent SDK subprocess/transport failure, walking the cause/context chain for the latter.
The turn-cap failure, usage-exhaustion, API request-validation (400)
rejections, authentication (401) failures, an E2BIG spawn refusal, and
a refused session option are explicitly excluded — and checked FIRST, so
they win even when the CLI surfaces them as a (normally-transient)
ProcessError or as the degenerate-success frame. Retrying any of them
would just repeat the identical failure, so all six must fail loudly rather
than burn retries and end in an opaque error.
is_claude_sdk_turn_limit
is_claude_sdk_turn_limit(exc)
True if exc (or anything in its cause/context chain) is the Claude Agent
SDK turn-cap failure — either the dedicated ClaudeSDKTurnLimitError or the
raw SDK message. Matched by name/string so this stays free of the SDK and the
model module (no import cycle).
is_claude_sdk_usage_exhausted
is_claude_sdk_usage_exhausted(exc)
True if exc (or anything in its cause/context chain) is the
dedicated ClaudeSDKUsageExhaustedError — a tier's usage credits are
exhausted. Matched by name so this stays free of an import cycle with
model.py, walking the bounded cause/context chain like the other
helpers.