Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1970102289 | ||
|
|
3af67f5ef9 | ||
|
|
480a8cf62b | ||
|
|
fa60ec4e0c | ||
|
|
6e6083ca2f | ||
|
|
7613142c48 | ||
|
|
7e6ca87241 | ||
|
|
28c5177122 |
No files matched your search
@@ -0,0 +1,441 @@
|
||||
# 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:
|
||||
|
||||
1. `orchestration.dispatchCommand` (client intent)
|
||||
2. `OrchestrationEngine` (decide + persist + publish domain events)
|
||||
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
|
||||
4. `ProviderService` (adapter routing + canonical runtime stream)
|
||||
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
|
||||
6. `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)
|
||||
|
||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
||||
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
|
||||
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
|
||||
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
|
||||
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
|
||||
6. 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:
|
||||
|
||||
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
|
||||
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
|
||||
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
|
||||
4. 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:
|
||||
|
||||
1. Introduce provider-scoped model lists (Codex + Claude).
|
||||
2. Add helpers that resolve model by provider.
|
||||
3. Preserve backwards compatibility for existing Codex defaults.
|
||||
|
||||
### 1.2 Turn-start provider intent
|
||||
|
||||
Update `packages/contracts/src/orchestration.ts`:
|
||||
|
||||
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
|
||||
2. Carry provider through `ThreadTurnStartRequestedPayload`.
|
||||
3. 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`:
|
||||
|
||||
1. Move provider-specific start fields into typed `providerOptions`:
|
||||
- `providerOptions.codex`
|
||||
- `providerOptions.claudeCode`
|
||||
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
|
||||
3. Deprecate/remove `resumeThreadId` from the generic start contract.
|
||||
4. Treat `resumeCursor` as adapter-owned opaque state.
|
||||
|
||||
### 1.4 Contract tests (completed)
|
||||
|
||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
||||
|
||||
1. New command payload shape.
|
||||
2. Provider-aware model resolution behavior.
|
||||
3. Breaking-change expectations for removed top-level provider fields.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Claude adapter implementation
|
||||
|
||||
### 2.1 Add adapter service + layer
|
||||
|
||||
Create:
|
||||
|
||||
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
|
||||
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts`
|
||||
|
||||
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
|
||||
### 2.1.a SDK dependency and baseline config
|
||||
|
||||
Add server dependency:
|
||||
|
||||
1. `@anthropic-ai/claude-agent-sdk`
|
||||
|
||||
Baseline adapter options to support from day one:
|
||||
|
||||
1. `cwd`
|
||||
2. `model`
|
||||
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
|
||||
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
|
||||
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
|
||||
6. `resume`
|
||||
7. `resumeSessionAt`
|
||||
8. `includePartialMessages`
|
||||
9. `canUseTool`
|
||||
10. `hooks`
|
||||
11. `env` and `additionalDirectories` (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:
|
||||
|
||||
1. Long-lived session context per adapter session.
|
||||
2. Multi-turn input queue.
|
||||
3. Interrupt support.
|
||||
4. Approval request/response bridge.
|
||||
5. 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:
|
||||
|
||||
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
|
||||
2. Multi-turn input is supported via async-iterable prompt input.
|
||||
3. Tool approval decisions are provided via `canUseTool`.
|
||||
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
|
||||
5. 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
|
||||
|
||||
```ts
|
||||
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:
|
||||
|
||||
```ts
|
||||
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):
|
||||
|
||||
```ts
|
||||
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:
|
||||
|
||||
1. assistant text deltas -> `content.delta`
|
||||
2. final assistant text -> `item.completed` and/or `turn.completed`
|
||||
3. approval requests -> `request.opened`
|
||||
4. approval results -> `request.resolved`
|
||||
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
|
||||
6. errors -> `runtime.error`
|
||||
7. plan/proposed-plan content when derivable
|
||||
|
||||
Implementation note:
|
||||
|
||||
1. Keep raw Claude message on `raw` for debugging.
|
||||
2. Prefer canonical item/request kinds over provider-native enums.
|
||||
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
|
||||
|
||||
### 2.4 Resume cursor strategy
|
||||
|
||||
Define Claude-owned opaque resume state, e.g.:
|
||||
|
||||
```ts
|
||||
interface ClaudeResumeCursor {
|
||||
readonly version: 1;
|
||||
readonly threadId?: string;
|
||||
readonly sessionAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
1. Serialize only adapter-owned state into `resumeCursor`.
|
||||
2. Parse/validate only inside Claude adapter.
|
||||
3. Store updated cursor when Claude runtime yields enough data to resume safely.
|
||||
4. Never overload orchestration thread id as Claude thread id.
|
||||
|
||||
### 2.5 Interrupt and stop semantics
|
||||
|
||||
Map orchestration stop/interrupt expectations onto SDK controls:
|
||||
|
||||
1. `interruptTurn()` -> active query interrupt.
|
||||
2. `stopSession()` -> close session resources and prevent future sends.
|
||||
3. `rollbackThread()` -> see Phase 4.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Provider service and composition
|
||||
|
||||
### 3.1 Register Claude adapter
|
||||
|
||||
Update provider registry layer to include Claude:
|
||||
|
||||
1. add `claudeCode` -> `ClaudeCodeAdapter`
|
||||
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
|
||||
|
||||
### 3.2 Persist provider binding
|
||||
|
||||
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
|
||||
|
||||
Required validation:
|
||||
|
||||
1. Claude bindings survive restart.
|
||||
2. resume cursor remains opaque and round-trips untouched.
|
||||
3. stopAll + restart can recover Claude sessions when possible.
|
||||
|
||||
### 3.3 Provider start routing
|
||||
|
||||
Update `ProviderCommandReactor` / orchestration flow:
|
||||
|
||||
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
|
||||
2. If a thread already has Claude session binding, reuse it.
|
||||
3. 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:
|
||||
|
||||
1. implement in Claude adapter
|
||||
2. keep `CheckpointReactor` unchanged
|
||||
|
||||
### Option B: session restart + state truncation shim
|
||||
|
||||
If no native rewind exists:
|
||||
|
||||
1. 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
|
||||
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
|
||||
|
||||
Whichever option is chosen:
|
||||
|
||||
1. behavior must be deterministic
|
||||
2. checkpoint revert tests must pass under orchestration expectations
|
||||
3. 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:
|
||||
|
||||
1. allow choosing Claude as thread provider before first turn
|
||||
2. show Claude model list from provider-aware model helpers
|
||||
3. preserve existing Codex default behavior when provider omitted
|
||||
|
||||
Likely touch points:
|
||||
|
||||
1. `apps/web/src/store.ts`
|
||||
2. `apps/web/src/components/ChatView.tsx`
|
||||
3. `apps/web/src/types.ts`
|
||||
4. `packages/shared/src/model.ts`
|
||||
|
||||
### 5.2 Settings for Claude executable/options
|
||||
|
||||
Add app settings if needed for:
|
||||
|
||||
1. Claude binary path
|
||||
2. default permission mode
|
||||
3. 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:
|
||||
|
||||
1. thread messages
|
||||
2. activities/worklog
|
||||
3. approvals
|
||||
4. session state
|
||||
5. checkpoints/diffs
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Testing strategy
|
||||
|
||||
### 6.1 Contract tests
|
||||
|
||||
Cover:
|
||||
|
||||
1. provider-aware model schemas
|
||||
2. provider field on turn-start command
|
||||
3. provider-specific start options schema
|
||||
|
||||
### 6.2 Adapter layer tests
|
||||
|
||||
Add `ClaudeCodeAdapter.test.ts` covering:
|
||||
|
||||
1. session start
|
||||
2. event mapping
|
||||
3. approval bridge
|
||||
4. resume cursor parse/serialize
|
||||
5. interrupt behavior
|
||||
6. 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`:
|
||||
|
||||
1. start Claude session
|
||||
2. send turn
|
||||
3. receive canonical runtime events
|
||||
4. restart/recover using persisted binding
|
||||
|
||||
### 6.4 Orchestration integration tests
|
||||
|
||||
Add/extend integration tests around:
|
||||
|
||||
1. first-turn provider selection
|
||||
2. Claude approval requests routed through orchestration
|
||||
3. Claude runtime ingestion -> messages/activities/session updates
|
||||
4. checkpoint revert behavior under Claude
|
||||
5. stopAll/restart recovery
|
||||
|
||||
These should validate real orchestration flows, not just adapter behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: Rollout order
|
||||
|
||||
Recommended implementation order:
|
||||
|
||||
1. contracts/provider-aware models
|
||||
2. provider field on turn-start
|
||||
3. Claude adapter skeleton + start/send/stream
|
||||
4. canonical event mapping
|
||||
5. provider registry/service wiring
|
||||
6. orchestration recovery + checkpoint strategy
|
||||
7. web provider/model picker
|
||||
8. full integration tests
|
||||
|
||||
---
|
||||
|
||||
## Non-goals
|
||||
|
||||
1. Reintroducing provider-specific WS methods/channels.
|
||||
2. Storing provider-native thread ids as orchestration ids.
|
||||
3. Bypassing orchestration engine for Claude-specific UI flows.
|
||||
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
|
||||
@@ -188,7 +188,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex" | "cursor";
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex" | "cursor";
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -206,7 +206,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: "codex" | "cursor",
|
||||
provider: "codex" | "claudeCode",
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -216,7 +216,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: "codex" | "cursor",
|
||||
provider: "codex" | "claudeCode",
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
|
||||
@@ -32,7 +32,7 @@ const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = "codex" | "cursor";
|
||||
type IntegrationProvider = "codex" | "claudeCode";
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -842,3 +842,416 @@ it.live(
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("starts a claudeCode session on first turn when provider is requested", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Claude first turn.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-initial",
|
||||
messageId: "msg-user-claude-initial",
|
||||
text: "Use Claude",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeCode" &&
|
||||
entry.session.status === "ready" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
|
||||
),
|
||||
);
|
||||
assert.equal(thread.session?.providerName, "claudeCode");
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("recovers claudeCode sessions after provider stopAll using persisted resume state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn before restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-1",
|
||||
messageId: "msg-user-claude-recover-1",
|
||||
text: "Before restart",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.providerService.stopAll();
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness.listActiveSessionIds(),
|
||||
(sessionIds) => sessionIds.length === 0,
|
||||
"provider stopAll",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn after restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-2",
|
||||
messageId: "msg-user-claude-recover-2",
|
||||
text: "After restart",
|
||||
});
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness.getStartCount(),
|
||||
(count) => count === 2,
|
||||
"claude provider recovery start",
|
||||
);
|
||||
|
||||
const recoveredThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeCode" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "user" && message.text === "After restart",
|
||||
) &&
|
||||
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
);
|
||||
assert.equal(recoveredThread.session?.providerName, "claudeCode");
|
||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards claudeCode approval responses to the provider session", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Approve Claude tool call",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-approval",
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "approval.requested"),
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
yield* harness.waitForPendingApproval(
|
||||
"req-approval-1",
|
||||
(row) => row.status === "resolved" && row.decision === "accept",
|
||||
);
|
||||
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness.getApprovalResponses(THREAD_ID),
|
||||
(responses) => responses.length === 1,
|
||||
"claude provider approval response",
|
||||
);
|
||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Long running output.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-interrupt",
|
||||
messageId: "msg-user-claude-interrupt",
|
||||
text: "Start long turn",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.session?.threadId === "thread-1",
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-interrupt-requested");
|
||||
|
||||
const interruptCalls = yield* waitForSync(
|
||||
() => harness.adapterHarness.getInterruptCalls(THREAD_ID),
|
||||
(calls) => calls.length === 1,
|
||||
"claude provider interrupt call",
|
||||
);
|
||||
assert.equal(interruptCalls.length, 1);
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("reverts claudeCode turns and rolls back provider conversation state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v2\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-1",
|
||||
messageId: "msg-user-claude-revert-1",
|
||||
text: "First Claude edit",
|
||||
provider: "claudeCode",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v3\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeCode"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-2",
|
||||
messageId: "msg-user-claude-revert-2",
|
||||
text: "Second Claude edit",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.session?.providerName === "claudeCode",
|
||||
);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const revertedThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
|
||||
);
|
||||
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness.getRollbackCalls(THREAD_ID), [1]);
|
||||
}),
|
||||
"claudeCode",
|
||||
),
|
||||
);
|
||||
@@ -22,6 +22,7 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.62",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
|
||||
@@ -43,7 +43,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -235,6 +235,7 @@ describe("CheckpointReactor", () => {
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: "codex" | "claudeCode";
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -242,7 +243,7 @@ describe("CheckpointReactor", () => {
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
"codex",
|
||||
options?.providerName ?? "codex",
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -475,6 +476,67 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
it("captures pre-turn and completion checkpoints for claudeCode runtime events", async () => {
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
providerName: "claudeCode",
|
||||
});
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
|
||||
provider: "claudeCode",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
|
||||
provider: "claudeCode",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurn?.turnId === "turn-claude-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
@@ -790,6 +852,75 @@ describe("CheckpointReactor", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("executes provider revert and emits thread.reverted for claudeCode sessions", async () => {
|
||||
const harness = await createHarness({ providerName: "claudeCode" });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
@@ -94,6 +94,7 @@ describe("ProviderCommandReactor", () => {
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
(input.provider === "codex" ||
|
||||
input.provider === "claudeCode" ||
|
||||
input.provider === "cursor")
|
||||
? input.provider
|
||||
: "codex";
|
||||
@@ -384,6 +385,43 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("starts first turn with requested provider when provider is specified", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-first"),
|
||||
role: "user",
|
||||
text: "hello claude",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeCode",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "claudeCode",
|
||||
cwd: "/tmp/provider-project",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerName).toBe("claudeCode");
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
});
|
||||
|
||||
it("starts first turn with cursor provider when provider is specified", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -657,6 +695,66 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("switches provider by restarting the session when turn request provider changes", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeCode",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).not.toHaveProperty("resumeCursor");
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("claudeCode");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -212,6 +212,7 @@ const make = Effect.gen(function* () {
|
||||
const desiredRuntimeMode = thread.runtimeMode;
|
||||
const currentProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" ||
|
||||
thread.session?.providerName === "claudeCode" ||
|
||||
thread.session?.providerName === "cursor"
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
|
||||
@@ -41,7 +41,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -384,6 +384,60 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => {
|
||||
const harness = await createHarness();
|
||||
const seededAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: seededAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt: seededAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-claude-placeholder"),
|
||||
provider: "claudeCode",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-claude-placeholder"),
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-claude-placeholder",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-claude-placeholder"),
|
||||
provider: "claudeCode",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-claude-placeholder"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null,
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores auxiliary turn completions from a different provider thread", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -0,0 +1,930 @@
|
||||
import type {
|
||||
Options as ClaudeQueryOptions,
|
||||
PermissionMode,
|
||||
PermissionResult,
|
||||
SDKMessage,
|
||||
SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Fiber, Random, Stream } from "effect";
|
||||
|
||||
import {
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import { ClaudeCodeAdapter } from "../Services/ClaudeCodeAdapter.ts";
|
||||
import {
|
||||
makeClaudeCodeAdapterLive,
|
||||
type ClaudeCodeAdapterLiveOptions,
|
||||
} from "./ClaudeCodeAdapter.ts";
|
||||
|
||||
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
|
||||
private readonly queue: Array<SDKMessage> = [];
|
||||
private readonly resolvers: Array<(value: IteratorResult<SDKMessage>) => void> = [];
|
||||
private done = false;
|
||||
|
||||
public readonly interruptCalls: Array<void> = [];
|
||||
public readonly setModelCalls: Array<string | undefined> = [];
|
||||
public readonly setPermissionModeCalls: Array<string> = [];
|
||||
public readonly setMaxThinkingTokensCalls: Array<number | null> = [];
|
||||
public closeCalls = 0;
|
||||
|
||||
emit(message: SDKMessage): void {
|
||||
if (this.done) {
|
||||
return;
|
||||
}
|
||||
const resolver = this.resolvers.shift();
|
||||
if (resolver) {
|
||||
resolver({ done: false, value: message });
|
||||
return;
|
||||
}
|
||||
this.queue.push(message);
|
||||
}
|
||||
|
||||
finish(): void {
|
||||
if (this.done) {
|
||||
return;
|
||||
}
|
||||
this.done = true;
|
||||
for (const resolver of this.resolvers.splice(0)) {
|
||||
resolver({ done: true, value: undefined });
|
||||
}
|
||||
}
|
||||
|
||||
readonly interrupt = async (): Promise<void> => {
|
||||
this.interruptCalls.push(undefined);
|
||||
};
|
||||
|
||||
readonly setModel = async (model?: string): Promise<void> => {
|
||||
this.setModelCalls.push(model);
|
||||
};
|
||||
|
||||
readonly setPermissionMode = async (mode: PermissionMode): Promise<void> => {
|
||||
this.setPermissionModeCalls.push(mode);
|
||||
};
|
||||
|
||||
readonly setMaxThinkingTokens = async (maxThinkingTokens: number | null): Promise<void> => {
|
||||
this.setMaxThinkingTokensCalls.push(maxThinkingTokens);
|
||||
};
|
||||
|
||||
readonly close = (): void => {
|
||||
this.closeCalls += 1;
|
||||
this.finish();
|
||||
};
|
||||
|
||||
[Symbol.asyncIterator](): AsyncIterator<SDKMessage> {
|
||||
return {
|
||||
next: () => {
|
||||
if (this.queue.length > 0) {
|
||||
const value = this.queue.shift();
|
||||
if (value) {
|
||||
return Promise.resolve({
|
||||
done: false,
|
||||
value,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (this.done) {
|
||||
return Promise.resolve({
|
||||
done: true,
|
||||
value: undefined,
|
||||
});
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
this.resolvers.push(resolve);
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
readonly layer: ReturnType<typeof makeClaudeCodeAdapterLive>;
|
||||
readonly query: FakeClaudeQuery;
|
||||
readonly getLastCreateQueryInput: () =>
|
||||
| {
|
||||
readonly prompt: AsyncIterable<SDKUserMessage>;
|
||||
readonly options: ClaudeQueryOptions;
|
||||
}
|
||||
| undefined;
|
||||
}
|
||||
|
||||
function makeHarness(config?: {
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: ClaudeCodeAdapterLiveOptions["nativeEventLogger"];
|
||||
}): Harness {
|
||||
const query = new FakeClaudeQuery();
|
||||
let createInput:
|
||||
| {
|
||||
readonly prompt: AsyncIterable<SDKUserMessage>;
|
||||
readonly options: ClaudeQueryOptions;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
const adapterOptions: ClaudeCodeAdapterLiveOptions = {
|
||||
createQuery: (input) => {
|
||||
createInput = input;
|
||||
return query;
|
||||
},
|
||||
...(config?.nativeEventLogger
|
||||
? {
|
||||
nativeEventLogger: config.nativeEventLogger,
|
||||
}
|
||||
: {}),
|
||||
...(config?.nativeEventLogPath
|
||||
? {
|
||||
nativeEventLogPath: config.nativeEventLogPath,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
return {
|
||||
layer: makeClaudeCodeAdapterLive(adapterOptions),
|
||||
query,
|
||||
getLastCreateQueryInput: () => createInput,
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeterministicRandomService(seed = 0x1234_5678): {
|
||||
nextIntUnsafe: () => number;
|
||||
nextDoubleUnsafe: () => number;
|
||||
} {
|
||||
let state = seed >>> 0;
|
||||
const nextIntUnsafe = (): number => {
|
||||
state = (Math.imul(1_664_525, state) + 1_013_904_223) >>> 0;
|
||||
return state;
|
||||
};
|
||||
|
||||
return {
|
||||
nextIntUnsafe,
|
||||
nextDoubleUnsafe: () => nextIntUnsafe() / 0x1_0000_0000,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1");
|
||||
const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume");
|
||||
|
||||
describe("ClaudeCodeAdapterLive", () => {
|
||||
it.effect("returns validation error for non-claudeCode provider on startSession", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
const result = yield* adapter
|
||||
.startSession({ threadId: THREAD_ID, provider: "codex", runtimeMode: "full-access" })
|
||||
.pipe(Effect.result);
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
if (result._tag !== "Failure") {
|
||||
return;
|
||||
}
|
||||
assert.deepEqual(
|
||||
result.failure,
|
||||
new ProviderAdapterValidationError({
|
||||
provider: "claudeCode",
|
||||
operation: "startSession",
|
||||
issue: "Expected provider 'claudeCode' but received 'codex'.",
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("derives bypass permission mode from full-access runtime policy", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("keeps explicit claude permission mode over runtime-derived defaults", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
claudeCode: {
|
||||
permissionMode: "plan",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.permissionMode, "plan");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("maps Claude stream/runtime messages to canonical provider runtime events", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 11).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
model: "claude-sonnet-4-5",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-1",
|
||||
uuid: "stream-1",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: "Hi",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-1",
|
||||
uuid: "stream-2",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_start",
|
||||
index: 1,
|
||||
content_block: {
|
||||
type: "tool_use",
|
||||
id: "tool-1",
|
||||
name: "Bash",
|
||||
input: {
|
||||
command: "ls",
|
||||
},
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-1",
|
||||
uuid: "stream-3",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_stop",
|
||||
index: 1,
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-1",
|
||||
uuid: "assistant-1",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "assistant-message-1",
|
||||
content: [{ type: "text", text: "Hi" }],
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-1",
|
||||
uuid: "result-1",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.completed",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
const turnStarted = runtimeEvents[3];
|
||||
assert.equal(turnStarted?.type, "turn.started");
|
||||
if (turnStarted?.type === "turn.started") {
|
||||
assert.equal(String(turnStarted.turnId), String(turn.turnId));
|
||||
}
|
||||
|
||||
const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta");
|
||||
assert.equal(deltaEvent?.type, "content.delta");
|
||||
if (deltaEvent?.type === "content.delta") {
|
||||
assert.equal(deltaEvent.payload.delta, "Hi");
|
||||
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
|
||||
}
|
||||
|
||||
const toolStarted = runtimeEvents.find((event) => event.type === "item.started");
|
||||
assert.equal(toolStarted?.type, "item.started");
|
||||
if (toolStarted?.type === "item.started") {
|
||||
assert.equal(toolStarted.payload.itemType, "command_execution");
|
||||
}
|
||||
|
||||
const turnCompleted = runtimeEvents[runtimeEvents.length - 1];
|
||||
assert.equal(turnCompleted?.type, "turn.completed");
|
||||
if (turnCompleted?.type === "turn.completed") {
|
||||
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
|
||||
assert.equal(turnCompleted.payload.state, "completed");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits completion only after turn result when assistant frames arrive before deltas", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-early-assistant",
|
||||
uuid: "assistant-early",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "assistant-message-early",
|
||||
content: [{ type: "tool_use", id: "tool-early", name: "Read", input: { path: "a.ts" } }],
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-early-assistant",
|
||||
uuid: "stream-early",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: "Late text",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-early-assistant",
|
||||
uuid: "result-early",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"item.updated",
|
||||
"content.delta",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
const deltaIndex = runtimeEvents.findIndex((event) => event.type === "content.delta");
|
||||
const completedIndex = runtimeEvents.findIndex((event) => event.type === "item.completed");
|
||||
assert.equal(deltaIndex >= 0 && completedIndex >= 0 && deltaIndex < completedIndex, true);
|
||||
|
||||
const deltaEvent = runtimeEvents[deltaIndex];
|
||||
assert.equal(deltaEvent?.type, "content.delta");
|
||||
if (deltaEvent?.type === "content.delta") {
|
||||
assert.equal(deltaEvent.payload.delta, "Late text");
|
||||
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("falls back to assistant payload text when stream deltas are absent", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-fallback-text",
|
||||
uuid: "assistant-fallback",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "assistant-message-fallback",
|
||||
content: [{ type: "text", text: "Fallback hello" }],
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-fallback-text",
|
||||
uuid: "result-fallback",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"item.updated",
|
||||
"content.delta",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta");
|
||||
assert.equal(deltaEvent?.type, "content.delta");
|
||||
if (deltaEvent?.type === "content.delta") {
|
||||
assert.equal(deltaEvent.payload.delta, "Fallback hello");
|
||||
assert.equal(String(deltaEvent.turnId), String(turn.turnId));
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not fabricate provider thread ids before first SDK session_id", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal(session.threadId, undefined);
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
assert.equal(turn.threadId, undefined);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-thread-real",
|
||||
uuid: "stream-thread-real",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "message_start",
|
||||
message: {
|
||||
id: "msg-thread-real",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-thread-real",
|
||||
uuid: "result-thread-real",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
],
|
||||
);
|
||||
|
||||
const sessionStarted = runtimeEvents[0];
|
||||
assert.equal(sessionStarted?.type, "session.started");
|
||||
if (sessionStarted?.type === "session.started") {
|
||||
assert.equal("threadId" in sessionStarted, false);
|
||||
}
|
||||
|
||||
const threadStarted = runtimeEvents[4];
|
||||
assert.equal(threadStarted?.type, "thread.started");
|
||||
if (threadStarted?.type === "thread.started") {
|
||||
assert.equal(threadStarted.threadId, "sdk-thread-real");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("bridges approval request/response lifecycle through canUseTool", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const canUseTool = createInput?.options.canUseTool;
|
||||
assert.equal(typeof canUseTool, "function");
|
||||
if (!canUseTool) {
|
||||
return;
|
||||
}
|
||||
|
||||
const permissionPromise = canUseTool(
|
||||
"Bash",
|
||||
{ command: "pwd" },
|
||||
{
|
||||
signal: new AbortController().signal,
|
||||
suggestions: [
|
||||
{
|
||||
type: "setMode",
|
||||
mode: "default",
|
||||
destination: "session",
|
||||
},
|
||||
],
|
||||
toolUseID: "tool-use-1",
|
||||
},
|
||||
);
|
||||
|
||||
const requested = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(requested._tag, "Some");
|
||||
if (requested._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(requested.value.type, "request.opened");
|
||||
if (requested.value.type !== "request.opened") {
|
||||
return;
|
||||
}
|
||||
const runtimeRequestId = requested.value.requestId;
|
||||
assert.equal(typeof runtimeRequestId, "string");
|
||||
if (runtimeRequestId === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
session.threadId,
|
||||
ApprovalRequestId.makeUnsafe(runtimeRequestId),
|
||||
"accept",
|
||||
);
|
||||
|
||||
const resolved = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(resolved._tag, "Some");
|
||||
if (resolved._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(resolved.value.type, "request.resolved");
|
||||
if (resolved.value.type !== "request.resolved") {
|
||||
return;
|
||||
}
|
||||
assert.equal(resolved.value.requestId, requested.value.requestId);
|
||||
assert.equal(resolved.value.payload.decision, "accept");
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "allow");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("passes parsed resume cursor values to Claude query options", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: RESUME_THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
resumeCursor: {
|
||||
threadId: "resume-thread-1",
|
||||
resume: "550e8400-e29b-41d4-a716-446655440000",
|
||||
resumeSessionAt: "assistant-99",
|
||||
turnCount: 3,
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(session.threadId, "resume-thread-1");
|
||||
assert.deepEqual(session.resumeCursor, {
|
||||
threadId: "resume-thread-1",
|
||||
resume: "550e8400-e29b-41d4-a716-446655440000",
|
||||
resumeSessionAt: "assistant-99",
|
||||
turnCount: 3,
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.resume, "550e8400-e29b-41d4-a716-446655440000");
|
||||
assert.equal(createInput?.options.resumeSessionAt, "assistant-99");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not synthesize resume session id from generated thread ids", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
"resume" in (session.resumeCursor as Record<string, unknown>),
|
||||
false,
|
||||
);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.resume, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("supports rollbackThread by trimming in-memory turns and preserving earlier turns", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const firstTurn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "first",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
const firstCompletedFiber = yield* Stream.filter(adapter.streamEvents, (event) => event.type === "turn.completed").pipe(
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-rollback",
|
||||
uuid: "result-first",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const firstCompleted = yield* Fiber.join(firstCompletedFiber);
|
||||
assert.equal(firstCompleted._tag, "Some");
|
||||
if (firstCompleted._tag === "Some" && firstCompleted.value.type === "turn.completed") {
|
||||
assert.equal(String(firstCompleted.value.turnId), String(firstTurn.turnId));
|
||||
}
|
||||
|
||||
const secondTurn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "second",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
const secondCompletedFiber = yield* Stream.filter(adapter.streamEvents, (event) => event.type === "turn.completed").pipe(
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-rollback",
|
||||
uuid: "result-second",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const secondCompleted = yield* Fiber.join(secondCompletedFiber);
|
||||
assert.equal(secondCompleted._tag, "Some");
|
||||
if (secondCompleted._tag === "Some" && secondCompleted.value.type === "turn.completed") {
|
||||
assert.equal(String(secondCompleted.value.turnId), String(secondTurn.turnId));
|
||||
}
|
||||
|
||||
const threadBeforeRollback = yield* adapter.readThread(session.threadId);
|
||||
assert.equal(threadBeforeRollback.turns.length, 2);
|
||||
|
||||
const rolledBack = yield* adapter.rollbackThread(session.threadId, 1);
|
||||
assert.equal(rolledBack.turns.length, 1);
|
||||
assert.equal(rolledBack.turns[0]?.id, firstTurn.turnId);
|
||||
|
||||
const threadAfterRollback = yield* adapter.readThread(session.threadId);
|
||||
assert.equal(threadAfterRollback.turns.length, 1);
|
||||
assert.equal(threadAfterRollback.turns[0]?.id, firstTurn.turnId);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("updates model on sendTurn when model override is provided", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
model: "claude-opus-4-6",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("writes provider-native observability records when enabled", () => {
|
||||
const nativeEvents: Array<{
|
||||
event?: {
|
||||
provider?: string;
|
||||
method?: string;
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
};
|
||||
}> = [];
|
||||
const harness = makeHarness({
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://claude-native-events",
|
||||
write: (event) => {
|
||||
nativeEvents.push(event as (typeof nativeEvents)[number]);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
},
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
const turnCompletedFiber = yield* Stream.filter(
|
||||
adapter.streamEvents,
|
||||
(event) => event.type === "turn.completed",
|
||||
).pipe(Stream.runHead, Effect.forkChild);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-native-log",
|
||||
uuid: "stream-native-log",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: {
|
||||
type: "text_delta",
|
||||
text: "hi",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-native-log",
|
||||
uuid: "result-native-log",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const turnCompleted = yield* Fiber.join(turnCompletedFiber);
|
||||
assert.equal(turnCompleted._tag, "Some");
|
||||
|
||||
assert.equal(nativeEvents.length > 0, true);
|
||||
assert.equal(nativeEvents.some((record) => record.event?.provider === "claudeCode"), true);
|
||||
assert.equal(nativeEvents.some((record) => String(record.event?.threadId) === String(session.threadId)), true);
|
||||
assert.equal(
|
||||
nativeEvents.some((record) => String(record.event?.turnId) === String(turn.turnId)),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some(
|
||||
(record) => record.event?.method === "claude/stream_event/content_block_delta/text_delta",
|
||||
),
|
||||
true,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -162,7 +162,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const result = yield* adapter
|
||||
.startSession({
|
||||
provider: "cursor",
|
||||
provider: "claudeCode",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
})
|
||||
@@ -174,7 +174,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "startSession",
|
||||
issue: "Expected provider 'codex' but received 'cursor'.",
|
||||
issue: "Expected provider 'codex' but received 'claudeCode'.",
|
||||
}),
|
||||
);
|
||||
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Layer, Stream } from "effect";
|
||||
|
||||
import { ClaudeCodeAdapter, ClaudeCodeAdapterShape } from "../Services/ClaudeCodeAdapter.ts";
|
||||
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
@@ -27,11 +28,31 @@ const fakeCodexAdapter: CodexAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeClaudeAdapter: ClaudeCodeAdapterShape = {
|
||||
provider: "claudeCode",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
Layer.provide(
|
||||
ProviderAdapterRegistryLive,
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(ClaudeCodeAdapter, fakeClaudeAdapter),
|
||||
),
|
||||
),
|
||||
NodeServices.layer,
|
||||
),
|
||||
@@ -42,10 +63,12 @@ layer("ProviderAdapterRegistryLive", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const codex = yield* registry.getByProvider("codex");
|
||||
const claude = yield* registry.getByProvider("claudeCode");
|
||||
assert.equal(codex, fakeCodexAdapter);
|
||||
assert.equal(claude, fakeClaudeAdapter);
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
assert.deepEqual(providers, ["codex"]);
|
||||
assert.deepEqual(providers, ["codex", "claudeCode"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
ProviderAdapterRegistry,
|
||||
type ProviderAdapterRegistryShape,
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ClaudeCodeAdapter } from "../Services/ClaudeCodeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
|
||||
export interface ProviderAdapterRegistryLiveOptions {
|
||||
@@ -26,7 +27,7 @@ const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOption
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter];
|
||||
: [yield* CodexAdapter, yield* ClaudeCodeAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
@@ -51,7 +51,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -216,12 +216,15 @@ const sleep = (ms: number) =>
|
||||
|
||||
function makeProviderServiceLayer() {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
const claude = makeFakeCodexAdapter("claudeCode");
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(codex.adapter)
|
||||
: provider === "claudeCode"
|
||||
? Effect.succeed(claude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeCode"]),
|
||||
};
|
||||
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
@@ -244,6 +247,7 @@ function makeProviderServiceLayer() {
|
||||
|
||||
return {
|
||||
codex,
|
||||
claude,
|
||||
layer,
|
||||
};
|
||||
}
|
||||
@@ -532,6 +536,29 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes explicit claudeCode provider session starts to the claude adapter", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
const session = yield* provider.startSession(asThreadId("thread-claude"), {
|
||||
provider: "claudeCode",
|
||||
threadId: asThreadId("thread-claude"),
|
||||
cwd: "/tmp/project-claude",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "claudeCode");
|
||||
assert.equal(routing.claude.startSession.mock.calls.length, 1);
|
||||
const startInput = routing.claude.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof startInput === "object" && startInput !== null, true);
|
||||
if (startInput && typeof startInput === "object") {
|
||||
const startPayload = startInput as { provider?: string; cwd?: string };
|
||||
assert.equal(startPayload.provider, "claudeCode");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
@@ -25,7 +25,7 @@ function decodeProviderKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
|
||||
if (providerName === "codex" || providerName === "cursor") {
|
||||
if (providerName === "codex" || providerName === "claudeCode" || providerName === "cursor") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.fail(
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* ClaudeCodeAdapter - Claude Code implementation of the generic provider adapter contract.
|
||||
*
|
||||
* This service owns Claude runtime/session semantics and emits canonical
|
||||
* provider runtime events. It does not perform cross-provider routing, shared
|
||||
* event fan-out, or checkpoint orchestration.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and returns the
|
||||
* shared provider-adapter error channel with `provider: "claudeCode"` context.
|
||||
*
|
||||
* @module ClaudeCodeAdapter
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* ClaudeCodeAdapterShape - Service API for the Claude Code provider adapter.
|
||||
*/
|
||||
export interface ClaudeCodeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "claudeCode";
|
||||
}
|
||||
|
||||
/**
|
||||
* ClaudeCodeAdapter - Service tag for Claude Code provider adapter operations.
|
||||
*/
|
||||
export class ClaudeCodeAdapter extends ServiceMap.Service<
|
||||
ClaudeCodeAdapter,
|
||||
ClaudeCodeAdapterShape
|
||||
>()("t3/provider/Services/ClaudeCodeAdapter") {}
|
||||
|
||||
@@ -18,6 +18,7 @@ import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/Proj
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||
import { ProviderUnsupportedError } from "./provider/Errors";
|
||||
import { makeClaudeCodeAdapterLive } from "./provider/Layers/ClaudeCodeAdapter";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
@@ -56,8 +57,12 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const claudeAdapterLayer = makeClaudeCodeAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
|
||||
@@ -16,7 +16,11 @@ describe("normalizeCustomModelSlugs", () => {
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
|
||||
it("normalizes provider-specific aliases for cursor", () => {
|
||||
it("normalizes provider-specific aliases for claude and cursor", () => {
|
||||
expect(normalizeCustomModelSlugs(["sonnet"], "claudeCode")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeCode")).toEqual([
|
||||
"claude/custom-sonnet",
|
||||
]);
|
||||
expect(normalizeCustomModelSlugs(["composer"], "cursor")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["cursor/custom-model"], "cursor")).toEqual([
|
||||
"cursor/custom-model",
|
||||
@@ -49,9 +53,9 @@ describe("getAppModelOptions", () => {
|
||||
});
|
||||
|
||||
it("keeps a saved custom provider model available as an exact slug option", () => {
|
||||
const options = getAppModelOptions("cursor", ["cursor/custom-model"], "cursor/custom-model");
|
||||
const options = getAppModelOptions("claudeCode", ["claude/custom-opus"], "claude/custom-opus");
|
||||
|
||||
expect(options.some((option) => option.slug === "cursor/custom-model" && option.isCustom)).toBe(
|
||||
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
@@ -81,8 +85,10 @@ describe("getSlashModelOptions", () => {
|
||||
});
|
||||
|
||||
it("includes provider-specific custom slugs in non-codex model lists", () => {
|
||||
const claudeOptions = getAppModelOptions("claudeCode", ["claude/custom-opus"]);
|
||||
const cursorOptions = getAppModelOptions("cursor", ["cursor/custom-model"]);
|
||||
|
||||
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
|
||||
expect(cursorOptions.some((option) => option.slug === "cursor/custom-model")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeCode: new Set(getModelOptions("claudeCode").map((option) => option.slug)),
|
||||
cursor: new Set(getModelOptions("cursor").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
@@ -25,6 +26,9 @@ const AppSettingsSchema = Schema.Struct({
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customCursorModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
@@ -75,6 +79,7 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeCode"),
|
||||
customCursorModels: normalizeCustomModelSlugs(settings.customCursorModels, "cursor"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -77,7 +77,6 @@ import {
|
||||
findLatestProposedPlan,
|
||||
type PendingApproval,
|
||||
type PendingUserInput,
|
||||
type ProviderPickerKind,
|
||||
PROVIDER_OPTIONS,
|
||||
deriveWorkLogEntries,
|
||||
hasToolActivityForTurn,
|
||||
@@ -5297,11 +5296,13 @@ const COMING_SOON_PROVIDER_OPTIONS = [
|
||||
|
||||
function getCustomModelOptionsByProvider(settings: {
|
||||
customCodexModels: readonly string[];
|
||||
customClaudeModels: readonly string[];
|
||||
customCursorModels: readonly string[];
|
||||
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
const cursorFamilyOptions = getCursorModelFamilyOptions();
|
||||
return {
|
||||
codex: getAppModelOptions("codex", settings.customCodexModels),
|
||||
claudeCode: getAppModelOptions("claudeCode", settings.customClaudeModels),
|
||||
cursor: [
|
||||
...cursorFamilyOptions,
|
||||
...getAppModelOptions("cursor", settings.customCursorModels).filter(
|
||||
@@ -5312,7 +5313,7 @@ function getCustomModelOptionsByProvider(settings: {
|
||||
};
|
||||
}
|
||||
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind, Icon> = {
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderKind, Icon> = {
|
||||
codex: OpenAI,
|
||||
claudeCode: ClaudeAI,
|
||||
cursor: CursorIcon,
|
||||
@@ -5393,7 +5394,10 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<ProviderIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/70"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
props.provider === "claudeCode" ? "" : "text-muted-foreground/70",
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
|
||||
@@ -208,7 +208,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
}
|
||||
|
||||
function normalizeProviderKind(value: unknown): ProviderKind | null {
|
||||
return value === "codex" || value === "cursor" ? value : null;
|
||||
return value === "codex" || value === "claudeCode" || value === "cursor" ? value : null;
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
|
||||
@@ -47,6 +47,13 @@ const MODEL_PROVIDER_SETTINGS: Array<{
|
||||
placeholder: "your-codex-model-slug",
|
||||
example: "gpt-6.7-codex-ultra-preview",
|
||||
},
|
||||
{
|
||||
provider: "claudeCode",
|
||||
title: "Claude Code",
|
||||
description: "Save additional Claude model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-claude-model-slug",
|
||||
example: "claude-sonnet-5-0",
|
||||
},
|
||||
] as const;
|
||||
|
||||
function getCustomModelsForProvider(
|
||||
@@ -54,6 +61,8 @@ function getCustomModelsForProvider(
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "claudeCode":
|
||||
return settings.customClaudeModels;
|
||||
case "cursor":
|
||||
return settings.customCursorModels;
|
||||
case "codex":
|
||||
@@ -67,6 +76,8 @@ function getDefaultCustomModelsForProvider(
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "claudeCode":
|
||||
return defaults.customClaudeModels;
|
||||
case "cursor":
|
||||
return defaults.customCursorModels;
|
||||
case "codex":
|
||||
@@ -77,6 +88,8 @@ function getDefaultCustomModelsForProvider(
|
||||
|
||||
function patchCustomModels(provider: ProviderKind, models: string[]) {
|
||||
switch (provider) {
|
||||
case "claudeCode":
|
||||
return { customClaudeModels: models };
|
||||
case "cursor":
|
||||
return { customCursorModels: models };
|
||||
case "codex":
|
||||
@@ -95,6 +108,7 @@ function SettingsRouteView() {
|
||||
Record<ProviderKind, string>
|
||||
>({
|
||||
codex: "",
|
||||
claudeCode: "",
|
||||
cursor: "",
|
||||
});
|
||||
const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<
|
||||
|
||||
@@ -514,18 +514,18 @@ describe("isLatestTurnSettled", () => {
|
||||
});
|
||||
|
||||
describe("PROVIDER_OPTIONS", () => {
|
||||
it("keeps Claude Code and Cursor visible as unavailable placeholders in the stack base", () => {
|
||||
it("advertises Claude Code on the Claude stack while keeping Cursor as a placeholder", () => {
|
||||
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeCode");
|
||||
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
|
||||
expect(PROVIDER_OPTIONS).toEqual([
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code", available: false },
|
||||
{ value: "claudeCode", label: "Claude Code", available: true },
|
||||
{ value: "cursor", label: "Cursor", available: false },
|
||||
]);
|
||||
expect(claude).toEqual({
|
||||
value: "claudeCode",
|
||||
label: "Claude Code",
|
||||
available: false,
|
||||
available: true,
|
||||
});
|
||||
expect(cursor).toEqual({
|
||||
value: "cursor",
|
||||
|
||||
@@ -18,7 +18,7 @@ export const PROVIDER_OPTIONS: Array<{
|
||||
available: boolean;
|
||||
}> = [
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code", available: false },
|
||||
{ value: "claudeCode", label: "Claude Code", available: true },
|
||||
{ value: "cursor", label: "Cursor", available: false },
|
||||
];
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ describe("store pure functions", () => {
|
||||
});
|
||||
|
||||
describe("store read model sync", () => {
|
||||
it("falls back to the codex default for unsupported provider models without an active session", () => {
|
||||
it("preserves claude model slugs without an active session", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
@@ -139,7 +139,29 @@ describe("store read model sync", () => {
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("gpt-5.3-codex");
|
||||
expect(next.threads[0]?.model).toBe("claude-opus-4-6");
|
||||
});
|
||||
|
||||
it("resolves claude aliases when session provider is claudeCode", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
model: "sonnet",
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("claude-sonnet-4-6");
|
||||
});
|
||||
|
||||
it("resolves cursor aliases when session provider is cursor", () => {
|
||||
|
||||
+13
-3
@@ -145,16 +145,21 @@ function toLegacySessionStatus(
|
||||
}
|
||||
|
||||
function toLegacyProvider(providerName: string | null): ProviderKind {
|
||||
if (providerName === "codex" || providerName === "cursor") {
|
||||
if (providerName === "codex" || providerName === "claudeCode" || providerName === "cursor") {
|
||||
return providerName;
|
||||
}
|
||||
return "codex";
|
||||
}
|
||||
|
||||
const CODEX_MODEL_SLUGS = new Set<string>(getModelOptions("codex").map((option) => option.slug));
|
||||
const CLAUDE_MODEL_SLUGS = new Set<string>(
|
||||
getModelOptions("claudeCode").map((option) => option.slug),
|
||||
);
|
||||
const CURSOR_MODEL_SLUGS = new Set<string>(getModelOptions("cursor").map((option) => option.slug));
|
||||
const CURSOR_DISTINCT_MODEL_SLUGS = new Set(
|
||||
[...CURSOR_MODEL_SLUGS].filter((slug) => !CODEX_MODEL_SLUGS.has(slug)),
|
||||
[...CURSOR_MODEL_SLUGS].filter(
|
||||
(slug) => !CODEX_MODEL_SLUGS.has(slug) && !CLAUDE_MODEL_SLUGS.has(slug),
|
||||
),
|
||||
);
|
||||
|
||||
function inferProviderForThreadModel(input: {
|
||||
@@ -163,6 +168,7 @@ function inferProviderForThreadModel(input: {
|
||||
}): ProviderKind {
|
||||
if (
|
||||
input.sessionProviderName === "codex" ||
|
||||
input.sessionProviderName === "claudeCode" ||
|
||||
input.sessionProviderName === "cursor"
|
||||
) {
|
||||
return input.sessionProviderName;
|
||||
@@ -171,6 +177,10 @@ function inferProviderForThreadModel(input: {
|
||||
if (normalizedCursor && CURSOR_DISTINCT_MODEL_SLUGS.has(normalizedCursor)) {
|
||||
return "cursor";
|
||||
}
|
||||
const normalizedClaude = normalizeModelSlug(input.model, "claudeCode");
|
||||
if (normalizedClaude && CLAUDE_MODEL_SLUGS.has(normalizedClaude)) {
|
||||
return "claudeCode";
|
||||
}
|
||||
const normalizedCodex = normalizeModelSlug(input.model, "codex");
|
||||
if (normalizedCodex && CODEX_MODEL_SLUGS.has(normalizedCodex)) {
|
||||
return "codex";
|
||||
@@ -182,7 +192,7 @@ function inferProviderForThreadModel(input: {
|
||||
) {
|
||||
return "cursor";
|
||||
}
|
||||
return "codex";
|
||||
return input.model.trim().startsWith("claude-") ? "claudeCode" : "codex";
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.62",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
@@ -162,6 +163,8 @@
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
"packages": {
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]", "", { "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-ABaB37jWt7dZXfIDHebHv99jX9GIyqc0aSjcz9nxq79eauOpa+64Cah5hx/yzhsWz7m5GEtjbMIZCClTfnRRhg=="],
|
||||
|
||||
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
|
||||
|
||||
"@babel/compat-data": ["@babel/[email protected]", "", {}, "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg=="],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProviderKind } from "./orchestration";
|
||||
|
||||
export const CURSOR_REASONING_OPTIONS = ["low", "normal", "high", "xhigh"] as const;
|
||||
export type CursorReasoningOption = (typeof CURSOR_REASONING_OPTIONS)[number];
|
||||
@@ -12,6 +13,11 @@ export const CodexModelOptions = Schema.Struct({
|
||||
});
|
||||
export type CodexModelOptions = typeof CodexModelOptions.Type;
|
||||
|
||||
export const ClaudeCodeModelOptions = Schema.Struct({
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ClaudeCodeModelOptions = typeof ClaudeCodeModelOptions.Type;
|
||||
|
||||
export const CursorModelOptions = Schema.Struct({
|
||||
reasoning: Schema.optional(Schema.Literals(CURSOR_REASONING_OPTIONS)),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
@@ -21,6 +27,7 @@ export type CursorModelOptions = typeof CursorModelOptions.Type;
|
||||
|
||||
export const ProviderModelOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexModelOptions),
|
||||
claudeCode: Schema.optional(ClaudeCodeModelOptions),
|
||||
cursor: Schema.optional(CursorModelOptions),
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
@@ -57,6 +64,11 @@ export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
{ slug: "gpt-5.2-codex", name: "GPT-5.2 Codex" },
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
],
|
||||
claudeCode: [
|
||||
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
{ slug: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
|
||||
],
|
||||
cursor: [
|
||||
{ slug: "auto", name: "Auto" },
|
||||
{ slug: "composer-1.5", name: "Composer 1.5" },
|
||||
@@ -78,23 +90,23 @@ export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
{ slug: "sonnet-4.6-thinking", name: "Claude 4.6 Sonnet (Thinking)" },
|
||||
{ slug: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },
|
||||
],
|
||||
} as const satisfies Record<"codex" | "cursor", readonly ModelOption[]>;
|
||||
} as const satisfies Record<ProviderKind, readonly ModelOption[]>;
|
||||
|
||||
type BuiltInModelSlug =
|
||||
(typeof MODEL_OPTIONS_BY_PROVIDER)[keyof typeof MODEL_OPTIONS_BY_PROVIDER][number]["slug"];
|
||||
type BuiltInModelSlug = (typeof MODEL_OPTIONS_BY_PROVIDER)[ProviderKind][number]["slug"];
|
||||
export type ModelSlug = BuiltInModelSlug | (string & {});
|
||||
export type CursorModelSlug = (typeof MODEL_OPTIONS_BY_PROVIDER)["cursor"][number]["slug"];
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER = {
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, ModelSlug> = {
|
||||
codex: "gpt-5.3-codex",
|
||||
claudeCode: "claude-sonnet-4-6",
|
||||
cursor: "opus-4.6-thinking",
|
||||
} as const satisfies Record<keyof typeof MODEL_OPTIONS_BY_PROVIDER, ModelSlug>;
|
||||
};
|
||||
|
||||
// Backward compatibility for existing Codex-only call sites.
|
||||
export const MODEL_OPTIONS = MODEL_OPTIONS_BY_PROVIDER.codex;
|
||||
export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER = {
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, ModelSlug>> = {
|
||||
codex: {
|
||||
"5.4": "gpt-5.4",
|
||||
"5.3": "gpt-5.3-codex",
|
||||
@@ -102,6 +114,20 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER = {
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
},
|
||||
claudeCode: {
|
||||
opus: "claude-opus-4-6",
|
||||
"opus-4.6": "claude-opus-4-6",
|
||||
"claude-opus-4.6": "claude-opus-4-6",
|
||||
"claude-opus-4-6-20251117": "claude-opus-4-6",
|
||||
sonnet: "claude-sonnet-4-6",
|
||||
"sonnet-4.6": "claude-sonnet-4-6",
|
||||
"claude-sonnet-4.6": "claude-sonnet-4-6",
|
||||
"claude-sonnet-4-6-20251117": "claude-sonnet-4-6",
|
||||
haiku: "claude-haiku-4-5",
|
||||
"haiku-4.5": "claude-haiku-4-5",
|
||||
"claude-haiku-4.5": "claude-haiku-4-5",
|
||||
"claude-haiku-4-5-20251001": "claude-haiku-4-5",
|
||||
},
|
||||
cursor: {
|
||||
composer: "composer-1.5",
|
||||
"composer-1.5": "composer-1.5",
|
||||
@@ -116,17 +142,16 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER = {
|
||||
"opus-4.6-thinking": "opus-4.6-thinking",
|
||||
"opus-4.5-thinking": "opus-4.5-thinking",
|
||||
},
|
||||
} as const satisfies Record<keyof typeof MODEL_OPTIONS_BY_PROVIDER, Record<string, ModelSlug>>;
|
||||
};
|
||||
|
||||
export const REASONING_EFFORT_OPTIONS_BY_PROVIDER = {
|
||||
codex: CODEX_REASONING_EFFORT_OPTIONS,
|
||||
claudeCode: [],
|
||||
cursor: [],
|
||||
} as const satisfies Record<
|
||||
keyof typeof MODEL_OPTIONS_BY_PROVIDER,
|
||||
readonly CodexReasoningEffort[]
|
||||
>;
|
||||
} as const satisfies Record<ProviderKind, readonly CodexReasoningEffort[]>;
|
||||
|
||||
export const DEFAULT_REASONING_EFFORT_BY_PROVIDER = {
|
||||
codex: "high",
|
||||
claudeCode: null,
|
||||
cursor: null,
|
||||
} as const satisfies Record<keyof typeof MODEL_OPTIONS_BY_PROVIDER, CodexReasoningEffort | null>;
|
||||
} as const satisfies Record<ProviderKind, CodexReasoningEffort | null>;
|
||||
@@ -128,11 +128,11 @@ it.effect("preserves explicit provider and runtime mode in thread.turn.start", (
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.provider, "cursor");
|
||||
assert.strictEqual(parsed.provider, "claudeCode");
|
||||
assert.strictEqual(parsed.runtimeMode, "full-access");
|
||||
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
}),
|
||||
|
||||
@@ -27,7 +27,7 @@ export const ORCHESTRATION_WS_CHANNELS = {
|
||||
domainEvent: "orchestration.domainEvent",
|
||||
} as const;
|
||||
|
||||
export const ProviderKind = Schema.Literals(["codex", "cursor"]);
|
||||
export const ProviderKind = Schema.Literals(["codex", "claudeCode", "cursor"]);
|
||||
export type ProviderKind = typeof ProviderKind.Type;
|
||||
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
|
||||
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
|
||||
|
||||
@@ -43,6 +43,28 @@ describe("ProviderSessionStartInput", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("accepts claude runtime knobs", () => {
|
||||
const parsed = decodeProviderSessionStartInput({
|
||||
threadId: "thread-1",
|
||||
provider: "claudeCode",
|
||||
cwd: "/tmp/workspace",
|
||||
model: "claude-sonnet-4-6",
|
||||
providerOptions: {
|
||||
claudeCode: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
permissionMode: "plan",
|
||||
maxThinkingTokens: 12_000,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
expect(parsed.provider).toBe("claudeCode");
|
||||
expect(parsed.providerOptions?.claudeCode?.binaryPath).toBe("/usr/local/bin/claude");
|
||||
expect(parsed.providerOptions?.claudeCode?.permissionMode).toBe("plan");
|
||||
expect(parsed.providerOptions?.claudeCode?.maxThinkingTokens).toBe(12_000);
|
||||
expect(parsed.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("accepts cursor provider payloads", () => {
|
||||
const parsed = decodeProviderSessionStartInput({
|
||||
threadId: "thread-1",
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
ProviderItemId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -50,12 +51,19 @@ const CodexProviderStartOptions = Schema.Struct({
|
||||
homePath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
|
||||
const ClaudeCodeProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
permissionMode: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
maxThinkingTokens: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
|
||||
const CursorProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
|
||||
const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
claudeCode: Schema.optional(ClaudeCodeProviderStartOptions),
|
||||
cursor: Schema.optional(CursorProviderStartOptions),
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ describe("ProviderRuntimeEvent", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "turn.plan.updated",
|
||||
eventId: "event-1",
|
||||
provider: "codex",
|
||||
provider: "claudeCode",
|
||||
sessionId: "runtime-session-1",
|
||||
createdAt: "2026-02-28T00:00:00.000Z",
|
||||
threadId: "thread-1",
|
||||
@@ -56,7 +56,7 @@ describe("ProviderRuntimeEvent", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
eventId: "event-2",
|
||||
provider: "codex",
|
||||
provider: "claudeCode",
|
||||
sessionId: "runtime-session-2",
|
||||
createdAt: "2026-02-28T00:00:01.000Z",
|
||||
threadId: "thread-2",
|
||||
@@ -94,7 +94,7 @@ describe("ProviderRuntimeEvent", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
eventId: "event-3",
|
||||
provider: "codex",
|
||||
provider: "claudeCode",
|
||||
sessionId: "runtime-session-2",
|
||||
createdAt: "2026-02-28T00:00:02.000Z",
|
||||
threadId: "thread-2",
|
||||
|
||||
@@ -19,6 +19,8 @@ const RuntimeEventRawSource = Schema.Literals([
|
||||
"codex.app-server.notification",
|
||||
"codex.app-server.request",
|
||||
"codex.eventmsg",
|
||||
"claude.sdk.message",
|
||||
"claude.sdk.permission",
|
||||
"codex.sdk.thread-event",
|
||||
"cursor.acp.notification",
|
||||
"cursor.acp.request",
|
||||
|
||||
@@ -4,8 +4,10 @@ import {
|
||||
CURSOR_REASONING_OPTIONS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_OPTIONS,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
} from "../../contracts/src";
|
||||
|
||||
import {
|
||||
@@ -40,6 +42,11 @@ describe("normalizeModelSlug", () => {
|
||||
});
|
||||
|
||||
it("uses provider-specific aliases", () => {
|
||||
expect(normalizeModelSlug("sonnet", "claudeCode")).toBe("claude-sonnet-4-6");
|
||||
expect(normalizeModelSlug("opus-4.6", "claudeCode")).toBe("claude-opus-4-6");
|
||||
expect(normalizeModelSlug("claude-haiku-4-5-20251001", "claudeCode")).toBe(
|
||||
"claude-haiku-4-5",
|
||||
);
|
||||
expect(normalizeModelSlug("composer", "cursor")).toBe("composer-1.5");
|
||||
expect(normalizeModelSlug("gpt-5.3-codex-spark", "cursor")).toBe(
|
||||
"gpt-5.3-codex-spark-preview",
|
||||
@@ -69,6 +76,13 @@ describe("resolveModelSlug", () => {
|
||||
});
|
||||
|
||||
it("supports provider-aware resolution", () => {
|
||||
expect(resolveModelSlugForProvider("claudeCode", undefined)).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.claudeCode,
|
||||
);
|
||||
expect(resolveModelSlugForProvider("claudeCode", "sonnet")).toBe("claude-sonnet-4-6");
|
||||
expect(resolveModelSlugForProvider("claudeCode", "gpt-5.3-codex")).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.claudeCode,
|
||||
);
|
||||
expect(resolveModelSlugForProvider("cursor", undefined)).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.cursor,
|
||||
);
|
||||
@@ -84,6 +98,7 @@ describe("resolveModelSlug", () => {
|
||||
it("keeps codex defaults for backward compatibility", () => {
|
||||
expect(getDefaultModel()).toBe(DEFAULT_MODEL);
|
||||
expect(getModelOptions()).toEqual(MODEL_OPTIONS);
|
||||
expect(getModelOptions("claudeCode")).toEqual(MODEL_OPTIONS_BY_PROVIDER.claudeCode);
|
||||
expect(getModelOptions("cursor")).toEqual(MODEL_OPTIONS_BY_PROVIDER.cursor);
|
||||
expect(getCursorModelFamilyOptions()).toEqual(CURSOR_MODEL_FAMILY_OPTIONS);
|
||||
});
|
||||
@@ -136,7 +151,13 @@ describe("cursor model selection", () => {
|
||||
|
||||
describe("getReasoningEffortOptions", () => {
|
||||
it("returns codex reasoning options for codex", () => {
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(["xhigh", "high", "medium", "low"]);
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns no reasoning options for claudeCode", () => {
|
||||
expect(getReasoningEffortOptions("claudeCode")).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns no reasoning options for cursor", () => {
|
||||
@@ -146,7 +167,14 @@ describe("getReasoningEffortOptions", () => {
|
||||
|
||||
describe("getDefaultReasoningEffort", () => {
|
||||
it("returns provider-scoped defaults", () => {
|
||||
expect(getDefaultReasoningEffort("codex")).toBe("high");
|
||||
expect(getDefaultReasoningEffort("cursor")).toBeNull();
|
||||
expect(getDefaultReasoningEffort("codex")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex,
|
||||
);
|
||||
expect(getDefaultReasoningEffort("claudeCode")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeCode,
|
||||
);
|
||||
expect(getDefaultReasoningEffort("cursor")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.cursor,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -2,10 +2,11 @@ import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
CURSOR_MODEL_FAMILY_OPTIONS,
|
||||
CURSOR_REASONING_OPTIONS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
type CodexReasoningEffort,
|
||||
type CursorModelFamily,
|
||||
type CursorModelSlug,
|
||||
@@ -14,8 +15,6 @@ import {
|
||||
type ProviderKind,
|
||||
} from "../../contracts/src";
|
||||
|
||||
type CatalogProvider = keyof typeof MODEL_OPTIONS_BY_PROVIDER;
|
||||
|
||||
type CursorModelCapability = {
|
||||
readonly supportsReasoning: boolean;
|
||||
readonly supportsFast: boolean;
|
||||
@@ -90,11 +89,8 @@ const CURSOR_MODEL_CAPABILITY_BY_FAMILY: Record<CursorModelFamily, CursorModelCa
|
||||
},
|
||||
};
|
||||
|
||||
function hasModelCatalog(provider: ProviderKind): provider is CatalogProvider {
|
||||
return Object.hasOwn(MODEL_OPTIONS_BY_PROVIDER, provider);
|
||||
}
|
||||
|
||||
const MODEL_SLUG_SET_BY_PROVIDER: Record<CatalogProvider, ReadonlySet<ModelSlug>> = {
|
||||
const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> = {
|
||||
claudeCode: new Set(MODEL_OPTIONS_BY_PROVIDER.claudeCode.map((option) => option.slug)),
|
||||
codex: new Set(MODEL_OPTIONS_BY_PROVIDER.codex.map((option) => option.slug)),
|
||||
cursor: new Set(MODEL_OPTIONS_BY_PROVIDER.cursor.map((option) => option.slug)),
|
||||
};
|
||||
@@ -111,7 +107,7 @@ export interface CursorModelSelection {
|
||||
}
|
||||
|
||||
export function getModelOptions(provider: ProviderKind = "codex") {
|
||||
return hasModelCatalog(provider) ? MODEL_OPTIONS_BY_PROVIDER[provider] : [];
|
||||
return MODEL_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function getCursorModelFamilyOptions() {
|
||||
@@ -227,7 +223,7 @@ export function resolveCursorModelFromSelection(input: {
|
||||
}
|
||||
|
||||
export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug {
|
||||
return hasModelCatalog(provider) ? DEFAULT_MODEL_BY_PROVIDER[provider] : DEFAULT_MODEL;
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function normalizeModelSlug(
|
||||
@@ -243,12 +239,7 @@ export function normalizeModelSlug(
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!hasModelCatalog(provider)) {
|
||||
return trimmed as ModelSlug;
|
||||
}
|
||||
|
||||
const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record<string, ModelSlug>;
|
||||
return aliases[trimmed] ?? (trimmed as ModelSlug);
|
||||
return MODEL_SLUG_ALIASES_BY_PROVIDER[provider][trimmed] ?? (trimmed as ModelSlug);
|
||||
}
|
||||
|
||||
export function resolveModelSlug(
|
||||
@@ -257,14 +248,12 @@ export function resolveModelSlug(
|
||||
): ModelSlug {
|
||||
const normalized = normalizeModelSlug(model, provider);
|
||||
if (!normalized) {
|
||||
return getDefaultModel(provider);
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
if (!hasModelCatalog(provider)) {
|
||||
return getDefaultModel(provider);
|
||||
}
|
||||
|
||||
return MODEL_SLUG_SET_BY_PROVIDER[provider].has(normalized) ? normalized : getDefaultModel(provider);
|
||||
return MODEL_SLUG_SET_BY_PROVIDER[provider].has(normalized)
|
||||
? normalized
|
||||
: DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function resolveModelSlugForProvider(
|
||||
@@ -277,7 +266,7 @@ export function resolveModelSlugForProvider(
|
||||
export function getReasoningEffortOptions(
|
||||
provider: ProviderKind = "codex",
|
||||
): ReadonlyArray<CodexReasoningEffort> {
|
||||
return provider === "codex" ? CODEX_REASONING_EFFORT_OPTIONS : [];
|
||||
return REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function getDefaultReasoningEffort(provider: "codex"): CodexReasoningEffort;
|
||||
@@ -285,7 +274,7 @@ export function getDefaultReasoningEffort(provider: ProviderKind): CodexReasonin
|
||||
export function getDefaultReasoningEffort(
|
||||
provider: ProviderKind = "codex",
|
||||
): CodexReasoningEffort | null {
|
||||
return provider === "codex" ? "high" : null;
|
||||
return DEFAULT_REASONING_EFFORT_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export { CODEX_REASONING_EFFORT_OPTIONS };
|
||||
Reference in new issue
Block a user