Co-authored-by: codex <[email protected]> Co-authored-by: JustYannicc <[email protected]> Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
14 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 (post-Stage 1)
- Provider runtime ingestion expects canonical
ProviderRuntimeEventshapes, not provider-native payloads. - Start input now uses typed
providerOptionsand genericresumeCursor; top-level provider-specific fields were removed. resumeCursoris intentionally opaque outside adapters and must never be synthesized fromproviderThreadId.ProviderServicestill requires 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 (completed)
Update packages/contracts/src/provider.ts:
- Move provider-specific start fields into typed
providerOptions:providerOptions.codexproviderOptions.claudeCode
- Keep
resumeCursoras the single cross-provider resume input inProviderSessionStartInput. - Deprecate/remove
resumeThreadIdfrom the generic start contract. - Treat
resumeCursoras adapter-owned opaque state.
1.4 Contract tests (completed)
Update/add tests in packages/contracts/src/*.test.ts for:
- New command payload shape.
- Provider-aware model resolution behavior.
- Breaking-change expectations for removed top-level provider fields.
Phase 2: Claude adapter implementation
2.1 Add adapter service + layer
Create:
apps/server/src/provider/Services/ClaudeAdapter.tsapps/server/src/provider/Layers/ClaudeAdapter.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(fromproviderOptions.claudeCode.binaryPath)permissionMode(fromproviderOptions.claudeCode.permissionMode)maxThinkingTokens(fromproviderOptions.claudeCode.maxThinkingTokens)resumeresumeSessionAtincludePartialMessagescanUseToolhooksenvandadditionalDirectories(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 opaque
resumeCursor(parsed inside Claude adapter only).
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, both derived by parsing adapter-ownedresumeCursor. - 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 claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
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 sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical ProviderRuntimeEvent.
Initial mapping target:
- assistant text deltas ->
content.delta - final assistant text ->
item.completedand/orturn.completed - approval requests ->
request.opened - approval results ->
request.resolved - system lifecycle ->
session.*,thread.*,turn.* - errors ->
runtime.error - plan/proposed-plan content when derivable
Implementation note:
- Keep raw Claude message on
rawfor debugging. - Prefer canonical item/request kinds over provider-native enums.
- If Claude emits extra event kinds we do not model yet, map them to
tool.summary,runtime.warning, orunknown-compatible payloads instead of dropping silently.
2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
Rules:
- Serialize only adapter-owned state into
resumeCursor. - Parse/validate only inside Claude adapter.
- Store updated cursor when Claude runtime yields enough data to resume safely.
- Never overload orchestration thread id as Claude thread id.
2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
interruptTurn()-> active query interrupt.stopSession()-> close session resources and prevent future sends.rollbackThread()-> see Phase 4.
Phase 3: Provider service and composition
3.1 Register Claude adapter
Update provider registry layer to include Claude:
- add
claudeCode->ClaudeAdapter - ensure
ProviderService.listProviderStatuses()reports Claude availability
3.2 Persist provider binding
Current ProviderSessionDirectory already stores provider/thread binding and opaque resumeCursor.
Required validation:
- Claude bindings survive restart.
- resume cursor remains opaque and round-trips untouched.
- stopAll + restart can recover Claude sessions when possible.
3.3 Provider start routing
Update ProviderCommandReactor / orchestration flow:
- If a thread turn start requests
provider: "claudeCode", start Claude if no active session exists. - If a thread already has Claude session binding, reuse it.
- If provider switches between Codex and Claude, explicitly stop/rebind before next send.
Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects providerService.rollbackConversation().
Pick one explicit strategy:
Option A: provider-native rewind
If SDK/runtime supports safe rewind:
- implement in Claude adapter
- keep
CheckpointReactorunchanged
Option B: session restart + state truncation shim
If no native rewind exists:
- Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
- Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
- behavior must be deterministic
- checkpoint revert tests must pass under orchestration expectations
- user-visible activity log should explain failures clearly when provider rollback is impossible
Phase 5: Web integration
5.1 Provider picker and model picker
Update web state/UI:
- allow choosing Claude as thread provider before first turn
- show Claude model list from provider-aware model helpers
- preserve existing Codex default behavior when provider omitted
Likely touch points:
apps/web/src/store.tsapps/web/src/components/ChatView.tsxapps/web/src/types.tspackages/shared/src/model.ts
5.2 Settings for Claude executable/options
Add app settings if needed for:
- Claude binary path
- default permission mode
- default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed providerOptions.
5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
- thread messages
- activities/worklog
- approvals
- session state
- checkpoints/diffs
Phase 6: Testing strategy
6.1 Contract tests
Cover:
- provider-aware model schemas
- provider field on turn-start command
- provider-specific start options schema
6.2 Adapter layer tests
Add ClaudeAdapter.test.ts covering:
- session start
- event mapping
- approval bridge
- resume cursor parse/serialize
- interrupt behavior
- rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through ProviderService:
- start Claude session
- send turn
- receive canonical runtime events
- restart/recover using persisted binding
6.4 Orchestration integration tests
Add/extend integration tests around:
- first-turn provider selection
- Claude approval requests routed through orchestration
- Claude runtime ingestion -> messages/activities/session updates
- checkpoint revert behavior under Claude
- stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
Phase 7: Rollout order
Recommended implementation order:
- contracts/provider-aware models
- provider field on turn-start
- Claude adapter skeleton + start/send/stream
- canonical event mapping
- provider registry/service wiring
- orchestration recovery + checkpoint strategy
- web provider/model picker
- full integration tests
Non-goals
- Reintroducing provider-specific WS methods/channels.
- Storing provider-native thread ids as orchestration ids.
- Bypassing orchestration engine for Claude-specific UI flows.
- Encoding Claude resume semantics outside adapter-owned
resumeCursor.