AI-generated illustrationChoose the Right Runtime: API Loop, Agent SDK, or Managed Agents
Run one refund workflow across API loop, Agent SDK, and Managed Agents (beta) to map ownership, verify capabilities, and write falsifiable ADRs.
- Reading
- 34 min
- Workshop
- 90 min
- Stack
- TS, Node 22, Anthropic SDKs
- Version
- 1.0.0
- Last verified
- Nov 22, 2026
01Outcomes
What you will build and be able to do
Each outcome has an observable criterion. The lab and the assessment check exactly these, nothing more and nothing less.
OBJ-001
Map the four runtime ownership layers
Assign owner, execution location, and dated evidence state across model call, harness loop, execution sandbox, and hosting boundary while keeping Cloud and Self-Hosted Managed Agents separate. Checked by pnpm lab1 and ASM-001.
OBJ-002
Run one control task across all three runtimes
Execute ticket T-1042 through API loop, Agent SDK (built-ins disabled), and Managed Agents with identical tools, approval enforcement, and system-of-record verification. Checked by pnpm test:lab1.
OBJ-003
Verify capabilities with falsifiable probes
Distinguish observed, documented, unsupported, and not_run claims using runnable capability probes paired with planted-fault self-tests that fail when protection is removed. Checked by pnpm lab2 and ASM-002.
OBJ-004
Recover cleanly from mid-task crashes
Stop each runtime between human approval and refund confirmation, inspect surviving state, and prove system-of-record idempotency stops duplicate refunds on restart. Checked by pnpm test:lab2.
OBJ-005
Route decisions through hard constraints and ADRs
Filter disqualified runtimes with dated hard constraints, defend the pick among surviving runtimes in a falsifiable Nygard ADR with review date, and supersede it when a constraint changes. Checked by pnpm lab3 and ASM-003.
02Prerequisites and setup
Unpack runtime-labs.zip and verify offline ($0.00)
- The tool-calling loop and Example Outfitters fixture. Build, Break, and Repair a Reliable Tool-Using Agent covers the bounded loop and introduces ticket T-1042; this download includes a standalone SDK 1.x copy.Start with Guide 01
- Approval fingerprints and least-privilege tool scoping. Contain Agent Actions covers pre-action human approval and prompt-injection containment.Read Guide 03
- Single-call structured outputs. If your workload does not need a multi-turn tool loop, start with structured output contracts before adopting any agent runtime.Read Guide 14
- Node.js 22.18.0 or newer and pnpm 12. The archive pins Node.js 22.23.5 and pnpm 12.21.0 and runs TypeScript natively.Node.js downloads
- No API key required. All three labs, planted-fault self-tests, and offline checks run at $0.00 against local 127.0.0.1 HTTP and SSE doubles.
unzip -q runtime-labs.zip -d runtime-labs-workcd runtime-labs-work && pnpm install --frozen-lockfilepnpm typecheck && pnpm test# tests 7 # pass 7 # fail 0 (all runs offline against 127.0.0.1)03The system picture
Four runtime layers: model, harness, sandbox, and hosting

