Run bounded Claude agents
A Claude-backed lending assessment can finish after customer status changes. Repeating every agent wastes unaffected work, while accepting a late result can restore stale reasoning. Use a bounded fresh execution per attempt, register only validated completed outputs and let the host select affected agents from Co2 plans. This cooperative configuration is not runtime isolation.
Install and run
Use the SDK build prerequisites in the Python guide:
python -m venv .venv
source .venv/bin/activate
python -m pip install -e '.[claude-agents]'
python examples/claude_agents_lending.py
python -m unittest discover -s agent_frameworks_tests/claude_agents -v
The optional extra pins claude-agent-sdk==0.2.189. Its wheel includes the Claude Code executable; the tested Apple Silicon wheel bundles Claude Code 2.1.332. A separate system Claude installation or Node runtime was unnecessary.
The worker checks the SDK and CLI versions and refuses unvalidated versions. The adapter currently requires POSIX process groups for timeout/cancellation cleanup; actual SDK/CLI boundary probes were exercised on macOS ARM64 with CPython 3.14. Linux mock adapter qualification does not establish the same actual CLI runtime boundary; see the configuration matrix.
The SDK wheel is substantial (about 158 MiB downloaded locally), and native runtime compatibility is a deployment requirement.
A combined install of all optional extras resolved and passed dependency checks. It selected Claude SDK 0.2.189, Google ADK 2.15.1, Google GenAI 2.34.0, OpenAI Agents SDK 0.20.0, OpenAI 2.54.0, LangGraph 1.2.24 and MCP 2.3.0. That tested resolver configuration reported no additional Claude conflict. The existing ADK shared dependency constraints still select websockets==15.0.1 and tenacity==9.1.4; they can require downgrades compared with an earlier Agents-only environment. Resolve optional extras in a clean environment and retain the tested package set.
The default demonstration replaces the SDK execution boundary with deterministic async responses. Its counters measure requests to that boundary, not real Claude or model calls. It proves host routing and Co2 registration behavior. The mock demonstration asserts eligibility 2, credit 1, recommendation 2, and one deliberately late execution. Credit is reused; eligibility/recommendation are replaced; human approval revalidates and irreversible funding escalates. Initial assessments overlap behind a two-party gate.
To exercise the actual Python SDK and bundled CLI reproducibly, install pytest and run the loopback-provider tests:
python -m pip install pytest
CO2_CLAUDE_RUNTIME_TEST=1 python -m pytest -q agent_frameworks_tests/claude_agents
These tests start a local fake Messages API with synthetic credentials and responses. They exercise the real worker, SDK, CLI and provider request path; they do not call Anthropic or evaluate real model behavior. They verify concurrent independent SDK/CLI sessions behind a provider barrier, artifact registration with no tools in the provider request, tool-list behavior, rejection of a provider-forged Bash call without creating its temporary canary, exclusion of ambient environment/user configuration, and cancellation of an in-flight worker/CLI process group without artifact publication.
Local socket permission is required; restricted CI can run the default execution-boundary and message-validation tests without enabling them.
A live experiment is optional and bounded to six executions, one turn each, a default 60-second timeout per attempt and a $0.05 CLI budget per attempt:
# ANTHROPIC_API_KEY must be explicitly supplied in the environment or local .env.
python examples/claude_agents_lending.py --live --model claude-haiku-4-5 --env-file .env
# Separate one-execution live smoke test; key must already be in the environment:
CO2_LIVE_CLAUDE_TEST=1 python -m unittest discover -s agent_frameworks_tests/claude_agents -v
Execution counters describe SDK boundaries, not hidden HTTP retries or provider-side work. Fake-provider usage and cost values are fixture data. A CLI budget may be exceeded by a completed request before it stops; rejecting an over-budget terminal result cannot reverse charges. Local process cancellation does not guarantee remote cancellation. Model access, pricing and endpoint behavior remain host responsibilities.
Map bounded executions
Construct ClaudeAgentsAdapter(api_key=...), register source versions, and call run_agent with a stable logical agent, immutable ClaudeExecution, complete accessible source versions, optional upstream (agent, artifact_id) pairs, an input builder and output encoder. The builder receives the public Co2 scoped context and invocation. The output encoder validates application output and must return bytes.
The lending example accepts exactly one JSON object, either bare or wrapped in a single JSON code fence; it rejects surrounding prose, duplicate keys and schema violations. A returned AgentResult binds the Co2 session/computation/attempt/artifact to the fresh Claude session UUID. Historical human/effect records have no Claude session and execute nothing.
Sessions cannot be restored, continued, forked or reconstructed after process restart.
The adapter registers a configuration dependency containing a digest of explicit instructions, model, endpoint, budget, timeout and the pinned SDK/CLI/boundary version. It records a scoped observation of that resource. Trusted structured declarations must include configuration_ref(agent) or conservatively fall back for an observed omission.
Credential values are excluded; hosts must supply an account/configuration identity resource when that distinction affects semantics. Configuration changes invalidate existing output and still require explicit probabilistic recomputation policy. The default invocation-level strategy, untrusted declaration fallback and RuntimeObservedFallback are unchanged.
No new completeness assurance is issued.
The allowed execution configuration is fixed by the adapter:
- Fresh UUID/session, one turn, no resume/continue/fork/session store, and CLI session persistence disabled.
tools=[],allowed_tools=[], no SDK hooks or custom agents, empty skill/plugin lists, strict empty MCP configuration anddontAskpermissions. The worker rejects assistant tool/server-tool activity, unexpected initialization, failed or duplicate/incomplete terminal results, mismatched sessions and invalid application output.- Explicit custom system instructions supplied through a temporary system-prompt file,
setting_sources=[],--bare,--disable-slash-commandsand settings disabling hooks. No user/project/local setting source or caller-provided CLI arguments are accepted. - A fresh empty working directory, fresh home/config/temp directories and a per-attempt environment allow-list. Only operating-system basics, explicit Anthropic API credentials/endpoint and disabled nonessential traffic are supplied. Environment inheritance is handled by launching a worker with a clean environment because
ClaudeAgentOptions.envalone only overlays the parent environment. The API key is not put in command-line arguments, records or logs. Worker/CLI stderr and raw error text are not exposed. - Finite positive timeout up to 120 seconds and CLI budget up to $0.10 per execution. The parent terminates the POSIX worker process group on exit, timeout or cancellation and removes the temporary directories. This is resource lifecycle management, not a sandbox or hostile-code containment.
plan and reuse delegate to Co2; the host explicitly routes affected agents. Unknown, human, effect and irreversible classifications cannot be executed by the adapter. Stale probabilistic work blocks unless PlanPolicy(allow_probabilistic_recomputation=True) is explicitly passed. Co2 atomically revalidates the entire invocation snapshot at publication, including accessible inputs omitted from a trusted output subset. Failed execution or validation publishes no artifact for that failed call; the adapter abandons captured Co2 work and burns unused issued identities. Direct SDK use and arbitrary host input/encoder/model code are outside this adapter's control.
Tool behavior verification
A public-API probe against the actual pinned CLI observed:
| Options | Reported tools |
|---|---|
allowed_tools=[], tools=None, otherwise the same bare configuration | Bash, Edit, Read |
allowed_tools=[], tools=[] | Empty |
The direct Anthropic init frame can omit the optional additional_directories field, while the local provider frame reports an empty list. The adapter accepts omission because it never configures additional directories, and still rejects any reported nonempty or malformed value. This is a compatibility check, not evidence of filesystem isolation.
The second configuration also sent no tool definitions in the loopback provider request. Thus this integration relies on the explicit base tool set, not an empty permission allow-list. See the official Python API and permission documentation.
Literal absence of every subagent/plugin registry entry is not achievable through the validated configuration. The pinned CLI still advertises built-in agent definitions (claude, Explore, general-purpose, Plan, statusline-setup) and three built-in plugin registry entries (cc-plugin-agents-md, cc-plugin-privacy, cc-plugin-plugin-authoring) under --bare. The adapter configures no subagents or plugins, accepts only that exact built-in registry and provides no Agent/Task/Skill or other dispatch tool. No subagent execution was observed. This is an explicit limitation of the requested boundary, not a claim that these registries are empty or that the bundled code cannot affect behavior.
User/project/local configuration is excluded, but administrator-managed policy and managed plugin behavior may still apply to Claude Code. The init frame does not attest that every possible lifecycle hook or hidden instruction is absent. The host must validate the deployed machine's managed configuration separately; a modified registry or observable tool capability is rejected. Do not interpret the supported settings as proof against a compromised CLI, malicious host, OS or provider.
Bound subprocess and permission assumptions
The SDK launches Claude Code as a subprocess and inherits its OS privileges unless an external runtime restricts them. dontAsk is a permission decision mode; a tool set is a capability configuration; neither establishes complete information-flow mediation. SDK sandbox settings configure Claude Code's sandbox facilities and this adapter does not establish a sandbox boundary. A subprocess boundary, clean home, request digest, runtime init report or absence of observed tool calls cannot establish runtime-enforced dependency completeness.
A future provider SPI needs independent validation of mediation for filesystem, process, network, environment, memory and tool channels; execution-bound evidence tied to the actual attempt/result; source-version binding; and a separately owned reference sandbox integration. It must also account for managed settings and built-in runtime/provider context. Co2 must remain independent of sandbox ownership and keep RuntimeObservedFallback until that boundary is demonstrated. No SPI or attestation protocol is introduced here.
The host must supply all accessible semantic inputs, accurately bind values to ordered resource versions, account for instructions/history/provider state/ambient influences, trust developer declarations correctly, respect plans and handle changes after a point-in-time check. A subprocess result is not a distributed transaction, proof of model correctness or semantic equivalence. No persistence, distributed execution, automatic scheduling or recovery is provided.
Example outcome
The default synthetic workflow records eligibility 2, credit 1, recommendation 2, plus a separate deliberately late attempt. These are executed mock-boundary counts, not billing or live-provider performance measurements. Credit retains its artifact; replacements get new attempt/artifact identities. Stale approval requires REVALIDATE; irreversible funding requires ESCALATE and funding execution stays zero. The host explicitly enables probabilistic recomputation for the reasoning demonstration. Without that policy, stale reasoning blocks.
Check versions, complete accessible context, output schema and current artifact bindings before using results. Session IDs correlate process-local state; they are not authorization credentials. Rejected late results need fresh current context and new identities when eligible. A source update after a successful check can still occur; no adapter locks external source systems. See execution semantics, failure handling and lifecycle cleanup.

