ADR-0020: Dual-runtime — Claude Agent SDK as a second worker type behind the frozen gRPC worker contract
- Status: Accepted (founder approval 2026-07-02,
upsquad-ai/upsquad-core#1627) — amended 2026-11-13 (Amendment 1,upsquad-ai/upsquad-core#4420): the Claude Agent SDK is the primary runtime for workflow orchestrators and their sub-agents; LangGraph is retained for existing single-turn agents; #2616 folded in. See Amendment 1. - Date: 2026-07-02
- Decision owners: Founder (sign-off), Principal Architect (author), Backend SME (spike), Product Manager (downstream PRDs)
- Related:
- ADR-0012 — this ADR resolves its parked runtime-vs-middleware question with "both, per-agent choice" (
upsquad-ai/upsquad-core#1198) - ADR-0019 — adopt-and-wrap autonomous runtime (the LangGraph worker this ADR keeps as default)
- Spike:
upsquad-ai/upsquad-core#1626— flag-gatedclaude_sdkexecutor (merge gated on approval of this ADR); PR #1628 - Pre-existing checkpoint schema v2/v1 mismatch:
upsquad-ai/upsquad-core#1630 upsquad-ai/upsquad-core#4420— Amendment 1 (primary runtime for workflow orchestrators + sub-agents; tracker #4419);#2616(SDLC coder-runtime proposal, folded in);#4432(SDK floor ≥ 0.2.127);#4421/#4422(R1/R2 runtime build);#4450(hook ↔ governance-port contract,internal/workflow/orchrt)- ADR-0023 Amendment 1 — the workflow engine this runtime now hosts (Temporal retired, same ruling)
- ADR-0012 — this ADR resolves its parked runtime-vs-middleware question with "both, per-agent choice" (
Status
Accepted — founder approval 2026-07-02 (via GitHub comment on #1627).
Amended 2026-11-13 — Amendment 1 below, founder ruling from his own account (#4420 comment 6849892608). The 2026-07-02 decision stands for what it decided — two worker types behind the frozen gRPC worker contract, the moat mapping, the four trade-offs — and is narrowed on one point and widened on another: the Claude SDK worker is no longer "positioned for dev / internal use cases" (narrowed away), and it becomes the primary runtime for workflow orchestrators and their sub-agents (widened). LangGraph stays the runtime for existing single-turn agents; it is not retired.
Context
UpsQuad runs agents behind a frozen gRPC worker contract — InitWorkerSession / ExecuteStep / Checkpoint / Heartbeat — with a Go orchestrator that owns the authoritative PlanLoop terminator, forced-submit_plan PLAN decomposition, BYOK multi-provider sourcing (modes B/C/D), and the stateless-worker tenet (P0.3.11). The single existing worker type is the Python LangGraph worker.
The parked question in ADR-0012 (runtime-vs-middleware, 2026-06-07) — "do we build a Claude-Code-equivalent runtime, or position as governance middleware over any runtime?" — remained open. The 2026-06-16 runtime-revamp investigation established that our LangGraph worker's tool execution, auto-compaction, and true streaming lag behind Claude Code's capability, which matters for dev/internal use cases even though the governed LangGraph path is the right answer for production/regulated agents.
Assessment (2026-07-02) confirmed the Claude Agent SDK can be embedded behind the existing frozen worker contract with all governance moats preserved via SDK hooks and canUseTool. Anthropic Commercial Terms permit SaaS embedding with API-key billing.
Decision
Adopt the Claude Agent SDK as a SECOND worker type behind the existing frozen gRPC worker contract — not a replacement. Users choose the runtime at agent creation:
Amendment 1, 2026-11-13 — ACCEPTED (founder approval from his own account,
#4420comment6849892608; ruling text#4419comments6776135827item 1 /6799098815). For orchestrated workflow runs (ADR-0023 Amendment 1) the Claude Agent SDK is the runtime: the orchestrator agent and every sub-agent it dispatches run on it. "Second worker type" and "positioned for dev / internal" no longer describe it. The per-agent choice below is unchanged for single-turn agents, where LangGraph remains the default. Details, the SDK floor and the primitives the decision rests on are in Amendment 1.
LangGraph worker (default)
Fully governed. Deterministic forced-submit_plan PLAN decomposition, Go PlanLoop terminator authoritative, BYOK multi-provider (anthropic/openai/google) + local Ollama, stateless-worker tenet holds. Positioned for production / regulated agents.
Claude SDK worker
Full Claude-Code capability: real tools, auto-compaction, context management, true streaming, subagents. Tool enablement configurable per agent. Positioned for dev / internal use cases. Trade-offs accepted for this worker type only:
- Anthropic-family models only (direct / Bedrock / Vertex) — sourcing modes B/C/D unavailable.
- SDK owns its internal agentic loop — the Go terminator demotes from authoritative planner to a budget + HITL guard; forced-
submit_plandeterminism is lost for this type. - Scoped exception to the stateless-worker tenet (P0.3.11) — one stateful SDK session per active session, with a documented memory/cost footprint model.
- New core-path dependency —
claude-agent-sdk(supply-chain + version-churn risk).
Moat mapping (all survive)
| Moat | Preserved via |
|---|---|
| Audit hash-chain | SDK hooks (PreToolUse / PostToolUse etc.) |
| Guardrails / clearance / HITL | canUseTool → interrupt_required |
| Tool governance | Built-in tools disabled + governed MCP proxy only |
| Persona | System prompt |
| Budgets | Per-turn usage → MetricsEvent (post-hoc per turn) |
| Tenant isolation | Orchestrator-side unchanged + per-session cwd / config-dir |
Licensing: Anthropic Commercial Terms permit SaaS embedding with API-key billing (verified).
Relationship to ADR-0012
This ADR resolves the parked ADR-0012 runtime-vs-middleware question with "both, per-agent choice" and supersedes/closes that open question. Production/regulated → governed LangGraph worker; dev/internal → Claude SDK worker. See upsquad-ai/upsquad-core#1198.
Consequences
Positive
- Best-in-class dev/internal agent capability (real tools, compaction, streaming, subagents) without abandoning the governed production path.
- Governance moats fully preserved for both worker types via SDK hooks /
canUseTool/ governed MCP proxy. - Resolves the long-parked ADR-0012 question without a disruptive rewrite — the frozen worker contract is untouched.
- Per-agent runtime choice becomes a product differentiator (governed vs. maximal-capability).
Negative
- Two worker runtimes to build, test, document, and maintain — higher surface area.
- Governance behaves differently across worker types (deterministic forced-plan vs. budget+HITL guard); users and docs must make this explicit.
- Claude SDK worker cannot serve BYOK modes B/C/D — a capability cliff between the two types.
Risks (top 3)
- Two-planner split-brain + checkpoint-semantics divergence. With the SDK owning its internal loop, the Go terminator is demoted to a guard.
Checkpointsemantics differ between a step-driven LangGraph worker and a turn-driven SDK session — risk of inconsistent resume/replay behaviour and audit-granularity mismatch across types. Mitigation: define per-type checkpoint contract explicitly in the LLD; keep the frozen gRPC surface identical while allowing per-type internal semantics. - Stateless-tenet exception + footprint. One stateful SDK session per active session breaks P0.3.11 for this type; memory/cost footprint grows with concurrency and long contexts. Mitigation: documented memory/cost model, per-session budget guard, session TTL/reaper, capacity planning before GA.
- Provider lock-in for the SDK type. Anthropic-family only (direct/Bedrock/Vertex); no modes B/C/D. Mitigation: position explicitly as dev/internal; steer regulated/BYOK tenants to the LangGraph worker; surface the constraint at agent-creation time.
Alternatives Considered
- SDK-only replacement (rip out LangGraph). Rejected — strands BYOK/multi-provider tenants (modes B/C/D), abandons deterministic forced-plan governance, and imposes provider lock-in platform-wide.
- Middleware-over-any-runtime (pure governance layer, no owned runtime). Deferred — this is ADR-0012's alternate framing; the "both, per-agent choice" decision subsumes it for now, and a generalized any-runtime middleware can be revisited later.
- Status quo (LangGraph worker only). Rejected — leaves the dev/internal capability gap (tools, compaction, streaming, subagents) unaddressed.
Spike evidence (#1626 / PR #1628)
Recorded 2026-07-02 after the spike closed the executor-level and full-stack verification legs.
(a) Executor-level live smoke (LiteLLM → Ollama qwen2.5:3b, no real key)
Real execute_step through ClaudeSDKExecutor (real claude CLI subprocess), ANTHROPIC_BASE_URL → throwaway LiteLLM proxy exposing Anthropic /v1/messages.
- Event contract proven:
status(THINKING)→token→metrics→completion(final_response). canUseTooldeny →interrupt_required: forced Bashrm -rf /denial producedinterrupt_requiredwith idempotency key + pending intent; per-session scratchcwdcreated.- Built-in-tools toggle: both states content-pinned (default OFF byte-identical; ON keeps PreToolUse/PostToolUse audit hooks +
canUseToolgating on ALL tools, isolated scratchcwd). 15/15 executor tests, 422/422 full worker suite green. - 3 real SDK-integration bugs found live (fake-SDK unit tests could not catch), all fixed: (1)
query()requires a streamingAsyncIterableprompt whenevercanUseToolis set; (2)extra_args={"max-tokens": …}emits an invalid--max-tokensCLI flag — removed; (3)allowed_tools=["mcp__*"]rejected by the CLI (glob only valid aftermcp__<server>__prefix) — emptied for the spike.
(b) Full-stack leg through the REAL Go orchestrator
Throwaway 2nd orchestrator + 2nd worker on the live docker network (shared Postgres/Redis, live stack untouched), LiteLLM → qwen2.5:3b, claude-agent-sdk==0.2.110 + native claude CLI 2.1.198.
- Audit hash-chain — PASS.
session_started → message_received → message_completed; eachprev_hash== predecessorrow_hash; chain intact from genesis. - Budget stop — PASS. Synthetic per-agent overage →
ResourceExhausted{reason:budget_exhausted},budget_deniedaudit row, hash chain intact, session → suspended. - HITL control plane — PASS (worker rehydration blocked by pre-existing #1630).
interrupt_required → sessionPaused(PAUSE_SOURCE_APPROVAL) → suspended;RecordDecision(APPROVED) → pauser.Resume → ResumePausedre-dialled the worker. Worker rehydration then fails on the checkpoint schema v2/v1 mismatch (#1630) — fails identically on the LangGraph path, NOT SDK-specific.
(c) Honest caveat
qwen-via-proxy proves the plumbing (event sequence, streaming input, canUseTool gating, hooks, metrics, audit, budget, HITL control plane) — not Claude-grade agentic behaviour. Claude-grade validation still needs one real-key run before GA.
Amendment 1 — 2026-11-13 — Claude Agent SDK as the primary runtime for workflow orchestrators and their sub-agents (core#4420)
- Status: Accepted — founder approval from his own account,
upsquad-ai/upsquad-core#4420comment6849892608(2026-11-13T10:06:39Z,user.type == "User", bodyApproved, on the issue whose body enumerates this amendment). Ruling text as relayed by the coordinator:#4419comment6776135827item 1 (2026-11-10) — "the Claude Agent SDK is the primary runtime for workflow orchestrators and their sub-agents; LangGraph stays for existing single-turn agents; #2616 is folded into this amendment" — read together with#4419comment6799098815(2026-11-11, no migration of Temporal workflows; SDLC workflow first). Tracker:#4419. Plan of record: the coordinator'scurried-brewing-allenplan (sections Context, Decisions taken, What is reused, Architecture). - Provenance line: Founder ruling from his own account: #4420 comment 6849892608; text #4419 comments 6776135827 / 6799098815.
- Record: the architecture this amendment serves (one orchestrator session per run, gates enforced by the
PreToolUsehook, sub-agents viaagents=, projection intoworkflow_runs/workflow_actions) is recorded in ADR-0023 Amendment 1 and in the W1/R1/R2 issues (#4423,#4421,#4422). This amendment records the runtime decision and the SDK facts it rests on; it does not restate the engine. - Supersedes: in the 2026-07-02 decision, (i) the positioning sentence "Positioned for dev / internal use cases" and the framing of the SDK worker as a second type that is not a replacement — for orchestrated runs it is the only runtime; (ii) the standing of trade-off 2 ("the Go terminator demotes to a budget + HITL guard") as a trade-off — for orchestrated runs the envelope + hook guard is the design, not a concession; (iii)
#2616's open question ("can we use the Claude Agent SDK as the coder runtime?") — answered here in the general: the SDK is the runtime for orchestrators and their sub-agents, and a coder sub-agent is admitted as soon as the governed-write rulings it depends on land (#3735workspace,#2597sandbox,#2568git-write,#2598deploy). Until then Stage 1 of the SDLC workflow keeps the coder step as a seat-bound human's own Claude Code (ADR-0027 Amendment 1). Everything else in the 2026-07-02 decision — the frozen gRPC worker contract, the moat mapping, the ADR-0012 resolution, LangGraph for single-turn agents and BYOK modes B/C/D — is unchanged.
A1.1 Decision
- The Claude Agent SDK is the primary runtime for workflow orchestrators and their sub-agents. Every orchestrated run (ADR-0023 Amendment 1) is one SDK session for the orchestrator agent; the roster's agents run as SDK sub-agents of that session (
agents=), each with its own tool allowlist, model, MCP servers and per-agent gateway token. - LangGraph stays for existing single-turn agents. Per-agent runtime selection (
SessionSnapshot.runtime,langgraph|claude_sdk,#1631) is unchanged;langgraphremains the default for an agent created outside a workflow. Non-Claude agents join orchestrated runs only as LangGraph sub-calls, later; the orchestrator itself is Claude-only. #2616is folded in. The SDLC coder-runtime proposal does not need a decision of its own: it is the special case "a coder sub-agent on the primary runtime", gated on the G rulings named above, not on this ADR.
A1.2 SDK floor
claude-agent-sdk >= 0.2.127(Python) is the dependency floor forservices/agent-worker— approved from the founder's own account on#4432(comment6849912398, 2026-11-13T10:07:31Z,user.type == "User"). The repo pinned0.2.110when this amendment was written (services/agent-worker/pyproject.toml);#4432carries the bump, the lock, and the pin of the Claude Code version the executor drives. The floor is whereagents=depth/concurrency caps,max_budget_usdand thedeferpermission decision all exist together;deferbehaviour on the pinned version is tested deliberately in week 2 of the build (#4422).
A1.3 Primitives the decision rests on, and their consequences
| Primitive | What we lean on | Consequence we accept |
|---|---|---|
defer gates — PreToolUse hook returns permissionDecision: "defer"; the session ends tool_deferred; the host later resumes the session and the same tool call re-fires the hook with the answer in updatedInput | Human gates (approval, question, input, per-tool approval) with compute released while a human decides — the park/resume Temporal used to supply | A gated call must be the only tool call — of any kind — in its turn, and defer exists only in -p mode. The SDK honours defer only when the turn makes a single tool call; with any sibling call (a second gate or an ordinary tool) it ignores defer with a warning and the call proceeds through the normal permission flow — i.e. the run would silently not park. The orchestrator prompt steers toward one call per gated turn, and the hook refuses the case the prompt misses: a gated call with siblings is denied, never let through (ReasonGateNotAlone, reported with sibling_calls, #4450). Permission mode is not restored on resume: the host re-applies permission mode, hook registration and strict_mcp_config on every resume, never assumes they persisted. |
SessionStore (Postgres adapter) | Cross-host resume of a parked session; the transcript is the evidence of what the orchestrator did | The store's mirror is best-effort: mirror_error must alert. The records of truth stay the hash-chained audit and llm_usage_events; the transcript is evidence, never the ledger. The stateless-worker exception of trade-off 3 widens from "dev/internal" to the orchestrator path, and is bounded the same way — the SDK session is the checkpoint, externalised by the store. |
agents= sub-agents — own tools/model/MCP servers, parallel, max_budget_usd; spawn depth and concurrency bounded by SDK defaults of 3 and 20 (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS — configurable, not hard caps) | The roster. Fixed roster + per-agent allowlists are half of "deterministic workflows with gates" (pilot criterion 6) | AskUserQuestion is not available inside sub-agents, so a sub-agent cannot ask: on_request questions travel as a structured needs_input{question, options} result the parent validates, and the orchestrator raises the gate. Sub-agents' tool calls are still gated: before_tool matches every call of a matching tool from any agent in the run (#4449), and the worker forwards a sub-agent's mcp__ calls to pre_tool_use under its own agent_ref (#4450 README rules 1 and 5). Whether the SDK honours defer from inside a sub-agent's turn is undocumented — an R2 (#4422) week-2 test item beside the defer smoke, not measurable before the #4432 bump. RunEnvelope.max_depth ≤ 3 (#4449) holds only because the worker sets the depth env var from it. |
Hooks — PreToolUse on ^mcp__, PostToolUse, SubagentStart / SubagentStop (the SDK Stop hook is not forwarded — #4450 README rule 7; completion arrives as the stopped{…} event and HookBridge.Stop is the Go-side mapping) | Per-call governance (Governor.Check) and hop audit; gate enforcement by the hook, never by the model remembering; per-agent attribution of dispatch and cost into workflow_actions; run completion from the stopped event | The hook ↔ governance-port contract is a Go interface with a fake SDK driver (internal/workflow/orchrt, PR #4450), so the engine is testable without the SDK. Built-ins are denied by name and strict_mcp_config=True; the team gateway remains the only tool path. |
Budgets — max_budget_usd, max_turns; model_usage includes sub-agents | The run envelope (max_sub_steps, max_cost_usd, max_wall_minutes); cost per team/agent/workflow (pilot criterion 7) | The SDK's model_usage is an estimate, reconciled against llm_usage_events written by the Model Gateway; resumed sessions report cumulative spend, so the host stores deltas (orchrt.Delta, #4450). Envelope exhaustion ends the session → run failed(exhausted) — the only transition #4449's state machine allows for it (RUNNING + EnvelopeExhausted → FAILED(exhausted); illegal while parked). timeout_policy is a per-gate park bound, not an envelope policy. |
A1.4 What this changes in the 2026-07-02 trade-offs
- Trade-off 1 (Anthropic-family only) now binds the orchestrator path, not just a dev/internal option: orchestrated runs are Claude-only. BYOK modes B/C/D remain available to single-turn LangGraph agents exactly as before.
- Trade-off 2 (Go terminator demoted to a guard) is the design for orchestrated runs: the envelope, the gates in the hook, and the audit of every sub-agent dispatch are the guard. Forced-
submit_plandeterminism is replaced by bounded, gated, repeatable — a fixed roster, hook-enforced gates, a hard envelope — which is what criterion 6 asks for. - Trade-off 3 (stateless-worker exception) widens to the orchestrator path and is bounded by
SessionStoreplus the crash sweeper in ADR-0023 Amendment 1: arunningrun whose orchestrator process is gone is resumed from the store, with idempotency keyedrun:step@ordinal. That key refuses a re-fired call only when itspost_tool_usewas already recorded; between a tool executing and itspost_tool_usereaching Go, delivery is at-least-once (#4450README rule 4), so a crash in that window re-runs the call — every gated or side-effecting tool must be idempotent on the hop key. - Trade-off 4 (new core-path dependency) is now a floor, not a pin of convenience:
#4432records the version; SDK behaviour drift (defer, cost semantics) is a named risk mitigated by the fake-driver regression suite.
A1.5 Companion records
- ADR-0023 Amendment 1 (same ruling): the engine this runtime hosts; Temporal retired, no migration.
- ADR-0027 Amendment 1 (same ruling): seat-bound external decisions; how a human's own Claude Code / Codex / Claude Desktop reaches a run.
- Agent Runtime (Ashik) owns R1
#4421and R2#4422and signs the#4450seam. The runtime contract page for him is linked from#4419. Architecture docs that describe the SDK worker as "dev/internal" (docs/architecture/agent-execution.md,docs/architecture/diff-claude-upsquad.md,docs/architecture/architecture-components.md) are updated with the W1/R1 PRs that change the behaviour they describe, not here.