Extended description
Layer 1 (Model and Tools) calls Anthropic /v1/messages in all three runtimes; custom tools and system-of-record verification run in your application process across all three paths.
Layer 2 (Harness Loop and State) stays inside your bounded for-loop under API Loop, moves into a bundled 381 MB proprietary claude child process under Agent SDK, and runs server-side with an SSE event log under Cloud Managed Agents (beta).
Layer 3 (Execution Sandbox) is absent by default in API Loop, requires team-managed container isolation for Agent SDK, and runs inside an Anthropic cloud container with closed or limited outbound networking under Cloud Managed Agents.
Layer 4 (Hosting and Compliance) distinguishes direct API (GA, ZDR and HIPAA BAA eligible) from Agent SDK (ZDR eligible, not HIPAA covered) and Cloud Managed Agents (beta, ineligible for ZDR and HIPAA). Self-Hosted Managed Agents sits in a separate dashed column marked Not Run.
04Lesson
Four layers instead of a single runtime box
Teams frequently debate API loop, Agent SDK, and Managed Agents as if they were interchangeable wrappers around the same call. In practice, every production agent divides into four distinct layers: model inference, harness loop and transcript storage, code execution sandbox, and hosting compliance boundary. Choosing a runtime only moves who operates layers 2 through 4; it never removes your responsibility for approval enforcement, least-privilege tool scoping, or system-of-record verification.
Extended description
The six-second loop steps through three views: API Loop (application team owns layers 2 to 4), Agent SDK (bundled claude subprocess owns layer 2 while team owns container sandbox and hosting), and Cloud Managed Agents beta (Anthropic cloud hosts layers 1 to 4 while custom tools and ledger invariants remain team-owned).
One synthetic control task across all three runtimes
To isolate runtime behavior from prompt or tool variance, we fix the workload as a control: synthetic store Example Outfitters ticket T-1042, requesting a $48.00 refund on damaged-on-arrival order ORD-5521 under policy POL-DOA-30. Every runtime calls the exact same five TypeScript tool handlers, enforces the same approval fingerprint bound to ticket, order, and cent amount, and is graded strictly by reading desk.json invariants INV-01 through INV-05.

Extended description
Batch L1 passed 4 of 4 runs across API loop, toolRunner, Agent SDK, and Cloud Managed Agents. Batch L2 passed 3 of 3 on API loop and Managed Agents, and 2 of 3 on Agent SDK where harness wall-clock date injection (2026-11-22) nudged 1 run into a clean safe escalation.
| Runtime variant | Wall ms | Calculated USD | Cache read | Local footprint | Verdict |
|---|---|---|---|---|---|
| API loop (for-loop) | 10,689 | $0.028626 | 0 (uncached) | 0 child, 0 files | verified_success |
| API loop (toolRunner) | 11,651 | $0.029406 | 0 (uncached) | 0 child, 0 files | verified_success |
| Agent SDK (query) | 11,873 | $0.018064 | 9,839 (auto 5m) | 1 claude child, 4 files | verified_success |
| Managed Agents (beta) | 17,099 | $0.023371 (+$0.000245 active) | 18,512 (auto 5m) | 0 local child, 0/0/0 cleanup | verified_success |
Capability matrix and compliance surprises
Every capability claim in a runtime review must state whether it was observed by a runnable probe, read from dated primary documentation, unsupported, or not run. Running primary documentation checks alongside shipped TypeScript declarations on 2026-11-22 surfaced four operational findings that landing pages rarely highlight: Anthropic data-retention docs explicitly exclude both Cloud Managed Agents and Claude Code (Agent SDK) from HIPAA readiness; Agent SDK installs a ~381 MB proprietary binary whose harness injects current wall-clock dates; beta.messages.toolRunner defaults to server-side threading unless thread: false is passed; and Managed Agents budget.max_list_cost.amount requires integer US cents as a string ("50" for $0.50).

Crash recovery and system-of-record idempotency
Stopping a runner partway through T-1042 (immediately after human approval and before refund verification) exposes what each runtime actually persists. An API loop loses in-memory messages unless your service writes checkpoints to its own database. The Agent SDK preserves JSONL transcripts only when CLAUDE_CONFIG_DIR lives on durable storage; ephemeral containers wipe it. Cloud Managed Agents preserves its server-side event log even if the client SSE stream disconnects, meaning a dropped stream is never proof of a failed task. Yet across all three runtimes, restarting without an idempotency key enforced by desk.json allows a duplicate $48.00 refund.
Extended description
Steps 1 through 5 animate ticket inspection, approval signing, mid-task process kill, worker restart retry, and INV-03 idempotency rejecting the duplicate refund across API Loop, Agent SDK, and Managed Agents.

