18 KiB
Plan: Claude Code Integration (Orchestration Architecture)
Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (ProviderManager, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
orchestration.dispatchCommand(client intent)OrchestrationEngine(decide + persist + publish domain events)ProviderCommandReactor(domain intent ->ProviderService)ProviderService(adapter routing + canonical runtime stream)ProviderRuntimeIngestion(provider runtime -> internal orchestration commands)orchestration.domainEvent(single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
Current constraints to design around
- Provider runtime ingestion expects canonical
ProviderRuntimeEventshapes, not provider-native payloads. ProviderService.startSessioncurrently defaults toprovider: "codex"unless explicitly provided.thread.turn.starthas no provider field today, so first-turn provider selection cannot be explicitly requested.ProviderServicerequires adapterstartSession()to return aProviderSessionwiththreadId.- Checkpoint revert currently calls
providerService.rollbackConversation(), so Claude adapter needs a rollback strategy compatible with current reactor behavior. - Web currently marks Claude as unavailable (
"Claude Code (soon)") and model picker is Codex-only.
Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
- Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
- Use the existing canonical runtime stream (
ProviderRuntimeEvent) as the only ingestion contract. - Keep provider session routing in
ProviderServiceandProviderSessionDirectory. - Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
Phase 1: Contracts and command shape updates
1.1 Provider-aware model contract
Update packages/contracts/src/model.ts so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
- Introduce provider-scoped model lists (Codex + Claude).
- Add helpers that resolve model by provider.
- Preserve backwards compatibility for existing Codex defaults.
1.2 Turn-start provider intent
Update packages/contracts/src/orchestration.ts:
- Add optional
provider: ProviderKindtoThreadTurnStartCommand. - Carry provider through
ThreadTurnStartRequestedPayload. - Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
1.3 Provider session start input for Claude runtime knobs
Update packages/contracts/src/provider.ts:
- Extend
ProviderSessionStartInputwith optional Claude-specific fields (for exampleclaudeBinaryPath,permissionMode,maxThinkingTokens). - Keep fields optional so current call sites remain valid.
- Continue using generic
resumeThreadId+resumeCursoras the cross-provider recovery mechanism.
1.4 Contract tests
Update/add tests in packages/contracts/src/*.test.ts for:
- New command payload shape.
- Provider-aware model resolution behavior.
- Backward compatibility of existing command/schema decoding.
Phase 2: Claude adapter implementation
2.1 Add adapter service + layer
Create:
apps/server/src/provider/Services/ClaudeCodeAdapter.tsapps/server/src/provider/Layers/ClaudeCodeAdapter.ts
Adapter must implement ProviderAdapterShape<ProviderAdapterError>.
2.1.a SDK dependency and baseline config
Add server dependency:
@anthropic-ai/claude-agent-sdk
Baseline adapter options to support from day one:
cwdmodelpathToClaudeCodeExecutable(fromclaudeBinaryPath)permissionModemaxThinkingTokensresumeresumeSessionAtincludePartialMessagescanUseToolhooksenvandadditionalDirectories(if needed for sandbox/workspace parity)
2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
- Long-lived session context per adapter session.
- Multi-turn input queue.
- Interrupt support.
- Approval request/response bridge.
- Resume support via
resumeThreadId/resumeCursor.
2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
query()returns an async iterable message stream and control methods (interrupt,setModel,setPermissionMode,setMaxThinkingTokens, account/status helpers).- Multi-turn input is supported via async-iterable prompt input.
- Tool approval decisions are provided via
canUseTool. - Resume support uses
resumeand optionalresumeSessionAt. - Hooks can be used for lifecycle signals (
Stop,PostToolUse, etc.) when we need adapter-originated checkpoint/runtime events.
2.2.b Effect-native session lifecycle skeleton
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(input.sessionId),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: input.permissionMode,
maxThinkingTokens: input.maxThinkingTokens,
pathToClaudeCodeExecutable: input.claudeBinaryPath,
resume: input.resumeThreadId,
resumeSessionAt: readResumeCursor(input.resumeCursor),
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(input.sessionId),
hooks: makeClaudeHooks(input.sessionId),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
Portable fallback (already aligned with current server patterns):
const queue = yield* Queue.unbounded<ClaudeSdkMessage>();
yield* Effect.forkScoped(
Effect.tryPromise({
try: async () => {
for await (const message of session.result) {
Queue.offerAllUnsafe(queue, [message]);
}
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream pump failed.",
cause,
}),
}),
);
const sdkMessageStream = Stream.fromQueue(queue);
2.2.d Multi-turn prompt queue pattern (Effect)
Use an Effect queue as the single input boundary:
const promptQueue = yield* Queue.unbounded<ClaudePromptEnvelope>();
const prompt: AsyncIterable<ClaudePromptEnvelope> = {
[Symbol.asyncIterator]() {
return {
next: async () => {
const item = await Effect.runPromise(Queue.take(promptQueue));
if (item.type === "terminate") {
return { done: true, value: undefined };
}
return { done: false, value: item };
},
};
},
};
sendTurn() enqueues a user envelope, while stopSession() enqueues terminate and aborts.
2.2.e Approval bridge with canUseTool
Map SDK approval checks to existing orchestration approval flows:
const canUseTool = async (toolName: string, toolInput: Record<string, unknown>) => {
if (approvalModeIsFullAccess(sessionId)) {
return { behavior: "allow", updatedInput: toolInput };
}
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
emitRuntimeEvent({
type: "approval.requested",
provider: "claudeCode",
sessionId,
requestId,
requestKind: classifyTool(toolName),
detail: summarizeToolRequest(toolName, toolInput),
// ... eventId/createdAt
});
const decision = await waitForApprovalDecision(requestId);
emitRuntimeEvent({
type: "approval.resolved",
provider: "claudeCode",
sessionId,
requestId,
decision,
// ... eventId/createdAt
});
return decision === "accept" || decision === "acceptForSession"
? { behavior: "allow", updatedInput: toolInput }
: { behavior: "deny", message: "User declined tool execution." };
};
2.2.f Hooks and checkpoint signals
If Claude hooks provide cleaner turn boundaries, convert them into canonical runtime events (turn.completed and optionally checkpoint.captured) so CheckpointReactor remains unchanged:
hooks: {
Stop: [
{
matcher: {},
hooks: [
async () => {
emitRuntimeEvent({
type: "checkpoint.captured",
provider: "claudeCode",
sessionId,
threadId,
turnId: activeTurnId,
turnCount: nextTurnCount(),
// ... eventId/createdAt
});
},
],
},
],
}
2.2.g Runtime control method wiring
Adapter should expose SDK controls through existing service methods and runtime payload updates:
interruptTurn()->result.interrupt()- Model override on send turn ->
result.setModel(model)before enqueuing prompt - Runtime mode changes ->
result.setPermissionMode(mode)if we support live mode switching - Thinking budget updates ->
result.setMaxThinkingTokens(tokens)when configured
2.3 Canonical event mapping
Map Claude SDK events to ProviderRuntimeEvent:
session.started/session.exitedturn.started/turn.completedmessage.delta/message.completedtool.started/tool.completedapproval.requested/approval.resolvedruntime.error
No provider-native event methods should leak beyond the adapter boundary.
Reference mapping table:
| Claude SDK message/callback | Canonical runtime event(s) | Notes |
|---|---|---|
| assistant partial text | message.delta |
Emit deltas only (do not resend full content each chunk). |
| assistant final message | message.completed |
Must include stable itemId for dedupe/finalize behavior. |
| result (success) | turn.completed (status: "completed") |
This is the main turn boundary for checkpointing. |
| result (interrupted/cancelled) | turn.completed (status: "interrupted"/"cancelled") |
Preserve state semantics used by ingestion + UI. |
| result (error) | runtime.error and turn.completed (status: "failed") |
Include concise error message. |
| tool start | tool.started |
Set toolKind using shared classifier (command, file-change, other). |
| tool result | tool.completed |
Include detail summary used by activity feed. |
| canUseTool prompt | approval.requested |
Source of request id shown in UI. |
| approval decision returned | approval.resolved |
Must correlate using same request id. |
| session initialization | session.started, optional thread.started |
Ensure threadId is emitted early and consistently. |
| process exit/close | session.exited |
Required for session status projection cleanup. |
2.4 Session/thread/resume identifiers
Define explicit adapter semantics:
sessionId: adapter-owned stable session id.threadId: Claude conversation/session identifier returned asProviderThreadId.resumeCursor: provider-specific cursor (for example message id) needed for precise recovery/rollback.
2.5 Rollback/read strategy
Implement readThread() and rollbackThread() in a way compatible with CheckpointReactor.
Preferred:
- Track per-turn resume cursors and reconstruct session state on rollback.
- Keep adapter
sessionIdstable across internal rehydration/restart.
Fallback (explicitly documented if chosen):
- Filesystem revert succeeds even when conversation rewind is partial.
- Reactor behavior is updated to surface a clear warning activity instead of silent drift.
2.6 Adapter unit tests
Add tests mirroring Codex adapter coverage:
- Provider validation (
provider === "claudeCode"). - Event mapping to canonical runtime events.
- Approval request lifecycle.
- Resume/recovery behavior.
- Rollback behavior.
Phase 3: Register adapter in runtime composition
3.1 Adapter registry wiring
Update:
apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
Register both Codex and Claude adapters.
3.2 Server layer composition
Update:
apps/server/src/serverLayers.ts
Provide ClaudeCodeAdapterLive alongside Codex in makeServerProviderLayer().
3.3 Composition tests
Update integration tests to ensure:
- Registry exposes Claude provider.
- Provider service can route Claude sessions.
Phase 4: Orchestration command/reactor updates
4.1 Decider propagation
Update apps/server/src/orchestration/decider.ts:
- Carry optional
providerfromthread.turn.startcommand intothread.turn-start-requestedevent payload.
4.2 ProviderCommandReactor provider selection
Update apps/server/src/orchestration/Layers/ProviderCommandReactor.ts:
- Prefer provider from turn-start event payload when starting a new session.
- Fallback to existing thread session provider when payload omitted.
- Fallback to default provider only when neither is present.
Switch behavior policy (explicit in implementation):
- If active session provider differs from requested provider, stop and recreate session before sending turn.
- Keep current provider when request omits provider.
4.3 Reactor/invariant tests
Update/add tests in:
apps/server/src/orchestration/Layers/ProviderCommandReactor.test.tsapps/server/src/orchestration/*.test.tsas needed
Validate first-turn provider choice, provider switching semantics, and backward compatibility when provider is omitted.
Phase 5: Web provider UX enablement
5.1 Enable Claude option
Update apps/web/src/session-logic.ts:
- Mark Claude provider option as available.
5.2 Provider selection in composer
Update apps/web/src/components/ChatView.tsx:
- Add provider picker near model/runtime controls.
- Include selected provider in
thread.turn.startcommand payload. - Keep selected provider sticky per thread in client state (or derive from active session provider when present).
5.3 Provider-aware model picker
Update model picker usage so model options reflect selected provider.
5.4 Web tests
Update/add tests for:
- Provider picker interactions.
- Turn-start command includes provider.
- Model list switches by provider.
Phase 6: Checkpoint and revert compatibility
6.1 Validate checkpoint reactor expectations
Exercise apps/server/src/orchestration/Layers/CheckpointReactor.ts flows with Claude:
- Turn baseline capture.
- Turn completion checkpoint capture.
- Revert + provider rollback coordination.
6.2 Policy for partial rollback support
If Claude cannot support full conversation rewind at parity with Codex:
- Document behavior clearly.
- Emit explicit thread activity for degraded rollback behavior.
- Ensure filesystem state remains correct and predictable.
6.3 Checkpoint tests
Add/update tests in checkpoint + provider service integration suites for Claude revert behavior.
Phase 7: End-to-end hardening and observability
7.1 Integration tests
Add integration coverage for:
thread.turn.startwithprovider: "claudeCode"from fresh thread.- Session recovery after restart (provider session alias/recovery path).
- Approval request/respond flow.
- Interrupt behavior.
- Revert flow with rollback.
7.2 WS behavior regression check
Ensure no contract regressions:
- Client still consumes only
orchestration.domainEvent. - No new provider-specific WS channels introduced.
7.3 Logging
Confirm both native and canonical provider logs remain useful with multi-adapter setup:
provider-native.ndjsonprovider-canonical.ndjson
File checklist
Likely files to touch:
packages/contracts/src/model.tspackages/contracts/src/orchestration.tspackages/contracts/src/provider.tsapps/server/src/provider/Services/ClaudeCodeAdapter.ts(new)apps/server/src/provider/Layers/ClaudeCodeAdapter.ts(new)apps/server/src/provider/Layers/ProviderAdapterRegistry.tsapps/server/src/serverLayers.tsapps/server/src/orchestration/decider.tsapps/server/src/orchestration/Layers/ProviderCommandReactor.tsapps/web/src/session-logic.tsapps/web/src/components/ChatView.tsx- Related tests under
packages/contracts/src,apps/server/src/provider/Layers,apps/server/src/orchestration/Layers,apps/server/integration, andapps/web/src.
Delivery order
- Contracts for provider selection + models.
- Claude adapter + unit tests.
- Registry/layer wiring.
- Reactor updates for provider-aware session start.
- Web provider picker + provider-aware models.
- Checkpoint/revert compatibility.
- End-to-end integration tests and stabilization.
This order keeps risk isolated and maintains a working orchestrated path at each stage.