Hard-constraint routing and falsifiable ADRs
Before comparing any agent runtime, verify whether a single structured model call already solves the workflow (see Dev Guide 14). When a multi-turn loop is genuinely required, filter candidates through dated hard constraints first: HIPAA BAA coverage (HC-01), Zero Data Retention (HC-02), partner cloud hosting on Bedrock or Vertex (HC-03), GA API requirement with no beta headers (HC-04), open-source dependency policy (HC-05), untrusted sandbox isolation (HC-06), zero internal container fleet (HC-07), and deterministic in-process loop ownership (HC-08). When multiple runtimes survive, weigh operational trade-offs in prose inside a Nygard Architecture Decision Record containing execution limits, a dated cost line with sample size, a concrete falsifier, and a review date.

05Hands-on lab
Lab 1: Run one refund workflow three ways
Execute synthetic ticket T-1042 across API loop, Agent SDK (with built-in tools disabled and disposable HOME/CLAUDE_CONFIG_DIR), and Managed Agents offline, verifying process counts, files written, tool isolation, and INV-01 through INV-05.
Acceptance checks
- Starter script fails cleanly (exit 1), demonstrating F-01 naive text verification and F-02 Agent SDK built-in tool leakage.
- Solution passes offline inside an isolated network namespace (exit 0) with 0 child processes on API loop, 1 claude child + isolated config writes on Agent SDK, 0 built-in tools leaked, and 0/0/0 post-cleanup counts on Managed Agents.
Run LAB-001 starter vs checkpoint solution
$ pnpm lab1:starter && echo PASS || pnpm lab1Initial: Initial (running pnpm lab1:starter before fixing verification and tool restriction)
FAIL: F-01 naive model-text check masked missing refund; F-02 leaked built-in tools [Bash, Read, Edit] (exit 1)Final: Final (running pnpm lab1 after enabling INV-01..05 verifier and disabling Agent SDK built-in tools)
PASS: api-loop (0 child, 0 config files), agent-sdk (1 child, tools: [] clean), managed-agents (0/0/0 active) -> all 3 verified_success (exit 0)Show the solution discussion
Replace naive final-message string matching with desk.json invariant verification (INV-01 through INV-05).
Configure Agent SDK with tools: [], settingSources: [], explicit cwd, disposable HOME and CLAUDE_CONFIG_DIR, and CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1.
Confirm all three runtimes report verified_success with zero leaked built-ins and zero retained Managed Agents resources.
More labs in this guide
Lab 2: Verify capabilities and execute the crash-recovery drill
Run one falsifiable capability probe per claimed runtime behavior, prove each probe fails under a planted-fault self-test, then crash each runner after approval and verify desk.json idempotency stops duplicate refunds.
Lab 3: Filter hard constraints and supersede an ADR
Validate an Architecture Decision Record against HC-01 through HC-08, defend a choice among surviving runtimes with cost and falsifier fields, then supersede ADR-001 with ADR-002 when constraints shift.
06Failure gallery
Twelve ways this breaks, and how you will know
Eight of these reproduce in the lab; the other four were observed in this guide's recorded runs. Learn the symptom first; it is what you will actually see.
- F-01
pnpm lab1:starterReproducibleTrusting model text instead of the system of record
- Symptom
- Runner prints a message claiming the $48.00 refund succeeded when zero refund rows exist in desk.json.
- Diagnosis
- Starter code matched keywords in the assistant's final text instead of checking ledger state.
- Fix
- Grade every run exclusively with verifyTicket checking invariants INV-01 through INV-05 in desk.json.
- Verify
- Run pnpm test:lab1 and pnpm test:lab2; verify F-01 control fails cleanly whenever no refund posts.
- F-02
pnpm lab1:starterReproducibleAgent SDK built-in tools left enabled beside custom tools
- Symptom
- Receipt telemetry shows Bash, Read, and Edit exposed during a narrow support-desk refund run.
- Diagnosis
- Default Claude Code presets remain active unless explicitly cleared.
- Fix
- Pass tools: [] and settingSources: [] to query() and expose only the five custom MCP tools.
- Verify
- Run pnpm test:lab1; assert built_in_tools_exposed is empty.
- F-03
pnpm lab2:starterReproduciblePermissive permission mode shadows canUseTool approval gate
- Symptom
- Agent SDK emits CLAUDE_SDK_CAN_USE_TOOL_SHADOWED and skips approval checks, or refuses root execution inside user namespaces.
- Diagnosis
- Setting permissionMode to bypassPermissions bypasses custom canUseTool callbacks.
- Fix
- Use default or dontAsk permission modes with an explicit canUseTool callback that verifies approval fingerprints.
- Verify
- Run pnpm test:lab2; confirm unapproved refund calls are denied with 0 ledger writes.
- F-04
pnpm lab2ReproducibleAgent SDK session transcript lost on ephemeral container restart
- Symptom
- Resuming a session ID fails after container recycle.
- Diagnosis
- The bundled claude subprocess wrote JSONL session state into an ephemeral local CLAUDE_CONFIG_DIR.
- Fix
- Mount durable storage for CLAUDE_CONFIG_DIR or configure an external SessionStore, and keep ledger idempotency independent of transcripts.
- Verify
- Run pnpm test:lab2 recovery drill comparing durable vs wiped config directories.
- F-05
pnpm lab2:starterReproducibleCrash restart posts a duplicate refund
- Symptom
- Restarting after a mid-task crash writes two $48.00 refund rows for ticket T-1042.
- Diagnosis
- The refund handler lacked idempotency-key deduplication against the approval fingerprint.
- Fix
- Require deterministic idempotency keys on issue_refund and enforce INV-03 (at most one payout per ticket).
- Verify
- Run pnpm test:lab2; verify planted fault fails when idempotency protection is removed.
- F-06Observed
Harness date injection alters edge-case policy reasoning
- Symptom
- On Claude Haiku 5.5 (Batch L2, n = 3), 1 of 3 Agent SDK runs escalated ticket T-1042 instead of refunding.
- Diagnosis
- The bundled Claude Code harness injected wall-clock date 2026-11-22 into system context, nudging the model to compare today against delivered_on rather than opened_on.
- Fix
- Anchor policy window math explicitly in deterministic tool results rather than letting the model infer dates from harness metadata.
- Verify
- Inspect Batch L2 receipts comparing API loop (3/3), Managed Agents (3/3), and Agent SDK (2/3 success, 1/3 safe escalation).
- F-07Observed
Missing native claude binary after --no-optional install
- Symptom
- Agent SDK throws a missing executable error immediately at query() startup.
- Diagnosis
- Installing dependencies with --no-optional skips the ~381 MB platform optional binary package.
- Fix
- Install from the frozen pnpm-lock.yaml with optional dependencies enabled so the matching OS/CPU package resolves.
- Verify
- Run pnpm install --frozen-lockfile in a clean home and confirm offline Agent SDK tests pass.
- F-08Observed
Node fetch bypasses corporate HTTPS_PROXY defaults
- Symptom
- Live SDK requests time out or fail TLS handshake inside proxied enterprise networks.
- Diagnosis
- Built-in Node fetch ignores HTTPS_PROXY unless an undici ProxyAgent or --use-env-proxy is configured.
- Fix
- Supply a proxy-aware custom fetch dispatcher or local loopback relay when calling Anthropic APIs behind a corporate proxy.
- Verify
- Test connectivity through the local proxy dispatcher before running live batches.
- F-09Observed
Managed Agents budget cap rejected on dollar decimals
- Symptom
- Session creation fails with HTTP 400 when budget.max_list_cost.amount is passed as "0.50".
- Diagnosis
- Shipped Managed Agents API requires integer US cents as a string ("50"), not fractional dollars.
- Fix
- Convert dollar caps to integer cents strings before calling sessions.create.
- Verify
- Inspect Managed Agents session creation schema and recorded Batch L1/L2 live receipts.
- F-10
pnpm lab1ReproducibleRetained Managed Agents sessions leave transcripts on server
- Symptom
- Active sessions, environments, or agents remain listed in the Anthropic account after a batch ends.
- Diagnosis
- Managed Agents stores session transcripts server-side until explicitly deleted.
- Fix
- Delete sessions and environments, archive agents (agents endpoint has archive, not delete), and assert 0/0/0 active resources in a post-run listing.
- Verify
- Run pnpm test:lab1 checking post_cleanup_active_counts equals 0 sessions, 0 environments, 0 agents.
- F-11
pnpm lab2ReproducibleDropped SSE stream misread as a failed Managed Agents task
- Symptom
- Client disconnects mid-stream and retries from scratch even though the server session continued running.
- Diagnosis
- Network drops terminate the local HTTP stream without halting the server-side Managed Agents session.
- Fix
- Reconnect and fetch stored session events before deciding whether to resume or cancel.
- Verify
- Run pnpm test:lab2 verifying offline stream replay reconciles stored events.
- F-12
pnpm lab3:starterReproducibleDecision-record cell copied from marketing table with no receipt
- Symptom
- ADR marks a capability observed without citing a probe run or violates HC-02/HC-04.
- Diagnosis
- Author treated vendor documentation as empirical verification and skipped hard-constraint validation.
- Fix
- Run lab3-checker.ts to enforce evidence states, hard constraints, cost lines, falsifiers, and review dates.
- Verify
- Run pnpm lab3:starter (rejected) followed by pnpm lab3 (accepted).
07Assessment
Transfer task and rubric
Map ownership, verify capabilities offline, and write linked falsifiable ADRs for an unfamiliar synthetic billing workload under shifting constraints.
| Criterion | 0 · Emerging | 1 · Developing | 2 · Proficient | 3 · Exemplary |
|---|---|---|---|---|
| C1 Responsibility mapping | Missing layers or collapses Cloud and Self-Hosted Managed Agents. | Covers most layers but leaves ownership or location ambiguous. | All 7 layers mapped accurately across all 3 runtimes with Cloud and Self-Hosted separated. | Complete mapping plus concrete blast-radius and state-cleanup notes per layer. |
| C2 Evidence hygiene | Marks vendor claims as observed with no probe receipt. | Cites sources inconsistently or omits verification dates. | Zero unbacked observed claims; dated primary citations on all documented cells. | Explicitly separates offline observed, live observed, and documentation limits. |
| C3 Capability verification and fault tests | Fewer than 2 probes or zero planted-fault tests. | Probes run but lack verified failing fault mutations. | At least 3 offline probes executed with receipts and passing planted-fault self-tests. | Adds crash-recovery restart receipt proving ledger duplicate protection. |
| C4 Hard-constraint routing | Picks a disqualified runtime or identical runtime across conflicting constraints. | Eliminates Cloud Managed Agents in Phase 1 but fails to weigh both survivors. | Eliminates Cloud Managed Agents on HC-02/HC-04, weighs both survivors, and switches cleanly under HC-06/HC-07. | Links every constraint check to required controls beyond runtime selection alone. |
| C5 ADR completeness, cost, and limits | Missing Nygard fields or ungrounded cost/speed ranking. | Includes Nygard fields but omits execution caps or pricing dates. | Both ADRs carry full Nygard structure, execution limits, dated cost lines with sample size, and review dates. | Separates active session-hour fees from token rates and notes prompt-caching caveats. |
| C6 Falsifiers and revision discipline | Omits falsifiers or presents Managed Agents beta as generally available. | Generic falsifiers or weak superseding linkage between ADR-001 and ADR-002. | Concrete measurable falsifiers on both ADRs; ADR-002 cleanly supersedes ADR-001 with beta caveat. | Maps falsifiers directly to repeatable staging checks and rollback triggers. |
Proficiency standard: Proficient or higher on every criterion. Proposed local standard, not an official certification.
The full brief
Case: Example Clinic Billing (billing.example-clinic.test, ops@example.com, synthetic data with zero PHI). Phase 1 audits duplicate invoice INV-8841 ($120.00, policy POL-DUP-14) under HC-02 (Zero Data Retention) and HC-04 (generally available API surface), plus host-side approval and ledger verification invariants.
Phase 2 introduces a separate public synthetic billing-code validation batch (CODE-RESEARCH-Q4) running untrusted third-party Python scripts under HC-06 (isolated container sandbox) and HC-07 (zero internal container fleet), lifting HC-02 and HC-04 for the public dataset.
Deliver three parts: ASM-001 (complete 7-layer responsibility matrix across all three runtimes with Self-Hosted Managed Agents kept separate and labeled documented), ASM-002 (at least three offline capability probes from runtime-labs.zip with receipts and failing planted-fault self-tests), and ASM-003 (ADR-001 weighing both Phase 1 survivors, superseded by ADR-002 for Phase 2 with beta caveat, execution caps, dated cost lines, review dates, and concrete falsifiers).
Passing requires Proficient (2) or Exemplary (3) on all six criteria (C1 through C6) and zero critical failures (CF-1 through CF-8). Completion confirms mastery within this course only and is not an external certification.
08Instructor kit
Teach it to a room
Timed facilitation plans (90-minute and half-day)
Minute-by-minute schedule, 3-level hint ladder, formative mid-workshop check, and troubleshooting guidance for macOS, Windows, and corporate proxy rooms without API keys.
12-person cohort and 100-person enterprise rollout plans
Pre-flight registry mirroring, instructor calibration across four sample submissions, and deterministic critical-failure pre-screening.
Dry-run observation rubric and seeded-failure drills
Six-competency classroom observation rubric paired with live diagnosis drills on seeded broken repairs and calibration submissions.
Pending instructor clearance record
Blank clearance record explicitly marked pending until an authorized observer scores a live dry run and second-instructor review completes.
Dual-denominator monthly pass-rate report template
Reports both per-attending (with 95% Wilson interval) and per-assessed pass rates, cell suppression below 10 learners, and non-ranking rules.
10Sources and verification
- [1]Anthropic API migration to 2026-10-21 · platform.claude.comchecked Nov 22, 2026
- [2]Anthropic Client SDK beta tool runner · platform.claude.comchecked Nov 22, 2026
- [3]Anthropic models overview · platform.claude.comchecked Nov 22, 2026
- [4]Anthropic platform pricing · platform.claude.comchecked Nov 22, 2026
- [5]Anthropic API and data retention (ZDR and HIPAA) · platform.claude.comchecked Nov 22, 2026
- [6]Claude Agent SDK overview · code.claude.comchecked Nov 22, 2026
- [7]Claude Agent SDK hosting and deployment · code.claude.comchecked Nov 22, 2026
- [8]Claude Agent SDK custom tools and MCP · code.claude.comchecked Nov 22, 2026
- [9]Claude Agent SDK permissions · code.claude.comchecked Nov 22, 2026
- [10]Claude Agent SDK session storage · code.claude.comchecked Nov 22, 2026
- [11]Claude Agent SDK secure deployment · code.claude.comchecked Nov 22, 2026
- [12]Claude Managed Agents overview (beta) · platform.claude.comchecked Nov 22, 2026
- [13]Claude Managed Agents cloud environments · platform.claude.comchecked Nov 22, 2026
- [14]Claude Managed Agents self-hosted sandboxes · platform.claude.comchecked Nov 22, 2026
- [15]Claude Managed Agents tools and events · platform.claude.comchecked Nov 22, 2026
- [16]Claude Managed Agents permission policies · platform.claude.comchecked Nov 22, 2026
- [17]Claude Managed Agents session budgets · platform.claude.comchecked Nov 22, 2026
- [18]Documenting Architecture Decisions · cognitect.comchecked Nov 22, 2026
Independent work. Not affiliated with or endorsed by any vendor named in this guide.
