diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 99b91464e1..9001cd78da 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -439,7 +439,7 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null { case "compaction": return item.summary ?? null; case "handoff": - return item.summary ?? `${item.strategy} handoff to ${item.toProvider}`; + return item.summary ?? `${item.strategy} handoff to ${item.toProviderInstanceId}`; case "fork": return `Forked to thread ${item.targetThreadId}.`; case "subagent": @@ -673,7 +673,7 @@ const make = Effect.gen(function* () { childRunId: childRun?.id ?? null, childNodeId: task.id, status, - providerInstanceId: ProviderInstanceId.make(task.provider), + providerInstanceId: ProviderInstanceId.make(task.driver), model: task.model, summary: derivedResult, resultContextTransferId: resultTransfer?.id ?? null, @@ -742,7 +742,7 @@ const make = Effect.gen(function* () { if ( parentRun === undefined || parentRun.rootNodeId === null || - parentRun.provider !== scope.providerInstanceId + parentRun.providerInstanceId !== scope.providerInstanceId ) { return yield* failure( "parent_not_active", diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 8e1065494e..1a7574d067 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -21,7 +21,6 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, - type ProviderKind, ProviderThreadId, ProviderTurnId, type ServerProvider, @@ -94,8 +93,8 @@ interface CapturedTurn { readonly text: string; } -function unsupported(provider: ProviderKind, detail: string) { - return Effect.fail(new ProviderAdapterProtocolError({ provider, detail })); +function unsupported(driver: ProviderDriverKind, detail: string) { + return Effect.fail(new ProviderAdapterProtocolError({ driver, detail })); } function makeProviderSnapshot(input: { @@ -127,7 +126,7 @@ function makeProviderSnapshot(input: { function makeDeterministicAdapter(input: { readonly instanceId: ProviderInstanceId; - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly capabilities: OrchestrationV2ProviderCapabilities; readonly capturedTurns: Ref.Ref>; readonly shouldComplete: (turn: ProviderAdapterV2TurnInput) => boolean; @@ -135,7 +134,7 @@ function makeDeterministicAdapter(input: { }): ProviderAdapterV2Shape { return { instanceId: input.instanceId, - provider: input.provider, + driver: input.driver, getCapabilities: () => Effect.succeed(input.capabilities), openSession: (sessionInput) => Effect.gen(function* () { @@ -143,7 +142,8 @@ function makeDeterministicAdapter(input: { const now = yield* DateTime.now; const providerSession: OrchestrationV2ProviderSession = { id: sessionInput.providerSessionId, - provider: input.provider, + driver: input.driver, + providerInstanceId: input.instanceId, status: "ready", cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(), model: sessionInput.modelSelection.model, @@ -160,7 +160,7 @@ function makeDeterministicAdapter(input: { return { instanceId: input.instanceId, - provider: input.provider, + driver: input.driver, providerSessionId: sessionInput.providerSessionId, providerSession, rawEvents: Stream.empty, @@ -168,15 +168,16 @@ function makeDeterministicAdapter(input: { ensureThread: (threadInput) => Effect.gen(function* () { const createdAt = yield* DateTime.now; - const nativeThreadId = `${input.provider}:${threadInput.threadId}`; + const nativeThreadId = `${input.driver}:${threadInput.threadId}`; return { id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`), - provider: input.provider, + driver: input.driver, + providerInstanceId: input.instanceId, providerSessionId: sessionInput.providerSessionId, appThreadId: threadInput.threadId, ownerNodeId: null, nativeThreadRef: { - provider: input.provider, + driver: input.driver, nativeId: nativeThreadId, strength: "strong", }, @@ -208,14 +209,14 @@ function makeDeterministicAdapter(input: { yield* publish([ { type: "provider_turn.updated", - provider: input.provider, + driver: input.driver, providerTurn: { id: providerTurnId, providerThreadId: turnInput.providerThread.id, nodeId: turnInput.rootNodeId, runAttemptId: turnInput.attemptId, nativeTurnRef: { - provider: input.provider, + driver: input.driver, nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`, strength: "strong", }, @@ -233,14 +234,14 @@ function makeDeterministicAdapter(input: { yield* publish([ { type: "provider_turn.updated", - provider: input.provider, + driver: input.driver, providerTurn: { id: providerTurnId, providerThreadId: turnInput.providerThread.id, nodeId: turnInput.rootNodeId, runAttemptId: turnInput.attemptId, nativeTurnRef: { - provider: input.provider, + driver: input.driver, nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`, strength: "strong", }, @@ -252,7 +253,7 @@ function makeDeterministicAdapter(input: { }, { type: "turn_item.updated", - provider: input.provider, + driver: input.driver, turnItem: { id: TurnItemId.make( `turn-item:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`, @@ -280,7 +281,7 @@ function makeDeterministicAdapter(input: { }, { type: "turn.terminal", - provider: input.provider, + driver: input.driver, providerTurnId, status: "completed", }, @@ -290,16 +291,15 @@ function makeDeterministicAdapter(input: { interruptTurn: ({ providerTurnId }) => PubSub.publish(events, { type: "turn.terminal", - provider: input.provider, + driver: input.driver, providerTurnId, status: "interrupted", }).pipe(Effect.asVoid), respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => - unsupported(input.provider, "readThreadSnapshot is unused in this test"), - rollbackThread: () => - unsupported(input.provider, "rollbackThread is unused in this test"), - forkThread: () => unsupported(input.provider, "forkThread is unused in this test"), + unsupported(input.driver, "readThreadSnapshot is unused in this test"), + rollbackThread: () => unsupported(input.driver, "rollbackThread is unused in this test"), + forkThread: () => unsupported(input.driver, "forkThread is unused in this test"), }; }), }; @@ -345,7 +345,7 @@ describe("orchestrator MCP toolkit", () => { const registryLayer = makeProviderAdapterRegistryLayer([ makeDeterministicAdapter({ instanceId: codexInstanceId, - provider: "codex", + driver: ProviderDriverKind.make("codex"), capabilities: CodexProviderCapabilitiesV2, capturedTurns, shouldComplete: (turn) => @@ -354,7 +354,7 @@ describe("orchestrator MCP toolkit", () => { }), makeDeterministicAdapter({ instanceId: claudeInstanceId, - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), capabilities: ClaudeProviderCapabilitiesV2, capturedTurns, shouldComplete: () => true, diff --git a/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts index affc09f1fe..cfa967823f 100644 --- a/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts +++ b/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts @@ -12,11 +12,18 @@ import { import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import { FetchHttpClient } from "effect/unstable/http"; import { describe } from "vite-plus/test"; import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts"; import { ServerConfig } from "../config.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts"; +import { + NoOpProviderEventLoggers, + ProviderEventLoggers, +} from "../provider/Layers/ProviderEventLoggers.ts"; +import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; @@ -43,25 +50,38 @@ const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe( const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer)); +const serverSettingsLayer = ServerSettingsService.layerTest({ + providerInstances: { + [liveInstanceId]: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: `ACP Registry: ${liveAgentId}`, + enabled: true, + config: { + agentId: liveAgentId, + ...(liveCommandPath ? { commandPath: liveCommandPath } : {}), + }, + }, + }, +}); +const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe( + Layer.provide( + Layer.mergeAll( + serverConfigLayer.pipe(Layer.provide(NodeServices.layer)), + serverSettingsLayer, + NodeServices.layer, + FetchHttpClient.layer, + OpenCodeRuntimeLive.pipe(Layer.provide(NodeServices.layer)), + Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers), + ), + ), +); + const liveLayer = OrchestrationV2LayerLive.pipe( Layer.provide(SqlitePersistenceMemory), Layer.provide(checkpointStoreLayer), Layer.provide(serverConfigLayer), - Layer.provide( - ServerSettingsService.layerTest({ - providerInstances: { - [liveInstanceId]: { - driver: ProviderDriverKind.make("acpRegistry"), - displayName: `ACP Registry: ${liveAgentId}`, - enabled: true, - config: { - agentId: liveAgentId, - ...(liveCommandPath ? { commandPath: liveCommandPath } : {}), - }, - }, - }, - }), - ), + Layer.provide(serverSettingsLayer), + Layer.provide(providerInstanceRegistryLayer), Layer.provide(NodeServices.layer), ); @@ -132,7 +152,7 @@ describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")( )?.text; assert.deepEqual( - firstProjection.runs.map((run) => [run.provider, run.status]), + firstProjection.runs.map((run) => [run.providerInstanceId, run.status]), [[liveInstanceId, "completed"]], ); assert.include(firstAssistant ?? "", marker); @@ -156,7 +176,7 @@ describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")( )?.text; assert.deepEqual( - finalProjection.runs.map((run) => [run.provider, run.status]), + finalProjection.runs.map((run) => [run.providerInstanceId, run.status]), [ [liveInstanceId, "completed"], [liveInstanceId, "completed"], diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index db8139199b..c343542336 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -4,6 +4,7 @@ import { MessageId, NodeId, ProjectId, + ProviderDriverKind, ProviderInstanceId, ProviderSessionId, RunAttemptId, @@ -40,6 +41,7 @@ const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { }).pipe(Layer.provide(NodeServices.layer)); const testLayer = Layer.mergeAll(NodeServices.layer, idAllocatorLayer, serverConfigLayer); +const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test"); function makeMockRuntime(input: { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; @@ -86,7 +88,7 @@ function makeTurnInput(input: { id: input.threadId, projectId: ProjectId.make(`project:${input.threadId}`), title: "ACP adapter test", - defaultProvider: "acp-test", + providerInstanceId: input.instanceId, modelSelection, runtimeMode: "approval-required", interactionMode: "default", @@ -140,7 +142,7 @@ describe("AcpAdapterV2", () => { const adapter = makeAcpAdapterV2({ instanceId, flavor: { - provider: "acp-test", + driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, makeRuntime, }, @@ -197,7 +199,7 @@ describe("AcpAdapterV2", () => { const adapter = makeAcpAdapterV2({ instanceId, flavor: { - provider: "acp-test", + driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, makeRuntime: makeMockRuntime({ childProcessSpawner, @@ -282,7 +284,7 @@ describe("AcpAdapterV2", () => { const adapter = makeAcpAdapterV2({ instanceId, flavor: { - provider: "acp-test", + driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, makeRuntime: makeMockRuntime({ childProcessSpawner, @@ -328,7 +330,7 @@ describe("AcpAdapterV2", () => { Stream.runHead, ); const providerTurnId = idAllocator.derive.providerTurn({ - provider: "acp-test", + driver: ACP_TEST_DRIVER, nativeTurnId: "mock-session-1:turn:1", }); const interruptFiber = yield* runtime diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts index f93281d4bc..c51b099308 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts @@ -1,5 +1,5 @@ import { - ProviderKind, + ProviderDriverKind, ProviderReplayEntry, type ProviderReplayTranscript, } from "@t3tools/contracts"; @@ -18,7 +18,7 @@ import { import { ACP_PROTOCOL, type AcpAdapterV2RuntimeInput } from "./AcpAdapterV2.ts"; export const AcpReplayTranscript = Schema.Struct({ - provider: ProviderKind, + provider: ProviderDriverKind, protocol: Schema.Literal(ACP_PROTOCOL), version: Schema.String, scenario: Schema.String, @@ -32,8 +32,8 @@ const decodeAcpReplayTranscriptSchema = Schema.decodeUnknownEffect(AcpReplayTran export class AcpReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( "AcpReplayTranscriptDecodeError", { - expectedProvider: ProviderKind, - provider: Schema.optional(Schema.String), + expectedProvider: ProviderDriverKind, + driver: Schema.optional(Schema.String), protocol: Schema.optional(Schema.String), scenario: Schema.optional(Schema.String), cause: Schema.Defect(), @@ -60,7 +60,7 @@ function metadataFromTranscript(transcript: ProviderReplayTranscript): { export function decodeAcpReplayTranscript( transcript: ProviderReplayTranscript, - expectedProvider: ProviderKind, + expectedProvider: ProviderDriverKind, options: { readonly retargetProvider?: boolean } = {}, ): Effect.Effect { const candidate = options.retargetProvider diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index 620f50d887..55d2e873ce 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -15,7 +15,7 @@ import { type OrchestrationV2UserInputQuestion, type ProviderApprovalDecision, type ProviderInstanceId, - type ProviderKind, + type ProviderDriverKind, type ProviderRequestKind, type ProviderUserInputAnswers, type RuntimeRequestId, @@ -97,7 +97,7 @@ export interface AcpAdapterV2ExtensionContext { } export interface AcpAdapterV2Flavor { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly capabilities: OrchestrationV2ProviderCapabilities; readonly makeRuntime: ( input: AcpAdapterV2RuntimeInput, @@ -265,11 +265,11 @@ function acpMcpServers(threadId: ThreadId): ReadonlyArray, ): Record { const content: Record = {}; for (const [key, value] of Object.entries(answers)) { + if (!allowedKeys.has(key)) continue; if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { content[key] = value; } else if (Array.isArray(value)) { @@ -596,11 +600,11 @@ function oppositeDirection(direction: "incoming" | "outgoing"): "incoming" | "ou export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV2Shape { const { flavor, fileSystem, idAllocator, serverConfig } = options; - const provider = flavor.provider; + const driver = flavor.driver; return ProviderAdapterV2.of({ instanceId: options.instanceId, - provider, + driver, getCapabilities: () => Effect.succeed(flavor.capabilities), openSession: Effect.fn("AcpAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { @@ -662,7 +666,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* Queue.offer(rawEvents, { id: rawEventId, - provider, + driver, + providerInstanceId: options.instanceId, providerSessionId: input.providerSessionId, sequence: state.sequence, direction: event.direction, @@ -676,7 +681,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }).pipe( Effect.catchCause((cause) => Effect.logWarning("orchestration-v2.acp-raw-event-failed", { - provider, + driver, providerSessionId: input.providerSessionId, cause, }), @@ -744,21 +749,21 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const now = yield* DateTime.now; const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider, + driver, nativeItemId: segment.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider, + driver, nativeItemId: segment.nativeItemId, }); const nativeItemRef = { - provider, + driver, nativeId: segment.nativeItemId, strength: "weak" as const, }; yield* emitProviderEvent({ type: "node.updated", - provider, + driver, node: { id: nodeId, threadId: context.input.threadId, @@ -779,7 +784,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); if (kind === "assistant") { const messageId = idAllocator.derive.messageFromProviderItem({ - provider, + driver, nativeItemId: segment.nativeItemId, }); const message: OrchestrationV2ConversationMessage = { @@ -796,10 +801,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV createdAt: segment.startedAt, updatedAt: now, }; - yield* emitProviderEvent({ type: "message.updated", provider, message }); + yield* emitProviderEvent({ type: "message.updated", driver, message }); yield* emitProviderEvent({ type: "turn_item.updated", - provider, + driver, turnItem: { id: turnItemId, threadId: context.input.threadId, @@ -826,7 +831,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV } yield* emitProviderEvent({ type: "turn_item.updated", - provider, + driver, turnItem: { id: turnItemId, threadId: context.input.threadId, @@ -896,15 +901,15 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV context.tools.set(toolCall.toolCallId, toolCall); const status = toolStatus(toolCall.status); const now = yield* DateTime.now; - const nativeItemId = `${nativeThreadId(provider, context.input.providerThread)}:tool:${toolCall.toolCallId}`; + const nativeItemId = `${nativeThreadId(driver, context.input.providerThread)}:tool:${toolCall.toolCallId}`; const ordinal = yield* resolveItemOrdinal(context, nativeItemId); - const nodeId = idAllocator.derive.nodeFromProviderItem({ provider, nativeItemId }); + const nodeId = idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider, + driver, nativeItemId, }); const nativeItemRef = { - provider, + driver, nativeId: toolCall.toolCallId, strength: "strong" as const, }; @@ -914,7 +919,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const title = toolCall.title ?? null; yield* emitProviderEvent({ type: "node.updated", - provider, + driver, node: { id: nodeId, threadId: context.input.threadId, @@ -1028,7 +1033,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV ...(rawOutput === undefined ? {} : { output: rawOutput }), }; } - yield* emitProviderEvent({ type: "turn_item.updated", provider, turnItem }); + yield* emitProviderEvent({ type: "turn_item.updated", driver, turnItem }); }); const emitPlan = Effect.fnUntraced(function* ( @@ -1039,9 +1044,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const nativeItemId = `${context.nativeTurnId}:plan`; const ordinal = yield* resolveItemOrdinal(context, nativeItemId); const now = yield* DateTime.now; - const nodeId = idAllocator.derive.nodeFromProviderItem({ provider, nativeItemId }); + const nodeId = idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider, + driver, nativeItemId, }); if (context.plan === null) { @@ -1049,7 +1054,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV id: yield* idAllocator.allocate.plan({ threadId: context.input.threadId, runId: context.input.runId, - provider, + driver, }), startedAt: now, }; @@ -1066,7 +1071,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV : "pending", })); const completed = steps.length > 0 && steps.every((step) => step.status === "completed"); - const nativeItemRef = { provider, nativeId: nativeItemId, strength: "weak" as const }; + const nativeItemRef = { driver, nativeId: nativeItemId, strength: "weak" as const }; const plan: OrchestrationV2PlanArtifact = { id: planId, threadId: context.input.threadId, @@ -1079,7 +1084,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }; yield* emitProviderEvent({ type: "node.updated", - provider, + driver, node: { id: nodeId, threadId: context.input.threadId, @@ -1098,10 +1103,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV completedAt: completed ? now : null, }, }); - yield* emitProviderEvent({ type: "plan.updated", provider, plan }); + yield* emitProviderEvent({ type: "plan.updated", driver, plan }); yield* emitProviderEvent({ type: "turn_item.updated", - provider, + driver, turnItem: { id: turnItemId, threadId: context.input.threadId, @@ -1138,7 +1143,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const loadingIndex = startsNew ? current.loadingIndex + 1 : current.loadingIndex; const nativeItemId = `${notification.sessionId}:history:${role}:${loadingIndex}`; const messageId = idAllocator.derive.messageFromProviderItem({ - provider, + driver, nativeItemId, }); const key = String(messageId); @@ -1249,7 +1254,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const parsed = parsePermissionRequest(params); const nativeRequestId = params.toolCall.toolCallId; const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider, + driver, providerTurnId: context.providerTurnId, nativeRequestId, }); @@ -1257,7 +1262,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const now = yield* DateTime.now; const nodeId = idAllocator.derive.approvalNode({ requestId }); const requestKind = providerRequestKind(parsed.kind); - const nativeItemRef = { provider, nativeId: nativeRequestId, strength: "weak" as const }; + const nativeItemRef = { driver, nativeId: nativeRequestId, strength: "weak" as const }; const ordinal = yield* resolveItemOrdinal( context, `${context.nativeTurnId}:approval:${nativeRequestId}`, @@ -1327,18 +1332,18 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* emitProviderEvent({ type: "node.updated", - provider, + driver, node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider, + driver, threadId: context.input.threadId, runtimeRequest, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider, + driver, turnItem, }); const resolved = yield* Deferred.await(decision).pipe( @@ -1394,22 +1399,22 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const context = yield* activeContext; yield* closeTextStreams(context); const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider, + driver, providerTurnId: context.providerTurnId, nativeRequestId: request.nativeRequestId, }); const answers = yield* Deferred.make(); const now = yield* DateTime.now; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider, + driver, nativeItemId: request.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider, + driver, nativeItemId: request.nativeItemId, }); const nativeItemRef = { - provider, + driver, nativeId: request.nativeItemId, strength: "weak" as const, }; @@ -1419,7 +1424,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV nodeId, providerTurnId: context.providerTurnId, nativeRequestRef: { - provider, + driver, nativeId: request.nativeRequestId, strength: "weak", }, @@ -1482,18 +1487,18 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* emitProviderEvent({ type: "node.updated", - provider, + driver, node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider, + driver, threadId: context.input.threadId, runtimeRequest, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider, + driver, turnItem, }); return yield* Deferred.await(answers).pipe( @@ -1534,7 +1539,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV yield* emitProviderEvent({ type: "runtime_request.updated", - provider, + driver, threadId: request.node.threadId, runtimeRequest: { ...request.runtimeRequest, @@ -1544,7 +1549,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* emitProviderEvent({ type: "node.updated", - provider, + driver, node: { ...request.node, status: "cancelled", @@ -1553,7 +1558,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* emitProviderEvent({ type: "turn_item.updated", - provider, + driver, turnItem: { ...request.turnItem, status: "cancelled", @@ -1606,7 +1611,15 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); return answers === null ? ({ action: { action: "cancel" } } as const) - : ({ action: { action: "accept", content: elicitationContent(answers) } } as const); + : ({ + action: { + action: "accept", + content: elicitationContent( + answers, + new Set(Object.keys(params.requestedSchema.properties ?? {})), + ), + }, + } as const); }), ); @@ -1631,7 +1644,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV return yield* runtime.resumeSession(sessionId); } return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: `ACP driver cannot load or resume session ${sessionId}`, }); }); @@ -1679,7 +1692,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const createdAt = yield* DateTime.now; const providerSession: OrchestrationV2ProviderSession = { id: input.providerSessionId, - provider, + driver, + providerInstanceId: options.instanceId, status: "ready", cwd: input.runtimePolicy.cwd ?? process.cwd(), model: input.modelSelection.model, @@ -1699,7 +1713,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV nodeId: context.input.rootNodeId, runAttemptId: context.input.attemptId, nativeTurnRef: { - provider, + driver, nativeId: context.nativeTurnId, strength: "weak", }, @@ -1725,13 +1739,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* emitProviderEvent({ type: "provider_turn.updated", - provider, + driver, threadId: context.input.threadId, providerTurn: turn, }); yield* emitProviderEvent({ type: "provider_thread.updated", - provider, + driver, providerThread: { ...context.input.providerThread, providerSessionId: input.providerSessionId, @@ -1744,7 +1758,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* emitProviderEvent({ type: "turn.terminal", - provider, + driver, providerTurnId: context.providerTurnId, status, }); @@ -1761,7 +1775,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV } if (turnInput.message.attachments.length > 0 && !supportsImagePrompts) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: "ACP driver did not negotiate image prompt support", }); } @@ -1772,7 +1786,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); if (path === null) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: `Invalid attachment id '${attachment.id}'`, }); } @@ -1780,7 +1794,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterProtocolError({ - provider, + driver, detail: `Failed to read attachment '${attachment.id}'`, payload: cause, }), @@ -1794,7 +1808,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV } if (prompt.length === 0) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: "ACP turn requires non-empty text or attachments", }); } @@ -1806,11 +1820,11 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const existing = yield* Ref.get(activeTurn); if (existing !== null) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: `ACP provider turn ${existing.providerTurnId} is still active`, }); } - const requestedSessionId = nativeThreadId(provider, turnInput.providerThread); + const requestedSessionId = nativeThreadId(driver, turnInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== requestedSessionId) { const activated = yield* activateSession(requestedSessionId); yield* Ref.set(activeSessionId, activated.sessionId); @@ -1819,7 +1833,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const prompt = yield* resolvePromptParts(turnInput); const startedAt = yield* DateTime.now; const nativeTurnId = `${requestedSessionId}:turn:${turnInput.providerTurnOrdinal}`; - const providerTurnId = idAllocator.derive.providerTurn({ provider, nativeTurnId }); + const providerTurnId = idAllocator.derive.providerTurn({ driver, nativeTurnId }); const completed = yield* Deferred.make(); const context: ActiveAcpTurn = { input: turnInput, @@ -1844,13 +1858,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); yield* emitProviderEvent({ type: "provider_turn.updated", - provider, + driver, threadId: turnInput.threadId, providerTurn: runningTurn, }); yield* emitProviderEvent({ type: "provider_thread.updated", - provider, + driver, providerThread: { ...turnInput.providerThread, providerSessionId: input.providerSessionId, @@ -1886,7 +1900,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV finalizeTurn(context, context.interrupted ? "interrupted" : "failed").pipe( Effect.andThen( Effect.logWarning("orchestration-v2.acp-prompt-failed", { - provider, + driver, providerSessionId: input.providerSessionId, providerThreadId: turnInput.providerThread.id, providerTurnId, @@ -1903,7 +1917,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterTurnStartError({ - provider, + driver, threadId: turnInput.threadId, providerThreadId: turnInput.providerThread.id, runId: turnInput.runId, @@ -1937,7 +1951,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const sessionRuntime: ProviderAdapterV2SessionRuntime = { instanceId: options.instanceId, - provider, + driver, providerSessionId: input.providerSessionId, providerSession, rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)), @@ -1948,12 +1962,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const sessionId = yield* Ref.get(activeSessionId); if (sessionId === null) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: "ACP runtime did not produce a session id", }); } return makeProviderThread({ - provider, + driver, + providerInstanceId: options.instanceId, idAllocator, appThreadId: threadInput.threadId, providerSessionId: input.providerSessionId, @@ -1966,7 +1981,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterEnsureThreadError({ - provider, + driver, threadId: threadInput.threadId, cause, }), @@ -1975,7 +1990,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV ), resumeThread: Effect.fn("AcpAdapterV2.resumeThread")( function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) { - const sessionId = nativeThreadId(provider, threadInput.providerThread); + const sessionId = nativeThreadId(driver, threadInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== sessionId) { yield* Ref.set(snapshot, { order: [], @@ -2000,7 +2015,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterResumeThreadError({ - provider, + driver, providerSessionId: input.providerSessionId, providerThreadId: threadInput.providerThread.id, cause, @@ -2012,7 +2027,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV steerTurn: (turnInput) => Effect.fail( new ProviderAdapterSteerRunUnsupportedError({ - provider, + driver, providerThreadId: turnInput.providerThread.id, }), ), @@ -2021,7 +2036,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const context = yield* Ref.get(activeTurn); if (context?.providerTurnId !== turnInput.providerTurnId) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: `ACP provider turn ${turnInput.providerTurnId} is not active`, }); } @@ -2032,7 +2047,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV ); if (Option.isNone(stopped)) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: `ACP provider turn ${turnInput.providerTurnId} did not acknowledge cancellation before the interrupt timeout`, }); } @@ -2042,7 +2057,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterInterruptError({ - provider, + driver, providerThreadId: turnInput.providerThread.id, providerTurnId: turnInput.providerTurnId, cause, @@ -2057,7 +2072,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV ); if (pending === undefined) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: `No pending ACP runtime request ${requestInput.requestId}`, }); } @@ -2067,7 +2082,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV } if (requestInput.decision === undefined) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: `ACP approval request ${requestInput.requestId} requires a decision`, }); } @@ -2076,7 +2091,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterRuntimeRequestResponseError({ - provider, + driver, requestId: requestInput.requestId, cause, }), @@ -2084,11 +2099,11 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV ), readThreadSnapshot: Effect.fn("AcpAdapterV2.readThreadSnapshot")( function* (snapshotInput) { - const sessionId = nativeThreadId(provider, snapshotInput.providerThread); + const sessionId = nativeThreadId(driver, snapshotInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== sessionId) { if (!capabilities.threads.canReadThreadSnapshot) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: "ACP driver does not support session/load snapshots", }); } @@ -2124,7 +2139,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterReadThreadSnapshotError({ - provider, + driver, providerThreadId: snapshotInput.providerThread.id, cause, }), @@ -2134,7 +2149,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV rollbackThread: (rollbackInput) => Effect.fail( new ProviderAdapterRollbackThreadError({ - provider, + driver, providerThreadId: rollbackInput.providerThread.id, checkpointId: rollbackInput.target.checkpointId, cause: "ACP does not define conversation rollback.", @@ -2144,22 +2159,23 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV function* (forkInput) { if (!capabilities.threads.canForkThread) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: "ACP driver did not negotiate session/fork", }); } if (forkInput.providerTurnId !== undefined) { return yield* new ProviderAdapterProtocolError({ - provider, + driver, detail: "ACP session/fork can only fork the current session head", }); } - const sourceSessionId = nativeThreadId(provider, forkInput.sourceProviderThread); + const sourceSessionId = nativeThreadId(driver, forkInput.sourceProviderThread); const forked = yield* runtime.forkSession(sourceSessionId); yield* Ref.set(activeSessionId, forked.sessionId); const now = yield* DateTime.now; return makeProviderThread({ - provider, + driver, + providerInstanceId: options.instanceId, idAllocator, appThreadId: forkInput.targetThreadId, providerSessionId: input.providerSessionId, @@ -2181,7 +2197,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterForkThreadError({ - provider, + driver, providerThreadId: forkInput.sourceProviderThread.id, cause, }), @@ -2196,7 +2212,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.mapError( (cause) => new ProviderAdapterOpenSessionError({ - provider, + driver, providerSessionId: input.providerSessionId, cause, }), diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 40d86f6086..acb2a48d57 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -148,7 +148,7 @@ describe("AcpRegistryAdapterV2", () => { runtimePolicy, }); - assert.equal(runtime.providerSession.provider, "acpRegistry"); + assert.equal(runtime.providerSession.driver, "acpRegistry"); assert.equal(providerThread.nativeThreadRef?.nativeId, "mock-session-1"); assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot); assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts index 6564a1bc6b..93cbc7f93f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts @@ -80,7 +80,7 @@ export const AcpRegistryOrchestratorReplayHarness: OrchestratorV2ProviderReplayH AcpReplayTranscript, AcpReplayTranscriptDecodeError > = { - provider: ACP_REGISTRY_PROVIDER, + driver: ACP_REGISTRY_PROVIDER, decodeTranscript: (transcript) => decodeAcpReplayTranscript(transcript, ACP_REGISTRY_PROVIDER, { retargetProvider: true, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts index d792da49b6..13a8c40ea8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.ts @@ -37,8 +37,8 @@ import { type AcpAdapterV2RuntimeInput, } from "./AcpAdapterV2.ts"; -export const ACP_REGISTRY_PROVIDER = "acpRegistry" as const; -export const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make(ACP_REGISTRY_PROVIDER); +export const ACP_REGISTRY_PROVIDER = ProviderDriverKind.make("acpRegistry"); +export const ACP_REGISTRY_DRIVER_KIND = ACP_REGISTRY_PROVIDER; export const ACP_REGISTRY_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(ACP_REGISTRY_DRIVER_KIND); @@ -92,7 +92,7 @@ function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) { export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) { const flavor: AcpAdapterV2Flavor = { - provider: ACP_REGISTRY_PROVIDER, + driver: ACP_REGISTRY_PROVIDER, capabilities: AcpProviderCapabilitiesV2, makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options), ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 96afc0021a..27f5d5150e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -357,7 +357,7 @@ describe("ClaudeAdapterV2 native fork", () => { nodeId: NodeId.make("node-claude-source"), runAttemptId: RunAttemptId.make("run-attempt-claude-source"), nativeTurnRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: "assistant-message-cursor", strength: "weak", }, @@ -393,7 +393,7 @@ describe("ClaudeAdapterV2 native fork", () => { id: targetThreadId, projectId: ProjectId.make("project-claude-fork-target"), title: "Claude fork target", - defaultProvider: ProviderInstanceId.make(CLAUDE_PROVIDER), + providerInstanceId: ProviderInstanceId.make(CLAUDE_PROVIDER), modelSelection: { instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER), model: "claude-sonnet-4-6", diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index 81a15010c7..a60a4057ad 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -53,7 +53,7 @@ type ClaudeAgentSdkReplayTranscript = typeof ClaudeAgentSdkReplayTranscript.Type export class ClaudeReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( "ClaudeReplayTranscriptDecodeError", { - provider: Schema.optional(Schema.String), + driver: Schema.optional(Schema.String), protocol: Schema.optional(Schema.String), scenario: Schema.optional(Schema.String), cause: Schema.Defect(), @@ -2359,7 +2359,7 @@ export const ClaudeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarnes ClaudeAgentSdkReplayTranscript, ClaudeAgentSdkReplayError > = { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, decodeTranscript: (transcript) => Schema.decodeUnknownEffect(ClaudeAgentSdkReplayTranscript)(transcript).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 8b7fe70cbb..f9121e66d3 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -96,9 +96,9 @@ import { subagentThreadTitle, } from "../SubagentProjection.ts"; -export const CLAUDE_PROVIDER = "claudeAgent" as const; +export const CLAUDE_PROVIDER = ProviderDriverKind.make("claudeAgent"); export const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const; -export const CLAUDE_DRIVER_KIND = ProviderDriverKind.make(CLAUDE_PROVIDER); +export const CLAUDE_DRIVER_KIND = CLAUDE_PROVIDER; export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_DRIVER_KIND); const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({}); @@ -674,13 +674,15 @@ export function claudeMcpQueryOverrides(input: { function providerSession(input: { readonly providerSessionId: OrchestrationV2ProviderSession["id"]; + readonly providerInstanceId: ProviderInstanceId; readonly cwd: string | null; readonly model: string; readonly now: DateTime.Utc; }): OrchestrationV2ProviderSession { return { id: input.providerSessionId, - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, + providerInstanceId: input.providerInstanceId, status: "ready", cwd: input.cwd ?? process.cwd(), model: input.model, @@ -721,6 +723,7 @@ function resultTextFromSdkMessage( function makeProviderThread(input: { readonly idAllocator: IdAllocatorV2Shape; + readonly providerInstanceId: ProviderInstanceId; readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"]; readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"]; readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; @@ -730,15 +733,16 @@ function makeProviderThread(input: { }): OrchestrationV2ProviderThread { return { id: input.idAllocator.derive.providerThread({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeThreadId: input.nativeThreadId, }), - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, + providerInstanceId: input.providerInstanceId, providerSessionId: input.providerSessionId, appThreadId: input.appThreadId, ownerNodeId: input.ownerNodeId ?? null, nativeThreadRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.nativeThreadId, strength: "strong", }, @@ -759,7 +763,7 @@ const getNativeThreadId = Effect.fnUntraced(function* ( const nativeThreadId = providerThread.nativeThreadRef?.nativeId; if (nativeThreadId === undefined || nativeThreadId === null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Provider thread ${providerThread.id} is missing a native Claude session id.`, }); } @@ -781,15 +785,15 @@ const getNativeConversationHeadId = Effect.fnUntraced(function* ( if (nativeHeadRef === null) { return undefined; } - if (nativeHeadRef.provider !== CLAUDE_PROVIDER) { + if (nativeHeadRef.driver !== CLAUDE_PROVIDER) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Provider thread ${providerThread.id} has a non-Claude native conversation head reference.`, }); } if (nativeHeadRef.nativeId === null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Provider thread ${providerThread.id} has a Claude native conversation head reference without a native id.`, }); } @@ -808,7 +812,7 @@ const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpT const boundaryIndex = sourceTurns.findIndex((turn) => turn.id === input.providerTurnId); if (boundaryIndex < 0) { return yield* new ProviderAdapterForkThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: input.sourceProviderThread.id, cause: `Cannot fork Claude thread from provider turn ${input.providerTurnId}: source turn was not found in provider thread ${input.sourceProviderThread.id}.`, }); @@ -831,7 +835,7 @@ const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpT } return yield* new ProviderAdapterForkThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: input.sourceProviderThread.id, cause: `Cannot fork Claude thread from prior provider turn ${input.providerTurnId}: no SDK assistant message cursor was recorded for that turn.`, }); @@ -848,7 +852,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn( const target = input.target; if (target.providerTurn.providerThreadId !== input.providerThread.id) { return yield* new ProviderAdapterRollbackThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: input.providerThread.id, cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: target turn belongs to provider thread ${target.providerTurn.providerThreadId}.`, }); @@ -857,7 +861,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn( const nativeTurnRef = target.providerTurn.nativeTurnRef; if ( nativeTurnRef !== null && - nativeTurnRef.provider === CLAUDE_PROVIDER && + nativeTurnRef.driver === CLAUDE_PROVIDER && nativeTurnRef.nativeId !== null && !isSyntheticClaudeTurnId(nativeTurnRef.nativeId) ) { @@ -872,7 +876,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn( } return yield* new ProviderAdapterRollbackThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: input.providerThread.id, cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: no SDK assistant message cursor was recorded for that turn.`, }); @@ -1553,19 +1557,19 @@ function buildAssistantArtifacts(input: { readonly turnItem: OrchestrationV2TurnItem; } { const nodeId = input.idAllocator.derive.nodeFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: input.nativeItemId, }); const messageId = input.idAllocator.derive.messageFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: input.nativeItemId, }); const turnItemId = input.idAllocator.derive.turnItemFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: input.nativeItemId, }); const nativeItemRef = { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.nativeItemId, strength: "strong" as const, }; @@ -1694,7 +1698,7 @@ export function makeClaudeAdapterV2( return ProviderAdapterV2.of({ instanceId: adapterOptions.instanceId, - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), openSession: Effect.fn("ClaudeAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { @@ -1702,6 +1706,7 @@ export function makeClaudeAdapterV2( const now = yield* DateTime.now; const session = providerSession({ providerSessionId: input.providerSessionId, + providerInstanceId: adapterOptions.instanceId, cwd: input.runtimePolicy.cwd, model: input.modelSelection.model, now, @@ -1758,7 +1763,7 @@ export function makeClaudeAdapterV2( nodeId: input.context.input.rootNodeId, runAttemptId: input.context.input.attemptId, nativeTurnRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.context.nativeMessageCursor ?? input.context.nativeTurnId, strength: "weak", }, @@ -1789,15 +1794,15 @@ export function makeClaudeAdapterV2( }) => { const completedAt = input.status === "running" ? null : input.updatedAt; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: input.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: input.nativeItemId, }); const nativeItemRef = { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.nativeItemId, strength: "strong" as const, }; @@ -1898,12 +1903,12 @@ export function makeClaudeAdapterV2( }) { yield* emitProviderEvent({ type: "node.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, turnItem: artifacts.turnItem, }); }); @@ -1934,19 +1939,19 @@ export function makeClaudeAdapterV2( const nodeId = existingSubagent?.task.id ?? idAllocator.derive.nodeFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId, }); const childRootNodeId = existingSubagent?.childRootNodeId ?? idAllocator.derive.nodeFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: `${nativeItemId}:thread-root`, }); const childThreadId = existingSubagent?.childThreadId ?? idAllocator.derive.threadFromProviderThread({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeThreadId: `${input.context.input.providerThread.id}:${input.taskId}`, }); if (existingSubagent === undefined) { @@ -1963,11 +1968,12 @@ export function makeClaudeAdapterV2( parentNodeId: input.context.input.rootNodeId, origin: "provider_native" as const, createdBy: "agent" as const, - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, + providerInstanceId: input.context.input.modelSelection.instanceId, providerThreadId: null, childThreadId, nativeTaskRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.taskId, strength: "strong" as const, }, @@ -1991,7 +1997,7 @@ export function makeClaudeAdapterV2( turnItemId: existingSubagent?.turnItemId ?? idAllocator.derive.turnItemFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: `${nativeItemId}:subagent`, }), turnItemOrdinal, @@ -2023,14 +2029,14 @@ export function makeClaudeAdapterV2( }); yield* emitProviderEvent({ type: "app_thread.created", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, appThread: childThread, }); } yield* emitProviderEvent({ type: "node.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, node: { id: nodeId, threadId: input.context.input.threadId, @@ -2043,7 +2049,7 @@ export function makeClaudeAdapterV2( providerThreadId: input.context.input.providerThread.id, providerTurnId: input.context.providerTurnId, nativeItemRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.taskId, strength: "strong", }, @@ -2055,7 +2061,7 @@ export function makeClaudeAdapterV2( }); yield* emitProviderEvent({ type: "node.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, node: { id: childRootNodeId, threadId: childThreadId, @@ -2078,11 +2084,11 @@ export function makeClaudeAdapterV2( const promptNativeItemId = `${nativeItemId}:prompt`; const promptArtifacts = makeSubagentConversationArtifacts({ messageId: idAllocator.derive.messageFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: promptNativeItemId, }), turnItemId: idAllocator.derive.turnItemFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: promptNativeItemId, }), threadId: childThreadId, @@ -2090,7 +2096,7 @@ export function makeClaudeAdapterV2( providerThreadId: null, providerTurnId: null, nativeItemRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: promptNativeItemId, strength: "strong", }, @@ -2101,23 +2107,23 @@ export function makeClaudeAdapterV2( }); yield* emitProviderEvent({ type: "message.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, message: promptArtifacts.message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, turnItem: promptArtifacts.turnItem, }); } yield* emitProviderEvent({ type: "subagent.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, subagent: task, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, turnItem: { id: subagent.turnItemId, threadId: task.threadId, @@ -2136,7 +2142,8 @@ export function makeClaudeAdapterV2( type: "subagent", subagentId: task.id, origin: task.origin, - provider: task.provider, + driver: task.driver, + providerInstanceId: task.providerInstanceId, childThreadId: task.childThreadId, prompt: task.prompt, result: task.result, @@ -2153,11 +2160,11 @@ export function makeClaudeAdapterV2( subagent.resultItemOrdinal = resultItemOrdinal; const resultArtifacts = makeSubagentConversationArtifacts({ messageId: idAllocator.derive.messageFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: resultNativeItemId, }), turnItemId: idAllocator.derive.turnItemFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: resultNativeItemId, }), threadId: childThreadId, @@ -2165,7 +2172,7 @@ export function makeClaudeAdapterV2( providerThreadId: null, providerTurnId: null, nativeItemRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: resultNativeItemId, strength: "strong", }, @@ -2176,12 +2183,12 @@ export function makeClaudeAdapterV2( }); yield* emitProviderEvent({ type: "message.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, message: resultArtifacts.message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, turnItem: resultArtifacts.turnItem, }); } @@ -2255,7 +2262,7 @@ export function makeClaudeAdapterV2( }) { const createdAt = yield* DateTime.now; const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerTurnId: input.context.providerTurnId, nativeRequestId: input.nativeRequestId, }); @@ -2263,7 +2270,7 @@ export function makeClaudeAdapterV2( const providerSessionId = input.context.input.providerThread.providerSessionId; if (providerSessionId === null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Provider thread ${input.context.input.providerThread.id} is missing a provider session id.`, }); } @@ -2272,7 +2279,7 @@ export function makeClaudeAdapterV2( `${input.nativeItemId}:approval:${input.nativeRequestId}`, ); const nativeItemRef = { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.nativeRequestId, strength: "strong" as const, }; @@ -2281,7 +2288,7 @@ export function makeClaudeAdapterV2( threadId: input.context.input.threadId, runId: input.context.input.runId, parentNodeId: idAllocator.derive.nodeFromProviderItem({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeItemId: input.nativeItemId, }), rootNodeId: input.context.input.rootNodeId, @@ -2301,7 +2308,7 @@ export function makeClaudeAdapterV2( nodeId, providerTurnId: input.context.providerTurnId, nativeRequestRef: { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: input.nativeRequestId, strength: "strong", }, @@ -2385,17 +2392,17 @@ export function makeClaudeAdapterV2( [ emitProviderEvent({ type: "node.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, node: artifacts.node, }), emitProviderEvent({ type: "message.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, message: artifacts.message, }), emitProviderEvent({ type: "turn_item.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, turnItem: artifacts.turnItem, }), ], @@ -2407,7 +2414,7 @@ export function makeClaudeAdapterV2( [ emitProviderEvent({ type: "provider_turn.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerTurn: providerTurnPayload({ context: input.context, status: input.status, @@ -2419,7 +2426,7 @@ export function makeClaudeAdapterV2( ? [ emitProviderEvent({ type: "provider_thread.updated" as const, - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThread: { ...input.context.input.providerThread, providerSessionId: session.id, @@ -2436,7 +2443,7 @@ export function makeClaudeAdapterV2( : []), emitProviderEvent({ type: "turn.terminal", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerTurnId: input.context.providerTurnId, status: input.status, }), @@ -2672,17 +2679,17 @@ export function makeClaudeAdapterV2( [ emitProviderEvent({ type: "node.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, node: artifacts.node, }), emitProviderEvent({ type: "runtime_request.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, runtimeRequest: artifacts.request, }), emitProviderEvent({ type: "turn_item.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, turnItem: artifacts.turnItem, }), ], @@ -2813,14 +2820,14 @@ export function makeClaudeAdapterV2( const nativeThreadId = yield* getNativeThreadId(turnInput.providerThread); const nativeTurnId = `turn:${turnInput.attemptId}`; const providerTurnId = idAllocator.derive.providerTurn({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeTurnId, }); const providerTurnOrdinal = turnInput.providerTurnOrdinal; const currentTurn = yield* Ref.get(activeTurn); if (currentTurn !== null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Claude provider turn ${currentTurn.providerTurnId} is still active.`, }); } @@ -2844,7 +2851,7 @@ export function makeClaudeAdapterV2( yield* Ref.set(activeTurn, context); yield* emitProviderEvent({ type: "provider_turn.updated", - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerTurn: providerTurnPayload({ context, status: "running", @@ -2860,7 +2867,7 @@ export function makeClaudeAdapterV2( Effect.mapError( (cause) => new ProviderAdapterTurnStartError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, threadId: turnInput.threadId, providerThreadId: turnInput.providerThread.id, runId: turnInput.runId, @@ -2875,14 +2882,14 @@ export function makeClaudeAdapterV2( const existing = yield* Ref.get(queryContext); if (existing === null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Claude provider thread ${turnInput.providerThread.id} has no live query.`, }); } const currentTurn = yield* Ref.get(activeTurn); if (currentTurn?.providerTurnId !== turnInput.providerTurnId) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } @@ -2921,7 +2928,7 @@ export function makeClaudeAdapterV2( Effect.mapError( (cause) => new ProviderAdapterInterruptError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: turnInput.providerThread.id, providerTurnId: turnInput.providerTurnId, cause, @@ -2935,14 +2942,14 @@ export function makeClaudeAdapterV2( const existing = yield* Ref.get(queryContext); if (existing === null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Claude provider thread ${turnInput.providerThread.id} has no live query.`, }); } const currentTurn = yield* Ref.get(activeTurn); if (currentTurn?.providerTurnId !== turnInput.providerTurnId) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } @@ -2960,7 +2967,7 @@ export function makeClaudeAdapterV2( Effect.mapError( (cause) => new ProviderAdapterSteerRunError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: turnInput.providerThread.id, providerTurnId: turnInput.providerTurnId, cause, @@ -3012,7 +3019,7 @@ export function makeClaudeAdapterV2( const runtime: ProviderAdapterV2SessionRuntime = { instanceId: adapterOptions.instanceId, - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, rawEvents: Stream.empty, @@ -3023,6 +3030,7 @@ export function makeClaudeAdapterV2( const nativeThreadId = yield* queryRunner.allocateSessionId; return makeProviderThread({ idAllocator, + providerInstanceId: adapterOptions.instanceId, appThreadId: threadInput.threadId, providerSessionId: input.providerSessionId, nativeThreadId, @@ -3034,7 +3042,7 @@ export function makeClaudeAdapterV2( Effect.mapError( (cause) => new ProviderAdapterEnsureThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, threadId: threadInput.threadId, cause, }), @@ -3056,7 +3064,7 @@ export function makeClaudeAdapterV2( Effect.mapError( (cause) => new ProviderAdapterResumeThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerSessionId: input.providerSessionId, providerThreadId: threadInput.providerThread.id, cause, @@ -3074,20 +3082,20 @@ export function makeClaudeAdapterV2( ); if (pending === undefined) { return yield* new ProviderAdapterRuntimeRequestResponseError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, requestId: requestInput.requestId, cause: new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `No pending Claude runtime request ${requestInput.requestId}.`, }), }); } if (requestInput.decision === undefined) { return yield* new ProviderAdapterRuntimeRequestResponseError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, requestId: requestInput.requestId, cause: new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Claude ${pending.requestKind} request ${requestInput.requestId} requires an approval decision.`, }), }); @@ -3100,7 +3108,7 @@ export function makeClaudeAdapterV2( Schema.is(ProviderAdapterRuntimeRequestResponseError)(cause) ? cause : new ProviderAdapterRuntimeRequestResponseError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, requestId: requestInput.requestId, cause, }), @@ -3110,7 +3118,7 @@ export function makeClaudeAdapterV2( readThreadSnapshot: (snapshotInput) => Effect.fail( new ProviderAdapterReadThreadSnapshotError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: snapshotInput.providerThread.id, cause: "Claude V2 adapter does not implement snapshots.", }), @@ -3120,7 +3128,7 @@ export function makeClaudeAdapterV2( const currentTurn = yield* Ref.get(activeTurn); if (currentTurn !== null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Cannot roll back Claude provider thread ${rollbackInput.providerThread.id} while provider turn ${currentTurn.providerTurnId} is active.`, }); } @@ -3135,6 +3143,7 @@ export function makeClaudeAdapterV2( providerThread: { ...makeProviderThread({ idAllocator, + providerInstanceId: adapterOptions.instanceId, appThreadId: rollbackInput.providerThread.appThreadId, ...(rollbackInput.providerThread.ownerNodeId === null ? {} @@ -3163,7 +3172,7 @@ export function makeClaudeAdapterV2( resumeSessionAt === null ? null : { - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, nativeId: resumeSessionAt, strength: "weak" as const, }, @@ -3182,7 +3191,7 @@ export function makeClaudeAdapterV2( Schema.is(ProviderAdapterRollbackThreadError)(cause) ? cause : new ProviderAdapterRollbackThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: rollbackInput.providerThread.id, cause, }), @@ -3194,7 +3203,7 @@ export function makeClaudeAdapterV2( const currentTurn = yield* Ref.get(activeTurn); if (currentTurn !== null) { return yield* new ProviderAdapterProtocolError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, detail: `Cannot fork Claude provider thread ${forkInput.sourceProviderThread.id} while provider turn ${currentTurn.providerTurnId} is active.`, }); } @@ -3220,6 +3229,7 @@ export function makeClaudeAdapterV2( const now = yield* DateTime.now; return makeProviderThread({ idAllocator, + providerInstanceId: adapterOptions.instanceId, appThreadId: forkInput.targetThreadId, ownerNodeId: forkInput.ownerNodeId ?? null, providerSessionId: input.providerSessionId, @@ -3238,7 +3248,7 @@ export function makeClaudeAdapterV2( Effect.mapError( (cause) => new ProviderAdapterForkThreadError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerThreadId: forkInput.sourceProviderThread.id, cause, }), @@ -3254,7 +3264,7 @@ export function makeClaudeAdapterV2( Effect.mapError( (cause) => new ProviderAdapterOpenSessionError({ - provider: CLAUDE_PROVIDER, + driver: CLAUDE_PROVIDER, providerSessionId: input.providerSessionId, cause, }), diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 0fe5efff2a..398ab91b70 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -22,6 +22,7 @@ import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts"; import { buildCodexTurnStartParams, + CODEX_DRIVER_KIND, codexAppServerMcpLaunchConfig, makeCodexAppServerProtocolLogger, makeCodexAppServerSpawnCommand, @@ -284,12 +285,13 @@ describe("CodexAdapterV2 rollback mapping", () => { const providerThreadId = ProviderThreadId.make("provider-thread-codex-rollback"); const providerThread: OrchestrationV2ProviderThread = { id: providerThreadId, - provider: "codex", + driver: CODEX_DRIVER_KIND, + providerInstanceId: ProviderInstanceId.make("codex"), providerSessionId: ProviderSessionId.make("provider-session-codex-rollback"), appThreadId: ThreadId.make("thread-codex-rollback"), ownerNodeId: null, nativeThreadRef: { - provider: "codex", + driver: CODEX_DRIVER_KIND, nativeId: "native-thread-codex-rollback", strength: "strong", }, @@ -312,7 +314,7 @@ describe("CodexAdapterV2 rollback mapping", () => { nodeId: NodeId.make(`node-${id}`), runAttemptId: RunAttemptId.make(`run-attempt-${id}`), nativeTurnRef: { - provider: "codex", + driver: CODEX_DRIVER_KIND, nativeId: `native-${id}`, strength: "strong", }, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts index b4f992cac3..c11dab1a79 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts @@ -19,7 +19,7 @@ import { CodexAppServerClientFactory, layer as codexAdapterLayer } from "./Codex export class CodexReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( "CodexReplayTranscriptDecodeError", { - provider: Schema.optional(Schema.String), + driver: Schema.optional(Schema.String), protocol: Schema.optional(Schema.String), scenario: Schema.optional(Schema.String), cause: Schema.Defect(), @@ -142,7 +142,7 @@ export function makeCodexProviderAdapterRegistryReplayLayer(input: { Effect.mapError( (cause) => new ProviderAdapterOpenSessionError({ - provider: "codex", + driver: CODEX_DRIVER_KIND, providerSessionId: openInput.providerSessionId, cause, }), @@ -182,7 +182,7 @@ export const CodexOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness CodexReplay.CodexAppServerReplayTranscript, CodexOrchestratorReplayHarnessError > = { - provider: "codex", + driver: CODEX_DRIVER_KIND, decodeTranscript: (transcript) => Schema.decodeUnknownEffect(CodexReplay.CodexAppServerReplayTranscript)(transcript).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 6812f74e36..ff37655da9 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -80,8 +80,8 @@ import { subagentThreadTitle, } from "../SubagentProjection.ts"; -const CODEX_PROVIDER = "codex" as const; -export const CODEX_DRIVER_KIND = ProviderDriverKind.make(CODEX_PROVIDER); +const CODEX_PROVIDER = ProviderDriverKind.make("codex"); +export const CODEX_DRIVER_KIND = CODEX_PROVIDER; export const CODEX_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CODEX_DRIVER_KIND); const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({}); const CODEX_CLIENT_INFO = { @@ -186,7 +186,7 @@ export const CodexProviderCapabilitiesV2 = { function toProtocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError { return new ProviderAdapterProtocolError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, detail, ...(payload === undefined ? {} : { payload }), }); @@ -322,7 +322,7 @@ export function projectCodexDynamicToolItem( function codexNativeItemRef(nativeItemId: string) { return { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: nativeItemId, strength: "strong" as const, }; @@ -409,12 +409,14 @@ function answerValueToStrings(value: unknown): ReadonlyArray { function toCodexUserInputAnswers( answers: ProviderUserInputAnswers, + allowedQuestionIds: ReadonlySet, ): CodexSchema.ToolRequestUserInputResponse["answers"] { return Object.fromEntries( - Object.entries(answers).map(([questionId, value]) => [ - questionId, - { answers: [...answerValueToStrings(value)] }, - ]), + Object.entries(answers).flatMap(([questionId, value]) => + allowedQuestionIds.has(questionId) + ? [[questionId, { answers: [...answerValueToStrings(value)] }]] + : [], + ), ); } @@ -534,13 +536,15 @@ export function buildCodexTurnStartParams(input: { function providerSession(input: { readonly providerSessionId: OrchestrationV2ProviderSession["id"]; + readonly providerInstanceId: ProviderInstanceId; readonly cwd: string | null; readonly model: string; readonly now: DateTime.Utc; }): OrchestrationV2ProviderSession { return { id: input.providerSessionId, - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, + providerInstanceId: input.providerInstanceId, status: "ready", cwd: input.cwd ?? process.cwd(), model: input.model, @@ -568,6 +572,7 @@ function providerThreadFromCodexThread(input: { readonly idAllocator: IdAllocatorV2Shape; readonly ownerNodeId: OrchestrationV2ProviderThread["ownerNodeId"]; readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; + readonly providerInstanceId: ProviderInstanceId; readonly thread: { readonly createdAt: number; readonly forkedFromId?: string | null; @@ -578,15 +583,16 @@ function providerThreadFromCodexThread(input: { }): OrchestrationV2ProviderThread { return { id: input.idAllocator.derive.providerThread({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeThreadId: input.thread.id, }), - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, + providerInstanceId: input.providerInstanceId, providerSessionId: input.providerSessionId, appThreadId: input.appThreadId, ownerNodeId: input.ownerNodeId, nativeThreadRef: { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: input.thread.id, strength: "strong" as const, }, @@ -639,7 +645,7 @@ const resolveCodexForkRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveForkR ); if (rollbackTurnCount === null) { return yield* new ProviderAdapterForkThreadError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThreadId: input.sourceProviderThread.id, cause: `Cannot fork Codex thread from provider turn ${input.providerTurnId}: source turn was not found in provider thread ${input.sourceProviderThread.id}.`, }); @@ -658,7 +664,7 @@ export const resolveCodexRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveRo case "provider_turn": { if (input.target.providerTurn.providerThreadId !== input.providerThread.id) { return yield* new ProviderAdapterRollbackThreadError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThreadId: input.providerThread.id, cause: `Cannot roll back Codex thread ${input.providerThread.id} to provider turn ${input.target.providerTurn.id}: target turn belongs to provider thread ${input.target.providerTurn.providerThreadId}.`, }); @@ -670,7 +676,7 @@ export const resolveCodexRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveRo ); if (rollbackTurnCount === null) { return yield* new ProviderAdapterRollbackThreadError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThreadId: input.providerThread.id, cause: `Cannot roll back Codex thread ${input.providerThread.id} to provider turn ${input.target.providerTurn.id}: target turn was not found in durable provider turn history.`, }); @@ -842,7 +848,7 @@ export const makeCodexAppServerClientFactoryCommandLayer = ( Effect.mapError( (cause) => new ProviderAdapterOpenSessionError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerSessionId: input.providerSessionId, cause, }), @@ -917,7 +923,7 @@ export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer< Effect.mapError( (cause) => new ProviderAdapterOpenSessionError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerSessionId: input.providerSessionId, cause, }), @@ -1035,7 +1041,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi return ProviderAdapterV2.of({ instanceId: adapterOptions.instanceId, - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), openSession: (input) => Effect.gen(function* () { @@ -1064,12 +1070,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const now = yield* DateTime.now; const session = providerSession({ providerSessionId: input.providerSessionId, + providerInstanceId: adapterOptions.instanceId, cwd: input.runtimePolicy.cwd, model: input.modelSelection.model, now, }); const events = yield* Queue.unbounded(); const activeTurns = yield* Ref.make(new Map()); + const pendingRootTurns = yield* Ref.make(new Map()); const turnWaiters = yield* Ref.make(new Map>()); const subagentThreads = yield* Ref.make(new Map()); const pendingSubagentTurns = yield* Ref.make( @@ -1088,6 +1096,64 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const emitProviderEvent = (event: ProviderAdapterV2Event) => Queue.offer(events, event).pipe(Effect.asVoid); + const registerRootTurn = (input: { + readonly turnInput: ProviderAdapterV2TurnInput; + readonly nativeTurnId: string; + readonly startedAt: DateTime.Utc; + }) => + Effect.gen(function* () { + const existing = (yield* Ref.get(activeTurns)).get(input.nativeTurnId); + if (existing !== undefined) { + return existing; + } + const providerTurnId = idAllocator.derive.providerTurn({ + driver: CODEX_PROVIDER, + nativeTurnId: input.nativeTurnId, + }); + const context: ActiveCodexTurnContext = { + input: input.turnInput, + projectionThreadId: input.turnInput.threadId, + projectionRunId: input.turnInput.runId, + nativeTurnId: input.nativeTurnId, + providerThread: input.turnInput.providerThread, + providerTurnId, + providerTurnOrdinal: input.turnInput.providerTurnOrdinal, + providerNodeId: input.turnInput.rootNodeId, + providerNodeKind: "root_turn", + providerNodeStartedAt: input.startedAt, + itemParentNodeId: input.turnInput.rootNodeId, + rootNodeId: input.turnInput.rootNodeId, + subagent: null, + startedAt: input.startedAt, + }; + yield* Ref.update(activeTurns, (current) => { + const updated = new Map(current); + updated.set(input.nativeTurnId, context); + return updated; + }); + yield* emitProviderEvent({ + type: "provider_turn.updated", + driver: CODEX_PROVIDER, + threadId: input.turnInput.threadId, + providerTurn: { + id: providerTurnId, + providerThreadId: input.turnInput.providerThread.id, + nodeId: input.turnInput.rootNodeId, + runAttemptId: input.turnInput.attemptId, + nativeTurnRef: { + driver: CODEX_PROVIDER, + nativeId: input.nativeTurnId, + strength: "strong", + }, + ordinal: input.turnInput.providerTurnOrdinal, + status: "running", + startedAt: input.startedAt, + completedAt: null, + }, + }); + return context; + }); + const findActiveTurnByNativeThreadId = (nativeThreadId: string) => Effect.gen(function* () { const turns = Array.from((yield* Ref.get(activeTurns)).values()); @@ -1096,6 +1162,19 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi ); }); + const awaitActiveTurn = ( + nativeTurnId: string, + attemptsRemaining = 1_000, + ): Effect.Effect => + Effect.gen(function* () { + const context = (yield* Ref.get(activeTurns)).get(nativeTurnId); + if (context !== undefined || attemptsRemaining <= 0) { + return context; + } + yield* Effect.yieldNow; + return yield* awaitActiveTurn(nativeTurnId, attemptsRemaining - 1); + }); + const resolveItemOrdinal = (context: ActiveCodexTurnContext, nativeItemId: string) => Effect.gen(function* () { const existing = (yield* Ref.get(itemOrdinals)).get(nativeItemId); @@ -1156,12 +1235,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* emitProviderEvent({ type: "subagent.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, subagent: task, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: { id: input.subagent.turnItemId, threadId: task.threadId, @@ -1180,7 +1259,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi type: "subagent", subagentId: task.id, origin: task.origin, - provider: task.provider, + driver: task.driver, + providerInstanceId: task.providerInstanceId, childThreadId: task.childThreadId, prompt: task.prompt, result: task.result, @@ -1194,7 +1274,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi ) => Effect.gen(function* () { const providerTurnId = idAllocator.derive.providerTurn({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeTurnId: turn.nativeTurnId, }); const providerTurnOrdinal = yield* nextProviderTurnOrdinal( @@ -1205,7 +1285,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi providerTurnOrdinal === 1 ? subagent.childRootNodeId : idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: `${turn.nativeTurnId}:thread-root`, }); const activeContext: ActiveCodexTurnContext = { @@ -1232,7 +1312,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const now = yield* DateTime.now; yield* emitProviderEvent({ type: "provider_thread.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThread: { ...subagent.providerThread, status: "active", @@ -1241,7 +1321,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "provider_turn.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: subagent.childThreadId, providerTurn: { id: providerTurnId, @@ -1249,7 +1329,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi nodeId: providerNodeId, runAttemptId: null, nativeTurnRef: { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: turn.nativeTurnId, strength: "strong", }, @@ -1261,7 +1341,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: { id: providerNodeId, threadId: subagent.childThreadId, @@ -1324,29 +1404,30 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const nativeItemId = `${input.item.id}:${nativeThreadId}`; const subagentNodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId, }); const childRootNodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: `${nativeItemId}:thread-root`, }); const childThreadId = idAllocator.derive.threadFromProviderThread({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeThreadId, }); const turnItemOrdinal = yield* resolveItemOrdinal(input.context, nativeItemId); const providerThread = { id: idAllocator.derive.providerThread({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeThreadId, }), - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, + providerInstanceId: input.context.input.modelSelection.instanceId, providerSessionId: input.context.providerThread.providerSessionId, appThreadId: childThreadId, ownerNodeId: null, nativeThreadRef: { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: nativeThreadId, strength: "strong" as const, }, @@ -1369,7 +1450,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi parentNodeId: input.context.rootNodeId, origin: "provider_native", createdBy: "agent", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, + providerInstanceId: input.context.input.modelSelection.instanceId, providerThreadId: providerThread.id, childThreadId, nativeTaskRef: codexNativeItemRef(nativeItemId), @@ -1395,7 +1477,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi ordinal: index + 1, startedAt: now, turnItemId: idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId, }), turnItemOrdinal, @@ -1457,11 +1539,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const promptNativeItemId = `${nativeItemId}:prompt`; const promptArtifacts = makeSubagentConversationArtifacts({ messageId: idAllocator.derive.messageFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: promptNativeItemId, }), turnItemId: idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: promptNativeItemId, }), threadId: childThreadId, @@ -1476,12 +1558,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "app_thread.created", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, appThread: childThread, }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: { id: subagentNodeId, threadId: input.context.input.threadId, @@ -1502,7 +1584,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: { id: childRootNodeId, threadId: childThreadId, @@ -1523,17 +1605,17 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "provider_thread.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThread, }); yield* emitProviderEvent({ type: "message.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, message: promptArtifacts.message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: promptArtifacts.turnItem, }); yield* emitSubagentTaskUpdate({ @@ -1603,7 +1685,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const planId = yield* idAllocator.allocate.plan({ threadId: context.projectionThreadId, ...(context.projectionRunId === null ? {} : { runId: context.projectionRunId }), - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, }); const toCodexInput = ( @@ -2275,16 +2357,16 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.gen(function* () { const completedAt = yield* DateTime.now; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const ordinal = yield* resolveItemOrdinal(context, item.id); const messageId = idAllocator.derive.messageFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const node: OrchestrationV2ExecutionNode = { @@ -2361,11 +2443,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const ordinal = yield* resolveItemOrdinal(context, item.id); const artifacts = makeSubagentConversationArtifacts({ messageId: idAllocator.derive.messageFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }), turnItemId: idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }), threadId: context.projectionThreadId, @@ -2380,12 +2462,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "message.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, message: artifacts.message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); return true; @@ -2404,11 +2486,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const status = codexItemStatus(item.status); const completedAt = status.completed ? updatedAt : null; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const ordinal = yield* resolveItemOrdinal(context, item.id); @@ -2473,11 +2555,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const status = codexItemStatus(item.status); const completedAt = status.completed ? updatedAt : null; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const ordinal = yield* resolveItemOrdinal(context, item.id); @@ -2529,11 +2611,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const updatedAt = yield* DateTime.now; const completedAt = input.completed ? updatedAt : null; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.item.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.item.id, }); const ordinal = yield* resolveItemOrdinal(input.context, input.item.id); @@ -2586,11 +2668,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const status = codexItemStatus(item.status); const completedAt = status.completed ? updatedAt : null; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: item.id, }); const ordinal = yield* resolveItemOrdinal(context, item.id); @@ -2647,11 +2729,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const completedAt = input.completed === true ? updatedAt : null; const planId = yield* resolvePlanId(input.context, input.nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.nativeItemId, }); const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); @@ -2717,11 +2799,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const completedAt = input.completed === true ? updatedAt : null; const planId = yield* resolvePlanId(input.context, input.nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.nativeItemId, }); const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); @@ -2785,7 +2867,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.gen(function* () { const createdAt = yield* DateTime.now; const parentNodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.nativeItemId, }); const ordinal = yield* resolveItemOrdinal( @@ -2793,7 +2875,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi `${input.nativeItemId}:approval:${input.nativeRequestId}`, ); const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerTurnId: input.context.providerTurnId, nativeRequestId: input.nativeRequestId, }); @@ -2826,7 +2908,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi nodeId, providerTurnId: input.context.providerTurnId, nativeRequestRef: { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: input.nativeRequestId, strength: "strong", }, @@ -2873,7 +2955,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.gen(function* () { const createdAt = yield* DateTime.now; const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerTurnId: input.context.providerTurnId, nativeRequestId: input.nativeRequestId, }); @@ -2894,11 +2976,11 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi })) ?? [], })); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeItemId: input.nativeItemId, }); const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); @@ -2924,7 +3006,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi nodeId, providerTurnId: input.context.providerTurnId, nativeRequestRef: { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: input.nativeRequestId, strength: "strong", }, @@ -2969,7 +3051,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerNotification("item/plan/delta", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return; } @@ -2987,17 +3069,17 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "plan.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, plan: artifacts.plan, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); }).pipe(Effect.orDie), @@ -3005,7 +3087,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerNotification("turn/plan/updated", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return; } @@ -3024,17 +3106,17 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "plan.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, plan: artifacts.plan, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); }).pipe(Effect.orDie), @@ -3046,6 +3128,20 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi if (context !== undefined) { return; } + const pendingRootTurn = (yield* Ref.get(pendingRootTurns)).get(payload.threadId); + if (pendingRootTurn !== undefined) { + yield* registerRootTurn({ + turnInput: pendingRootTurn, + nativeTurnId: payload.turn.id, + startedAt: codexTimestamp(payload.turn.startedAt), + }); + yield* Ref.update(pendingRootTurns, (current) => { + const updated = new Map(current); + updated.delete(payload.threadId); + return updated; + }); + return; + } yield* rememberSubagentTurnStarted({ nativeThreadId: payload.threadId, nativeTurnId: payload.turn.id, @@ -3056,7 +3152,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerNotification("item/started", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return; } @@ -3071,12 +3167,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); return; @@ -3086,12 +3182,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const artifacts = yield* buildDynamicToolArtifacts(context, payload.item); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); return; @@ -3108,12 +3204,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); }).pipe(Effect.orDie), @@ -3121,7 +3217,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerNotification("item/completed", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return; } @@ -3136,12 +3232,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); return; @@ -3151,12 +3247,12 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const artifacts = yield* buildDynamicToolArtifacts(context, payload.item); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); return; @@ -3167,12 +3263,44 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi if (artifacts === null) { return; } - const markdown = yield* Ref.modify(planDeltas, (current) => { - const updated = new Map(current); - const next = `${updated.get(payload.itemId) ?? ""}${payload.delta}`; - updated.set(payload.itemId, next); - return [next, updated]; + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: artifacts.node, }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: artifacts.turnItem, + }); + return; + } + + if (payload.item.type === "webSearch") { + const artifacts = yield* buildWebSearchArtifacts({ + context, + item: payload.item, + completed: true, + }); + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: artifacts.node, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: artifacts.turnItem, + }); + return; + } + + if (payload.item.type === "plan") { + const deltas = yield* Ref.get(planDeltas); + const markdown = + payload.item.text.length > 0 + ? payload.item.text + : (deltas.get(payload.item.id) ?? ""); const artifacts = yield* buildProposedPlanArtifacts({ context, nativeItemId: payload.itemId, @@ -3181,17 +3309,17 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "plan.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, plan: artifacts.plan, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); }).pipe(Effect.orDie), @@ -3237,17 +3365,17 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "message.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, message: artifacts.message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); if ( @@ -3266,7 +3394,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return yield* toProtocolError( `No active Codex turn context for approval turn ${payload.turnId}.`, @@ -3297,18 +3425,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: artifacts.node.threadId, runtimeRequest: artifacts.request, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); @@ -3329,7 +3457,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return yield* toProtocolError( `No active Codex turn context for file change approval turn ${payload.turnId}.`, @@ -3357,18 +3485,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: artifacts.node.threadId, runtimeRequest: artifacts.request, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); @@ -3389,7 +3517,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerRequest("item/permissions/requestApproval", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return yield* toProtocolError( `No active Codex turn context for permissions approval turn ${payload.turnId}.`, @@ -3418,18 +3546,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: artifacts.node.threadId, runtimeRequest: artifacts.request, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); @@ -3480,18 +3608,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: artifacts.node.threadId, runtimeRequest: artifacts.request, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); @@ -3540,18 +3668,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: artifacts.node.threadId, runtimeRequest: artifacts.request, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); @@ -3572,7 +3700,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi yield* client.handleServerRequest("item/tool/requestUserInput", (payload) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); + const context = yield* awaitActiveTurn(payload.turnId); if (context === undefined) { return yield* toProtocolError( `No active Codex turn context for user input request turn ${payload.turnId}.`, @@ -3598,18 +3726,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }); yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: artifacts.node, }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: artifacts.node.threadId, runtimeRequest: artifacts.request, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, turnItem: artifacts.turnItem, }); @@ -3623,7 +3751,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi ), ); return { - answers: toCodexUserInputAnswers(resolved), + answers: toCodexUserInputAnswers( + resolved, + new Set(payload.questions.map((question) => question.id)), + ), } satisfies CodexSchema.ToolRequestUserInputResponse; }).pipe(Effect.orDie), ); @@ -3638,7 +3769,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const status = mapCodexTurnStatus(payload.turn.status); yield* emitProviderEvent({ type: "provider_turn.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: context.projectionThreadId, providerTurn: { id: context.providerTurnId, @@ -3646,7 +3777,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi nodeId: context.providerNodeId, runAttemptId: context.subagent === null ? context.input.attemptId : null, nativeTurnRef: { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: payload.turn.id, strength: "strong", }, @@ -3659,7 +3790,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi if (context.subagent !== null) { yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: { id: context.providerNodeId, threadId: context.projectionThreadId, @@ -3679,14 +3810,18 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }, }); yield* emitProviderEvent({ - type: "plan.updated", - provider: CODEX_PROVIDER, - plan: artifacts.plan, + type: "provider_thread.updated", + driver: CODEX_PROVIDER, + providerThread: { + ...context.providerThread, + status: "idle", + updatedAt: completedAt, + }, }); if (context.providerTurnOrdinal === 1) { yield* emitProviderEvent({ type: "node.updated", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, node: { id: context.subagent.subagentNodeId, threadId: context.subagent.parentContext.projectionThreadId, @@ -3715,7 +3850,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi if (context.subagent === null) { yield* emitProviderEvent({ type: "turn.terminal", - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerTurnId: context.providerTurnId, status: providerTurnStatusToTerminal(status), }); @@ -3733,8 +3868,8 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi ); const runtime: ProviderAdapterV2SessionRuntime = { - instanceId: CODEX_DEFAULT_INSTANCE_ID, - provider: CODEX_PROVIDER, + instanceId: adapterOptions.instanceId, + driver: CODEX_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, rawEvents: Stream.empty, @@ -3749,13 +3884,14 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi idAllocator, ownerNodeId: null, providerSessionId: input.providerSessionId, + providerInstanceId: adapterOptions.instanceId, thread: response.thread, }), ), Effect.mapError( (cause) => new ProviderAdapterEnsureThreadError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, threadId: threadInput.threadId, cause: normalizeCodexCause(cause), }), @@ -3768,36 +3904,16 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi return; } - const artifacts = yield* buildWebSearchArtifacts({ - context, - item: payload.item, - completed: false, - }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - provider: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); - }).pipe(Effect.orDie), - ); - - yield* client.handleServerNotification("item/completed", (payload) => - Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); - if (context === undefined) { - return; - } - - if (payload.item.type === "commandExecution") { - const artifacts = yield* buildCommandExecutionArtifacts(context, payload.item); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, + const response = yield* ensureInitialized.pipe( + Effect.andThen(client.request("thread/resume", { threadId: nativeThreadId })), + ); + return { + ...threadInput.providerThread, + providerSessionId: input.providerSessionId, + providerInstanceId: adapterOptions.instanceId, + status: "idle", + nativeThreadRef: { + driver: CODEX_PROVIDER, nativeId: response.thread.id, strength: "strong", }, @@ -3808,7 +3924,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.mapError( (cause) => new ProviderAdapterResumeThreadError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerSessionId: input.providerSessionId, providerThreadId: threadInput.providerThread.id, cause: normalizeCodexCause(cause), @@ -3826,403 +3942,52 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi runtimePolicy: turnInput.runtimePolicy, model: turnInput.modelSelection.model, }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, - }); - const providerTurnOrdinal = turnInput.providerTurnOrdinal; - const context: ActiveCodexTurnContext = { - input: turnInput, - projectionThreadId: turnInput.threadId, - projectionRunId: turnInput.runId, - nativeTurnId, - providerThread: turnInput.providerThread, - providerTurnId: pTurnId, - providerTurnOrdinal, - providerNodeId: turnInput.rootNodeId, - providerNodeKind: "root_turn", - providerNodeStartedAt: startedAt, - itemParentNodeId: turnInput.rootNodeId, - rootNodeId: turnInput.rootNodeId, - subagent: null, - startedAt, - }; - yield* Ref.update(activeTurns, (current) => { + yield* Ref.update(pendingRootTurns, (current) => { const updated = new Map(current); - updated.set(String(artifacts.request.id), { - type: "approval", - requestId: artifacts.request.id, - requestKind: "command", - decision, - }); + updated.set(threadId, turnInput); return updated; }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, + const started = yield* client.request("turn/start", turnStartParams); + const nativeTurnId = started.turn.id; + const startedAt = codexTimestamp(started.turn.startedAt); + yield* registerRootTurn({ turnInput, nativeTurnId, startedAt }); + yield* Ref.update(pendingRootTurns, (current) => { + const updated = new Map(current); + updated.delete(threadId); + return updated; }); - yield* emitProviderEvent({ - type: "runtime_request.updated", - provider: CODEX_PROVIDER, - runtimeRequest: artifacts.request, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - provider: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); - - const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring( - Ref.update(pendingRuntimeRequests, (current) => { + }).pipe( + Effect.ensuring( + Effect.flatMap(getNativeThreadId(turnInput.providerThread), (threadId) => + Ref.update(pendingRootTurns, (current) => { const updated = new Map(current); - updated.delete(String(artifacts.request.id)); + updated.delete(threadId); return updated; }), - ), - ); - return { - decision: resolved, - } satisfies CodexSchema.CommandExecutionRequestApprovalResponse; - }).pipe(Effect.orDie), - ); - - yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) => + ).pipe(Effect.ignore), + ), + Effect.mapError( + (cause) => + new ProviderAdapterTurnStartError({ + driver: CODEX_PROVIDER, + threadId: turnInput.threadId, + providerThreadId: turnInput.providerThread.id, + runId: turnInput.runId, + cause, + }), + ), + ), + steerTurn: (turnInput) => Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); - if (context === undefined) { + const threadId = yield* getNativeThreadId(turnInput.providerThread); + const activeTurn = Array.from((yield* Ref.get(activeTurns)).values()).find( + (candidate) => candidate.providerTurnId === turnInput.providerTurnId, + ); + if (activeTurn === undefined) { return yield* toProtocolError( - `No active Codex turn context for file change approval turn ${payload.turnId}.`, - payload, + `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`, ); } - - const artifacts = yield* buildApprovalRequestArtifacts({ - context, - nativeItemId: payload.itemId, - nativeRequestId: payload.itemId, - requestKind: "file-change", - ...(payload.reason === undefined ? {} : { prompt: payload.reason }), - }); - const decision = yield* Deferred.make(); - yield* Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.set(String(artifacts.request.id), { - type: "approval", - requestId: artifacts.request.id, - requestKind: "file-change", - decision, - }); - return updated; - }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "runtime_request.updated", - provider: CODEX_PROVIDER, - runtimeRequest: artifacts.request, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - provider: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); - - const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring( - Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.delete(String(artifacts.request.id)); - return updated; - }), - ), - ); - return { - decision: resolved, - } satisfies CodexSchema.FileChangeRequestApprovalResponse; - }).pipe(Effect.orDie), - ); - - yield* client.handleServerRequest("item/permissions/requestApproval", (payload) => - Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); - if (context === undefined) { - return yield* toProtocolError( - `No active Codex turn context for permissions approval turn ${payload.turnId}.`, - payload, - ); - } - - const requestKind = providerRequestKindFromPermissions(payload.permissions); - const artifacts = yield* buildApprovalRequestArtifacts({ - context, - nativeItemId: payload.itemId, - nativeRequestId: payload.itemId, - requestKind, - ...(payload.reason === undefined ? {} : { prompt: payload.reason }), - }); - const decision = yield* Deferred.make(); - yield* Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.set(String(artifacts.request.id), { - type: "approval", - requestId: artifacts.request.id, - requestKind, - decision, - }); - return updated; - }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "runtime_request.updated", - provider: CODEX_PROVIDER, - runtimeRequest: artifacts.request, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - provider: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); - - const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring( - Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.delete(String(artifacts.request.id)); - return updated; - }), - ), - ); - return permissionsResponseFromDecision({ - decision: resolved, - permissions: payload.permissions, - }); - }).pipe(Effect.orDie), - ); - - yield* client.handleServerRequest("execCommandApproval", (payload) => - Effect.gen(function* () { - const context = yield* findActiveTurnByNativeThreadId(payload.conversationId); - if (context === undefined) { - return yield* toProtocolError( - `No active Codex turn context for exec approval thread ${payload.conversationId}.`, - payload, - ); - } - - const nativeRequestId = payload.approvalId ?? payload.callId; - const artifacts = yield* buildApprovalRequestArtifacts({ - context, - nativeItemId: payload.callId, - nativeRequestId, - requestKind: "command", - prompt: payload.reason ?? payload.command.join(" "), - }); - const decision = yield* Deferred.make(); - yield* Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.set(String(artifacts.request.id), { - type: "approval", - requestId: artifacts.request.id, - requestKind: "command", - decision, - }); - return updated; - }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "runtime_request.updated", - provider: CODEX_PROVIDER, - runtimeRequest: artifacts.request, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - provider: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); - - const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring( - Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.delete(String(artifacts.request.id)); - return updated; - }), - ), - ); - return { - decision: approvalDecisionToLegacyReviewDecision(resolved), - } satisfies CodexSchema.ExecCommandApprovalResponse; - }).pipe(Effect.orDie), - ); - - yield* client.handleServerRequest("applyPatchApproval", (payload) => - Effect.gen(function* () { - const context = yield* findActiveTurnByNativeThreadId(payload.conversationId); - if (context === undefined) { - return yield* toProtocolError( - `No active Codex turn context for apply patch approval thread ${payload.conversationId}.`, - payload, - ); - } - - const artifacts = yield* buildApprovalRequestArtifacts({ - context, - nativeItemId: payload.callId, - nativeRequestId: payload.callId, - requestKind: "file-change", - prompt: payload.reason ?? Object.keys(payload.fileChanges).join(", "), - }); - const decision = yield* Deferred.make(); - yield* Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.set(String(artifacts.request.id), { - type: "approval", - requestId: artifacts.request.id, - requestKind: "file-change", - decision, - }); - return updated; - }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "runtime_request.updated", - provider: CODEX_PROVIDER, - runtimeRequest: artifacts.request, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - provider: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); - - const resolved = yield* Deferred.await(decision).pipe( - Effect.ensuring( - Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.delete(String(artifacts.request.id)); - return updated; - }), - ), - ); - return { - decision: approvalDecisionToLegacyReviewDecision(resolved), - } satisfies CodexSchema.ApplyPatchApprovalResponse; - }).pipe(Effect.orDie), - ); - - yield* client.handleServerRequest("item/tool/requestUserInput", (payload) => - Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turnId); - if (context === undefined) { - return yield* toProtocolError( - `No active Codex turn context for user input request turn ${payload.turnId}.`, - payload, - ); - } - - const artifacts = yield* buildUserInputRequestArtifacts({ - context, - nativeItemId: payload.itemId, - nativeRequestId: payload.itemId, - questions: payload.questions, - }); - const answers = yield* Deferred.make(); - yield* Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.set(String(artifacts.request.id), { - type: "user_input", - requestId: artifacts.request.id, - answers, - }); - return updated; - }); - yield* emitProviderEvent({ - type: "node.updated", - provider: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "runtime_request.updated", - provider: CODEX_PROVIDER, - runtimeRequest: artifacts.request, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - provider: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); - - const resolved = yield* Deferred.await(answers).pipe( - Effect.ensuring( - Ref.update(pendingRuntimeRequests, (current) => { - const updated = new Map(current); - updated.delete(String(artifacts.request.id)); - return updated; - }), - ), - ); - return { - answers: toCodexUserInputAnswers(resolved), - } satisfies CodexSchema.ToolRequestUserInputResponse; - }).pipe(Effect.orDie), - ); - - yield* client.handleServerNotification("turn/completed", (payload) => - Effect.gen(function* () { - const context = (yield* Ref.get(activeTurns)).get(payload.turn.id); - if (context === undefined) { - return; - } - const completedAt = codexTimestamp(payload.turn.completedAt); - const status = mapCodexTurnStatus(payload.turn.status); - yield* emitProviderEvent({ - type: "provider_turn.updated", - provider: CODEX_PROVIDER, - threadId: turnInput.threadId, - providerTurn: { - id: context.providerTurnId, - providerThreadId: context.input.providerThread.id, - nodeId: context.input.rootNodeId, - runAttemptId: context.input.attemptId, - nativeTurnRef: { - provider: CODEX_PROVIDER, - nativeId: payload.turn.id, - strength: "strong", - }, - ordinal: context.providerTurnOrdinal, - status, - startedAt: context.startedAt, - completedAt, - }, - }); - yield* emitProviderEvent({ - type: "turn.terminal", - provider: CODEX_PROVIDER, - providerTurnId: context.providerTurnId, - status: providerTurnStatusToTerminal(status), - }); - const waiter = (yield* Ref.get(turnWaiters)).get(payload.turn.id); - if (waiter !== undefined) { - yield* Deferred.succeed(waiter, undefined); - } yield* Ref.update(activeTurns, (current) => { const updated = new Map(current); updated.delete(payload.turn.id); @@ -4231,33 +3996,21 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }), ); - const runtime: ProviderAdapterV2SessionRuntime = { - provider: CODEX_PROVIDER, - providerSessionId: input.providerSessionId, - providerSession: session, - rawEvents: Stream.empty, - events: Stream.fromQueue(events), - ensureThread: (threadInput) => - ensureInitialized.pipe( - Effect.andThen(client.request("thread/start", {})), - Effect.map( - (response): OrchestrationV2ProviderThread => - providerThreadFromCodexThread({ - appThreadId: threadInput.threadId, - idAllocator, - ownerNodeId: null, - providerSessionId: input.providerSessionId, - thread: response.thread, - }), - ), - Effect.mapError( - (cause) => - new ProviderAdapterEnsureThreadError({ - provider: CODEX_PROVIDER, - threadId: threadInput.threadId, - cause: normalizeCodexCause(cause), - }), - ), + const codexInput = yield* toCodexInput(turnInput); + yield* client.request("turn/steer", { + expectedTurnId: activeTurn.nativeTurnId, + input: codexInput, + threadId, + }); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterSteerRunError({ + driver: CODEX_PROVIDER, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + cause, + }), ), resumeThread: (threadInput) => Effect.gen(function* () { @@ -4266,38 +4019,34 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi const response = yield* ensureInitialized.pipe( Effect.andThen(client.request("thread/resume", { threadId: nativeThreadId })), ); - return { - ...threadInput.providerThread, - providerSessionId: input.providerSessionId, - status: "idle", - nativeThreadRef: { - provider: CODEX_PROVIDER, - nativeId: response.thread.id, - strength: "strong", - }, - updatedAt: codexTimestamp(response.thread.updatedAt), - } satisfies OrchestrationV2ProviderThread; - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterResumeThreadError({ - provider: CODEX_PROVIDER, - providerSessionId: input.providerSessionId, - providerThreadId: threadInput.providerThread.id, - cause: normalizeCodexCause(cause), - }), - ), + } + yield* client.request("turn/interrupt", { + threadId, + turnId: activeTurn.nativeTurnId, + }); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterInterruptError({ + driver: CODEX_PROVIDER, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + cause, + }), ), - startTurn: (turnInput) => - Effect.gen(function* () { - const threadId = yield* getNativeThreadId(turnInput.providerThread); - - const codexInput = yield* toCodexInput(turnInput); - const turnStartParams = yield* buildTurnStartParams({ - nativeThreadId: threadId, - codexInput, - runtimePolicy: turnInput.runtimePolicy, - model: turnInput.modelSelection.model, + ), + respondToRuntimeRequest: (requestInput) => + Effect.gen(function* () { + const pending = (yield* Ref.get(pendingRuntimeRequests)).get( + String(requestInput.requestId), + ); + if (pending === undefined) { + return yield* new ProviderAdapterRuntimeRequestResponseError({ + driver: CODEX_PROVIDER, + requestId: requestInput.requestId, + cause: toProtocolError( + `No pending Codex runtime request ${requestInput.requestId}.`, + ), }); const started = yield* client.request("turn/start", turnStartParams); const nativeTurnId = started.turn.id; @@ -4412,17 +4161,32 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi ); if (pending === undefined) { return yield* new ProviderAdapterRuntimeRequestResponseError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, requestId: requestInput.requestId, cause: toProtocolError( `No pending Codex runtime request ${requestInput.requestId}.`, ), }); } - if (pending.type === "user_input") { - if (requestInput.answers === undefined) { - return yield* new ProviderAdapterRuntimeRequestResponseError({ - provider: CODEX_PROVIDER, + yield* Deferred.succeed(pending.answers, requestInput.answers); + return; + } + if (requestInput.decision === undefined) { + return yield* new ProviderAdapterRuntimeRequestResponseError({ + driver: CODEX_PROVIDER, + requestId: requestInput.requestId, + cause: toProtocolError( + `Codex ${pending.requestKind} request ${requestInput.requestId} requires an approval decision.`, + ), + }); + } + yield* Deferred.succeed(pending.decision, requestInput.decision); + }).pipe( + Effect.mapError((cause) => + Schema.is(ProviderAdapterRuntimeRequestResponseError)(cause) + ? cause + : new ProviderAdapterRuntimeRequestResponseError({ + driver: CODEX_PROVIDER, requestId: requestInput.requestId, cause: toProtocolError( `Codex user input request ${requestInput.requestId} requires answers.`, @@ -4484,29 +4248,20 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi }), ), ), - rollbackThread: (threadInput) => - Effect.gen(function* () { - const threadId = yield* getNativeThreadId(threadInput.providerThread); - const numTurns = - typeof threadInput.providerPayload === "object" && - threadInput.providerPayload !== null && - "numTurns" in threadInput.providerPayload && - typeof threadInput.providerPayload.numTurns === "number" - ? threadInput.providerPayload.numTurns - : 1; - const response = yield* ensureInitialized.pipe( - Effect.andThen(client.request("thread/rollback", { threadId, numTurns })), - ); - return { - providerThread: { - ...threadInput.providerThread, - nativeThreadRef: { - provider: CODEX_PROVIDER, - nativeId: response.thread.id, - strength: "strong" as const, - }, - status: "idle" as const, - updatedAt: codexTimestamp(response.thread.updatedAt), + ), + readThreadSnapshot: (threadInput) => + Effect.gen(function* () { + const threadId = yield* getNativeThreadId(threadInput.providerThread); + const response = yield* ensureInitialized.pipe( + Effect.andThen(client.request("thread/read", { threadId, includeTurns: true })), + ); + return { + providerThread: { + ...threadInput.providerThread, + nativeThreadRef: { + driver: CODEX_PROVIDER, + nativeId: response.thread.id, + strength: "strong" as const, }, nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef, updatedAt: codexTimestamp(response.thread.updatedAt), @@ -4520,7 +4275,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.mapError( (cause) => new ProviderAdapterReadThreadSnapshotError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThreadId: threadInput.providerThread.id, cause, }), @@ -4553,7 +4308,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi providerThread: { ...threadInput.providerThread, nativeThreadRef: { - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, nativeId: response.thread.id, strength: "strong" as const, }, @@ -4570,7 +4325,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.mapError( (cause) => new ProviderAdapterRollbackThreadError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThreadId: threadInput.providerThread.id, cause: normalizeCodexCause(cause), }), @@ -4584,23 +4339,66 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi Effect.mapError( (cause) => new ProviderAdapterForkThreadError({ - provider: CODEX_PROVIDER, + driver: CODEX_PROVIDER, providerThreadId: threadInput.sourceProviderThread.id, cause: normalizeCodexCause(cause), }), ), - ), - }; - return runtime; - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapterOpenSessionError({ - provider: CODEX_PROVIDER, + ); + const rollbackTurnCount = yield* resolveCodexForkRollbackTurnCount(threadInput); + const forkedThread = + rollbackTurnCount === 0 + ? response.thread + : (yield* ensureInitialized.pipe( + Effect.andThen( + client.request("thread/rollback", { + threadId: response.thread.id, + numTurns: rollbackTurnCount, + }), + ), + Effect.mapError( + (cause) => + new ProviderAdapterForkThreadError({ + driver: CODEX_PROVIDER, + providerThreadId: threadInput.sourceProviderThread.id, + cause: normalizeCodexCause(cause), + }), + ), + )).thread; + return providerThreadFromCodexThread({ + appThreadId: threadInput.targetThreadId, + idAllocator, + ownerNodeId: threadInput.ownerNodeId ?? null, providerSessionId: input.providerSessionId, - cause, - }), - ), + providerInstanceId: adapterOptions.instanceId, + thread: forkedThread, + forkedFrom: { + providerThreadId: threadInput.sourceProviderThread.id, + ...(threadInput.providerTurnId === undefined + ? {} + : { providerTurnId: threadInput.providerTurnId }), + }, + }); + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterForkThreadError({ + driver: CODEX_PROVIDER, + providerThreadId: threadInput.sourceProviderThread.id, + cause: normalizeCodexCause(cause), + }), + ), + ), + }; + return runtime; + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapterOpenSessionError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), ), }); }), diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts index 42d609c106..c5f0ab5cfa 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts @@ -58,7 +58,7 @@ const decodeCursorAgentSdkReplayTranscript = Schema.decodeUnknownEffect( export class CursorReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( "CursorReplayTranscriptDecodeError", { - provider: Schema.optional(Schema.String), + driver: Schema.optional(Schema.String), protocol: Schema.optional(Schema.String), scenario: Schema.optional(Schema.String), cause: Schema.Defect(), @@ -628,7 +628,7 @@ export const CursorOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarnes CursorAgentSdkReplayTranscript, CursorOrchestratorReplayHarnessError > = { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, decodeTranscript: (transcript) => decodeCursorAgentSdkReplayTranscript(transcript).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts index 2796f827cb..83372035de 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts @@ -24,7 +24,6 @@ import { type OrchestrationV2ProviderTurn, type OrchestrationV2Subagent, type OrchestrationV2TurnItem, - ProviderDriverKind, type ProviderInstanceId, type ThreadId, } from "@t3tools/contracts"; @@ -87,7 +86,7 @@ import { export { CURSOR_PROVIDER } from "./CursorAgentSdk.ts"; -export const CURSOR_DRIVER_KIND = ProviderDriverKind.make(CURSOR_PROVIDER); +export const CURSOR_DRIVER_KIND = CURSOR_PROVIDER; export const CURSOR_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CURSOR_DRIVER_KIND); const DEFAULT_CURSOR_SETTINGS = Schema.decodeSync(CursorSettings)({}); @@ -241,13 +240,15 @@ export function cursorMcpServers(threadId: ThreadId): Record Effect.succeed(CursorProviderCapabilitiesV2), openSession: Effect.fn("CursorAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { @@ -834,6 +837,7 @@ export function makeCursorAdapterV2( const createdAt = yield* DateTime.now; const session = providerSession({ providerSessionId: input.providerSessionId, + providerInstanceId: adapterOptions.instanceId, cwd: input.runtimePolicy.cwd, model: input.modelSelection.model, now: createdAt, @@ -882,7 +886,7 @@ export function makeCursorAdapterV2( const planId = yield* idAllocator.allocate.plan({ threadId: context.input.threadId, runId: context.input.runId, - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, }); yield* Ref.update(planIds, (current) => { const updated = new Map(current); @@ -912,25 +916,25 @@ export function makeCursorAdapterV2( const now = yield* DateTime.now; const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: segment.nativeItemId, }); const messageId = idAllocator.derive.messageFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: segment.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: segment.nativeItemId, }); const nativeItemRef = { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: segment.nativeItemId, strength: "weak" as const, }; yield* emitProviderEvent({ type: "node.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, node: { id: nodeId, threadId: context.input.threadId, @@ -951,7 +955,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "message.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, message: { createdBy: "agent", creationSource: "provider", @@ -969,7 +973,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem: { id: turnItemId, threadId: context.input.threadId, @@ -1004,21 +1008,21 @@ export function makeCursorAdapterV2( const now = yield* DateTime.now; const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: segment.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: segment.nativeItemId, }); const nativeItemRef = { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: segment.nativeItemId, strength: "weak" as const, }; yield* emitProviderEvent({ type: "node.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, node: { id: nodeId, threadId: context.input.threadId, @@ -1039,7 +1043,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem: { id: turnItemId, threadId: context.input.threadId, @@ -1105,15 +1109,15 @@ export function makeCursorAdapterV2( const failed = input.completed && cursorToolFailed(toolCall); const status = input.completed ? (failed ? "failed" : "completed") : "running"; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: active.callId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: active.callId, }); const nativeItemRef = { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: active.callId, strength: "strong" as const, }; @@ -1236,12 +1240,12 @@ export function makeCursorAdapterV2( } yield* emitProviderEvent({ type: "node.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, node, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem, }); }); @@ -1282,16 +1286,16 @@ export function makeCursorAdapterV2( const planId = yield* resolvePlanId(input.context, nativeItemId); const ordinal = yield* resolveItemOrdinal(input.context, nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId, }); const status = input.failed ? "failed" : input.completed ? "completed" : "running"; const nativeItemRef = { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: input.callId, strength: "strong" as const, }; @@ -1306,7 +1310,7 @@ export function makeCursorAdapterV2( }; yield* emitProviderEvent({ type: "node.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, node: { id: nodeId, threadId: input.context.input.threadId, @@ -1327,12 +1331,12 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "plan.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, plan, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem: { id: turnItemId, threadId: input.context.input.threadId, @@ -1368,23 +1372,23 @@ export function makeCursorAdapterV2( const planId = yield* resolvePlanId(input.context, nativeItemId); const ordinal = yield* resolveItemOrdinal(input.context, nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId, }); const status = input.failed ? "failed" : input.completed ? "completed" : "running"; const steps = cursorTodoSteps(input.toolCall); const nativeItemRef = { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: input.callId, strength: "strong" as const, }; yield* emitProviderEvent({ type: "node.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, node: { id: nodeId, threadId: input.context.input.threadId, @@ -1405,7 +1409,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "plan.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, plan: { id: planId, threadId: input.context.input.threadId, @@ -1418,7 +1422,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem: { id: turnItemId, threadId: input.context.input.threadId, @@ -1467,19 +1471,19 @@ export function makeCursorAdapterV2( const nodeId = existing?.task.id ?? idAllocator.derive.nodeFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId, }); const childRootNodeId = existing?.childRootNodeId ?? idAllocator.derive.nodeFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: `${nativeItemId}:child-root`, }); const childThreadId = existing?.childThreadId ?? idAllocator.derive.threadFromProviderThread({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeThreadId: `${input.context.run.runId}:task:${input.callId}`, }); const task: OrchestrationV2Subagent = { @@ -1490,11 +1494,12 @@ export function makeCursorAdapterV2( parentNodeId: input.context.input.rootNodeId, origin: "provider_native" as const, createdBy: "agent" as const, - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, + providerInstanceId: input.context.input.modelSelection.instanceId, providerThreadId: null, childThreadId, nativeTaskRef: { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: input.callId, strength: "strong" as const, }, @@ -1505,7 +1510,7 @@ export function makeCursorAdapterV2( startedAt: now, }), nativeTaskRef: { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: input.callId, strength: "strong" as const, }, @@ -1522,7 +1527,7 @@ export function makeCursorAdapterV2( turnItemId: existing?.turnItemId ?? idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId, }), turnItemOrdinal: @@ -1535,7 +1540,7 @@ export function makeCursorAdapterV2( if (existing === undefined) { yield* emitProviderEvent({ type: "app_thread.created", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, appThread: makeSubagentChildThread({ parentThread: input.context.input.appThread, childThreadId, @@ -1557,11 +1562,11 @@ export function makeCursorAdapterV2( const promptNativeId = `${nativeItemId}:prompt`; const promptArtifacts = makeSubagentConversationArtifacts({ messageId: idAllocator.derive.messageFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: promptNativeId, }), turnItemId: idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: promptNativeId, }), threadId: childThreadId, @@ -1569,7 +1574,7 @@ export function makeCursorAdapterV2( providerThreadId: null, providerTurnId: null, nativeItemRef: { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: promptNativeId, strength: "weak", }, @@ -1580,19 +1585,19 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "message.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, message: promptArtifacts.message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem: promptArtifacts.turnItem, }); } yield* emitProviderEvent({ type: "node.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, node: { id: nodeId, threadId: input.context.input.threadId, @@ -1613,7 +1618,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "node.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, node: { id: childRootNodeId, threadId: childThreadId, @@ -1634,12 +1639,12 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "subagent.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, subagent: task, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem: { id: subagent.turnItemId, threadId: input.context.input.threadId, @@ -1658,7 +1663,8 @@ export function makeCursorAdapterV2( type: "subagent", subagentId: task.id, origin: task.origin, - provider: task.provider, + driver: task.driver, + providerInstanceId: task.providerInstanceId, childThreadId, prompt: task.prompt, result: task.result, @@ -1692,11 +1698,11 @@ export function makeCursorAdapterV2( const resultNativeId = `${nativeItemId}:result`; const resultArtifacts = makeSubagentConversationArtifacts({ messageId: idAllocator.derive.messageFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: resultNativeId, }), turnItemId: idAllocator.derive.turnItemFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: resultNativeId, }), threadId: childThreadId, @@ -1704,7 +1710,7 @@ export function makeCursorAdapterV2( providerThreadId: null, providerTurnId: null, nativeItemRef: { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: resultNativeId, strength: "weak", }, @@ -1715,12 +1721,12 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "message.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, message: resultArtifacts.message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, turnItem: resultArtifacts.turnItem, }); } @@ -1863,7 +1869,7 @@ export function makeCursorAdapterV2( nodeId: input.context.input.rootNodeId, runAttemptId: input.context.input.attemptId, nativeTurnRef: { - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeId: input.context.run.runId, strength: "strong", }, @@ -1893,7 +1899,7 @@ export function makeCursorAdapterV2( yield* completeAssistant(input.context); yield* emitProviderEvent({ type: "provider_turn.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerTurn: providerTurnPayload({ context: input.context, status: input.status, @@ -1902,7 +1908,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "provider_thread.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerThread: { ...input.context.input.providerThread, providerSessionId: session.id, @@ -1916,7 +1922,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "turn.terminal", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerTurnId: input.context.providerTurnId, status: input.status, }); @@ -1998,7 +2004,7 @@ export function makeCursorAdapterV2( }); if (path === null) { return yield* new ProviderAdapterProtocolError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, detail: `Invalid attachment id '${attachment.id}'.`, }); } @@ -2006,7 +2012,7 @@ export function makeCursorAdapterV2( Effect.mapError( (cause) => new ProviderAdapterProtocolError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, detail: `Failed to read attachment '${attachment.id}'.`, payload: cause, }), @@ -2021,7 +2027,7 @@ export function makeCursorAdapterV2( ); if (turnInput.message.text.length === 0 && images.length === 0) { return yield* new ProviderAdapterProtocolError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, detail: "Cursor turn requires non-empty text or attachments.", }); } @@ -2038,7 +2044,7 @@ export function makeCursorAdapterV2( const current = yield* Ref.get(activeTurn); if (current !== null) { return yield* new ProviderAdapterProtocolError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, detail: `Cursor provider turn ${current.providerTurnId} is still active.`, }); } @@ -2073,7 +2079,7 @@ export function makeCursorAdapterV2( const startedAt = yield* DateTime.now; const completed = yield* Deferred.make(); const providerTurnId = idAllocator.derive.providerTurn({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeTurnId: sdkRun.runId, }); context = { @@ -2098,7 +2104,7 @@ export function makeCursorAdapterV2( yield* Ref.set(activeTurn, context); yield* emitProviderEvent({ type: "provider_turn.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerTurn: providerTurnPayload({ context, status: "running", @@ -2107,7 +2113,7 @@ export function makeCursorAdapterV2( }); yield* emitProviderEvent({ type: "provider_thread.updated", - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerThread: { ...turnInput.providerThread, providerSessionId: session.id, @@ -2167,7 +2173,7 @@ export function makeCursorAdapterV2( Effect.mapError( (cause) => new ProviderAdapterTurnStartError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, threadId: turnInput.threadId, providerThreadId: turnInput.providerThread.id, runId: turnInput.runId, @@ -2196,7 +2202,7 @@ export function makeCursorAdapterV2( const runtime: ProviderAdapterV2SessionRuntime = { instanceId: adapterOptions.instanceId, - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, rawEvents: Stream.empty, @@ -2212,6 +2218,7 @@ export function makeCursorAdapterV2( const now = yield* DateTime.now; return makeProviderThread({ idAllocator, + providerInstanceId: adapterOptions.instanceId, appThreadId: threadInput.threadId, providerSessionId: input.providerSessionId, nativeThreadId: opened.nativeThreadId, @@ -2223,7 +2230,7 @@ export function makeCursorAdapterV2( Effect.mapError( (cause) => new ProviderAdapterEnsureThreadError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, threadId: threadInput.threadId, cause, }), @@ -2253,7 +2260,7 @@ export function makeCursorAdapterV2( Effect.mapError( (cause) => new ProviderAdapterResumeThreadError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerSessionId: input.providerSessionId, providerThreadId: threadInput.providerThread.id, cause, @@ -2265,7 +2272,7 @@ export function makeCursorAdapterV2( steerTurn: (turnInput) => Effect.fail( new ProviderAdapterSteerRunUnsupportedError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerThreadId: turnInput.providerThread.id, }), ), @@ -2274,7 +2281,7 @@ export function makeCursorAdapterV2( const context = yield* Ref.get(activeTurn); if (context?.providerTurnId !== turnInput.providerTurnId) { return yield* new ProviderAdapterProtocolError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, detail: `Cursor provider turn ${turnInput.providerTurnId} is not active.`, }); } @@ -2298,7 +2305,7 @@ export function makeCursorAdapterV2( Effect.mapError( (cause) => new ProviderAdapterInterruptError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerThreadId: turnInput.providerThread.id, providerTurnId: turnInput.providerTurnId, cause, @@ -2309,10 +2316,10 @@ export function makeCursorAdapterV2( respondToRuntimeRequest: (requestInput) => Effect.fail( new ProviderAdapterRuntimeRequestResponseError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, requestId: requestInput.requestId, cause: new ProviderAdapterProtocolError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, detail: "Cursor Agent SDK does not expose interactive approval requests.", }), }), @@ -2341,7 +2348,7 @@ export function makeCursorAdapterV2( createdBy: message.type === "user" ? "user" : "agent", creationSource: "provider", id: idAllocator.derive.messageFromProviderItem({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, nativeItemId: message.uuid, }), threadId, @@ -2378,7 +2385,7 @@ export function makeCursorAdapterV2( Effect.mapError( (cause) => new ProviderAdapterReadThreadSnapshotError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerThreadId: snapshotInput.providerThread.id, cause, }), @@ -2388,7 +2395,7 @@ export function makeCursorAdapterV2( rollbackThread: (rollbackInput) => Effect.fail( new ProviderAdapterRollbackThreadError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerThreadId: rollbackInput.providerThread.id, checkpointId: rollbackInput.target.checkpointId, cause: "Cursor Agent SDK does not expose conversation rollback.", @@ -2397,7 +2404,7 @@ export function makeCursorAdapterV2( forkThread: (forkInput) => Effect.fail( new ProviderAdapterForkThreadError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerThreadId: forkInput.sourceProviderThread.id, cause: "Cursor Agent SDK does not expose native agent forks.", }), @@ -2410,7 +2417,7 @@ export function makeCursorAdapterV2( Effect.mapError( (cause) => new ProviderAdapterOpenSessionError({ - provider: CURSOR_PROVIDER, + driver: CURSOR_PROVIDER, providerSessionId: input.providerSessionId, cause, }), diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts b/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts index 35c784c7c2..5c474d9207 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts @@ -7,7 +7,11 @@ import { type SDKUserMessage, type SendOptions, } from "@cursor/sdk"; -import type { OrchestrationV2ProviderSession, ThreadId } from "@t3tools/contracts"; +import { + type OrchestrationV2ProviderSession, + ProviderDriverKind, + type ThreadId, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -20,7 +24,7 @@ import { } from "../../provider/Layers/EventNdjsonLogger.ts"; export const CURSOR_AGENT_SDK_PROTOCOL = "cursor-agent-sdk.local" as const; -export const CURSOR_PROVIDER = "cursor" as const; +export const CURSOR_PROVIDER = ProviderDriverKind.make("cursor"); export class CursorAgentSdkRunnerError extends Schema.TaggedErrorClass()( "CursorAgentSdkRunnerError", diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts index ec8bbf3501..68834a7126 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts @@ -70,7 +70,7 @@ export const GrokOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness< AcpReplayTranscript, AcpReplayTranscriptDecodeError > = { - provider: GROK_PROVIDER, + driver: GROK_PROVIDER, decodeTranscript: (transcript) => decodeAcpReplayTranscript(transcript, GROK_PROVIDER), makeProviderAdapterRegistryLayer: makeGrokProviderAdapterRegistryReplayLayer, }; diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts index 4bb0f1ef5f..bd5caa0859 100644 --- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts @@ -41,8 +41,8 @@ import { type AcpAdapterV2RuntimeInput, } from "./AcpAdapterV2.ts"; -export const GROK_PROVIDER = "grok" as const; -export const GROK_DRIVER_KIND = ProviderDriverKind.make(GROK_PROVIDER); +export const GROK_PROVIDER = ProviderDriverKind.make("grok"); +export const GROK_DRIVER_KIND = GROK_PROVIDER; export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND); const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({}); @@ -119,7 +119,7 @@ export const registerGrokAcpExtensions: NonNullable resolveGrokAcpBaseModelId(selection.model), makeRuntime: diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts index 222e24aa07..7686740ee1 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts @@ -12,6 +12,7 @@ import { openCodePermissionRules, openCodePermissionRequestKind, openCodeToolProjectionKind, + OPENCODE_PROVIDER, OpenCodeProviderCapabilitiesV2, } from "./OpenCodeAdapterV2.ts"; import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts"; @@ -46,7 +47,7 @@ function providerTurn(input: { nativeTurnRef: input.nativeId === null ? null - : { provider: "opencode", nativeId: input.nativeId, strength: "weak" }, + : { driver: OPENCODE_PROVIDER, nativeId: input.nativeId, strength: "weak" }, ordinal: input.ordinal, status: "completed", startedAt: null, diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts index 312c49153f..e5457c8daf 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts @@ -42,7 +42,7 @@ const decodeOpenCodeSdkReplayTranscript = Schema.decodeUnknownEffect(OpenCodeSdk export class OpenCodeReplayTranscriptDecodeError extends Schema.TaggedErrorClass()( "OpenCodeReplayTranscriptDecodeError", { - provider: Schema.optional(Schema.String), + driver: Schema.optional(Schema.String), protocol: Schema.optional(Schema.String), scenario: Schema.optional(Schema.String), cause: Schema.Defect(), @@ -370,7 +370,7 @@ export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarn OpenCodeSdkReplayTranscript, OpenCodeOrchestratorReplayHarnessError > = { - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, decodeTranscript: (transcript) => decodeOpenCodeSdkReplayTranscript(transcript).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts index 4a817b604d..209afd2696 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts @@ -92,8 +92,8 @@ import { } from "../ProviderAdapterDriver.ts"; import { makeSubagentChildThread, subagentThreadTitle } from "../SubagentProjection.ts"; -export const OPENCODE_PROVIDER = "opencode" as const; -export const OPENCODE_DRIVER_KIND = ProviderDriverKind.make(OPENCODE_PROVIDER); +export const OPENCODE_PROVIDER = ProviderDriverKind.make("opencode"); +export const OPENCODE_DRIVER_KIND = OPENCODE_PROVIDER; export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_DRIVER_KIND); const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettingsSchema)({}); @@ -274,7 +274,7 @@ export interface OpenCodeAdapterV2Options { function protocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError { return new ProviderAdapterProtocolError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, detail, ...(payload === undefined ? {} : { payload }), }); @@ -628,6 +628,7 @@ function taskSessionId(part: ToolPart): string | null { function makeProviderThread(input: { readonly idAllocator: IdAllocatorV2Shape; + readonly providerInstanceId: ProviderInstanceId; readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"]; readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"]; @@ -638,15 +639,16 @@ function makeProviderThread(input: { const createdAt = dateTimeFromEpoch(input.nativeSession.time.created, input.now); return { id: input.idAllocator.derive.providerThread({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeThreadId: input.nativeSession.id, }), - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, + providerInstanceId: input.providerInstanceId, providerSessionId: input.providerSessionId, appThreadId: input.appThreadId, ownerNodeId: input.ownerNodeId ?? null, nativeThreadRef: { - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeId: input.nativeSession.id, strength: "strong", }, @@ -663,7 +665,7 @@ function makeProviderThread(input: { function providerRef(nativeId: string, strength: "strong" | "weak" = "strong") { return { - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeId, strength, } satisfies OrchestrationV2ProviderRef; @@ -701,7 +703,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid return ProviderAdapterV2.of({ instanceId: options.instanceId, - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, getCapabilities: () => Effect.succeed(OpenCodeProviderCapabilitiesV2), openSession: Effect.fn("OpenCodeAdapterV2.openSession")( function* (input: ProviderAdapterV2OpenSessionInput) { @@ -738,7 +740,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const now = yield* DateTime.now; let sessionEntity: OrchestrationV2ProviderSession = { id: input.providerSessionId, - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, + providerInstanceId: options.instanceId, status: "ready", cwd, model: input.modelSelection.model, @@ -775,7 +778,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* Queue.offer(rawEvents, { id: rawEventId, - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, + providerInstanceId: options.instanceId, providerSessionId: input.providerSessionId, sequence, direction: raw.direction, @@ -825,7 +829,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid sessionEntity = { ...sessionEntity, status, lastError, updatedAt }; yield* emitProviderEvent({ type: "provider_session.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerSession: sessionEntity, }); }); @@ -839,7 +843,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state.providerThread = { ...state.providerThread, ...patch, updatedAt }; yield* emitProviderEvent({ type: "provider_thread.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerThread: state.providerThread, }); }); @@ -871,7 +875,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state.providerTurns.set(String(providerTurn.id), providerTurn); return emitProviderEvent({ type: "provider_turn.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, threadId: turn.threadId, providerTurn, }); @@ -891,17 +895,17 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const completedAt = isCompleted ? dateTimeFromEpoch(part.time?.end, emittedAt) : null; const nativeItemRef = providerRef(part.id); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.id, }); const ordinal = itemOrdinal(turn, part.id); yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: nodeId, threadId: turn.threadId, @@ -922,7 +926,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); if (part.type === "text") { const messageId = idAllocator.derive.messageFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.id, }); const message: OrchestrationV2ConversationMessage = { @@ -942,12 +946,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state.messages.set(String(message.id), message); yield* emitProviderEvent({ type: "message.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, message, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem: { id: turnItemId, threadId: turn.threadId, @@ -973,7 +977,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid } yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem: { id: turnItemId, threadId: turn.threadId, @@ -1004,11 +1008,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const now = yield* DateTime.now; const nativeItemRef = providerRef(part.id); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.id, }); const input = toolInput(part); @@ -1036,11 +1040,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid if (childSessionId !== null && context.childSessionId === null) { context.childSessionId = childSessionId; context.childThreadId = idAllocator.derive.threadFromProviderThread({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeThreadId: childSessionId, }); context.childProviderThreadId = idAllocator.derive.providerThread({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeThreadId: childSessionId, }); subagentsByChildSessionId.set(childSessionId, context); @@ -1067,7 +1071,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); const childProviderThread: OrchestrationV2ProviderThread = { id: context.childProviderThreadId, - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, + providerInstanceId: options.instanceId, providerSessionId: inputProviderSessionId, appThreadId: context.childThreadId, ownerNodeId: nodeId, @@ -1115,12 +1120,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* emitProviderEvent({ type: "app_thread.created", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, appThread: childThread, }); yield* emitProviderEvent({ type: "provider_thread.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerThread: childProviderThread, }); } @@ -1143,7 +1148,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid parentNodeId: turn.rootNodeId, origin: "provider_native", createdBy: "agent", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, + providerInstanceId: options.instanceId, providerThreadId: context.childProviderThreadId, childThreadId: context.childThreadId, nativeTaskRef: nativeItemRef, @@ -1158,7 +1164,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }; yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: nodeId, threadId: turn.threadId, @@ -1179,12 +1185,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* emitProviderEvent({ type: "subagent.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, subagent, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem: { id: turnItemId, threadId: turn.threadId, @@ -1203,7 +1209,8 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid type: "subagent", subagentId: nodeId, origin: "provider_native", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, + providerInstanceId: options.instanceId, childThreadId: context.childThreadId, prompt, result: context.result, @@ -1230,11 +1237,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const completedAt = toolCompletedAt(part, now); const nativeItemRef = providerRef(part.id); const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.id, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.id, }); const base = { @@ -1344,7 +1351,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid } yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: nodeId, threadId: turn.threadId, @@ -1365,7 +1372,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem, }); }); @@ -1380,17 +1387,17 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid turn.planId = yield* idAllocator.allocate.plan({ threadId: turn.threadId, ...(turn.runId === null ? {} : { runId: turn.runId }), - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, }); } const planId = turn.planId; const nativeItemId = `${state.nativeSessionId}:todo:${turn.providerTurnId}`; const nodeId = idAllocator.derive.nodeFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId, }); const steps: Array = todos.map((todo, index) => ({ @@ -1406,7 +1413,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const completed = steps.length > 0 && steps.every((step) => step.status === "completed"); yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: nodeId, threadId: turn.threadId, @@ -1427,7 +1434,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* emitProviderEvent({ type: "plan.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, plan: { id: planId, threadId: turn.threadId, @@ -1440,7 +1447,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem: { id: turnItemId, threadId: turn.threadId, @@ -1532,7 +1539,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid if (pendingRequestsByNativeId.has(nativeRequestId)) return; const now = yield* DateTime.now; const requestId = yield* idAllocator.allocate.runtimeRequest({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerTurnId: turn.providerTurnId, nativeRequestId, }); @@ -1583,7 +1590,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state.runtimeRequests.set(String(requestId), runtimeRequest); yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: nodeId, threadId: turn.threadId, @@ -1604,13 +1611,13 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, threadId: turn.threadId, runtimeRequest, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem: runtimeRequestTurnItem(pending, "waiting", null, now), }); yield* updateProviderSession("waiting", null); @@ -1633,14 +1640,14 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid pending.state.runtimeRequests.set(String(pending.requestId), resolved); yield* emitProviderEvent({ type: "runtime_request.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, threadId: pending.turn.threadId, runtimeRequest: resolved, }); } yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: pending.nodeId, threadId: pending.turn.threadId, @@ -1661,7 +1668,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem: runtimeRequestTurnItem( pending, status === "resolved" ? "completed" : "cancelled", @@ -1707,7 +1714,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid if (!turn.isRoot) { yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: turn.rootNodeId, threadId: turn.threadId, @@ -1737,7 +1744,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid ); yield* emitProviderEvent({ type: "turn.terminal", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerTurnId: turn.providerTurnId, status, }); @@ -1751,11 +1758,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const now = yield* DateTime.now; const startedAt = dateTimeFromEpoch(message.time.created, now); const rootNodeId = idAllocator.derive.nodeFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: `${state.nativeSessionId}:root:${message.id}`, }); const providerTurnId = idAllocator.derive.providerTurn({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeTurnId: message.id, }); const providerTurn: OrchestrationV2ProviderTurn = { @@ -1795,7 +1802,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state.providerTurns.set(String(providerTurnId), providerTurn); yield* emitProviderEvent({ type: "node.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, node: { id: rootNodeId, threadId: turn.threadId, @@ -1825,11 +1832,11 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid ) { const now = yield* DateTime.now; const messageId = idAllocator.derive.messageFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.messageID, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: part.messageID, }); const projected: OrchestrationV2ConversationMessage = { @@ -1849,12 +1856,12 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid state.messages.set(String(messageId), projected); yield* emitProviderEvent({ type: "message.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, message: projected, }); yield* emitProviderEvent({ type: "turn_item.updated", - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, turnItem: { createdBy: "agent", creationSource: "provider", @@ -2198,7 +2205,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid createdBy: info.role === "user" ? "user" : "agent", creationSource: "provider", id: idAllocator.derive.messageFromProviderItem({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeItemId: info.id, }), threadId: providerThread.appThreadId ?? input.threadId, @@ -2236,7 +2243,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const runtimeSession: ProviderAdapterV2SessionRuntime = { instanceId: options.instanceId, - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerSessionId: input.providerSessionId, providerSession: sessionEntity, rawEvents: Stream.fromEffectRepeat(Queue.take(rawEvents)), @@ -2264,6 +2271,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const createdAt = yield* DateTime.now; const providerThread = makeProviderThread({ idAllocator, + providerInstanceId: options.instanceId, providerSessionId: input.providerSessionId, appThreadId: threadInput.threadId, nativeSession, @@ -2275,7 +2283,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterEnsureThreadError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, threadId: threadInput.threadId, cause, }), @@ -2301,7 +2309,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterResumeThreadError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerSessionId: input.providerSessionId, providerThreadId: threadInput.providerThread.id, cause, @@ -2330,7 +2338,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const startedAt = yield* DateTime.now; const syntheticNativeTurnId = `${sessionId}:attempt:${turnInput.attemptId}`; const providerTurnId = idAllocator.derive.providerTurn({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, nativeTurnId: syntheticNativeTurnId, }); const providerTurn: OrchestrationV2ProviderTurn = { @@ -2405,7 +2413,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterTurnStartError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, threadId: turnInput.threadId, providerThreadId: turnInput.providerThread.id, runId: turnInput.runId, @@ -2463,7 +2471,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterSteerRunError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerThreadId: steerInput.providerThread.id, providerTurnId: steerInput.providerTurnId, cause, @@ -2492,7 +2500,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterInterruptError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerThreadId: interruptInput.providerThread.id, providerTurnId: interruptInput.providerTurnId, cause, @@ -2544,7 +2552,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterRuntimeRequestResponseError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, requestId: requestInput.requestId, cause, }), @@ -2555,7 +2563,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterReadThreadSnapshotError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerThreadId: snapshotInput.providerThread.id, cause, }), @@ -2606,7 +2614,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterRollbackThreadError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerThreadId: rollbackInput.providerThread.id, checkpointId: rollbackInput.target.checkpointId, cause, @@ -2649,6 +2657,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid const forkedAt = yield* DateTime.now; const providerThread = makeProviderThread({ idAllocator, + providerInstanceId: options.instanceId, providerSessionId: input.providerSessionId, appThreadId: forkInput.targetThreadId, ...(forkInput.ownerNodeId === undefined @@ -2669,7 +2678,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterForkThreadError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerThreadId: forkInput.sourceProviderThread.id, cause, }), @@ -2684,7 +2693,7 @@ export function makeOpenCodeAdapterV2(options: OpenCodeAdapterV2Options): Provid Effect.mapError( (cause) => new ProviderAdapterOpenSessionError({ - provider: OPENCODE_PROVIDER, + driver: OPENCODE_PROVIDER, providerSessionId: input.providerSessionId, cause, }), diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts new file mode 100644 index 0000000000..cdc763f854 --- /dev/null +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -0,0 +1,217 @@ +import { + CheckpointScopeId, + CommandId, + type OrchestrationV2Checkpoint, + type OrchestrationV2ExecutionNode, + type OrchestrationV2ProviderThread, + type OrchestrationV2Run, + type OrchestrationV2TurnItem, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { CheckpointServiceV2 } from "./CheckpointService.ts"; +import { EventSinkV2 } from "./EventSink.ts"; +import { IdAllocatorV2, type IdAllocatorV2Shape } from "./IdAllocator.ts"; +import { ProjectionStoreV2 } from "./ProjectionStore.ts"; + +export class CheckpointCaptureExecutionError extends Schema.TaggedErrorClass()( + "CheckpointCaptureExecutionError", + { + threadId: ThreadId, + runId: RunId, + scopeId: CheckpointScopeId, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface CheckpointCaptureServiceV2Shape { + readonly execute: (input: { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly scopeId: CheckpointScopeId; + }) => Effect.Effect; +} + +export class CheckpointCaptureServiceV2 extends Context.Service< + CheckpointCaptureServiceV2, + CheckpointCaptureServiceV2Shape +>()("t3/orchestration-v2/CheckpointCaptureService/CheckpointCaptureServiceV2") {} + +export const layer: Layer.Layer< + CheckpointCaptureServiceV2, + never, + CheckpointServiceV2 | EventSinkV2 | IdAllocatorV2 | ProjectionStoreV2 +> = Layer.effect( + CheckpointCaptureServiceV2, + Effect.gen(function* () { + const checkpoints = yield* CheckpointServiceV2; + const eventSink = yield* EventSinkV2; + const ids = yield* IdAllocatorV2; + const projections = yield* ProjectionStoreV2; + + const execute = Effect.fn("orchestrationV2.checkpointCapture.execute")(function* (input: { + readonly threadId: ThreadId; + readonly runId: RunId; + readonly scopeId: CheckpointScopeId; + }) { + const projection = yield* projections.getThreadProjection(input.threadId); + const run = projection.runs.find((candidate) => candidate.id === input.runId); + + // The effect is at-least-once. A completed run with a checkpoint proves + // that an earlier execution committed its result. + if (run?.status === "completed" && run.checkpointId !== null) { + return; + } + + const rootNode = projection.nodes.find((candidate) => candidate.id === run?.rootNodeId); + const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId); + const providerThread = projection.providerThreads.find( + (candidate) => candidate.id === run?.providerThreadId, + ); + if ( + run === undefined || + run.status !== "waiting" || + rootNode === undefined || + scope === undefined || + rootNode.checkpointScopeId !== scope.id || + providerThread === undefined + ) { + return yield* new CheckpointCaptureExecutionError({ + threadId: input.threadId, + runId: input.runId, + scopeId: input.scopeId, + cause: "The persisted checkpoint capture target is incomplete or no longer waiting.", + }); + } + + const capturedAt = yield* DateTime.now; + const checkpoint = yield* checkpoints.capture({ + scope, + runId: run.id, + nodeId: rootNode.id, + ordinalWithinScope: run.ordinal, + appRunOrdinal: run.ordinal, + capturedAt, + }); + const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`); + yield* eventSink.commitCommand({ + commandId, + threadId: input.threadId, + commandType: "checkpoint.capture", + acceptedAt: capturedAt, + effects: [], + events: [ + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "checkpoint.captured", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: checkpoint, + }, + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "turn-item.updated", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + driver: providerThread.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: makeCheckpointTurnItem({ + idAllocator: ids, + run, + rootNode, + providerThread, + checkpoint, + completedAt: capturedAt, + }), + }, + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "run.updated", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: { + ...run, + status: "completed", + completedAt: capturedAt, + checkpointId: checkpoint.id, + }, + }, + { + id: yield* ids.allocate.event({ threadId: input.threadId, commandId }), + type: "node.updated", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: capturedAt, + payload: { + ...rootNode, + status: "completed", + completedAt: capturedAt, + checkpointScopeId: scope.id, + }, + }, + ], + }); + }); + + return CheckpointCaptureServiceV2.of({ + execute: (input) => + execute(input).pipe( + Effect.mapError((cause) => + Schema.is(CheckpointCaptureExecutionError)(cause) + ? cause + : new CheckpointCaptureExecutionError({ ...input, cause }), + ), + ), + }); + }), +); + +function makeCheckpointTurnItem(input: { + readonly idAllocator: IdAllocatorV2Shape; + readonly run: OrchestrationV2Run; + readonly rootNode: OrchestrationV2ExecutionNode; + readonly providerThread: OrchestrationV2ProviderThread; + readonly checkpoint: OrchestrationV2Checkpoint; + readonly completedAt: DateTime.Utc; +}): OrchestrationV2TurnItem { + return { + id: input.idAllocator.derive.turnItemFromProviderItem({ + driver: input.providerThread.driver, + nativeItemId: `checkpoint:${input.checkpoint.id}`, + }), + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerThreadId: input.providerThread.id, + providerTurnId: input.rootNode.providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: input.run.ordinal * 100 + 99, + status: "completed", + title: null, + startedAt: input.completedAt, + completedAt: input.completedAt, + updatedAt: input.completedAt, + type: "checkpoint", + checkpointId: input.checkpoint.id, + scopeId: input.checkpoint.scopeId, + files: input.checkpoint.files, + }; +} diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts new file mode 100644 index 0000000000..f8732c22ae --- /dev/null +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -0,0 +1,254 @@ +import { + CheckpointId, + CheckpointScopeId, + type OrchestrationV2DomainEvent, + ProviderThreadId, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { CheckpointServiceV2 } from "./CheckpointService.ts"; +import { EventSinkV2 } from "./EventSink.ts"; +import { IdAllocatorV2 } from "./IdAllocator.ts"; +import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts"; +import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; +import { RuntimePolicyV2 } from "./RuntimePolicy.ts"; + +export class CheckpointRollbackExecutionError extends Schema.TaggedErrorClass()( + "CheckpointRollbackExecutionError", + { + threadId: ThreadId, + providerThreadId: ProviderThreadId, + checkpointId: CheckpointId, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface CheckpointRollbackServiceV2Shape { + readonly execute: (input: { + readonly threadId: ThreadId; + readonly providerThreadId: ProviderThreadId; + readonly checkpointId: CheckpointId; + readonly scopeId: CheckpointScopeId; + }) => Effect.Effect; +} + +export class CheckpointRollbackServiceV2 extends Context.Service< + CheckpointRollbackServiceV2, + CheckpointRollbackServiceV2Shape +>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {} + +export const layer: Layer.Layer< + CheckpointRollbackServiceV2, + never, + | CheckpointServiceV2 + | EventSinkV2 + | IdAllocatorV2 + | ProjectionStoreV2 + | ProviderSessionManagerV2 + | RuntimePolicyV2 +> = Layer.effect( + CheckpointRollbackServiceV2, + Effect.gen(function* () { + const checkpoints = yield* CheckpointServiceV2; + const eventSink = yield* EventSinkV2; + const ids = yield* IdAllocatorV2; + const projections = yield* ProjectionStoreV2; + const sessions = yield* ProviderSessionManagerV2; + const runtimePolicy = yield* RuntimePolicyV2; + + const execute = Effect.fn("orchestrationV2.checkpointRollback.execute")(function* (input: { + readonly threadId: ThreadId; + readonly providerThreadId: ProviderThreadId; + readonly checkpointId: CheckpointId; + readonly scopeId: CheckpointScopeId; + }) { + const projection = yield* projections.getThreadProjection(input.threadId); + const providerThread = projection.providerThreads.find( + (candidate) => candidate.id === input.providerThreadId, + ); + const checkpoint = projection.checkpoints.find( + (candidate) => candidate.id === input.checkpointId, + ); + const scope = projection.checkpointScopes.find((candidate) => candidate.id === input.scopeId); + if ( + providerThread === undefined || + providerThread.providerSessionId === null || + checkpoint === undefined || + scope === undefined || + checkpoint.scopeId !== scope.id + ) { + return yield* new CheckpointRollbackExecutionError({ + threadId: input.threadId, + providerThreadId: input.providerThreadId, + checkpointId: input.checkpointId, + cause: "The persisted rollback target is incomplete or no longer valid.", + }); + } + + const modelSelection = projection.thread.modelSelection; + const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ + thread: projection.thread, + modelSelection, + }); + const existingSession = projection.providerSessions.find( + (candidate) => candidate.id === providerThread.providerSessionId, + ); + const session = yield* sessions.open({ + threadId: input.threadId, + providerSessionId: providerThread.providerSessionId, + modelSelection, + runtimePolicy: resolvedRuntimePolicy, + ...(existingSession === undefined ? {} : { resumeFromSession: existingSession }), + }); + + const targetOrdinal = checkpoint.appRunOrdinal ?? 0; + const runsToRollback = projection.runs.filter( + (run) => run.ordinal > targetOrdinal && run.status === "completed", + ); + const providerThreadTurns = projection.providerTurns.filter( + (turn) => turn.providerThreadId === providerThread.id, + ); + const rollbackTarget: ProviderAdapterV2RollbackTarget = + targetOrdinal === 0 + ? { + type: "thread_start", + checkpointId: checkpoint.id, + appRunOrdinal: 0, + } + : yield* Effect.gen(function* () { + const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal); + const targetAttempt = projection.attempts.find( + (attempt) => attempt.id === targetRun?.activeAttemptId, + ); + const targetTurn = projection.providerTurns.find( + (turn) => + turn.id === targetAttempt?.providerTurnId || + turn.runAttemptId === targetAttempt?.id, + ); + if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) { + return yield* new CheckpointRollbackExecutionError({ + threadId: input.threadId, + providerThreadId: input.providerThreadId, + checkpointId: input.checkpointId, + cause: "The provider rollback turn is unavailable.", + }); + } + return { + type: "provider_turn" as const, + checkpointId: checkpoint.id, + appRunOrdinal: targetOrdinal, + providerTurn: targetTurn, + }; + }); + + yield* checkpoints.restore({ scope, checkpoint }); + const snapshot = + runsToRollback.length === 0 + ? { providerThread } + : yield* session.rollbackThread({ + providerThread, + target: rollbackTarget, + providerThreadTurns, + }); + const staleCheckpoints = projection.checkpoints.filter( + (candidate) => + candidate.scopeId === scope.id && + candidate.appRunOrdinal !== null && + candidate.appRunOrdinal > targetOrdinal && + candidate.status === "ready", + ); + if (staleCheckpoints.length > 0) { + yield* checkpoints.deleteStaleRefs({ scope, checkpoints: staleCheckpoints }); + } + + const now = yield* DateTime.now; + const makeEvent = (event: Omit) => + Effect.map( + ids.allocate.event({ threadId: event.threadId }), + (id) => + ({ + ...event, + id, + }) as Event, + ); + const events: Array = []; + events.push( + yield* makeEvent({ + type: "provider-thread.updated", + threadId: input.threadId, + driver: providerThread.driver, + providerInstanceId: providerThread.providerInstanceId, + occurredAt: now, + payload: { + ...snapshot.providerThread, + lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal, + updatedAt: now, + }, + }), + ); + for (const staleCheckpoint of staleCheckpoints) { + events.push( + yield* makeEvent({ + type: "checkpoint.captured", + threadId: input.threadId, + ...(staleCheckpoint.runId === null ? {} : { runId: staleCheckpoint.runId }), + nodeId: staleCheckpoint.nodeId, + providerInstanceId: providerThread.providerInstanceId, + occurredAt: now, + payload: { ...staleCheckpoint, status: "stale" }, + }), + ); + } + for (const run of runsToRollback) { + const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId); + events.push( + yield* makeEvent({ + type: "run.updated", + threadId: input.threadId, + runId: run.id, + ...(rootNode === undefined ? {} : { nodeId: rootNode.id }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, status: "rolled_back", completedAt: now }, + }), + ); + if (rootNode !== undefined) { + events.push( + yield* makeEvent({ + type: "node.updated", + threadId: input.threadId, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...rootNode, status: "rolled_back", completedAt: now }, + }), + ); + } + } + yield* eventSink.write({ events }); + }); + + return CheckpointRollbackServiceV2.of({ + execute: (input) => + execute(input).pipe( + Effect.mapError((cause) => + Schema.is(CheckpointRollbackExecutionError)(cause) + ? cause + : new CheckpointRollbackExecutionError({ + threadId: input.threadId, + providerThreadId: input.providerThreadId, + checkpointId: input.checkpointId, + cause, + }), + ), + ), + }); + }), +); diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index 4dc99f2b00..90f004f313 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -1,5 +1,10 @@ import { assert, it } from "@effect/vitest"; -import { CommandId, type OrchestrationV2ProviderCapabilities, ThreadId } from "@t3tools/contracts"; +import { + CommandId, + type OrchestrationV2ProviderCapabilities, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; @@ -32,7 +37,7 @@ layer("CommandPolicyV2", (it) => { const result = yield* policy.decideSteeringExecution({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: baseCapabilities, }); @@ -47,7 +52,7 @@ layer("CommandPolicyV2", (it) => { const result = yield* policy.decideSteeringExecution({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: capabilities((current) => ({ ...current, turns: { @@ -70,7 +75,7 @@ layer("CommandPolicyV2", (it) => { const result = yield* policy.decideSteeringExecution({ commandId, threadId, - provider: "grok", + providerInstanceId: ProviderInstanceId.make("grok"), capabilities: GrokProviderCapabilitiesV2, }); @@ -85,7 +90,7 @@ layer("CommandPolicyV2", (it) => { const result = yield* policy.decideSteeringExecution({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: CodexProviderCapabilitiesV2, forceRestart: true, }); @@ -102,7 +107,7 @@ layer("CommandPolicyV2", (it) => { .decideSteeringExecution({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: capabilities((current) => ({ ...current, turns: { @@ -128,7 +133,7 @@ layer("CommandPolicyV2", (it) => { .ensureNativeFork({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), fromSpecificTurn: true, capabilities: capabilities((current) => ({ ...current, @@ -152,7 +157,7 @@ layer("CommandPolicyV2", (it) => { const result = yield* policy.decideForkExecution({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: CodexProviderCapabilitiesV2, sameProvider: true, hasStrongNativeSource: true, @@ -170,7 +175,7 @@ layer("CommandPolicyV2", (it) => { const result = yield* policy.decideForkExecution({ commandId, threadId, - provider: "cursor", + providerInstanceId: ProviderInstanceId.make("cursor"), capabilities: CursorProviderCapabilitiesV2, sameProvider: true, hasStrongNativeSource: true, @@ -188,7 +193,7 @@ layer("CommandPolicyV2", (it) => { const result = yield* policy.decideForkExecution({ commandId, threadId, - provider: "grok", + providerInstanceId: ProviderInstanceId.make("grok"), capabilities: GrokProviderCapabilitiesV2, sameProvider: true, hasStrongNativeSource: true, @@ -207,7 +212,7 @@ layer("CommandPolicyV2", (it) => { .decideForkExecution({ commandId, threadId, - provider: "cursor", + providerInstanceId: ProviderInstanceId.make("cursor"), capabilities: capabilities((current) => ({ ...current, threads: { @@ -238,7 +243,7 @@ layer("CommandPolicyV2", (it) => { .ensureRollback({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: capabilities((current) => ({ ...current, checkpointing: { @@ -262,7 +267,7 @@ layer("CommandPolicyV2", (it) => { .ensureContextHandoff({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), strategy: "fork_delta_context", capabilities: capabilities((current) => ({ ...current, @@ -287,7 +292,7 @@ layer("CommandPolicyV2", (it) => { .ensureQueuedMessages({ commandId, threadId, - provider: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: capabilities((current) => ({ ...current, turns: { diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index f42954feeb..c917c14bac 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -3,7 +3,7 @@ import { ModelSelection, OrchestrationV2ProviderCapabilities, OrchestrationV2ThreadProjection, - ProviderKind, + ProviderInstanceId, ProviderTurnId, RunId, ThreadId, @@ -34,7 +34,7 @@ export const MessageDispatchDecisionV2 = Schema.Union([ }), Schema.Struct({ type: Schema.Literal("switch_provider"), - fromProvider: ProviderKind, + fromProviderInstanceId: ProviderInstanceId, toModelSelection: ModelSelection, }), ]); @@ -79,11 +79,11 @@ export class CommandPolicyUnsupportedError extends Schema.TaggedErrorClass { @@ -200,7 +204,7 @@ const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = unsupported( input, input.capabilities.turns.supportsInterrupt ? "interrupt_restart_steering" : "active_steering", - "provider cannot steer active turns directly or by interrupt-and-restart", + "providerInstanceId cannot steer active turns directly or by interrupt-and-restart", ), ); }; @@ -208,22 +212,32 @@ const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) => input.capabilities.turns.supportsInterrupt ? Effect.void - : Effect.fail(unsupported(input, "interrupt", "provider does not support turn interrupts")); + : Effect.fail( + unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"), + ); const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => { if (!input.capabilities.threads.canForkThread) { return Effect.fail( - unsupported(input, "native_fork", "provider does not support native thread forks"), + unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"), ); } if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) { return Effect.fail( - unsupported(input, "fork_from_turn", "provider cannot fork from a specific completed turn"), + unsupported( + input, + "fork_from_turn", + "providerInstanceId cannot fork from a specific completed turn", + ), ); } if (input.capabilities.identity.nativeThreadIds !== "strong") { return Effect.fail( - unsupported(input, "native_fork", "provider does not expose strong native thread ids"), + unsupported( + input, + "native_fork", + "providerInstanceId does not expose strong native thread ids", + ), ); } return Effect.void; @@ -235,12 +249,16 @@ const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => { !input.capabilities.checkpointing.providerCanRollbackConversation ) { return Effect.fail( - unsupported(input, "rollback", "provider conversation rollback is unavailable"), + unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"), ); } if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) { return Effect.fail( - unsupported(input, "rollback_snapshot", "rollback must return a provider thread snapshot"), + unsupported( + input, + "rollback_snapshot", + "rollback must return a providerInstanceId thread snapshot", + ), ); } return Effect.void; @@ -249,12 +267,16 @@ const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => { const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => { if (!input.capabilities.context.canConsumeHandoffSummaries) { return Effect.fail( - unsupported(input, "context_handoff", "provider cannot consume handoff summaries"), + unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"), ); } if (!input.capabilities.context.acceptsSyntheticUserContext) { return Effect.fail( - unsupported(input, "context_handoff", "provider cannot receive synthetic user context"), + unsupported( + input, + "context_handoff", + "providerInstanceId cannot receive synthetic user context", + ), ); } if ( @@ -262,7 +284,7 @@ const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (inpu !input.capabilities.context.supportsDeltaHandoff ) { return Effect.fail( - unsupported(input, "context_handoff", "provider does not support delta handoff"), + unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"), ); } if ( @@ -270,7 +292,11 @@ const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (inpu !input.capabilities.context.supportsFullThreadHandoff ) { return Effect.fail( - unsupported(input, "context_handoff", "provider does not support full-thread handoff"), + unsupported( + input, + "context_handoff", + "providerInstanceId does not support full-thread handoff", + ), ); } return Effect.void; @@ -291,7 +317,7 @@ const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) return ensureContextHandoff({ commandId: input.commandId, threadId: input.threadId, - provider: input.provider, + providerInstanceId: input.providerInstanceId, capabilities: input.capabilities, strategy: "full_thread_summary", }).pipe(Effect.as("portable_context")); @@ -311,7 +337,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in commandId: input.commandId, threadId: input.projection.thread.id, requestedMode: input.requestedMode.type, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, }), ); } @@ -327,7 +353,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in new CommandPolicyMessageDispatchError({ commandId: input.commandId, threadId: input.projection.thread.id, - cause: `No running provider turn found for active run ${activeRun.id}.`, + cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`, }), ) : Effect.succeed({ @@ -343,7 +369,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in commandId: input.commandId, threadId: input.projection.thread.id, requestedMode: input.requestedMode.type, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, }), ); } @@ -355,7 +381,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in new CommandPolicyMessageDispatchError({ commandId: input.commandId, threadId: input.projection.thread.id, - cause: `No running provider turn found for active run ${activeRun.id}.`, + cause: `No running providerInstanceId turn found for active run ${activeRun.id}.`, }), ) : Effect.succeed({ @@ -370,7 +396,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in : ensureQueuedMessages({ commandId: input.commandId, threadId: input.projection.thread.id, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, capabilities: input.capabilities, }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id })); case "start_immediately": @@ -380,7 +406,7 @@ const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (in return ensureQueuedMessages({ commandId: input.commandId, threadId: input.projection.thread.id, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, capabilities: input.capabilities, }).pipe(Effect.as({ type: "queue_after_active", activeRunId: activeRun.id })); } diff --git a/apps/server/src/orchestration-v2/CommandReceiptStore.ts b/apps/server/src/orchestration-v2/CommandReceiptStore.ts index b9db529150..6f4b12541d 100644 --- a/apps/server/src/orchestration-v2/CommandReceiptStore.ts +++ b/apps/server/src/orchestration-v2/CommandReceiptStore.ts @@ -58,6 +58,9 @@ export const CommandReceiptV2 = Schema.Struct({ export type CommandReceiptV2 = typeof CommandReceiptV2.Type; export interface CommandReceiptStoreV2Shape { + readonly insertIfAbsent: ( + receipt: CommandReceiptV2, + ) => Effect.Effect; readonly upsert: (receipt: CommandReceiptV2) => Effect.Effect; readonly getByCommandId: ( commandId: CommandId, @@ -107,6 +110,38 @@ export const layer: Layer.Layer + sql<{ readonly command_id: string }>` + INSERT INTO orchestration_v2_command_receipts ( + command_id, + thread_id, + command_type, + accepted_at, + result_sequence, + status, + error + ) + VALUES ( + ${receipt.commandId}, + ${receipt.threadId}, + ${receipt.commandType}, + ${DateTime.formatIso(receipt.acceptedAt)}, + ${receipt.resultSequence}, + ${receipt.status}, + ${receipt.error} + ) + ON CONFLICT(command_id) DO NOTHING + RETURNING command_id + `.pipe( + Effect.map((rows) => rows.length === 1), + Effect.mapError( + (cause) => + new CommandReceiptStoreWriteError({ + commandId: receipt.commandId, + cause, + }), + ), + ), upsert: (receipt) => sql` INSERT INTO orchestration_v2_command_receipts ( diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.ts b/apps/server/src/orchestration-v2/ContextHandoffService.ts index 167079c877..2f644fcf79 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.ts @@ -1,7 +1,7 @@ import { OrchestrationV2ContextHandoff, type OrchestrationV2TurnItem, - type ProviderKind, + ProviderInstanceId, ProviderThreadId, RunId, ThreadId, @@ -46,8 +46,8 @@ export interface ContextHandoffServiceV2Shape { readonly transferId: OrchestrationV2ContextHandoff["transferId"]; readonly fromProviderThreadIds: ReadonlyArray; readonly toProviderThreadId: ProviderThreadId; - readonly fromProvider: ProviderKind; - readonly toProvider: ProviderKind; + readonly fromProviderInstanceId: ProviderInstanceId; + readonly toProviderInstanceId: ProviderInstanceId; readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly deltaItems: ReadonlyArray; readonly createdAt: DateTime.Utc; @@ -58,8 +58,8 @@ export interface ContextHandoffServiceV2Shape { readonly transferId: NonNullable; readonly fromProviderThreadIds: ReadonlyArray; readonly toProviderThreadId: ProviderThreadId; - readonly fromProvider: ProviderKind; - readonly toProvider: ProviderKind; + readonly fromProviderInstanceId: ProviderInstanceId; + readonly toProviderInstanceId: ProviderInstanceId; readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly strategy: Extract< OrchestrationV2ContextHandoff["strategy"], @@ -124,8 +124,8 @@ function makeForkDeltaSummary(input: { } function makeProviderHandoffSummary(input: { - readonly fromProvider: ProviderKind; - readonly toProvider: ProviderKind; + readonly fromProviderInstanceId: ProviderInstanceId; + readonly toProviderInstanceId: ProviderInstanceId; readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly strategy: Extract< OrchestrationV2ContextHandoff["strategy"], @@ -144,8 +144,8 @@ function makeProviderHandoffSummary(input: { input.strategy === "full_thread_summary" ? "Full conversation context for provider handoff." : "Conversation delta since this provider last participated.", - `From provider: ${input.fromProvider}`, - `To provider: ${input.toProvider}`, + `From driver: ${input.fromProviderInstanceId}`, + `To driver: ${input.toProviderInstanceId}`, `Covered app runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`, "", "Canonical conversation context:", @@ -191,8 +191,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi const handoffId = yield* idAllocator.allocate .contextHandoff({ threadId: input.threadId, - fromProvider: "codex", - toProvider: "codex", + fromProviderInstanceId: ProviderInstanceId.make("manual"), + toProviderInstanceId: ProviderInstanceId.make("manual"), }) .pipe( Effect.mapError( @@ -218,7 +218,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi status: "ready", summaryMessageId: null, summaryText: "Manual context handoff.", - createdByProvider: null, + createdByProviderInstanceId: null, createdAt: now, updatedAt: now, } satisfies OrchestrationV2ContextHandoff; @@ -232,8 +232,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi readonly transferId: OrchestrationV2ContextHandoff["transferId"]; readonly fromProviderThreadIds: ReadonlyArray; readonly toProviderThreadId: ProviderThreadId; - readonly fromProvider: ProviderKind; - readonly toProvider: ProviderKind; + readonly fromProviderInstanceId: ProviderInstanceId; + readonly toProviderInstanceId: ProviderInstanceId; readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly deltaItems: ReadonlyArray; readonly createdAt: DateTime.Utc; @@ -241,8 +241,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi const handoffId = yield* idAllocator.allocate .contextHandoff({ threadId: input.targetThreadId, - fromProvider: input.fromProvider, - toProvider: input.toProvider, + fromProviderInstanceId: input.fromProviderInstanceId, + toProviderInstanceId: input.toProviderInstanceId, }) .pipe( Effect.mapError( @@ -268,7 +268,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi status: "ready", summaryMessageId: null, summaryText: makeForkDeltaSummary(input), - createdByProvider: null, + createdByProviderInstanceId: null, createdAt: input.createdAt, updatedAt: input.createdAt, } satisfies OrchestrationV2ContextHandoff; @@ -283,8 +283,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi readonly transferId: NonNullable; readonly fromProviderThreadIds: ReadonlyArray; readonly toProviderThreadId: ProviderThreadId; - readonly fromProvider: ProviderKind; - readonly toProvider: ProviderKind; + readonly fromProviderInstanceId: ProviderInstanceId; + readonly toProviderInstanceId: ProviderInstanceId; readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"]; readonly strategy: Extract< OrchestrationV2ContextHandoff["strategy"], @@ -296,8 +296,8 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi const handoffId = yield* idAllocator.allocate .contextHandoff({ threadId: input.threadId, - fromProvider: input.fromProvider, - toProvider: input.toProvider, + fromProviderInstanceId: input.fromProviderInstanceId, + toProviderInstanceId: input.toProviderInstanceId, }) .pipe( Effect.mapError( @@ -323,7 +323,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi status: "ready", summaryMessageId: null, summaryText: makeProviderHandoffSummary(input), - createdByProvider: null, + createdByProviderInstanceId: null, createdAt: input.createdAt, updatedAt: input.createdAt, } satisfies OrchestrationV2ContextHandoff; diff --git a/apps/server/src/orchestration-v2/CorrelationStore.ts b/apps/server/src/orchestration-v2/CorrelationStore.ts deleted file mode 100644 index f55ad9ddd7..0000000000 --- a/apps/server/src/orchestration-v2/CorrelationStore.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { - MessageId, - NodeId, - OrchestrationV2ProviderRef, - ProviderKind, - ProviderSessionId, - ProviderThreadId, - ProviderTurnId, - RawEventId, - RunAttemptId, - RunId, - RuntimeRequestId, - ThreadId, - TurnItemId, -} from "@t3tools/contracts"; -import * as Context from "effect/Context"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import type * as Effect from "effect/Effect"; - -export const CorrelationScopeV2 = Schema.Struct({ - provider: ProviderKind, - providerSessionId: Schema.optional(ProviderSessionId), - providerThreadId: Schema.optional(ProviderThreadId), - providerTurnId: Schema.optional(ProviderTurnId), -}); -export type CorrelationScopeV2 = typeof CorrelationScopeV2.Type; - -export const CorrelationEntityV2 = Schema.Union([ - Schema.Struct({ type: Schema.Literal("thread"), id: ThreadId }), - Schema.Struct({ type: Schema.Literal("run"), id: RunId }), - Schema.Struct({ type: Schema.Literal("run_attempt"), id: RunAttemptId }), - Schema.Struct({ type: Schema.Literal("node"), id: NodeId }), - Schema.Struct({ type: Schema.Literal("message"), id: MessageId }), - Schema.Struct({ type: Schema.Literal("provider_session"), id: ProviderSessionId }), - Schema.Struct({ type: Schema.Literal("provider_thread"), id: ProviderThreadId }), - Schema.Struct({ type: Schema.Literal("provider_turn"), id: ProviderTurnId }), - Schema.Struct({ type: Schema.Literal("runtime_request"), id: RuntimeRequestId }), - Schema.Struct({ type: Schema.Literal("turn_item"), id: TurnItemId }), - Schema.Struct({ type: Schema.Literal("raw_event"), id: RawEventId }), -]); -export type CorrelationEntityV2 = typeof CorrelationEntityV2.Type; - -export const CorrelationBindingV2 = Schema.Struct({ - scope: CorrelationScopeV2, - providerRef: OrchestrationV2ProviderRef, - entity: CorrelationEntityV2, - createdByRawEventId: Schema.optional(RawEventId), -}); -export type CorrelationBindingV2 = typeof CorrelationBindingV2.Type; - -export class CorrelationBindError extends Schema.TaggedErrorClass()( - "CorrelationBindError", - { - scope: CorrelationScopeV2, - providerRef: OrchestrationV2ProviderRef, - entity: CorrelationEntityV2, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Failed to bind ${this.scope.provider} provider ref to ${this.entity.type}.`; - } -} - -export class CorrelationLookupError extends Schema.TaggedErrorClass()( - "CorrelationLookupError", - { - scope: CorrelationScopeV2, - providerRef: Schema.optional(OrchestrationV2ProviderRef), - entity: Schema.optional(CorrelationEntityV2), - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Failed to look up ${this.scope.provider} provider correlation.`; - } -} - -export class CorrelationOrdinalError extends Schema.TaggedErrorClass()( - "CorrelationOrdinalError", - { - scope: CorrelationScopeV2, - key: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Failed to allocate correlation ordinal for ${this.scope.provider}:${this.key}.`; - } -} - -export const CorrelationStoreV2Error = Schema.Union([ - CorrelationBindError, - CorrelationLookupError, - CorrelationOrdinalError, -]); -export type CorrelationStoreV2Error = typeof CorrelationStoreV2Error.Type; - -export interface CorrelationStoreV2Shape { - readonly bind: (binding: CorrelationBindingV2) => Effect.Effect; - readonly lookupByProviderRef: (input: { - readonly scope: CorrelationScopeV2; - readonly providerRef: OrchestrationV2ProviderRef; - }) => Effect.Effect, CorrelationStoreV2Error>; - readonly lookupByEntity: (input: { - readonly scope: CorrelationScopeV2; - readonly entity: CorrelationEntityV2; - }) => Effect.Effect, CorrelationStoreV2Error>; - readonly nextOrdinal: (input: { - readonly scope: CorrelationScopeV2; - readonly key: string; - }) => Effect.Effect; -} - -export class CorrelationStoreV2 extends Context.Service< - CorrelationStoreV2, - CorrelationStoreV2Shape ->()("t3/orchestration-v2/CorrelationStore/CorrelationStoreV2") {} diff --git a/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts index 904450978e..72327d272c 100644 --- a/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts +++ b/apps/server/src/orchestration-v2/CursorOrchestratorV2.live.test.ts @@ -10,11 +10,18 @@ import { import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import { FetchHttpClient } from "effect/unstable/http"; import { describe } from "vite-plus/test"; import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts"; import { ServerConfig } from "../config.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts"; +import { + NoOpProviderEventLoggers, + ProviderEventLoggers, +} from "../provider/Layers/ProviderEventLoggers.ts"; +import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; @@ -34,17 +41,30 @@ const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe( const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer)); +const serverSettingsLayer = ServerSettingsService.layerTest({ + providers: { + cursor: { enabled: true }, + }, +}); +const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe( + Layer.provide( + Layer.mergeAll( + serverConfigLayer.pipe(Layer.provide(NodeServices.layer)), + serverSettingsLayer, + NodeServices.layer, + FetchHttpClient.layer, + OpenCodeRuntimeLive.pipe(Layer.provide(NodeServices.layer)), + Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers), + ), + ), +); + const liveLayer = OrchestrationV2LayerLive.pipe( Layer.provide(SqlitePersistenceMemory), Layer.provide(checkpointStoreLayer), Layer.provide(serverConfigLayer), - Layer.provide( - ServerSettingsService.layerTest({ - providers: { - cursor: { enabled: true }, - }, - }), - ), + Layer.provide(serverSettingsLayer), + Layer.provide(providerInstanceRegistryLayer), Layer.provide(NodeServices.layer), ); @@ -141,11 +161,11 @@ describe.runIf(process.env.T3_CURSOR_LIVE_ORCHESTRATOR === "1")( .join("\n"); assert.deepEqual( - sourceProjection.runs.map((run) => [run.provider, run.status]), + sourceProjection.runs.map((run) => [run.providerInstanceId, run.status]), [["cursor", "completed"]], ); assert.deepEqual( - targetProjection.runs.map((run) => [run.provider, run.status]), + targetProjection.runs.map((run) => [run.providerInstanceId, run.status]), [["cursor", "completed"]], ); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts new file mode 100644 index 0000000000..49d8989356 --- /dev/null +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -0,0 +1,410 @@ +import { + CheckpointId, + CheckpointScopeId, + CommandId, + MessageId, + ProviderSessionId, + RunAttemptId, + ProviderApprovalDecision, + ProviderUserInputAnswers, + ProviderThreadId, + ProviderTurnId, + RunId, + RuntimeRequestId, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export const OrchestrationEffectRequestV2 = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("provider-session.release"), + providerSessionId: ProviderSessionId, + reason: Schema.Literals([ + "idle_timeout", + "runtime_error", + "manual_shutdown", + "server_shutdown", + ]), + detail: Schema.optional(Schema.String), + }), + Schema.Struct({ + type: Schema.Literal("provider-turn.start"), + runId: RunId, + }), + Schema.Struct({ + type: Schema.Literal("provider-turn.interrupt"), + providerSessionId: ProviderSessionId, + providerThreadId: ProviderThreadId, + providerTurnId: ProviderTurnId, + }), + Schema.Struct({ + type: Schema.Literal("provider-turn.steer"), + providerSessionId: ProviderSessionId, + providerThreadId: ProviderThreadId, + providerTurnId: ProviderTurnId, + messageId: MessageId, + }), + Schema.Struct({ + type: Schema.Literal("provider-turn.restart"), + providerSessionId: ProviderSessionId, + providerThreadId: ProviderThreadId, + providerTurnId: ProviderTurnId, + interruptedAttemptId: RunAttemptId, + runId: RunId, + }), + Schema.Struct({ + type: Schema.Literal("runtime-request.respond"), + providerSessionId: ProviderSessionId, + requestId: RuntimeRequestId, + decision: Schema.optional(ProviderApprovalDecision), + answers: Schema.optional(ProviderUserInputAnswers), + }), + Schema.Struct({ + type: Schema.Literal("provider-thread.rollback"), + providerThreadId: ProviderThreadId, + checkpointId: CheckpointId, + scopeId: CheckpointScopeId, + }), + Schema.Struct({ + type: Schema.Literal("provider-thread.fork"), + sourceProviderThreadId: ProviderThreadId, + targetProviderThreadId: ProviderThreadId, + }), + Schema.Struct({ + type: Schema.Literal("checkpoint.capture"), + runId: RunId, + scopeId: CheckpointScopeId, + }), + Schema.Struct({ + type: Schema.Literal("terminal.cleanup"), + runId: RunId, + }), + Schema.Struct({ + type: Schema.Literal("attachment.cleanup"), + attachmentIds: Schema.Array(Schema.String), + }), +]); +export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type; + +export const OrchestrationEffectStatusV2 = Schema.Literals([ + "pending", + "running", + "succeeded", + "failed", +]); +export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type; + +export interface OrchestrationEffectV2 { + readonly id: string; + readonly commandId: CommandId; + readonly threadId: ThreadId; + readonly request: OrchestrationEffectRequestV2; + readonly status: OrchestrationEffectStatusV2; + readonly attemptCount: number; + readonly availableAt: string; + readonly leaseOwner: string | null; + readonly leaseExpiresAt: string | null; + readonly createdAt: string; + readonly updatedAt: string; + readonly completedAt: string | null; + readonly lastError: string | null; +} + +export interface PendingOrchestrationEffectV2 { + readonly id: string; + readonly commandId: CommandId; + readonly threadId: ThreadId; + readonly request: OrchestrationEffectRequestV2; + readonly availableAt?: DateTime.Utc; +} + +export class EffectOutboxError extends Schema.TaggedErrorClass()( + "EffectOutboxError", + { + operation: Schema.String, + effectId: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`; + } +} + +export interface EffectOutboxV2Shape { + readonly awaitAvailable: Effect.Effect; + readonly notifyAvailable: Effect.Effect; + readonly enqueue: ( + effects: ReadonlyArray, + ) => Effect.Effect; + readonly get: ( + effectId: string, + ) => Effect.Effect, EffectOutboxError>; + readonly listByCommandId: ( + commandId: CommandId, + ) => Effect.Effect, EffectOutboxError>; + readonly claimNext: (input: { + readonly workerId: string; + readonly leaseDurationMs: number; + }) => Effect.Effect, EffectOutboxError>; + readonly succeed: (input: { + readonly effectId: string; + readonly workerId: string; + }) => Effect.Effect; + readonly retry: (input: { + readonly effectId: string; + readonly workerId: string; + readonly error: string; + readonly delayMs: number; + }) => Effect.Effect; + readonly fail: (input: { + readonly effectId: string; + readonly workerId: string; + readonly error: string; + }) => Effect.Effect; +} + +export class EffectOutboxV2 extends Context.Service()( + "t3/orchestration-v2/EffectOutbox/EffectOutboxV2", +) {} + +type EffectRow = { + readonly effect_id: string; + readonly command_id: string; + readonly thread_id: string; + readonly effect_type: string; + readonly payload_json: string; + readonly status: string; + readonly attempt_count: number; + readonly available_at: string; + readonly lease_owner: string | null; + readonly lease_expires_at: string | null; + readonly created_at: string; + readonly updated_at: string; + readonly completed_at: string | null; + readonly last_error: string | null; +}; + +const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2)); +const decodeRequest = Schema.decodeUnknownEffect( + Schema.fromJsonString(OrchestrationEffectRequestV2), +); + +const rowToEffect = (row: EffectRow) => + decodeRequest(row.payload_json).pipe( + Effect.map( + (request): OrchestrationEffectV2 => ({ + id: row.effect_id, + commandId: CommandId.make(row.command_id), + threadId: ThreadId.make(row.thread_id), + request, + status: row.status as OrchestrationEffectStatusV2, + attemptCount: row.attempt_count, + availableAt: row.available_at, + leaseOwner: row.lease_owner, + leaseExpiresAt: row.lease_expires_at, + createdAt: row.created_at, + updatedAt: row.updated_at, + completedAt: row.completed_at, + lastError: row.last_error, + }), + ), + ); + +export const layer: Layer.Layer = Layer.effect( + EffectOutboxV2, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const available = yield* Queue.unbounded(); + + const decodeRows = (operation: string, rows: ReadonlyArray) => + Effect.forEach(rows, rowToEffect).pipe( + Effect.mapError((cause) => new EffectOutboxError({ operation, cause })), + ); + + const service: EffectOutboxV2Shape = { + enqueue: (effects) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const nowIso = DateTime.formatIso(now); + yield* Effect.forEach( + effects, + (effect) => sql` + INSERT INTO orchestration_v2_effect_outbox ( + effect_id, + command_id, + thread_id, + effect_type, + payload_json, + status, + attempt_count, + available_at, + created_at, + updated_at + ) + VALUES ( + ${effect.id}, + ${effect.commandId}, + ${effect.threadId}, + ${effect.request.type}, + ${encodeRequest(effect.request)}, + 'pending', + 0, + ${DateTime.formatIso(effect.availableAt ?? now)}, + ${nowIso}, + ${nowIso} + ) + ON CONFLICT(effect_id) DO NOTHING + `, + { concurrency: 1, discard: true }, + ); + if (effects.length > 0) { + yield* Queue.offer(available, undefined); + } + }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))), + get: (effectId) => + sql` + SELECT * + FROM orchestration_v2_effect_outbox + WHERE effect_id = ${effectId} + LIMIT 1 + `.pipe( + Effect.flatMap((rows) => { + const row = rows[0]; + return row === undefined + ? Effect.succeed(Option.none()) + : rowToEffect(row).pipe(Effect.map(Option.some)); + }), + Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })), + ), + awaitAvailable: Queue.take(available), + notifyAvailable: Queue.offer(available, undefined).pipe(Effect.asVoid), + listByCommandId: (commandId) => + sql` + SELECT * + FROM orchestration_v2_effect_outbox + WHERE command_id = ${commandId} + ORDER BY created_at ASC, effect_id ASC + `.pipe( + Effect.flatMap((rows) => decodeRows("list", rows)), + Effect.mapError((cause) => + Schema.is(EffectOutboxError)(cause) + ? cause + : new EffectOutboxError({ operation: "list", cause }), + ), + ), + claimNext: ({ workerId, leaseDurationMs }) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const nowIso = DateTime.formatIso(now); + const leaseExpiresAt = DateTime.formatIso( + DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }), + ); + const rows = yield* sql` + UPDATE orchestration_v2_effect_outbox + SET + status = 'running', + attempt_count = attempt_count + 1, + lease_owner = ${workerId}, + lease_expires_at = ${leaseExpiresAt}, + updated_at = ${nowIso}, + last_error = NULL + WHERE effect_id = ( + SELECT effect_id + FROM orchestration_v2_effect_outbox + WHERE available_at <= ${nowIso} + AND ( + status = 'pending' + OR (status = 'running' AND lease_expires_at <= ${nowIso}) + ) + ORDER BY available_at ASC, created_at ASC, effect_id ASC + LIMIT 1 + ) + RETURNING * + `; + const row = rows[0]; + return row === undefined ? Option.none() : Option.some(yield* rowToEffect(row)); + }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))), + succeed: ({ effectId, workerId }) => + Effect.gen(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + const rows = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET + status = 'succeeded', + lease_owner = NULL, + lease_expires_at = NULL, + completed_at = ${now}, + updated_at = ${now}, + last_error = NULL + WHERE effect_id = ${effectId} + AND status = 'running' + AND lease_owner = ${workerId} + RETURNING effect_id + `; + return rows.length === 1; + }).pipe( + Effect.mapError( + (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }), + ), + ), + retry: ({ effectId, workerId, error, delayMs }) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const nowIso = DateTime.formatIso(now); + const availableAt = DateTime.formatIso( + DateTime.add(now, { milliseconds: Math.max(0, delayMs) }), + ); + const rows = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET + status = 'pending', + available_at = ${availableAt}, + lease_owner = NULL, + lease_expires_at = NULL, + updated_at = ${nowIso}, + last_error = ${error} + WHERE effect_id = ${effectId} + AND status = 'running' + AND lease_owner = ${workerId} + RETURNING effect_id + `; + return rows.length === 1; + }).pipe( + Effect.mapError( + (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }), + ), + ), + fail: ({ effectId, workerId, error }) => + Effect.gen(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + const rows = yield* sql<{ readonly effect_id: string }>` + UPDATE orchestration_v2_effect_outbox + SET + status = 'failed', + lease_owner = NULL, + lease_expires_at = NULL, + completed_at = ${now}, + updated_at = ${now}, + last_error = ${error} + WHERE effect_id = ${effectId} + AND status = 'running' + AND lease_owner = ${workerId} + RETURNING effect_id + `; + return rows.length === 1; + }).pipe( + Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })), + ), + }; + + return service; + }), +); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts new file mode 100644 index 0000000000..60f61b99bc --- /dev/null +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -0,0 +1,352 @@ +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { CheckpointCaptureServiceV2 } from "./CheckpointCaptureService.ts"; +import { EffectOutboxV2, type OrchestrationEffectV2 } from "./EffectOutbox.ts"; +import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts"; +import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; +import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts"; +import { ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts"; +import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts"; + +export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass()( + "OrchestrationEffectExecutionError", + { + effectId: Schema.String, + effectType: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface OrchestrationEffectExecutorV2Shape { + readonly execute: ( + effect: OrchestrationEffectV2, + ) => Effect.Effect; +} + +export class OrchestrationEffectExecutorV2 extends Context.Service< + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2Shape +>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectExecutorV2") {} + +export const executorLayer: Layer.Layer< + OrchestrationEffectExecutorV2, + never, + | ProviderSessionManagerV2 + | CheckpointCaptureServiceV2 + | CheckpointRollbackServiceV2 + | ProviderTurnControlServiceV2 + | ProviderTurnStartServiceV2 + | RuntimeRequestServiceV2 +> = Layer.effect( + OrchestrationEffectExecutorV2, + Effect.gen(function* () { + const checkpointCapture = yield* CheckpointCaptureServiceV2; + const checkpointRollback = yield* CheckpointRollbackServiceV2; + const providerSessions = yield* ProviderSessionManagerV2; + const providerTurnControl = yield* ProviderTurnControlServiceV2; + const providerTurnStart = yield* ProviderTurnStartServiceV2; + const runtimeRequests = yield* RuntimeRequestServiceV2; + return OrchestrationEffectExecutorV2.of({ + execute: (effect) => { + switch (effect.request.type) { + case "provider-session.release": + return providerSessions + .release({ + providerSessionId: effect.request.providerSessionId, + reason: effect.request.reason, + ...(effect.request.detail === undefined ? {} : { detail: effect.request.detail }), + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "provider-turn.start": + return providerTurnStart + .start({ threadId: effect.threadId, runId: effect.request.runId }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "provider-turn.interrupt": + return providerTurnControl + .interrupt({ + threadId: effect.threadId, + providerSessionId: effect.request.providerSessionId, + providerThreadId: effect.request.providerThreadId, + providerTurnId: effect.request.providerTurnId, + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "provider-turn.steer": + return providerTurnControl + .steer({ + threadId: effect.threadId, + providerSessionId: effect.request.providerSessionId, + providerThreadId: effect.request.providerThreadId, + providerTurnId: effect.request.providerTurnId, + messageId: effect.request.messageId, + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "provider-turn.restart": + return providerTurnControl + .interruptAndAwaitTerminal({ + threadId: effect.threadId, + providerSessionId: effect.request.providerSessionId, + providerThreadId: effect.request.providerThreadId, + providerTurnId: effect.request.providerTurnId, + interruptedAttemptId: effect.request.interruptedAttemptId, + }) + .pipe( + Effect.andThen( + providerTurnStart.start({ + threadId: effect.threadId, + runId: effect.request.runId, + }), + ), + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "runtime-request.respond": + return runtimeRequests + .respond({ + threadId: effect.threadId, + providerSessionId: effect.request.providerSessionId, + requestId: effect.request.requestId, + ...(effect.request.decision === undefined + ? {} + : { decision: effect.request.decision }), + ...(effect.request.answers === undefined + ? {} + : { answers: effect.request.answers }), + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "provider-thread.rollback": + return checkpointRollback + .execute({ + threadId: effect.threadId, + providerThreadId: effect.request.providerThreadId, + checkpointId: effect.request.checkpointId, + scopeId: effect.request.scopeId, + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "checkpoint.capture": + return checkpointCapture + .execute({ + threadId: effect.threadId, + runId: effect.request.runId, + scopeId: effect.request.scopeId, + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); + case "provider-thread.fork": + case "terminal.cleanup": + case "attachment.cleanup": + return Effect.fail( + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause: `No Shape 1 executor is registered for ${effect.request.type}.`, + }), + ); + } + }, + }); + }), +); + +export class OrchestrationEffectWorkerError extends Schema.TaggedErrorClass()( + "OrchestrationEffectWorkerError", + { + operation: Schema.String, + effectId: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface OrchestrationEffectWorkerV2Shape { + readonly awaitWork: Effect.Effect; + readonly runOnce: Effect.Effect; + readonly drain: (maxEffects?: number) => Effect.Effect; +} + +export class OrchestrationEffectWorkerV2 extends Context.Service< + OrchestrationEffectWorkerV2, + OrchestrationEffectWorkerV2Shape +>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {} + +export interface OrchestrationEffectWorkerOptions { + readonly workerId?: string; + readonly leaseDurationMs?: number; + readonly maxAttempts?: number; +} + +export const layerWithOptions = ( + options: OrchestrationEffectWorkerOptions = {}, +): Layer.Layer< + OrchestrationEffectWorkerV2, + never, + EffectOutboxV2 | OrchestrationEffectExecutorV2 +> => + Layer.effect( + OrchestrationEffectWorkerV2, + Effect.gen(function* () { + const outbox = yield* EffectOutboxV2; + const executor = yield* OrchestrationEffectExecutorV2; + const workerId = options.workerId ?? `orchestration-v2:${process.pid}`; + const leaseDurationMs = Math.max(1, options.leaseDurationMs ?? 30_000); + const maxAttempts = Math.max(1, options.maxAttempts ?? 5); + + const runOnce = Effect.gen(function* () { + const claimed = yield* outbox.claimNext({ workerId, leaseDurationMs }); + if (Option.isNone(claimed)) { + return false; + } + const effect = claimed.value; + const exit = yield* Effect.exit(executor.execute(effect)); + if (Exit.isSuccess(exit)) { + const completed = yield* outbox.succeed({ effectId: effect.id, workerId }); + if (!completed) { + return yield* new OrchestrationEffectWorkerError({ + operation: "complete", + effectId: effect.id, + cause: "The worker no longer owns the effect lease.", + }); + } + return true; + } + + const error = Cause.pretty(exit.cause); + yield* Effect.logWarning("Orchestration effect execution failed", { + effectId: effect.id, + effectType: effect.request.type, + attemptCount: effect.attemptCount, + error, + }); + const updated = + effect.attemptCount >= maxAttempts + ? yield* outbox.fail({ effectId: effect.id, workerId, error }) + : yield* outbox.retry({ + effectId: effect.id, + workerId, + error, + delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)), + }); + if (!updated) { + return yield* new OrchestrationEffectWorkerError({ + operation: "reschedule", + effectId: effect.id, + cause: "The worker no longer owns the effect lease.", + }); + } + return true; + }).pipe( + Effect.mapError((cause) => + Schema.is(OrchestrationEffectWorkerError)(cause) + ? cause + : new OrchestrationEffectWorkerError({ operation: "run", cause }), + ), + ); + + return OrchestrationEffectWorkerV2.of({ + awaitWork: outbox.awaitAvailable, + runOnce, + drain: (maxEffects = Number.MAX_SAFE_INTEGER) => + Effect.gen(function* () { + let completed = 0; + while (completed < maxEffects && (yield* runOnce)) { + completed += 1; + } + return completed; + }), + }); + }), + ); + +export const layer = layerWithOptions(); + +export const daemonLayer: Layer.Layer = + Layer.effectDiscard( + Effect.gen(function* () { + const worker = yield* OrchestrationEffectWorkerV2; + yield* Effect.forever( + worker.runOnce.pipe( + Effect.catchCause((cause) => + Effect.logWarning("Orchestration effect worker failed", cause).pipe(Effect.as(false)), + ), + Effect.flatMap((worked) => + worked + ? Effect.yieldNow + : Effect.raceFirst(worker.awaitWork, Effect.sleep(Duration.millis(50))), + ), + ), + ).pipe(Effect.forkScoped); + }), + ); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 81ce981615..0115ac44d7 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -5,15 +5,31 @@ import { ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SqlClient from "effect/unstable/sql/SqlClient"; +import { + CommandReceiptStoreV2, + type CommandReceiptV2, + layer as commandReceiptStoreLayer, +} from "./CommandReceiptStore.ts"; +import { + EffectOutboxV2, + type PendingOrchestrationEffectV2, + layer as effectOutboxLayer, +} from "./EffectOutbox.ts"; import { EventStoreV2 } from "./EventStore.ts"; import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { + TurnItemPositionStoreV2, + layer as turnItemPositionStoreLayer, +} from "./TurnItemPositionStore.ts"; /** * ERRORS @@ -57,6 +73,33 @@ export interface EventSinkV2Shape { readonly commandId?: CommandId; readonly events: ReadonlyArray; }) => Effect.Effect, EventSinkV2Error>; + readonly writeWithEffects: (input: { + readonly commandId?: CommandId; + readonly events: ReadonlyArray; + readonly effects: ReadonlyArray; + }) => Effect.Effect, EventSinkV2Error>; + readonly commitCommand: (input: { + readonly commandId: CommandId; + readonly threadId: ThreadId; + readonly commandType: string; + readonly acceptedAt: DateTime.Utc; + readonly events: ReadonlyArray; + readonly effects: ReadonlyArray; + }) => Effect.Effect< + { + readonly receipt: CommandReceiptV2; + readonly storedEvents: ReadonlyArray; + readonly committed: boolean; + }, + EventSinkV2Error + >; + readonly commitRejectedCommand: (input: { + readonly commandId: CommandId; + readonly threadId: ThreadId; + readonly commandType: string; + readonly rejectedAt: DateTime.Utc; + readonly error: string; + }) => Effect.Effect; readonly stream: (input?: { readonly threadId?: ThreadId; readonly afterSequence?: number; @@ -76,20 +119,76 @@ export class EventSinkV2 extends Context.Service( /** * IMPLEMENTATIONS */ -export const layer: Layer.Layer< +const baseLayer: Layer.Layer< EventSinkV2, never, - EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient + | CommandReceiptStoreV2 + | EffectOutboxV2 + | EventStoreV2 + | ProjectionStoreV2 + | SqlClient.SqlClient + | TurnItemPositionStoreV2 > = Layer.effect( EventSinkV2, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const commandReceipts = yield* CommandReceiptStoreV2; + const effectOutbox = yield* EffectOutboxV2; const eventStore = yield* EventStoreV2; const projectionStore = yield* ProjectionStoreV2; + const turnItemPositions = yield* TurnItemPositionStoreV2; const liveEvents = yield* PubSub.unbounded(); + const normalizeEvents = (events: ReadonlyArray) => { + const runOrdinals = new Map( + events.flatMap((event) => + event.type === "run.created" || event.type === "run.updated" + ? [[event.payload.id, event.payload.ordinal] as const] + : [], + ), + ); + return Effect.forEach( + events, + (event): Effect.Effect => + event.type === "turn-item.updated" + ? turnItemPositions + .normalize( + event.payload, + event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId), + ) + .pipe(Effect.map((payload) => ({ ...event, payload }))) + : Effect.succeed(event), + { concurrency: 1 }, + ); + }; + + const applyStoredEvents = (storedEvents: ReadonlyArray) => + Effect.gen(function* () { + yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), { + concurrency: 1, + }); + const sequence = storedEvents.at(-1)?.sequence; + if (sequence !== undefined) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* sql` + INSERT INTO orchestration_v2_projection_metadata ( + projection_name, + schema_version, + last_sequence, + updated_at + ) + VALUES ('thread-projections', 1, ${sequence}, ${now}) + ON CONFLICT(projection_name) + DO UPDATE SET + schema_version = excluded.schema_version, + last_sequence = excluded.last_sequence, + updated_at = excluded.updated_at + `; + } + }); + const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* ( - input: Parameters[0], + input: Parameters[0], ) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.command_id": input.commandId ?? null, @@ -99,22 +198,186 @@ export const layer: Layer.Layer< const storedEvents = yield* sql.withTransaction( Effect.gen(function* () { + const normalized = yield* normalizeEvents(input.events); const committed = yield* eventStore.append({ ...(input.commandId === undefined ? {} : { commandId: input.commandId }), - events: input.events, - }); - yield* Effect.forEach(committed, (stored) => projectionStore.apply(stored.event), { - concurrency: 1, + events: normalized, }); + yield* applyStoredEvents(committed); + yield* effectOutbox.enqueue(input.effects); return committed; }), ); + if (input.effects.length > 0) { + yield* effectOutbox.notifyAvailable; + } yield* PubSub.publishAll(liveEvents, storedEvents); return storedEvents; }); + const existingCommandResult = (commandId: CommandId) => + Effect.gen(function* () { + const existing = yield* commandReceipts.getByCommandId(commandId); + if (Option.isNone(existing)) { + return yield* Effect.die( + new Error(`Command receipt ${commandId} disappeared during its transaction.`), + ); + } + const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe( + Stream.runCollect, + Effect.map((events): ReadonlyArray => Array.from(events)), + ); + return { receipt: existing.value, storedEvents }; + }); + + const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* ( + input: Parameters[0], + ) { + const result = yield* sql.withTransaction( + Effect.gen(function* () { + const reserved = yield* commandReceipts.insertIfAbsent({ + commandId: input.commandId, + threadId: input.threadId, + commandType: input.commandType, + acceptedAt: input.acceptedAt, + resultSequence: 0, + status: "accepted", + error: null, + }); + if (!reserved) { + const existing = yield* existingCommandResult(input.commandId); + return { ...existing, committed: false as const }; + } + + const normalized = yield* normalizeEvents(input.events); + const storedEvents = yield* eventStore.append({ + commandId: input.commandId, + events: normalized, + }); + const sequence = storedEvents.at(-1)?.sequence; + if (sequence === undefined) { + return yield* Effect.die( + new Error(`Command ${input.commandId} produced no orchestration events.`), + ); + } + yield* applyStoredEvents(storedEvents); + yield* effectOutbox.enqueue(input.effects); + const receipt: CommandReceiptV2 = { + commandId: input.commandId, + threadId: input.threadId, + commandType: input.commandType, + acceptedAt: input.acceptedAt, + resultSequence: sequence, + status: "accepted", + error: null, + }; + yield* commandReceipts.upsert(receipt); + return { receipt, storedEvents, committed: true as const }; + }), + ); + if (input.effects.length > 0) { + yield* effectOutbox.notifyAvailable; + } + if (result.committed) { + yield* PubSub.publishAll(liveEvents, result.storedEvents); + } + return result; + }); + + const commitRejectedCommandEffect = Effect.fn( + "orchestrationV2.EventSink.commitRejectedCommand", + )(function* (input: Parameters[0]) { + return yield* sql.withTransaction( + Effect.gen(function* () { + const sequence = yield* eventStore.latestSequence({ threadId: input.threadId }); + const receipt: CommandReceiptV2 = { + commandId: input.commandId, + threadId: input.threadId, + commandType: input.commandType, + acceptedAt: input.rejectedAt, + resultSequence: sequence, + status: "rejected", + error: input.error, + }; + const inserted = yield* commandReceipts.insertIfAbsent(receipt); + if (inserted) { + return receipt; + } + const existing = yield* commandReceipts.getByCommandId(input.commandId); + return Option.getOrElse(existing, () => receipt); + }), + ); + }); + + const catchUp = (input: { + readonly afterSequence: number; + readonly throughSequence: number; + readonly threadId?: ThreadId; + }): Stream.Stream => { + const pageSize = 256; + const loop = (afterSequence: number): Stream.Stream => + Stream.unwrap( + eventStore + .read({ + afterSequence, + throughSequence: input.throughSequence, + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + limit: pageSize, + }) + .pipe( + Stream.runCollect, + Effect.map((chunk) => Array.from(chunk)), + Effect.map((events) => { + if (events.length === 0) { + return Stream.empty; + } + const current = Stream.fromIterable(events); + const last = events.at(-1)?.sequence ?? input.throughSequence; + return events.length < pageSize || last >= input.throughSequence + ? current + : Stream.concat(current, loop(last)); + }), + ), + ); + return loop(input.afterSequence); + }; + + const stream = (input?: { readonly threadId?: ThreadId; readonly afterSequence?: number }) => + Stream.unwrap( + Effect.gen(function* () { + // Subscribe first, then capture the database high-water mark. Events + // committed between those operations are buffered by the subscription. + const subscription = yield* PubSub.subscribe(liveEvents); + const highWater = yield* eventStore.latestSequence(); + const afterSequence = input?.afterSequence ?? 0; + const replay = catchUp({ + afterSequence, + throughSequence: highWater, + ...(input?.threadId === undefined ? {} : { threadId: input.threadId }), + }); + const live = Stream.fromSubscription(subscription).pipe( + Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)), + Stream.filter( + (stored) => input?.threadId === undefined || stored.event.threadId === input.threadId, + ), + ); + return Stream.concat(replay, live); + }), + ); + return EventSinkV2.of({ write: (input) => + writeEffect({ ...input, effects: [] }).pipe( + Effect.mapError( + (cause) => + new EventSinkWriteError({ + eventCount: input.events.length, + ...(input.commandId === undefined ? {} : { commandId: input.commandId }), + cause, + }), + ), + ), + writeWithEffects: (input) => writeEffect(input).pipe( Effect.mapError( (cause) => @@ -125,20 +388,30 @@ export const layer: Layer.Layer< }), ), ), - stream: (input) => - eventStore.read(input).pipe( - Stream.concat( - Stream.fromPubSub(liveEvents).pipe( - Stream.filter( - (stored) => - input?.threadId === undefined || stored.event.threadId === input.threadId, - ), - Stream.filter( - (stored) => - input?.afterSequence === undefined || stored.sequence > input.afterSequence, - ), - ), + commitCommand: (input) => + commitCommandEffect(input).pipe( + Effect.mapError( + (cause) => + new EventSinkWriteError({ + commandId: input.commandId, + eventCount: input.events.length, + cause, + }), ), + ), + commitRejectedCommand: (input) => + commitRejectedCommandEffect(input).pipe( + Effect.mapError( + (cause) => + new EventSinkWriteError({ + commandId: input.commandId, + eventCount: 0, + cause, + }), + ), + ), + stream: (input) => + stream(input).pipe( Stream.mapError( (cause) => new EventSinkStreamError({ @@ -172,3 +445,21 @@ export const layer: Layer.Layer< } satisfies EventSinkV2Shape); }), ); + +/** + * Event sink layer for application compositions that already own the + * persistence services. Keeping the outbox instance shared with the worker is + * important because enqueue notifications are in-memory wakeups backed by the + * durable SQL queue. + */ +export const layerFromStores = baseLayer; + +export const layer: Layer.Layer< + EventSinkV2, + never, + EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient +> = baseLayer.pipe( + Layer.provide( + Layer.mergeAll(commandReceiptStoreLayer, effectOutboxLayer, turnItemPositionStoreLayer), + ), +); diff --git a/apps/server/src/orchestration-v2/EventStore.ts b/apps/server/src/orchestration-v2/EventStore.ts index 72bac0d442..0f7ced986a 100644 --- a/apps/server/src/orchestration-v2/EventStore.ts +++ b/apps/server/src/orchestration-v2/EventStore.ts @@ -58,6 +58,7 @@ export interface EventStoreV2Shape { }) => Effect.Effect, EventStoreV2Error>; readonly read: (input?: { readonly afterSequence?: number; + readonly throughSequence?: number; readonly threadId?: ThreadId; readonly limit?: number; }) => Stream.Stream; @@ -83,7 +84,8 @@ type EventRow = { readonly thread_id: string; readonly run_id: string | null; readonly node_id: string | null; - readonly provider: string | null; + readonly driver: string | null; + readonly provider_instance_id: string | null; readonly raw_event_id: string | null; readonly event_type: string; readonly occurred_at: string; @@ -119,7 +121,8 @@ export const layer: Layer.Layer = Laye threadId: row.thread_id, runId: row.run_id ?? undefined, nodeId: row.node_id ?? undefined, - provider: row.provider ?? undefined, + driver: row.driver ?? undefined, + providerInstanceId: row.provider_instance_id ?? undefined, rawEventId: row.raw_event_id ?? undefined, type: row.event_type, occurredAt: row.occurred_at, @@ -161,7 +164,8 @@ export const layer: Layer.Layer = Laye thread_id, run_id, node_id, - provider, + driver, + provider_instance_id, raw_event_id, event_type, occurred_at, @@ -173,7 +177,8 @@ export const layer: Layer.Layer = Laye ${event.threadId}, ${event.runId ?? null}, ${event.nodeId ?? null}, - ${event.provider ?? null}, + ${event.driver ?? null}, + ${event.providerInstanceId ?? null}, ${event.rawEventId ?? null}, ${event.type}, ${normalized.occurredAt}, @@ -186,7 +191,8 @@ export const layer: Layer.Layer = Laye thread_id, run_id, node_id, - provider, + driver, + provider_instance_id, raw_event_id, event_type, occurred_at, @@ -230,13 +236,15 @@ export const layer: Layer.Layer = Laye thread_id, run_id, node_id, - provider, + driver, + provider_instance_id, raw_event_id, event_type, occurred_at, payload_json FROM orchestration_v2_events WHERE sequence > ${input?.afterSequence ?? 0} + AND sequence <= ${input?.throughSequence ?? Number.MAX_SAFE_INTEGER} AND (${input?.threadId ?? null} IS NULL OR thread_id = ${input?.threadId ?? null}) ORDER BY sequence ASC LIMIT ${input?.limit ?? 1000} @@ -267,7 +275,8 @@ export const layer: Layer.Layer = Laye thread_id, run_id, node_id, - provider, + driver, + provider_instance_id, raw_event_id, event_type, occurred_at, diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts new file mode 100644 index 0000000000..6e2a531792 --- /dev/null +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -0,0 +1,475 @@ +import { assert, it } from "@effect/vitest"; +import { + CheckpointId, + CheckpointRef, + CheckpointScopeId, + CommandId, + EventId, + MessageId, + type ModelSelection, + NodeId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { CommandReceiptStoreV2, layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts"; +import { EffectOutboxV2, layer as effectOutboxLayer } from "./EffectOutbox.ts"; +import { + layerWithOptions as effectWorkerLayerWithOptions, + OrchestrationEffectExecutorV2, + OrchestrationEffectWorkerV2, +} from "./EffectWorker.ts"; +import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts"; +import { EventStoreV2, layer as eventStoreLayer } from "./EventStore.ts"; +import { + ProjectionMaintenanceV2, + layer as projectionMaintenanceLayer, +} from "./ProjectionMaintenance.ts"; +import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts"; + +const databaseLayer = SqlitePersistenceMemory; +const eventStoreProvided = eventStoreLayer.pipe(Layer.provideMerge(databaseLayer)); +const projectionStoreProvided = projectionStoreLayer.pipe(Layer.provideMerge(databaseLayer)); +const storesProvided = Layer.mergeAll(databaseLayer, eventStoreProvided, projectionStoreProvided); +const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesProvided)); +const effectOutboxProvided = effectOutboxLayer.pipe(Layer.provide(databaseLayer)); +const commandReceiptStoreProvided = commandReceiptStoreLayer.pipe(Layer.provide(databaseLayer)); +const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe( + Layer.provide(storesProvided), +); +const TestLayer = Layer.mergeAll( + storesProvided, + eventSinkProvided, + effectOutboxProvided, + commandReceiptStoreProvided, + projectionMaintenanceProvided, +); + +const providerInstanceId = ProviderInstanceId.make("codex"); +const modelSelection = { + instanceId: providerInstanceId, + model: "gpt-5.4", +} satisfies ModelSelection; + +function makeThread(threadId: ThreadId, now: DateTime.Utc): OrchestrationV2AppThread { + return { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make(`project:${threadId}`), + title: `Thread ${threadId}`, + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + }; +} + +function threadCreatedEvent(input: { + readonly id: string; + readonly thread: OrchestrationV2AppThread; + readonly now: DateTime.Utc; +}): OrchestrationV2DomainEvent { + return { + id: EventId.make(input.id), + type: "thread.created", + threadId: input.thread.id, + providerInstanceId, + occurredAt: input.now, + payload: input.thread, + }; +} + +it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { + it.effect("paginates catch-up beyond the event-store read limit", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:foundation-large-catch-up"); + const thread = makeThread(threadId, now); + const eventCount = 1_005; + const events: Array = [ + threadCreatedEvent({ id: "event:foundation-catch-up:0", thread, now }), + ...Array.from({ length: eventCount - 1 }, (_, index) => ({ + id: EventId.make(`event:foundation-catch-up:${index + 1}`), + type: "thread.metadata-updated" as const, + threadId, + providerInstanceId, + occurredAt: now, + payload: { + ...thread, + title: `Catch-up update ${index + 1}`, + }, + })), + ]; + + yield* eventSink.write({ events }); + const replayed = yield* eventSink.stream({ afterSequence: 0 }).pipe( + Stream.take(eventCount), + Stream.runCollect, + Effect.map((events) => Array.from(events)), + ); + + assert.lengthOf(replayed, eventCount); + assert.deepEqual( + replayed.map((stored) => stored.sequence), + Array.from({ length: eventCount }, (_, index) => index + 1), + ); + }), + ); + + it.effect("does not lose or duplicate events while transitioning from catch-up to live", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:foundation-stream-race"); + const thread = makeThread(threadId, now); + const created = yield* eventSink.write({ + events: [threadCreatedEvent({ id: "event:foundation-stream-race:0", thread, now })], + }); + + let afterSequence = created[0]!.sequence; + for (let index = 1; index <= 32; index += 1) { + const nextEvent = { + id: EventId.make(`event:foundation-stream-race:${index}`), + type: "thread.metadata-updated" as const, + threadId, + providerInstanceId, + occurredAt: now, + payload: { ...thread, title: `Race update ${index}` }, + } satisfies OrchestrationV2DomainEvent; + const reader = yield* eventSink + .stream({ threadId, afterSequence }) + .pipe(Stream.runHead, Effect.forkChild); + yield* Effect.yieldNow; + const written = yield* eventSink.write({ events: [nextEvent] }); + const received = yield* Fiber.join(reader); + if (Option.isNone(received)) { + return yield* Effect.die("The event stream ended before delivering the live event."); + } + assert.equal(received.value.sequence, written[0]?.sequence); + assert.equal(received.value.event.id, nextEvent.id); + afterSequence = received.value.sequence; + } + }), + ); + + it.effect( + "rolls back events, projections, receipts, and effects after a projection failure", + () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const eventStore = yield* EventStoreV2; + const receipts = yield* CommandReceiptStoreV2; + const outbox = yield* EffectOutboxV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const commandId = CommandId.make("command:foundation-atomic-failure"); + const threadId = ThreadId.make("thread:foundation-atomic-failure"); + const scopeId = CheckpointScopeId.make("scope:foundation-atomic-failure"); + const checkpoint = (index: number) => ({ + id: CheckpointId.make(`checkpoint:foundation-atomic-failure:${index}`), + threadId, + scopeId, + runId: null, + nodeId: NodeId.make("node:foundation-atomic-failure"), + parentCheckpointId: null, + ordinalWithinScope: 1, + appRunOrdinal: null, + ref: CheckpointRef.make(`checkpoint-ref:foundation-atomic-failure:${index}`), + status: "ready" as const, + files: [], + capturedAt: now, + }); + const events = [1, 2].map( + (index) => + ({ + id: EventId.make(`event:foundation-atomic-failure:${index}`), + type: "checkpoint.captured", + threadId, + occurredAt: now, + payload: checkpoint(index), + }) satisfies OrchestrationV2DomainEvent, + ); + + const exit = yield* Effect.exit( + eventSink.commitCommand({ + commandId, + threadId, + commandType: "checkpoint.atomicity-test", + acceptedAt: now, + events, + effects: [ + { + id: "effect:foundation-atomic-failure", + commandId, + threadId, + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-atomic-failure"), + }, + }, + ], + }), + ); + assert.equal(exit._tag, "Failure"); + assert.isTrue(Option.isNone(yield* receipts.getByCommandId(commandId))); + assert.deepEqual(yield* outbox.listByCommandId(commandId), []); + assert.deepEqual( + yield* eventStore.readByCommandId({ commandId }).pipe( + Stream.runCollect, + Effect.map((events) => Array.from(events)), + ), + [], + ); + const checkpointRows = yield* sql<{ readonly count: number }>` + SELECT COUNT(*) AS count + FROM orchestration_v2_projection_checkpoints + WHERE thread_id = ${threadId} + `; + assert.equal(checkpointRows[0]?.count, 0); + }), + ); + + it.effect("keeps one durable effect across command retries and executes it after recovery", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const outbox = yield* EffectOutboxV2; + const now = yield* DateTime.now; + const commandId = CommandId.make("command:foundation-effect-recovery"); + const threadId = ThreadId.make("thread:foundation-effect-recovery"); + const thread = makeThread(threadId, now); + const event = threadCreatedEvent({ + id: "event:foundation-effect-recovery", + thread, + now, + }); + const effect = { + id: "effect:foundation-effect-recovery", + commandId, + threadId, + request: { + type: "provider-turn.start" as const, + runId: RunId.make("run:foundation-effect-recovery"), + }, + }; + + const first = yield* eventSink.commitCommand({ + commandId, + threadId, + commandType: "foundation.effect-recovery", + acceptedAt: now, + events: [event], + effects: [effect], + }); + const retry = yield* eventSink.commitCommand({ + commandId, + threadId, + commandType: "foundation.effect-recovery", + acceptedAt: now, + events: [event], + effects: [effect], + }); + + assert.isTrue(first.committed); + assert.isFalse(retry.committed); + assert.equal(retry.receipt.resultSequence, first.receipt.resultSequence); + assert.lengthOf(retry.storedEvents, 1); + assert.lengthOf(yield* outbox.listByCommandId(commandId), 1); + + const executionCount = yield* Ref.make(0); + const executorLayer = Layer.succeed( + OrchestrationEffectExecutorV2, + OrchestrationEffectExecutorV2.of({ + execute: () => Ref.update(executionCount, (count) => count + 1), + }), + ); + const workerLayer = effectWorkerLayerWithOptions({ workerId: "recovery-worker" }).pipe( + Layer.provide(Layer.merge(Layer.succeed(EffectOutboxV2, outbox), executorLayer)), + ); + yield* Effect.gen(function* () { + const worker = yield* OrchestrationEffectWorkerV2; + assert.isTrue(yield* worker.runOnce); + assert.isFalse(yield* worker.runOnce); + }).pipe(Effect.provide(workerLayer)); + + assert.equal(yield* Ref.get(executionCount), 1); + const storedEffect = yield* outbox.get(effect.id); + assert.isTrue(Option.isSome(storedEffect)); + if (Option.isSome(storedEffect)) { + assert.equal(storedEffect.value.status, "succeeded"); + } + }), + ); + + it.effect("allows only one worker to claim an available effect", () => + Effect.gen(function* () { + const outbox = yield* EffectOutboxV2; + const commandId = CommandId.make("command:foundation-exclusive-claim"); + yield* outbox.enqueue([ + { + id: "effect:foundation-exclusive-claim", + commandId, + threadId: ThreadId.make("thread:foundation-exclusive-claim"), + request: { + type: "provider-turn.start", + runId: RunId.make("run:foundation-exclusive-claim"), + }, + }, + ]); + + const claims = yield* Effect.all( + [ + outbox.claimNext({ workerId: "worker-a", leaseDurationMs: 30_000 }), + outbox.claimNext({ workerId: "worker-b", leaseDurationMs: 30_000 }), + ], + { concurrency: "unbounded" }, + ); + assert.equal(claims.filter(Option.isSome).length, 1); + assert.equal(claims.filter(Option.isNone).length, 1); + }), + ); + + it.effect("allocates collision-free positions beyond 100 items and rebuilds equivalently", () => + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const projectionStore = yield* ProjectionStoreV2; + const maintenance = yield* ProjectionMaintenanceV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:foundation-many-items"); + const runId = RunId.make("run:foundation-many-items"); + const thread = makeThread(threadId, now); + const runEvent = { + id: EventId.make("event:foundation-many-items:run"), + type: "run.created" as const, + threadId, + runId, + providerInstanceId, + occurredAt: now, + payload: { + id: runId, + threadId, + ordinal: 1, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("message:foundation-many-items"), + rootNodeId: null, + activeAttemptId: null, + status: "completed" as const, + queuePosition: null, + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }, + } satisfies OrchestrationV2DomainEvent; + const items = Array.from({ length: 151 }, (_, index) => ({ + id: TurnItemId.make(`turn-item:foundation-many-items:${index}`), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: index % 3, + status: "completed" as const, + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "dynamic_tool" as const, + toolName: `tool-${index}`, + input: { index }, + output: { completed: true }, + })); + const itemEvents = items.map( + (item, index) => + ({ + id: EventId.make(`event:foundation-many-items:item:${index}`), + type: "turn-item.updated", + threadId, + runId, + providerInstanceId, + occurredAt: now, + payload: item, + }) satisfies OrchestrationV2DomainEvent, + ); + + yield* eventSink.write({ + events: [ + threadCreatedEvent({ id: "event:foundation-many-items:thread", thread, now }), + runEvent, + ...itemEvents, + ], + }); + const beforeUpdate = yield* projectionStore.getThreadProjection(threadId); + const ordinals = beforeUpdate.turnItems.map((item) => item.ordinal); + assert.lengthOf(ordinals, 151); + assert.equal(new Set(ordinals).size, 151); + assert.isTrue(ordinals.every((ordinal) => ordinal > 1_000_000)); + assert.isTrue( + ordinals.every((ordinal, index) => index === 0 || ordinal > ordinals[index - 1]!), + ); + + yield* eventSink.write({ + events: [ + { + id: EventId.make("event:foundation-many-items:update"), + type: "turn-item.updated", + threadId, + runId, + providerInstanceId, + occurredAt: now, + payload: { ...items[0]!, ordinal: 99_999_999, title: "Updated" }, + }, + ], + }); + const afterUpdate = yield* projectionStore.getThreadProjection(threadId); + assert.equal(afterUpdate.turnItems[0]?.ordinal, ordinals[0]); + assert.equal((yield* maintenance.verify).valid, true); + + yield* sql` + DELETE FROM orchestration_v2_projection_turn_items + WHERE turn_item_id = ${items[75]!.id} + `; + const broken = yield* maintenance.verify; + assert.isFalse(broken.valid); + assert.deepEqual(broken.differingThreadIds, [threadId]); + + const rebuilt = yield* maintenance.rebuild; + assert.isTrue(rebuilt.valid); + assert.lengthOf((yield* projectionStore.getThreadProjection(threadId)).turnItems, 151); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts index e73f00b8cc..3d4762bf04 100644 --- a/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts +++ b/apps/server/src/orchestration-v2/GrokOrchestratorV2.live.test.ts @@ -10,11 +10,18 @@ import { import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import { FetchHttpClient } from "effect/unstable/http"; import { describe } from "vite-plus/test"; import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts"; import { ServerConfig } from "../config.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts"; +import { + NoOpProviderEventLoggers, + ProviderEventLoggers, +} from "../provider/Layers/ProviderEventLoggers.ts"; +import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; @@ -34,17 +41,30 @@ const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe( const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(vcsDriverRegistryLayer)); +const serverSettingsLayer = ServerSettingsService.layerTest({ + providers: { + grok: { enabled: true }, + }, +}); +const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe( + Layer.provide( + Layer.mergeAll( + serverConfigLayer.pipe(Layer.provide(NodeServices.layer)), + serverSettingsLayer, + NodeServices.layer, + FetchHttpClient.layer, + OpenCodeRuntimeLive.pipe(Layer.provide(NodeServices.layer)), + Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers), + ), + ), +); + const liveLayer = OrchestrationV2LayerLive.pipe( Layer.provide(SqlitePersistenceMemory), Layer.provide(checkpointStoreLayer), Layer.provide(serverConfigLayer), - Layer.provide( - ServerSettingsService.layerTest({ - providers: { - grok: { enabled: true }, - }, - }), - ), + Layer.provide(serverSettingsLayer), + Layer.provide(providerInstanceRegistryLayer), Layer.provide(NodeServices.layer), ); @@ -139,11 +159,11 @@ describe.runIf(process.env.T3_GROK_LIVE_ORCHESTRATOR === "1")("Grok V2 live orch .join("\n"); assert.deepEqual( - sourceProjection.runs.map((run) => [run.provider, run.status]), + sourceProjection.runs.map((run) => [run.providerInstanceId, run.status]), [["grok", "completed"]], ); assert.deepEqual( - targetProjection.runs.map((run) => [run.provider, run.status]), + targetProjection.runs.map((run) => [run.providerInstanceId, run.status]), [["grok", "completed"]], ); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/IdAllocator.ts b/apps/server/src/orchestration-v2/IdAllocator.ts index 936cbb221a..f6081a33e6 100644 --- a/apps/server/src/orchestration-v2/IdAllocator.ts +++ b/apps/server/src/orchestration-v2/IdAllocator.ts @@ -9,7 +9,8 @@ import { NodeId, PlanId, ProjectId, - ProviderKind, + ProviderDriverKind, + ProviderInstanceId, ProviderSessionId, ProviderThreadId, ProviderTurnId, @@ -92,11 +93,11 @@ export interface IdAllocatorV2AllocateShape { readonly ordinal: number; }) => Effect.Effect; readonly providerSession: (input: { - readonly provider: ProviderKind; + readonly providerInstanceId: ProviderInstanceId; readonly threadId: ThreadId; }) => Effect.Effect; readonly runtimeRequest: (input: { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly providerTurnId?: ProviderTurnId; readonly nativeRequestId?: string; }) => Effect.Effect; @@ -110,8 +111,8 @@ export interface IdAllocatorV2AllocateShape { }) => Effect.Effect; readonly contextHandoff: (input: { readonly threadId: ThreadId; - readonly fromProvider: ProviderKind; - readonly toProvider: ProviderKind; + readonly fromProviderInstanceId: ProviderInstanceId; + readonly toProviderInstanceId: ProviderInstanceId; }) => Effect.Effect; readonly contextTransfer: (input: { readonly sourceThreadId: ThreadId; @@ -121,7 +122,7 @@ export interface IdAllocatorV2AllocateShape { readonly plan: (input: { readonly threadId: ThreadId; readonly runId?: RunId; - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; }) => Effect.Effect; } @@ -131,7 +132,7 @@ export interface IdAllocatorV2DeriveShape { readonly delegatedTaskMessage: (input: { readonly commandId: CommandId }) => MessageId; readonly delegatedTaskTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId; readonly threadFromProviderThread: (input: { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly nativeThreadId: string; }) => ThreadId; readonly run: (input: { readonly threadId: ThreadId; readonly ordinal: number }) => RunId; @@ -150,23 +151,23 @@ export interface IdAllocatorV2DeriveShape { readonly signal: string; }) => TurnItemId; readonly providerThread: (input: { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly nativeThreadId: string; }) => ProviderThreadId; readonly providerTurn: (input: { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly nativeTurnId: string; }) => ProviderTurnId; readonly nodeFromProviderItem: (input: { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly nativeItemId: string; }) => NodeId; readonly messageFromProviderItem: (input: { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly nativeItemId: string; }) => MessageId; readonly turnItemFromProviderItem: (input: { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly nativeItemId: string; }) => TurnItemId; readonly approvalNode: (input: { readonly requestId: RuntimeRequestId }) => NodeId; @@ -270,7 +271,7 @@ export const layer: Layer.Layer = Layer.succeed( randomId({ kind: "provider_session", prefix: "provider-session", - parts: ["provider", input.provider, "thread", input.threadId], + parts: ["provider-instance", input.providerInstanceId, "thread", input.threadId], make: ProviderSessionId.make, })(input), runtimeRequest: (input) => @@ -279,7 +280,7 @@ export const layer: Layer.Layer = Layer.succeed( prefix: "runtime-request", parts: [ "provider", - input.provider, + input.driver, ...(input.providerTurnId === undefined ? [] : ["provider-turn", input.providerTurnId]), ...(input.nativeRequestId === undefined ? [] @@ -306,10 +307,10 @@ export const layer: Layer.Layer = Layer.succeed( parts: [ "thread", input.threadId, - "from-provider", - input.fromProvider, - "to-provider", - input.toProvider, + "from-provider-instance", + input.fromProviderInstanceId, + "to-provider-instance", + input.toProviderInstanceId, ], make: ContextHandoffId.make, })(input), @@ -335,7 +336,7 @@ export const layer: Layer.Layer = Layer.succeed( "thread", input.threadId, "provider", - input.provider, + input.driver, ...(input.runId === undefined ? [] : ["run", input.runId]), ], make: PlanId.make, @@ -351,7 +352,7 @@ export const layer: Layer.Layer = Layer.succeed( TurnItemId.make(joinId("turn-item", "delegated-task", input.commandId)), threadFromProviderThread: (input) => ThreadId.make( - joinId("thread", "provider", input.provider, "native-thread", input.nativeThreadId), + joinId("thread", "provider", input.driver, "native-thread", input.nativeThreadId), ), run: (input) => RunId.make(joinId("run", "thread", input.threadId, "ordinal", input.ordinal)), runAttempt: (input) => @@ -369,24 +370,24 @@ export const layer: Layer.Layer = Layer.succeed( joinId( "provider-thread", "provider", - input.provider, + input.driver, "native-thread", input.nativeThreadId, ), ), providerTurn: (input) => ProviderTurnId.make( - joinId("provider-turn", "provider", input.provider, "native-turn", input.nativeTurnId), + joinId("provider-turn", "provider", input.driver, "native-turn", input.nativeTurnId), ), nodeFromProviderItem: (input) => - NodeId.make(joinId("node", "provider", input.provider, "native-item", input.nativeItemId)), + NodeId.make(joinId("node", "provider", input.driver, "native-item", input.nativeItemId)), messageFromProviderItem: (input) => MessageId.make( - joinId("message", "provider", input.provider, "native-item", input.nativeItemId), + joinId("message", "provider", input.driver, "native-item", input.nativeItemId), ), turnItemFromProviderItem: (input) => TurnItemId.make( - joinId("turn-item", "provider", input.provider, "native-item", input.nativeItemId), + joinId("turn-item", "provider", input.driver, "native-item", input.nativeItemId), ), approvalNode: (input) => NodeId.make(joinId("node", "runtime-request", input.requestId)), approvalTurnItem: (input) => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index d7436ddd10..7e1b4abde9 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4,7 +4,6 @@ import { type ModelSelection, OrchestrationV2Command, type OrchestrationV2AppThread, - type OrchestrationV2Checkpoint, type OrchestrationV2ContextHandoff, type OrchestrationV2ContextSourcePoint, type OrchestrationV2ContextTransfer, @@ -21,6 +20,7 @@ import { type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, + ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; @@ -36,23 +36,22 @@ import * as Semaphore from "effect/Semaphore"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { CommandPolicyV2 } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts"; -import { - ContextHandoffServiceV2, - providerMessageWithContextHandoff, - providerMessageWithContextHandoffs, -} from "./ContextHandoffService.ts"; +import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts"; import { EventSinkV2 } from "./EventSink.ts"; +import type { PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; +import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; -import { ProjectionStoreV2 } from "./ProjectionStore.ts"; -import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts"; +import { applyToProjection, emptyProjection, ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts"; import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; -import { RunExecutionServiceV2 } from "./RunExecutionService.ts"; +import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts"; import { RuntimePolicyV2 } from "./RuntimePolicy.ts"; import { makeSubagentChildThread, subagentResultForRun, subagentThreadTitle, } from "./SubagentProjection.ts"; +import { ThreadForkServiceV2 } from "./ThreadForkService.ts"; export class OrchestratorDispatchError extends Schema.TaggedErrorClass()( "OrchestratorDispatchError", @@ -94,7 +93,7 @@ export class OrchestratorProviderAdapterError extends Schema.TaggedErrorClass Effect.Effect; + readonly getThreadSnapshot: (threadId: ThreadId) => Effect.Effect< + { + readonly schemaVersion: number; + readonly snapshotSequence: number; + readonly projection: OrchestrationV2ThreadProjection; + }, + OrchestratorV2Error + >; readonly getShellSnapshot: () => Effect.Effect; readonly getThreadEventSequence: ( threadId: ThreadId, ) => Effect.Effect; readonly streamStoredEvents: Stream.Stream; + readonly streamStoredEventsFrom: (input?: { + readonly threadId?: ThreadId; + readonly afterSequence?: number; + }) => Stream.Stream; readonly streamDomainEvents: Stream.Stream; } @@ -156,6 +167,14 @@ function nextRunOrdinal(projection: OrchestrationV2ThreadProjection): number { function commandThreadId(command: OrchestrationV2Command): ThreadId { switch (command.type) { case "thread.create": + case "thread.archive": + case "thread.unarchive": + case "thread.delete": + case "thread.metadata.update": + case "thread.runtime-mode.set": + case "thread.interaction-mode.set": + case "thread.model-selection.set": + case "provider-session.release": case "message.dispatch": case "run.interrupt": case "queued-message.promote-to-steer": @@ -172,28 +191,10 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId { } } -function lastSequence(storedEvents: ReadonlyArray): number { - return storedEvents.at(-1)?.sequence ?? 0; -} - function nextTurnItemOrdinal(projection: OrchestrationV2ThreadProjection): number { return Math.max(0, ...projection.turnItems.map((item) => item.ordinal)) + 1; } -function nextProviderTurnOrdinal( - projection: OrchestrationV2ThreadProjection, - providerThreadId: OrchestrationV2ProviderThread["id"], -): number { - return ( - Math.max( - 0, - ...projection.providerTurns - .filter((turn) => turn.providerThreadId === providerThreadId) - .map((turn) => turn.ordinal), - ) + 1 - ); -} - function isBlockingRun(run: OrchestrationV2Run): boolean { return run.status === "starting" || run.status === "running" || run.status === "waiting"; } @@ -362,12 +363,12 @@ function visibleDeltaRunOrdinals( function rootProviderThreadsForProvider( projection: OrchestrationV2ThreadProjection, - provider: ModelSelection["instanceId"], + providerInstanceId: ModelSelection["instanceId"], ): ReadonlyArray { return projection.providerThreads .filter( (providerThread) => - providerThread.provider === provider && + providerThread.providerInstanceId === providerInstanceId && providerThread.appThreadId === projection.thread.id && providerThread.ownerNodeId === null, ) @@ -383,12 +384,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandPolicy = yield* CommandPolicyV2; const contextHandoffService = yield* ContextHandoffServiceV2; const eventSink = yield* EventSinkV2; + const effectWorker = yield* OrchestrationEffectWorkerV2; const commandReceipts = yield* CommandReceiptStoreV2; const idAllocator = yield* IdAllocatorV2; const projectionStore = yield* ProjectionStoreV2; + const providerAdapters = yield* ProviderAdapterRegistryV2; const providerSessions = yield* ProviderSessionManagerV2; - const runExecution = yield* RunExecutionServiceV2; + const providerSwitchService = yield* ProviderSwitchServiceV2; const runtimePolicy = yield* RuntimePolicyV2; + const threadForkService = yield* ThreadForkServiceV2; const dispatchSemaphore = yield* Semaphore.make(1); const mapDispatchError = @@ -437,34 +441,47 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); const emit = - (events: Ref.Ref>, command: OrchestrationV2Command) => + (events: Ref.Ref>, command: OrchestrationV2Command) => (event: Omit) => Effect.gen(function* () { const withId = yield* makeEvent(command, event); - const storedEvents = yield* eventSink - .write({ commandId: command.commandId, events: [withId] }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); - const storedEvent = storedEvents[0]; - if (!storedEvent) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: "Event sink did not return a stored event.", - }); - } - yield* Ref.update(events, (existing) => [...existing, storedEvent]); - return storedEvent.event; + yield* Ref.update(events, (existing) => [...existing, withId]); + return withId; }); + const getProjectionWithPendingEvents = ( + threadId: ThreadId, + events: Ref.Ref>, + ) => + Effect.gen(function* () { + const pending = (yield* Ref.get(events)).filter((event) => event.threadId === threadId); + const stored = yield* Effect.option(projectionStore.getThreadProjection(threadId)); + let projection: OrchestrationV2ThreadProjection; + if (Option.isSome(stored)) { + projection = stored.value; + } else { + const created = pending.find( + ( + event, + ): event is Extract => + event.type === "thread.created", + ); + if (created === undefined) { + return yield* new OrchestratorProjectionError({ threadId }); + } + projection = emptyProjection(created); + } + + for (const event of pending) { + if (event.type === "thread.created" && projection.thread.id === event.payload.id) { + projection = { ...projection, thread: event.payload, updatedAt: event.occurredAt }; + continue; + } + projection = applyToProjection(projection, event); + } + return projection; + }); + const makeSystemEvent = (event: Omit) => Effect.gen(function* () { const eventId = yield* idAllocator.allocate.event({ @@ -476,12 +493,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } as Event; }); - const writeSystemEvents = (events: ReadonlyArray>) => + const writeSystemEvents = ( + events: ReadonlyArray>, + effects: ReadonlyArray = [], + ) => Effect.gen(function* () { const withIds = yield* Effect.forEach(events, (event) => makeSystemEvent(event as Omit), ); - yield* eventSink.write({ events: withIds }); + yield* eventSink.writeWithEffects({ events: withIds, effects }); }); const startNextQueuedRun = (threadId: ThreadId) => @@ -508,17 +528,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const rootNode = projection.nodes.find((candidate) => candidate.id === rootNodeId); const attempt = projection.attempts.find((candidate) => candidate.id === attemptId); - const message = projection.messages.find( - (candidate) => candidate.id === queuedRun.userMessageId, - ); const queuedProviderThread = projection.providerThreads.find( (candidate) => candidate.id === providerThreadId, ); + const checkpointScope = projection.checkpointScopes.find( + (scope) => scope.id === rootNode?.checkpointScopeId, + ); if ( rootNode === undefined || attempt === undefined || - message === undefined || - queuedProviderThread === undefined + queuedProviderThread === undefined || + checkpointScope === undefined ) { return yield* new OrchestratorDispatchError({ commandId: CommandId.make(`command:system:start-queued:${queuedRun.id}`), @@ -527,185 +547,69 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } - const modelSelection = projection.thread.modelSelection; - if (modelSelection.provider !== queuedRun.provider) { - return yield* new OrchestratorDispatchError({ - commandId: CommandId.make(`command:system:start-queued:${queuedRun.id}`), - commandType: "message.dispatch", - cause: `Queued provider ${queuedRun.provider} does not match thread model provider ${modelSelection.provider}.`, - }); - } - const providerSessionId = queuedProviderThread.providerSessionId ?? (yield* idAllocator.allocate.providerSession({ - provider: queuedRun.provider, + providerInstanceId: queuedRun.providerInstanceId, threadId, })); - const existingProviderSession = projection.providerSessions.find( - (candidate) => candidate.id === providerSessionId, - ); - const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ - thread: projection.thread, - modelSelection, - }); - const activeSession = yield* providerSessions.get(providerSessionId); - const session = yield* providerSessions.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy: resolvedRuntimePolicy, - ...(existingProviderSession === undefined - ? {} - : { resumeFromSession: existingProviderSession }), - }); - const resumedProviderThread = - Option.isSome(activeSession) || queuedProviderThread.providerSessionId === null - ? queuedProviderThread - : yield* session.resumeThread({ providerThread: queuedProviderThread }); - const now = yield* DateTime.now; const providerThread: OrchestrationV2ProviderThread = { - ...resumedProviderThread, + ...queuedProviderThread, providerSessionId, - status: "active", - firstRunOrdinal: resumedProviderThread.firstRunOrdinal ?? queuedRun.ordinal, + status: "not_loaded", + firstRunOrdinal: queuedProviderThread.firstRunOrdinal ?? queuedRun.ordinal, lastRunOrdinal: queuedRun.ordinal, updatedAt: now, }; - const checkpointScope = - rootNode.checkpointScopeId === null - ? yield* checkpointService.prepareRootRunScope({ - threadId, - runId: queuedRun.id, - rootNodeId, - providerThreadId: providerThread.id, - cwd: resolvedRuntimePolicy.cwd ?? session.providerSession.cwd, - createdAt: now, - }) - : (projection.checkpointScopes.find((scope) => scope.id === rootNode.checkpointScopeId) ?? - (yield* checkpointService.prepareRootRunScope({ - threadId, - runId: queuedRun.id, - rootNodeId, - providerThreadId: providerThread.id, - cwd: resolvedRuntimePolicy.cwd ?? session.providerSession.cwd, - createdAt: now, - }))); - const ensuredCheckpointScope = yield* checkpointService.ensureScope(checkpointScope); - const runningRun: OrchestrationV2Run = { + const startingRun: OrchestrationV2Run = { ...queuedRun, - status: "running", + status: "starting", queuePosition: null, - startedAt: now, - }; - const runningAttempt: OrchestrationV2RunAttempt = { - ...attempt, - status: "running", - startedAt: now, - }; - const runningRootNode: OrchestrationV2ExecutionNode = { - ...rootNode, - status: "running", - providerThreadId: providerThread.id, - checkpointScopeId: ensuredCheckpointScope.id, - startedAt: now, + startedAt: null, }; + const commandId = CommandId.make(`command:system:start-queued:${queuedRun.id}`); - yield* writeSystemEvents([ - { - type: "provider-session.updated", - threadId, - provider: queuedRun.provider, - occurredAt: now, - payload: session.providerSession, - }, - { - type: "provider-thread.updated", - threadId, - provider: queuedRun.provider, - occurredAt: now, - payload: providerThread, - }, - { - type: "run.updated", - threadId, - runId: queuedRun.id, - nodeId: rootNodeId, - provider: queuedRun.provider, - occurredAt: now, - payload: runningRun, - }, - { - type: "run-attempt.updated", - threadId, - runId: queuedRun.id, - nodeId: rootNodeId, - provider: queuedRun.provider, - occurredAt: now, - payload: runningAttempt, - }, - { - type: "node.updated", - threadId, - runId: queuedRun.id, - nodeId: rootNodeId, - provider: queuedRun.provider, - occurredAt: now, - payload: runningRootNode, - }, - { - type: "checkpoint-scope.created", - threadId, - runId: queuedRun.id, - nodeId: rootNodeId, - provider: queuedRun.provider, - occurredAt: now, - payload: ensuredCheckpointScope, - }, - ]); - - yield* runExecution.startRootRun({ - commandId: CommandId.make(`command:system:start-queued:${queuedRun.id}`), - appThread: projection.thread, - providerSessionId, - session, - run: runningRun, - rootNode: runningRootNode, - checkpointScope: ensuredCheckpointScope, - providerThread, - attempt: runningAttempt, - attemptId, - providerTurnOrdinal: nextProviderTurnOrdinal(projection, providerThread.id), - shouldFinalizeRun: () => - projectionStore.getThreadProjection(threadId).pipe( - Effect.map((current) => { - const currentRun = current.runs.find((candidate) => candidate.id === queuedRun.id); - return currentRun?.activeAttemptId === attemptId; - }), - Effect.catchCause(() => Effect.succeed(false)), - ), - message: { - messageId: message.id, - text: message.text, - attachments: message.attachments, - createdBy: message.createdBy, - creationSource: message.creationSource, - }, - modelSelection, - runtimePolicy: resolvedRuntimePolicy, - }); + yield* writeSystemEvents( + [ + { + type: "provider-thread.updated", + threadId, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: providerThread, + }, + { + type: "run.updated", + threadId, + runId: queuedRun.id, + nodeId: rootNodeId, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: startingRun, + }, + ], + [ + { + id: `effect:${commandId}:provider-turn.start:${queuedRun.id}`, + commandId, + threadId, + request: { type: "provider-turn.start", runId: queuedRun.id }, + }, + ], + ); + yield* effectWorker.drain(1); }); const dispatchThreadCreate = Effect.fn("orchestrationV2.dispatch.threadCreate")(function* ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, ) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.command_id": command.commandId, "orchestration_v2.command_type": command.type, "orchestration_v2.thread_id": command.threadId, - "orchestration_v2.provider": command.modelSelection.provider, + "orchestration_v2.driver": command.modelSelection.instanceId, }); const now = yield* DateTime.now; @@ -716,7 +620,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: command.threadId, projectId: command.projectId, title: command.title, - defaultProvider: command.modelSelection.provider, + providerInstanceId: command.modelSelection.instanceId, modelSelection: command.modelSelection, runtimeMode: command.runtimeMode, interactionMode: command.interactionMode, @@ -738,15 +642,257 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* emitEvent({ type: "thread.created", threadId: command.threadId, - provider: command.modelSelection.provider, + providerInstanceId: command.modelSelection.instanceId, occurredAt: now, payload: thread, }); }); + const dispatchThreadMutation = Effect.fn("orchestrationV2.dispatch.threadMutation")(function* ( + command: Extract< + OrchestrationV2Command, + { + readonly type: + | "thread.archive" + | "thread.unarchive" + | "thread.delete" + | "thread.metadata.update" + | "thread.runtime-mode.set" + | "thread.interaction-mode.set" + | "thread.model-selection.set" + | "provider.switch"; + } + >, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + const projection = yield* projectionStore.getThreadProjection(command.threadId).pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: command.threadId, + cause, + }), + ), + ); + const thread = projection.thread; + if (thread.deletedAt !== null && command.type !== "thread.delete") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is deleted.`, + }); + } + if (command.type === "thread.archive" && thread.archivedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is already archived.`, + }); + } + if (command.type === "thread.unarchive" && thread.archivedAt === null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is not archived.`, + }); + } + + const providerSwitchPlan = + command.type === "thread.model-selection.set" || command.type === "provider.switch" + ? yield* Effect.gen(function* () { + yield* providerAdapters.get(command.modelSelection.instanceId).pipe( + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: command.commandId, + providerInstanceId: command.modelSelection.instanceId, + cause, + }), + ), + ); + return yield* providerSwitchService + .plan({ + projection, + targetModelSelection: command.modelSelection, + }) + .pipe(mapDispatchError(command)); + }) + : null; + + const now = yield* DateTime.now; + const updatedThread: OrchestrationV2AppThread = (() => { + switch (command.type) { + case "thread.archive": + return { ...thread, archivedAt: now, updatedAt: now }; + case "thread.unarchive": + return { ...thread, archivedAt: null, updatedAt: now }; + case "thread.delete": + return { ...thread, deletedAt: thread.deletedAt ?? now, updatedAt: now }; + case "thread.metadata.update": + return { + ...thread, + ...(command.title === undefined ? {} : { title: command.title }), + ...(command.branch === undefined ? {} : { branch: command.branch }), + ...(command.worktreePath === undefined ? {} : { worktreePath: command.worktreePath }), + updatedAt: now, + }; + case "thread.runtime-mode.set": + return { ...thread, runtimeMode: command.runtimeMode, updatedAt: now }; + case "thread.interaction-mode.set": + return { ...thread, interactionMode: command.interactionMode, updatedAt: now }; + case "thread.model-selection.set": + case "provider.switch": + return { + ...thread, + providerInstanceId: command.modelSelection.instanceId, + modelSelection: command.modelSelection, + updatedAt: now, + }; + } + })(); + const eventType = (() => { + switch (command.type) { + case "thread.archive": + return "thread.archived" as const; + case "thread.unarchive": + return "thread.unarchived" as const; + case "thread.delete": + return "thread.deleted" as const; + case "thread.metadata.update": + return "thread.metadata-updated" as const; + case "thread.runtime-mode.set": + return "thread.runtime-mode-updated" as const; + case "thread.interaction-mode.set": + return "thread.interaction-mode-updated" as const; + case "thread.model-selection.set": + return "thread.model-selection-updated" as const; + case "provider.switch": + return "thread.provider-switched" as const; + } + })(); + yield* emit( + events, + command, + )({ + type: eventType, + threadId: command.threadId, + providerInstanceId: updatedThread.providerInstanceId, + occurredAt: now, + payload: updatedThread, + }); + + const releaseSessionIds = new Set( + command.type === "thread.archive" || command.type === "thread.delete" + ? projection.providerSessions.map((session) => session.id) + : command.type === "thread.runtime-mode.set" + ? projection.providerSessions + .filter( + (session) => !session.capabilities.sessions.supportsRuntimeModeSwitchInSession, + ) + .map((session) => session.id) + : (providerSwitchPlan?.releaseProviderSessionIds ?? []), + ); + if (releaseSessionIds.size > 0) { + const liveSessions = projection.providerSessions.filter( + (session) => + releaseSessionIds.has(session.id) && + session.status !== "stopped" && + session.status !== "error", + ); + yield* Effect.forEach( + liveSessions, + (session) => + Effect.gen(function* () { + yield* emit( + events, + command, + )({ + type: "provider-session.updated", + threadId: command.threadId, + driver: session.driver, + providerInstanceId: session.providerInstanceId, + occurredAt: now, + payload: { ...session, status: "stopped", updatedAt: now }, + }); + const pendingEffect = { + id: `effect:${command.commandId}:provider-session.release:${session.id}`, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "provider-session.release", + providerSessionId: session.id, + reason: "manual_shutdown", + detail: + command.type === "thread.archive" + ? "Thread archived." + : command.type === "thread.delete" + ? "Thread deleted." + : command.type === "thread.runtime-mode.set" + ? "Runtime mode changed." + : "Provider or model selection changed.", + }, + } satisfies PendingOrchestrationEffectV2; + yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); + }), + { concurrency: 1, discard: true }, + ); + } + }); + + const dispatchProviderSessionRelease = Effect.fn( + "orchestrationV2.dispatch.providerSessionRelease", + )(function* ( + command: Extract, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + const projection = yield* projectionStore + .getThreadProjection(command.threadId) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + const session = projection.providerSessions.find( + (candidate) => candidate.id === command.providerSessionId, + ); + if (session === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Provider session ${command.providerSessionId} does not belong to thread ${command.threadId}.`, + }); + } + const now = yield* DateTime.now; + yield* emit( + events, + command, + )({ + type: "provider-session.updated", + threadId: command.threadId, + driver: session.driver, + providerInstanceId: session.providerInstanceId, + occurredAt: now, + payload: { ...session, status: "stopped", updatedAt: now }, + }); + const pendingEffect = { + id: `effect:${command.commandId}:provider-session.release:${command.providerSessionId}`, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "provider-session.release", + providerSessionId: command.providerSessionId, + reason: "manual_shutdown", + ...(command.reason === undefined ? {} : { detail: command.reason }), + }, + } satisfies PendingOrchestrationEffectV2; + yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); + }); + const dispatchThreadFork = Effect.fn("orchestrationV2.dispatch.threadFork")(function* ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, ) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.command_id": command.commandId, @@ -787,28 +933,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const sourceProviderThread = providerThreadForRun(sourceProjection, sourceRun); const now = command.createdAt ?? (yield* DateTime.now); const emitEvent = emit(events, command); - const targetThread: OrchestrationV2AppThread = { - ...sourceProjection.thread, - createdBy: command.createdBy, - creationSource: command.creationSource, - id: command.targetThreadId, - title: command.title ?? `${sourceProjection.thread.title} fork`, - activeProviderThreadId: null, - lineage: { - parentThreadId: sourceProjection.thread.id, - relationshipToParent: "fork", - rootThreadId: sourceProjection.thread.lineage.rootThreadId, - }, - forkedFrom: { - type: "run", - threadId: sourceProjection.thread.id, - runId: sourceRun.id, - }, - createdAt: now, - updatedAt: now, - archivedAt: null, - deletedAt: null, - }; const transferId = yield* mapDispatchError(command)( idAllocator.allocate.contextTransfer({ sourceThreadId: sourceProjection.thread.id, @@ -816,39 +940,32 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "fork", }), ); - const transfer: OrchestrationV2ContextTransfer = { - id: transferId, - type: "fork", - sourceThreadId: sourceProjection.thread.id, - targetThreadId: command.targetThreadId, - sourcePoint: contextSourcePointForRun(sourceProjection, sourceRun), - basePoint: null, - sourceProvider: sourceRun.provider, - targetProvider: null, - targetRunId: null, - status: "pending", - resolution: null, - createdBy: command.createdBy, - error: - sourceProviderThread?.nativeThreadRef?.strength === "strong" - ? null - : "Source provider thread does not expose a strong native thread ref.", - createdAt: now, - updatedAt: now, - consumedAt: null, - }; + const { targetThread, transfer } = yield* threadForkService + .plan({ + sourceProjection, + sourceRun, + sourceProviderThread, + canonicalSourcePoint: contextSourcePointForRun(sourceProjection, sourceRun), + transferId, + targetThreadId: command.targetThreadId, + ...(command.title === undefined ? {} : { title: command.title }), + createdBy: command.createdBy, + creationSource: command.creationSource, + createdAt: now, + }) + .pipe(mapDispatchError(command)); yield* emitEvent({ type: "thread.created", threadId: command.targetThreadId, - provider: targetThread.defaultProvider, + providerInstanceId: targetThread.providerInstanceId, occurredAt: now, payload: targetThread, }); yield* emitEvent({ type: "context-transfer.created", threadId: command.targetThreadId, - provider: sourceRun.provider, + providerInstanceId: sourceRun.providerInstanceId, occurredAt: now, payload: transfer, }); @@ -856,7 +973,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const dispatchThreadMergeBack = Effect.fn("orchestrationV2.dispatch.threadMergeBack")(function* ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, ) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.command_id": command.commandId, @@ -954,8 +1071,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio targetThreadId: command.targetThreadId, sourcePoint: contextSourcePointForRun(sourceProjection, sourceRun), basePoint: forkTransfer.sourcePoint, - sourceProvider: sourceRun.provider, - targetProvider: targetProjection.thread.modelSelection.provider, + sourceProviderInstanceId: sourceRun.providerInstanceId, + targetProviderInstanceId: targetProjection.thread.modelSelection.instanceId, targetRunId: null, status: "pending", resolution: null, @@ -971,7 +1088,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* emitEvent({ type: "context-transfer.updated", threadId: command.targetThreadId, - provider: sourceRun.provider, + providerInstanceId: sourceRun.providerInstanceId, occurredAt: now, payload: { ...pendingTransfer, @@ -984,7 +1101,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* emitEvent({ type: "context-transfer.created", threadId: command.targetThreadId, - provider: sourceRun.provider, + providerInstanceId: sourceRun.providerInstanceId, occurredAt: now, payload: transfer, }); @@ -995,7 +1112,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio OrchestrationV2Command, { readonly type: "message.dispatch" | "queued-message.promote-to-steer" } >; - readonly events: Ref.Ref>; + readonly events: Ref.Ref>; + readonly effects: Ref.Ref>; readonly projection: OrchestrationV2ThreadProjection; readonly modelSelection: ModelSelection; readonly targetRunId: OrchestrationV2Run["id"]; @@ -1042,6 +1160,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Provider thread ${targetRun.providerThreadId} has no active provider session for steering.`, }); } + const providerSessionId = providerThread.providerSessionId; const providerTurn = input.projection.providerTurns.find( (candidate) => candidate.runAttemptId === targetRun.activeAttemptId && candidate.status === "running", @@ -1053,7 +1172,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `No running provider turn found for active run ${targetRun.id}.`, }); } - const sessionOption = yield* providerSessions.get(providerThread.providerSessionId).pipe( + const sessionOption = yield* providerSessions.get(providerSessionId).pipe( Effect.mapError( (cause) => new OrchestratorDispatchError({ @@ -1125,7 +1244,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: messageInput.runId, nodeId: messageInput.nodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: message, }); @@ -1134,7 +1253,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: messageInput.runId, nodeId: messageInput.nodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: turnItem, }); @@ -1144,107 +1263,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandPolicy.decideSteeringExecution({ commandId: input.command.commandId, threadId: input.command.threadId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, capabilities: session.providerSession.capabilities, forceRestart: input.forceRestart, }), ); if (steeringPolicy === "active_steering") { - yield* session - .steerTurn({ - threadId: input.command.threadId, - runId: targetRun.id, - providerThread, - providerTurnId: providerTurn.id, - message: { - messageId: input.messageId, - text: input.text, - attachments: input.attachments, - createdBy: input.createdBy, - creationSource: input.creationSource, - }, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: input.command.commandId, - provider: targetRun.provider, - cause, - }), - ), - ); yield* appendSteeringMessage({ runId: targetRun.id, nodeId: rootNodeId, providerTurnId: providerTurn.id, }); + yield* Ref.update(input.effects, (existing) => [ + ...existing, + { + id: `effect:${input.command.commandId}:provider-turn.steer:${providerTurn.id}`, + commandId: input.command.commandId, + threadId: input.command.threadId, + request: { + type: "provider-turn.steer", + providerSessionId, + providerThreadId: providerThread.id, + providerTurnId: providerTurn.id, + messageId: input.messageId, + }, + } satisfies PendingOrchestrationEffectV2, + ]); return; } - yield* session.interruptTurn({ providerThread, providerTurnId: providerTurn.id }).pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: input.command.commandId, - provider: targetRun.provider, - cause, - }), - ), - ); - - const waitForInterruptedExecution = ( - attemptsRemaining = 1_000, - ): Effect.Effect => - Effect.gen(function* () { - const current = yield* projectionStore - .getThreadProjection(input.command.threadId) - .pipe( - Effect.mapError( - () => new OrchestratorProjectionError({ threadId: input.command.threadId }), - ), - ); - const interruptedTurn = current.providerTurns.find( - (candidate) => candidate.id === providerTurn.id, - ); - const interruptedAttempt = current.attempts.find( - (candidate) => candidate.id === targetRun.activeAttemptId, - ); - const interruptedRun = current.runs.find((candidate) => candidate.id === targetRun.id); - if ( - interruptedTurn !== undefined && - interruptedTurn.status !== "running" && - interruptedAttempt !== undefined && - interruptedAttempt.status !== "running" && - interruptedRun !== undefined && - !["queued", "starting", "running", "waiting"].includes(interruptedRun.status) - ) { - return current; - } - if (attemptsRemaining <= 0) { - return yield* new OrchestratorDispatchError({ - commandId: input.command.commandId, - commandType: input.command.type, - cause: `Provider turn ${providerTurn.id} and attempt ${targetRun.activeAttemptId} did not terminalize before steering restart.`, - }); - } - yield* Effect.yieldNow; - return yield* waitForInterruptedExecution(attemptsRemaining - 1); - }); - - const postInterruptProjection = yield* waitForInterruptedExecution(); - - const currentAttempt = postInterruptProjection.attempts.find( + const currentAttempt = input.projection.attempts.find( (candidate) => candidate.id === targetRun.activeAttemptId, ); - const currentRootNode = postInterruptProjection.nodes.find( + const currentRootNode = input.projection.nodes.find( (candidate) => candidate.id === rootNodeId, ); const attemptOrdinal = Math.max( 0, - ...postInterruptProjection.attempts + ...input.projection.attempts .filter((candidate) => candidate.runId === targetRun.id) .map((candidate) => candidate.attemptOrdinal), ) + 1; @@ -1301,19 +1359,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...targetRun, rootNodeId: nextRootNodeId, activeAttemptId: nextAttemptId, - status: "running", + userMessageId: input.messageId, + status: "starting", }; const nextAttempt: OrchestrationV2RunAttempt = { id: nextAttemptId, runId: targetRun.id, attemptOrdinal, rootNodeId: nextRootNodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, providerThreadId: providerThread.id, providerTurnId: null, reason: "steering_restart", - status: "running", - startedAt: now, + status: "pending", + startedAt: null, completedAt: null, }; const nextRootNode: OrchestrationV2ExecutionNode = { @@ -1323,32 +1382,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio parentNodeId: null, rootNodeId: nextRootNodeId, kind: "root_turn", - status: "running", + status: "pending", countsForRun: true, providerThreadId: providerThread.id, providerTurnId: null, nativeItemRef: null, runtimeRequestId: null, checkpointScopeId: ensuredCheckpointScope.id, - startedAt: now, + startedAt: null, completedAt: null, }; - yield* emitEvent({ - type: "provider-turn.updated", - threadId: input.command.threadId, - runId: targetRun.id, - nodeId: rootNodeId, - provider: targetRun.provider, - occurredAt: now, - payload: { ...providerTurn, status: "interrupted", completedAt: now }, - }); if (currentAttempt !== undefined) { yield* emitEvent({ type: "run-attempt.updated", threadId: input.command.threadId, runId: targetRun.id, nodeId: rootNodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: { ...currentAttempt, status: "superseded", completedAt: now }, }); @@ -1359,7 +1409,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: rootNodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: { ...currentRootNode, status: "interrupted", completedAt: now }, }); @@ -1369,7 +1419,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: restartedRun, }); @@ -1378,7 +1428,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: nextAttempt, }); @@ -1387,7 +1437,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: nextRootNode, }); @@ -1396,7 +1446,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, runId: targetRun.id, nodeId: nextRootNodeId, - provider: targetRun.provider, + providerInstanceId: targetRun.providerInstanceId, occurredAt: now, payload: ensuredCheckpointScope, }); @@ -1405,59 +1455,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio nodeId: nextRootNodeId, providerTurnId: null, }); - yield* runExecution - .startRootRun({ + const interruptedAttemptId = targetRun.activeAttemptId; + if (interruptedAttemptId === null) { + return yield* new OrchestratorDispatchError({ commandId: input.command.commandId, - appThread: input.projection.thread, - providerSessionId: providerThread.providerSessionId, - session, - run: restartedRun, - rootNode: nextRootNode, - checkpointScope: ensuredCheckpointScope, - providerThread, - attempt: nextAttempt, - attemptId: nextAttemptId, - providerTurnOrdinal: nextProviderTurnOrdinal(input.projection, providerThread.id), - shouldFinalizeRun: () => - projectionStore.getThreadProjection(input.command.threadId).pipe( - Effect.map((current) => { - const currentRun = current.runs.find((candidate) => candidate.id === targetRun.id); - return currentRun?.activeAttemptId === nextAttemptId; - }), - Effect.catchCause(() => Effect.succeed(false)), - ), - message: { - messageId: input.messageId, - text: input.text, - attachments: input.attachments, - createdBy: input.createdBy, - creationSource: input.creationSource, + commandType: input.command.type, + cause: `Active run ${targetRun.id} has no attempt to interrupt.`, + }); + } + yield* Ref.update(input.effects, (existing) => [ + ...existing, + { + id: `effect:${input.command.commandId}:provider-turn.restart:${providerTurn.id}`, + commandId: input.command.commandId, + threadId: input.command.threadId, + request: { + type: "provider-turn.restart", + providerSessionId, + providerThreadId: providerThread.id, + providerTurnId: providerTurn.id, + interruptedAttemptId, + runId: targetRun.id, }, - modelSelection: input.modelSelection, - runtimePolicy: resolvedRuntimePolicy, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: input.command.commandId, - commandType: input.command.type, - cause, - }), - ), - ); + } satisfies PendingOrchestrationEffectV2, + ]); }); const dispatchMessage = ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, + effects: Ref.Ref>, ) => Effect.gen(function* () { - const projection = yield* projectionStore - .getThreadProjection(command.threadId) - .pipe( - Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })), - ); + const projection = yield* getProjectionWithPendingEvents(command.threadId, events); const modelSelection = command.modelSelection ?? projection.thread.modelSelection; const dispatchMode = command.dispatchMode; @@ -1465,6 +1495,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* dispatchSteerIntoRun({ command, events, + effects, projection, modelSelection, targetRunId: dispatchMode.targetRunId, @@ -1506,11 +1537,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Active run ${activeRun.id} has no provider thread for queued dispatch.`, }); } - if (modelSelection.provider !== queueProviderThread.provider) { + if (modelSelection.instanceId !== queueProviderThread.providerInstanceId) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, - cause: `Queued dispatch for provider ${modelSelection.provider} cannot run behind active provider ${queueProviderThread.provider}.`, + cause: `Queued dispatch for provider instance ${modelSelection.instanceId} cannot run behind active provider instance ${queueProviderThread.providerInstanceId}.`, }); } const existingProviderSession = @@ -1524,7 +1555,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandPolicy.ensureQueuedMessages({ commandId: command.commandId, threadId: command.threadId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, capabilities: existingProviderSession.capabilities, }), ); @@ -1574,7 +1605,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: runId, threadId: command.threadId, ordinal, - provider: modelSelection.instanceId, + providerInstanceId: modelSelection.instanceId, modelSelection, providerThreadId: queueProviderThread.id, userMessageId: command.messageId, @@ -1599,7 +1630,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId, attemptOrdinal: 1, rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, providerThreadId: queueProviderThread.id, providerTurnId: null, reason: "initial", @@ -1667,7 +1698,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: run, }); @@ -1676,7 +1707,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: attempt, }); @@ -1685,7 +1716,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: rootNode, }); @@ -1694,7 +1725,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: yield* checkpointService.ensureScope(checkpointScope).pipe( Effect.mapError( @@ -1712,7 +1743,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: message, }); @@ -1721,7 +1752,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: turnItem, }); @@ -1748,7 +1779,237 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const latestCompletedRun = projection.runs.findLast((run) => run.status === "completed"); const isProviderSwitch = activeProviderThread !== undefined && - activeProviderThread.provider !== modelSelection.instanceId; + activeProviderThread.providerInstanceId !== modelSelection.instanceId; + + if ( + pendingForkTransfer === undefined && + pendingMergeBackTransfer === undefined && + !isProviderSwitch + ) { + const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe( + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: command.commandId, + providerInstanceId: modelSelection.instanceId, + cause, + }), + ), + ); + const providerSessionId = + activeProviderThread?.providerSessionId ?? + (yield* mapDispatchError(command)( + idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId: command.threadId, + }), + )); + const providerThreadId = + activeProviderThread?.id ?? + idAllocator.derive.providerThread({ + driver: adapter.driver, + nativeThreadId: `pending:${runId}`, + }); + const providerThread: OrchestrationV2ProviderThread = + activeProviderThread === undefined + ? { + id: providerThreadId, + driver: adapter.driver, + providerInstanceId: modelSelection.instanceId, + providerSessionId, + appThreadId: command.threadId, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "not_loaded", + firstRunOrdinal: ordinal, + lastRunOrdinal: ordinal, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + } + : { + ...activeProviderThread, + providerSessionId, + lastRunOrdinal: ordinal, + updatedAt: now, + }; + const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }); + const rootNodeId = idAllocator.derive.rootNode({ runId }); + const resolvedRuntimePolicy = yield* runtimePolicy + .resolve({ + thread: projection.thread, + modelSelection, + }) + .pipe(mapDispatchError(command)); + const checkpointScope = yield* checkpointService + .prepareRootRunScope({ + threadId: command.threadId, + runId, + rootNodeId, + providerThreadId, + cwd: resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), + createdAt: now, + }) + .pipe(mapDispatchError(command)); + const run: OrchestrationV2Run = { + id: runId, + threadId: command.threadId, + ordinal, + providerInstanceId: modelSelection.instanceId, + modelSelection, + providerThreadId, + userMessageId: command.messageId, + rootNodeId, + activeAttemptId: attemptId, + status: "starting", + queuePosition: null, + requestedAt: now, + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + const attempt: OrchestrationV2RunAttempt = { + id: attemptId, + runId, + attemptOrdinal: 1, + rootNodeId, + providerInstanceId: modelSelection.instanceId, + providerThreadId, + providerTurnId: null, + reason: "initial", + status: "pending", + startedAt: null, + completedAt: null, + }; + const rootNode: OrchestrationV2ExecutionNode = { + id: rootNodeId, + threadId: command.threadId, + runId, + parentNodeId: null, + rootNodeId, + kind: "root_turn", + status: "pending", + countsForRun: true, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: checkpointScope.id, + startedAt: null, + completedAt: null, + }; + const message: OrchestrationV2ConversationMessage = { + createdBy: command.createdBy, + creationSource: command.creationSource, + id: command.messageId, + threadId: command.threadId, + runId, + nodeId: rootNodeId, + role: "user", + text: command.text, + attachments: command.attachments, + streaming: false, + createdAt: now, + updatedAt: now, + }; + const turnItem: OrchestrationV2TurnItem = { + createdBy: command.createdBy, + creationSource: command.creationSource, + id: idAllocator.derive.userTurnItem({ messageId: command.messageId }), + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: nextTurnItemOrdinal(projection), + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "user_message", + messageId: command.messageId, + inputIntent: "turn_start", + text: command.text, + attachments: command.attachments, + }; + const emitEvent = emit(events, command); + yield* emitEvent({ + type: "provider-thread.updated", + threadId: command.threadId, + driver: adapter.driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: providerThread, + }); + yield* emitEvent({ + type: "run.created", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: run, + }); + yield* emitEvent({ + type: "run-attempt.created", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: attempt, + }); + yield* emitEvent({ + type: "node.updated", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: rootNode, + }); + yield* emitEvent({ + type: "checkpoint-scope.created", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: checkpointScope, + }); + yield* emitEvent({ + type: "message.updated", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: message, + }); + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: turnItem, + }); + const pendingEffect = { + id: `effect:${command.commandId}:provider-turn.start:${runId}`, + commandId: command.commandId, + threadId: command.threadId, + request: { type: "provider-turn.start", runId }, + } satisfies PendingOrchestrationEffectV2; + yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); + return; + } const sourceProjection = pendingForkTransfer === undefined ? null @@ -1789,7 +2050,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Pending fork transfer ${pendingForkTransfer.id} has no resolvable source provider thread.`, }); } - if (pendingForkTransfer.sourceProvider === null) { + if (pendingForkTransfer.sourceProviderInstanceId === null) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, @@ -1805,7 +2066,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio targetProviderThread?.providerSessionId ?? (yield* mapDispatchError(command)( idAllocator.allocate.providerSession({ - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, threadId: command.threadId, }), )); @@ -1825,36 +2086,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); - const activeSession = yield* providerSessions.get(providerSessionId).pipe( + const adapter = yield* providerAdapters.get(modelSelection.instanceId).pipe( Effect.mapError( (cause) => new OrchestratorProviderAdapterError({ commandId: command.commandId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, + cause, + }), + ), + ); + const capabilities = yield* adapter.getCapabilities().pipe( + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: command.commandId, + providerInstanceId: modelSelection.instanceId, cause, }), ), ); - const session = yield* providerSessions - .open({ - threadId: command.threadId, - providerSessionId, - modelSelection, - runtimePolicy: resolvedRuntimePolicy, - ...(existingProviderSession === undefined - ? {} - : { resumeFromSession: existingProviderSession }), - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: modelSelection.provider, - cause, - }), - ), - ); const forkExecution = pendingForkTransfer === undefined ? null @@ -1862,9 +2113,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandPolicy.decideForkExecution({ commandId: command.commandId, threadId: command.threadId, - provider: modelSelection.instanceId, - capabilities: session.providerSession.capabilities, - sameProvider: pendingForkTransfer.sourceProvider === modelSelection.instanceId, + providerInstanceId: modelSelection.instanceId, + capabilities, + sameProvider: + pendingForkTransfer.sourceProviderInstanceId === modelSelection.instanceId, hasStrongNativeSource: sourceProviderThread?.nativeThreadRef?.strength === "strong", fromSpecificTurn: sourceRun !== null, }), @@ -1877,70 +2129,48 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandPolicy.ensureNativeFork({ commandId: command.commandId, threadId: command.threadId, - provider: modelSelection.provider, - capabilities: session.providerSession.capabilities, + providerInstanceId: modelSelection.instanceId, + capabilities, fromSpecificTurn: sourceRun !== null, }), ); } - const ensuredProviderThread = - canResolveForkNatively && sourceProviderThread !== undefined - ? yield* session - .forkThread({ - sourceProviderThread, - ...(sourceProjection === null - ? {} - : { sourceProviderTurns: sourceProjection.providerTurns }), - targetThreadId: command.threadId, - ...(sourceProviderTurnId === undefined - ? {} - : { providerTurnId: sourceProviderTurnId }), - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: modelSelection.provider, - cause, - }), - ), - ) - : targetProviderThread === undefined - ? yield* session - .ensureThread({ - threadId: command.threadId, - modelSelection, - runtimePolicy: resolvedRuntimePolicy, - providerSessionId, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: modelSelection.provider, - cause, - }), - ), - ) - : Option.isSome(activeSession) - ? targetProviderThread - : yield* session - .resumeThread({ - providerThread: targetProviderThread, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: modelSelection.provider, - cause, - }), - ), - ); + const ensuredProviderThread: OrchestrationV2ProviderThread = + targetProviderThread === undefined + ? { + id: idAllocator.derive.providerThread({ + driver: adapter.driver, + nativeThreadId: `pending:${runId}`, + }), + driver: adapter.driver, + providerInstanceId: modelSelection.instanceId, + providerSessionId, + appThreadId: command.threadId, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "not_loaded", + firstRunOrdinal: ordinal, + lastRunOrdinal: ordinal, + handoffIds: [], + forkedFrom: + canResolveForkNatively && sourceProviderThread !== undefined + ? { + providerThreadId: sourceProviderThread.id, + ...(sourceProviderTurnId === undefined + ? {} + : { providerTurnId: sourceProviderTurnId }), + } + : null, + createdAt: now, + updatedAt: now, + } + : { + ...targetProviderThread, + providerSessionId, + updatedAt: now, + }; const portableForkItems = !requiresPortableFork || sourceProjection === null || sourceRun === null ? [] @@ -1967,8 +2197,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio fromProviderThreadIds: sourceProviderThread === undefined ? [] : [sourceProviderThread.id], toProviderThreadId: ensuredProviderThread.id, - fromProvider: sourceRun.provider, - toProvider: modelSelection.instanceId, + fromProviderInstanceId: sourceRun.providerInstanceId, + toProviderInstanceId: modelSelection.instanceId, coveredRunOrdinals: visibleDeltaRunOrdinals(sourceProjection, portableForkItems), strategy: "full_thread_summary", items: portableForkItems, @@ -2021,8 +2251,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandPolicy.ensureContextHandoff({ commandId: command.commandId, threadId: command.threadId, - provider: modelSelection.instanceId, - capabilities: session.providerSession.capabilities, + providerInstanceId: modelSelection.instanceId, + capabilities, strategy: targetProviderThread === undefined || requiresFullProviderSwitchContext ? "full_thread_summary" @@ -2046,8 +2276,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ), toProviderThreadId: ensuredProviderThread.id, - fromProvider: latestCompletedRun.provider, - toProvider: modelSelection.instanceId, + fromProviderInstanceId: latestCompletedRun.providerInstanceId, + toProviderInstanceId: modelSelection.instanceId, coveredRunOrdinals: { from: providerSwitchCoveredRuns[0]!.ordinal, to: providerSwitchCoveredRuns.at(-1)!.ordinal, @@ -2130,8 +2360,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandPolicy.ensureContextHandoff({ commandId: command.commandId, threadId: command.threadId, - provider: modelSelection.provider, - capabilities: session.providerSession.capabilities, + providerInstanceId: modelSelection.instanceId, + capabilities, strategy: "fork_delta_context", }), ); @@ -2162,8 +2392,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio transferId: pendingMergeBackTransfer.id, fromProviderThreadIds: [mergeBackSourceProviderThread.id], toProviderThreadId: providerThread.id, - fromProvider: mergeBackSourceRun.provider, - toProvider: modelSelection.provider, + fromProviderInstanceId: mergeBackSourceRun.providerInstanceId, + toProviderInstanceId: modelSelection.instanceId, coveredRunOrdinals: visibleDeltaRunOrdinals( mergeBackSourceProjection, mergeBackDeltaItems, @@ -2187,7 +2417,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId, rootNodeId, providerThreadId: providerThread.id, - cwd: resolvedRuntimePolicy.cwd ?? session.providerSession.cwd, + cwd: + resolvedRuntimePolicy.cwd ?? + existingProviderSession?.cwd ?? + projection.thread.worktreePath ?? + process.cwd(), createdAt: now, }) .pipe( @@ -2204,16 +2438,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: runId, threadId: command.threadId, ordinal, - provider: modelSelection.instanceId, + providerInstanceId: modelSelection.instanceId, modelSelection, providerThreadId: providerThread.id, userMessageId: command.messageId, rootNodeId, activeAttemptId: attemptId, - status: "running", + status: "starting", queuePosition: null, requestedAt: now, - startedAt: now, + startedAt: null, completedAt: null, checkpointId: null, contextHandoffId: @@ -2224,12 +2458,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId, attemptOrdinal: 1, rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, providerThreadId: providerThread.id, providerTurnId: null, reason: "initial", - status: "running", - startedAt: now, + status: "pending", + startedAt: null, completedAt: null, }; const rootNode: OrchestrationV2ExecutionNode = { @@ -2239,14 +2473,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio parentNodeId: null, rootNodeId, kind: "root_turn", - status: "running", + status: "pending", countsForRun: true, providerThreadId: providerThread.id, providerTurnId: null, nativeItemRef: null, runtimeRequestId: null, checkpointScopeId: checkpointScope.id, - startedAt: now, + startedAt: null, completedAt: null, }; const message: OrchestrationV2ConversationMessage = { @@ -2287,11 +2521,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio attachments: command.attachments, }; const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff; - const providerHandoffs = [ - portableForkHandoff, - providerSwitchHandoff, - mergeBackHandoff, - ].flatMap((handoff) => (handoff === null ? [] : [handoff])); const handoffTurnItem: OrchestrationV2TurnItem | null = activeHandoff === null ? null @@ -2322,17 +2551,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio contextHandoffId: activeHandoff.id, fromProviderThreadIds: activeHandoff.fromProviderThreadIds, toProviderThreadId: activeHandoff.toProviderThreadId, - fromProviders: + fromProviderInstanceIds: portableForkHandoff !== null ? sourceRun === null ? [] - : [sourceRun.provider] + : [sourceRun.providerInstanceId] : providerSwitchHandoff === null ? mergeBackSourceRun === null ? [] - : [mergeBackSourceRun.provider] - : Array.from(new Set(providerSwitchCoveredRuns.map((run) => run.provider))), - toProvider: modelSelection.instanceId, + : [mergeBackSourceRun.providerInstanceId] + : Array.from( + new Set(providerSwitchCoveredRuns.map((run) => run.providerInstanceId)), + ), + toProviderInstanceId: modelSelection.instanceId, strategy: activeHandoff.strategy, summary: activeHandoff.summaryText, }; @@ -2358,19 +2589,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio contextHandoffId: mergeBackHandoff.id, }; - if (pendingForkTransfer !== undefined && nativeForkResolution !== null) { + if (pendingForkTransfer !== undefined && canResolveForkNatively) { yield* emitEvent({ type: "context-transfer.updated", threadId: command.threadId, runId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: { ...pendingForkTransfer, - targetProvider: modelSelection.provider, + targetProviderInstanceId: modelSelection.instanceId, targetRunId: runId, - status: "resolved_native", - resolution: nativeForkResolution, + status: "pending", + resolution: null, error: null, updatedAt: now, }, @@ -2381,11 +2612,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-transfer.updated", threadId: command.threadId, runId, - provider: modelSelection.instanceId, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: { ...pendingForkTransfer, - targetProvider: modelSelection.instanceId, + targetProviderInstanceId: modelSelection.instanceId, targetRunId: runId, status: "resolved_portable", resolution: portableForkResolution, @@ -2394,17 +2625,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, }); } - yield* emitEvent({ - type: "provider-session.updated", - threadId: command.threadId, - provider: modelSelection.provider, - occurredAt: now, - payload: session.providerSession, - }); yield* emitEvent({ type: "provider-thread.updated", threadId: command.threadId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: providerThread, }); @@ -2413,7 +2637,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-handoff.updated", threadId: command.threadId, runId, - provider: modelSelection.instanceId, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: portableForkHandoff, }); @@ -2442,8 +2666,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? null : contextSourcePointForRun(projection, baseRun); })(), - sourceProvider: latestCompletedRun.provider, - targetProvider: modelSelection.instanceId, + sourceProviderInstanceId: latestCompletedRun.providerInstanceId, + targetProviderInstanceId: modelSelection.instanceId, targetRunId: runId, status: "consumed", resolution: { @@ -2463,7 +2687,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-transfer.created", threadId: command.threadId, runId, - provider: modelSelection.instanceId, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: transfer, }); @@ -2471,7 +2695,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-handoff.updated", threadId: command.threadId, runId, - provider: modelSelection.instanceId, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: providerSwitchHandoff, }); @@ -2481,7 +2705,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-handoff.updated", threadId: command.threadId, runId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: mergeBackHandoff, }); @@ -2491,7 +2715,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-transfer.updated", threadId: command.threadId, runId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: { ...supersededTransfer, @@ -2509,11 +2733,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-transfer.updated", threadId: command.threadId, runId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: { ...pendingMergeBackTransfer, - targetProvider: modelSelection.provider, + targetProviderInstanceId: modelSelection.instanceId, targetRunId: runId, status: "consumed", resolution: mergeBackResolution, @@ -2528,7 +2752,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: run, }); @@ -2537,7 +2761,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: attempt, }); @@ -2546,7 +2770,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: rootNode, }); @@ -2555,7 +2779,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: yield* checkpointService.ensureScope(checkpointScope).pipe( Effect.mapError( @@ -2574,7 +2798,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: handoffTurnItem, }); @@ -2584,7 +2808,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: message, }); @@ -2593,7 +2817,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId, nodeId: rootNodeId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: turnItem, }); @@ -2603,11 +2827,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-transfer.updated", threadId: command.threadId, runId, - provider: modelSelection.provider, + providerInstanceId: modelSelection.instanceId, occurredAt: now, payload: { ...pendingForkTransfer, - targetProvider: modelSelection.provider, + targetProviderInstanceId: modelSelection.instanceId, targetRunId: runId, status: "consumed", resolution: forkResolution, @@ -2618,65 +2842,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } - const providerMessageText = - providerHandoffs.length === 0 - ? command.text - : providerHandoffs.length === 1 - ? providerMessageWithContextHandoff({ - handoff: providerHandoffs[0]!, - userText: command.text, - }) - : providerMessageWithContextHandoffs({ - handoffs: providerHandoffs, - userText: command.text, - }); - yield* runExecution - .startRootRun({ - commandId: command.commandId, - appThread: projection.thread, - providerSessionId, - session, - run, - rootNode, - checkpointScope, - providerThread, - attempt, - attemptId, - providerTurnOrdinal: nextProviderTurnOrdinal(projection, providerThread.id), - shouldFinalizeRun: () => - projectionStore.getThreadProjection(command.threadId).pipe( - Effect.map((current) => { - const currentRun = current.runs.find((candidate) => candidate.id === run.id); - return currentRun?.activeAttemptId === attemptId; - }), - Effect.catchCause(() => Effect.succeed(false)), - ), - message: { - messageId: command.messageId, - text: providerMessageText, - attachments: command.attachments, - createdBy: command.createdBy, - creationSource: command.creationSource, - }, - modelSelection, - runtimePolicy: resolvedRuntimePolicy, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); + const pendingEffect = { + id: `effect:${command.commandId}:provider-turn.start:${runId}`, + commandId: command.commandId, + threadId: command.threadId, + request: { type: "provider-turn.start", runId }, + } satisfies PendingOrchestrationEffectV2; + yield* Ref.update(effects, (existing) => [...existing, pendingEffect]); }); const dispatchDelegatedTaskRequest = Effect.fn("orchestrationV2.dispatch.delegatedTaskRequest")( function* ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, + effects: Ref.Ref>, ) { const parentProjection = yield* projectionStore .getThreadProjection(command.parentThreadId) @@ -2714,6 +2893,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } + const targetAdapter = yield* providerAdapters.get(command.modelSelection.instanceId).pipe( + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: command.commandId, + providerInstanceId: command.modelSelection.instanceId, + cause, + }), + ), + ); + const now = command.createdAt ?? (yield* DateTime.now); const taskNodeId = idAllocator.derive.delegatedTaskNode({ commandId: command.commandId, @@ -2756,7 +2946,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio parentNodeId: command.parentNodeId, origin: "app_owned", createdBy: command.createdBy, - provider: command.modelSelection.instanceId, + driver: targetAdapter.driver, + providerInstanceId: command.modelSelection.instanceId, providerThreadId: null, childThreadId, nativeTaskRef: null, @@ -2805,7 +2996,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "subagent", subagentId: taskNodeId, origin: "app_owned", - provider: command.modelSelection.instanceId, + driver: targetAdapter.driver, + providerInstanceId: command.modelSelection.instanceId, childThreadId, prompt: command.task, result: null, @@ -2815,7 +3007,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* emitEvent({ type: "thread.created", threadId: childThreadId, - provider: command.modelSelection.instanceId, + driver: targetAdapter.driver, + providerInstanceId: command.modelSelection.instanceId, occurredAt: now, payload: childThread, }); @@ -2824,7 +3017,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.parentThreadId, runId: parentRun.id, nodeId: taskNodeId, - provider: command.modelSelection.instanceId, + driver: targetAdapter.driver, + providerInstanceId: command.modelSelection.instanceId, occurredAt: now, payload: taskNode, }); @@ -2833,7 +3027,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.parentThreadId, runId: parentRun.id, nodeId: taskNodeId, - provider: command.modelSelection.instanceId, + driver: targetAdapter.driver, + providerInstanceId: command.modelSelection.instanceId, occurredAt: now, payload: task, }); @@ -2842,7 +3037,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.parentThreadId, runId: parentRun.id, nodeId: taskNodeId, - provider: command.modelSelection.instanceId, + driver: targetAdapter.driver, + providerInstanceId: command.modelSelection.instanceId, occurredAt: now, payload: taskTurnItem, }); @@ -2859,17 +3055,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio modelSelection: command.modelSelection, dispatchMode: { type: "start_immediately" }, } satisfies Extract; - yield* dispatchMessage(childMessageCommand, events); + yield* dispatchMessage(childMessageCommand, events, effects); - const childProjection = yield* projectionStore.getThreadProjection(childThreadId).pipe( - Effect.mapError( - (cause) => - new OrchestratorProjectionError({ - threadId: childThreadId, - cause, - }), - ), - ); + const childProjection = yield* getProjectionWithPendingEvents(childThreadId, events); const childRun = childProjection.runs[0]; if (childRun === undefined) { return yield* new OrchestratorDispatchError({ @@ -2895,8 +3083,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio turnItemId: taskTurnItemId, }, basePoint: null, - sourceProvider: parentRun.provider, - targetProvider: command.modelSelection.instanceId, + sourceProviderInstanceId: parentRun.providerInstanceId, + targetProviderInstanceId: command.modelSelection.instanceId, targetRunId: childRun.id, status: "consumed", resolution: null, @@ -2910,7 +3098,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-transfer.created", threadId: childThreadId, runId: childRun.id, - provider: command.modelSelection.instanceId, + providerInstanceId: command.modelSelection.instanceId, occurredAt: now, payload: spawnTransfer, }); @@ -2919,7 +3107,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const dispatchRuntimeRequestRespond = ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, + effects: Ref.Ref>, ) => Effect.gen(function* () { const projection = yield* projectionStore @@ -2951,45 +3140,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: runtimeRequest.responseCapability.reason, }); } + const providerSessionId = runtimeRequest.responseCapability.providerSessionId; - const sessionOption = yield* providerSessions - .get(runtimeRequest.responseCapability.providerSessionId) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); - if (Option.isNone(sessionOption)) { + const providerSession = projection.providerSessions.find( + (candidate) => candidate.id === providerSessionId, + ); + if (providerSession === undefined) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, - cause: `Provider session ${runtimeRequest.responseCapability.providerSessionId} is not active.`, + cause: `Provider session ${providerSessionId} was not found.`, }); } - const session = sessionOption.value; - yield* session - .respondToRuntimeRequest({ - requestId: command.requestId, - ...(command.decision === undefined ? {} : { decision: command.decision }), - ...(command.answers === undefined ? {} : { answers: command.answers }), - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: session.provider, - cause, - }), - ), - ); - const now = yield* DateTime.now; const resolvedRequest = { ...runtimeRequest, @@ -3007,7 +3170,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, ...(requestNode?.runId == null ? {} : { runId: requestNode.runId }), nodeId: runtimeRequest.nodeId, - provider: session.provider, + driver: providerSession.driver, + providerInstanceId: providerSession.providerInstanceId, occurredAt: now, payload: resolvedRequest, }); @@ -3017,7 +3181,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, ...(requestNode.runId === null ? {} : { runId: requestNode.runId }), nodeId: requestNode.id, - provider: session.provider, + driver: providerSession.driver, + providerInstanceId: providerSession.providerInstanceId, occurredAt: now, payload: { ...requestNode, @@ -3028,7 +3193,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } const approvalTurnItem = projection.turnItems.find( - (item) => item.type === "approval_request" && item.requestId === command.requestId, + (item) => + (item.type === "approval_request" || item.type === "user_input_request") && + item.requestId === command.requestId, ); if (approvalTurnItem !== undefined) { yield* emitEvent({ @@ -3036,7 +3203,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, ...(approvalTurnItem.runId === null ? {} : { runId: approvalTurnItem.runId }), ...(approvalTurnItem.nodeId === null ? {} : { nodeId: approvalTurnItem.nodeId }), - provider: session.provider, + driver: providerSession.driver, + providerInstanceId: providerSession.providerInstanceId, occurredAt: now, payload: { ...approvalTurnItem, @@ -3046,11 +3214,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, }); } + yield* Ref.update(effects, (existing) => [ + ...existing, + { + id: `effect:${command.commandId}:runtime-request.respond:${command.requestId}`, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "runtime-request.respond", + providerSessionId, + requestId: command.requestId, + ...(command.decision === undefined ? {} : { decision: command.decision }), + ...(command.answers === undefined ? {} : { answers: command.answers }), + }, + } satisfies PendingOrchestrationEffectV2, + ]); }); const dispatchQueuedMessagePromoteToSteer = ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, + effects: Ref.Ref>, ) => Effect.gen(function* () { const projection = yield* projectionStore @@ -3096,7 +3280,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId: queuedRun.id, nodeId: queuedRootNode.id, - provider: queuedRun.provider, + providerInstanceId: queuedRun.providerInstanceId, occurredAt: now, payload: { ...queuedRun, @@ -3110,7 +3294,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId: queuedRun.id, nodeId: queuedRootNode.id, - provider: queuedRun.provider, + providerInstanceId: queuedRun.providerInstanceId, occurredAt: now, payload: { ...queuedAttempt, @@ -3123,7 +3307,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId: queuedRun.id, nodeId: queuedRootNode.id, - provider: queuedRun.provider, + providerInstanceId: queuedRun.providerInstanceId, occurredAt: now, payload: { ...queuedRootNode, @@ -3135,6 +3319,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* dispatchSteerIntoRun({ command, events, + effects, projection, modelSelection: projection.thread.modelSelection, targetRunId: command.targetRunId, @@ -3149,7 +3334,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const dispatchQueuedRunReorder = ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, ) => Effect.gen(function* () { const projection = yield* projectionStore @@ -3204,7 +3389,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId: run.id, ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), - provider: run.provider, + providerInstanceId: run.providerInstanceId, occurredAt: now, payload: { ...run, @@ -3227,7 +3412,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const dispatchRunInterrupt = ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, + effects: Ref.Ref>, ) => Effect.gen(function* () { const findInterruptTarget = ( @@ -3291,12 +3477,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Provider thread ${providerThread.id} has no active provider session.`, }); } - const sessionOption = yield* providerSessions.get(providerThread.providerSessionId).pipe( + const providerSessionId = providerThread.providerSessionId; + const sessionOption = yield* providerSessions.get(providerSessionId).pipe( Effect.mapError( (cause) => new OrchestratorProviderAdapterError({ commandId: command.commandId, - provider: run.provider, + providerInstanceId: run.providerInstanceId, cause, }), ), @@ -3312,7 +3499,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandPolicy.ensureInterrupt({ commandId: command.commandId, threadId: command.threadId, - provider: run.provider, + providerInstanceId: run.providerInstanceId, capabilities: sessionOption.value.providerSession.capabilities, }), ); @@ -3371,30 +3558,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, runId: run.id, nodeId: rootNode.id, - provider: run.provider, + providerInstanceId: run.providerInstanceId, occurredAt: now, payload: interruptRequestItem, }); - yield* sessionOption.value - .interruptTurn({ - providerThread, - providerTurnId: providerTurn.id, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: run.provider, - cause, - }), - ), - ); + yield* Ref.update(effects, (existing) => [ + ...existing, + { + id: `effect:${command.commandId}:provider-turn.interrupt:${providerTurn.id}`, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "provider-turn.interrupt", + providerSessionId, + providerThreadId: providerThread.id, + providerTurnId: providerTurn.id, + }, + } satisfies PendingOrchestrationEffectV2, + ]); }); const dispatchCheckpointRollback = ( command: Extract, - events: Ref.Ref>, + events: Ref.Ref>, + effects: Ref.Ref>, ) => Effect.gen(function* () { const projection = yield* loadProjectionForCommand(command); @@ -3417,47 +3604,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } const modelSelection = projection.thread.modelSelection; - const resolvedRuntimePolicy = yield* runtimePolicy - .resolve({ thread: projection.thread, modelSelection }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); - const existingProviderSession = projection.providerSessions.find( - (candidate) => candidate.id === providerThread.providerSessionId, + const capabilities = yield* providerAdapters.get(modelSelection.instanceId).pipe( + Effect.flatMap((adapter) => adapter.getCapabilities()), + Effect.mapError( + (cause) => + new OrchestratorProviderAdapterError({ + commandId: command.commandId, + providerInstanceId: modelSelection.instanceId, + cause, + }), + ), ); - const session = yield* providerSessions - .open({ - threadId: command.threadId, - providerSessionId: providerThread.providerSessionId, - modelSelection, - runtimePolicy: resolvedRuntimePolicy, - ...(existingProviderSession === undefined - ? {} - : { resumeFromSession: existingProviderSession }), - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: modelSelection.provider, - cause, - }), - ), - ); yield* enforceCommandPolicy(command)( commandPolicy.ensureRollback({ commandId: command.commandId, threadId: command.threadId, - provider: modelSelection.provider, - capabilities: session.providerSession.capabilities, + providerInstanceId: modelSelection.instanceId, + capabilities, }), ); @@ -3481,173 +3644,63 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Checkpoint scope ${targetCheckpoint.scopeId} was not found.`, }); } + if (targetScope.id !== command.scopeId) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Checkpoint ${command.checkpointId} belongs to scope ${targetScope.id}, not ${command.scopeId}.`, + }); + } const targetOrdinal = targetCheckpoint.appRunOrdinal ?? 0; - const runsToRollback = projection.runs.filter( - (run) => run.ordinal > targetOrdinal && run.status === "completed", - ); - const providerThreadTurns = projection.providerTurns.filter( - (turn) => turn.providerThreadId === providerThread.id, - ); - const rollbackTarget: ProviderAdapterV2RollbackTarget = - targetOrdinal === 0 - ? { - type: "thread_start", - checkpointId: targetCheckpoint.id, - appRunOrdinal: 0, - } - : yield* Effect.gen(function* () { - const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal); - if (targetRun === undefined) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: `Cannot roll back to checkpoint ${targetCheckpoint.id}: no run exists for app ordinal ${targetOrdinal}.`, - }); - } - const targetProviderTurn = providerTurnForRun(projection, targetRun); - if (targetProviderTurn === undefined) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: `Cannot roll back to checkpoint ${targetCheckpoint.id}: run ${targetRun.id} has no provider turn.`, - }); - } - if (targetProviderTurn.providerThreadId !== providerThread.id) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: `Cannot roll back provider thread ${providerThread.id} to checkpoint ${targetCheckpoint.id}: target provider turn ${targetProviderTurn.id} belongs to provider thread ${targetProviderTurn.providerThreadId}.`, - }); - } - return { - type: "provider_turn" as const, - checkpointId: targetCheckpoint.id, - appRunOrdinal: targetOrdinal, - providerTurn: targetProviderTurn, - }; - }); - yield* checkpointService - .restore({ - scope: targetScope, - checkpoint: targetCheckpoint, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); - const numTurns = runsToRollback.length; - const snapshot = - numTurns === 0 - ? { providerThread } - : yield* session - .rollbackThread({ - providerThread, - target: rollbackTarget, - providerThreadTurns, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProviderAdapterError({ - commandId: command.commandId, - provider: modelSelection.provider, - cause, - }), - ), - ); - const staleCheckpoints = projection.checkpoints.filter( - (checkpoint): checkpoint is OrchestrationV2Checkpoint => - checkpoint.scopeId === targetScope.id && - checkpoint.appRunOrdinal !== null && - checkpoint.appRunOrdinal > targetOrdinal && - checkpoint.status === "ready", - ); - if (staleCheckpoints.length > 0) { - yield* checkpointService - .deleteStaleRefs({ - scope: targetScope, - checkpoints: staleCheckpoints, - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause, - }), - ), - ); - } - - const now = yield* DateTime.now; - const emitEvent = emit(events, command); - yield* emitEvent({ - type: "provider-thread.updated", - threadId: command.threadId, - provider: modelSelection.provider, - occurredAt: now, - payload: { - ...snapshot.providerThread, - lastRunOrdinal: targetOrdinal === 0 ? null : targetOrdinal, - updatedAt: now, - }, - }); - for (const checkpoint of staleCheckpoints) { - yield* emitEvent({ - type: "checkpoint.captured", - threadId: command.threadId, - ...(checkpoint.runId === null ? {} : { runId: checkpoint.runId }), - nodeId: checkpoint.nodeId, - provider: modelSelection.provider, - occurredAt: now, - payload: { - ...checkpoint, - status: "stale", - }, - }); - } - - for (const run of runsToRollback) { - const rootNode = - run.rootNodeId === null - ? undefined - : projection.nodes.find((candidate) => candidate.id === run.rootNodeId); - yield* emitEvent({ - type: "run.updated", - threadId: command.threadId, - runId: run.id, - ...(rootNode === undefined ? {} : { nodeId: rootNode.id }), - provider: run.provider, - occurredAt: now, - payload: { - ...run, - status: "rolled_back", - completedAt: now, - }, - }); - if (rootNode !== undefined) { - yield* emitEvent({ - type: "node.updated", - threadId: command.threadId, - runId: run.id, - nodeId: rootNode.id, - provider: run.provider, - occurredAt: now, - payload: { - ...rootNode, - status: "rolled_back", - completedAt: now, - }, + if (targetOrdinal > 0) { + const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal); + const targetProviderTurn = + targetRun === undefined ? undefined : providerTurnForRun(projection, targetRun); + if (targetRun === undefined || targetProviderTurn === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Cannot roll back to checkpoint ${targetCheckpoint.id}: its provider turn is unavailable.`, + }); + } + if (targetProviderTurn.providerThreadId !== providerThread.id) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Cannot roll back provider thread ${providerThread.id} to checkpoint ${targetCheckpoint.id}: target provider turn ${targetProviderTurn.id} belongs to provider thread ${targetProviderTurn.providerThreadId}.`, }); } } + + const now = yield* DateTime.now; + yield* emit( + events, + command, + )({ + type: "checkpoint.rollback-requested", + threadId: command.threadId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { + scopeId: targetScope.id, + checkpointId: targetCheckpoint.id, + requestedAt: now, + }, + }); + yield* Ref.update(effects, (existing) => [ + ...existing, + { + id: `effect:${command.commandId}:provider-thread.rollback:${providerThread.id}:${targetCheckpoint.id}`, + commandId: command.commandId, + threadId: command.threadId, + request: { + type: "provider-thread.rollback", + providerThreadId: providerThread.id, + checkpointId: targetCheckpoint.id, + scopeId: targetScope.id, + }, + } satisfies PendingOrchestrationEffectV2, + ]); }); const finalizeAppOwnedSubagent = (childThreadId: ThreadId) => @@ -3734,8 +3787,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { id: yield* idAllocator.allocate.contextHandoff({ threadId: parentThreadId, - fromProvider: childRun.provider, - toProvider: parentRun.provider, + fromProviderInstanceId: childRun.providerInstanceId, + toProviderInstanceId: parentRun.providerInstanceId, }), transferId: resultTransferId, threadId: parentThreadId, @@ -3750,7 +3803,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio status: "ready", summaryMessageId: result.messageId, summaryText: result.text, - createdByProvider: childRun.provider, + createdByProviderInstanceId: childRun.providerInstanceId, createdAt: now, updatedAt: now, }; @@ -3764,8 +3817,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(result.turnItemId === null ? {} : { turnItemId: result.turnItemId }), }, basePoint: null, - sourceProvider: childRun.provider, - targetProvider: parentRun?.provider ?? parentProjection.thread.defaultProvider, + sourceProviderInstanceId: childRun.providerInstanceId, + targetProviderInstanceId: + parentRun?.providerInstanceId ?? parentProjection.thread.providerInstanceId, targetRunId: parentRun?.id ?? null, status: "consumed", resolution: @@ -3788,7 +3842,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: parentThreadId, ...(task.runId === null ? {} : { runId: task.runId }), nodeId: task.id, - provider: task.provider, + driver: task.driver, occurredAt: now, payload: updatedTask, }, @@ -3800,7 +3854,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: parentThreadId, ...(parentNode.runId === null ? {} : { runId: parentNode.runId }), nodeId: parentNode.id, - provider: task.provider, + driver: task.driver, occurredAt: now, payload: { ...parentNode, @@ -3818,7 +3872,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: parentThreadId, ...(parentTurnItem.runId === null ? {} : { runId: parentTurnItem.runId }), ...(parentTurnItem.nodeId === null ? {} : { nodeId: parentTurnItem.nodeId }), - provider: task.provider, + driver: task.driver, occurredAt: now, payload: { ...parentTurnItem, @@ -3836,7 +3890,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-handoff.updated" as const, threadId: parentThreadId, ...(parentRun === undefined ? {} : { runId: parentRun.id }), - provider: childRun.provider, + providerInstanceId: childRun.providerInstanceId, occurredAt: now, payload: resultHandoff, }, @@ -3845,7 +3899,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "context-transfer.created", threadId: parentThreadId, ...(parentRun === undefined ? {} : { runId: parentRun.id }), - provider: childRun.provider, + providerInstanceId: childRun.providerInstanceId, occurredAt: now, payload: resultTransfer, }, @@ -3862,35 +3916,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const dispatchOnce = Effect.fn("orchestrationV2.dispatch.once")(function* ( command: OrchestrationV2Command, - ): Effect.fn.Return, OrchestratorV2Error> { + ): Effect.fn.Return< + { + readonly events: ReadonlyArray; + readonly effects: ReadonlyArray; + }, + OrchestratorV2Error + > { yield* Effect.annotateCurrentSpan({ "orchestration_v2.command_id": command.commandId, "orchestration_v2.command_type": command.type, "orchestration_v2.thread_id": commandThreadId(command), }); - const events = yield* Ref.make>([]); + const events = yield* Ref.make>([]); + const effects = yield* Ref.make>([]); switch (command.type) { case "thread.create": yield* dispatchThreadCreate(command, events); break; + case "thread.archive": + case "thread.unarchive": + case "thread.delete": + case "thread.metadata.update": + case "thread.runtime-mode.set": + case "thread.interaction-mode.set": + case "thread.model-selection.set": + case "provider.switch": + yield* dispatchThreadMutation(command, events, effects); + break; + case "provider-session.release": + yield* dispatchProviderSessionRelease(command, events, effects); + break; case "message.dispatch": - yield* dispatchMessage(command, events); + yield* dispatchMessage(command, events, effects); break; case "runtime-request.respond": - yield* dispatchRuntimeRequestRespond(command, events); + yield* dispatchRuntimeRequestRespond(command, events, effects); break; case "run.interrupt": - yield* dispatchRunInterrupt(command, events); + yield* dispatchRunInterrupt(command, events, effects); break; case "queued-message.promote-to-steer": - yield* dispatchQueuedMessagePromoteToSteer(command, events); + yield* dispatchQueuedMessagePromoteToSteer(command, events, effects); break; case "queued-run.reorder": yield* dispatchQueuedRunReorder(command, events); break; case "checkpoint.rollback": - yield* dispatchCheckpointRollback(command, events); + yield* dispatchCheckpointRollback(command, events, effects); break; case "thread.fork": yield* dispatchThreadFork(command, events); @@ -3899,12 +3973,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* dispatchThreadMergeBack(command, events); break; case "delegated_task.request": - yield* dispatchDelegatedTaskRequest(command, events); + yield* dispatchDelegatedTaskRequest(command, events, effects); break; default: return yield* dispatchUnsupported(command); } - return yield* Ref.get(events); + return { + events: yield* Ref.get(events), + effects: yield* Ref.get(effects), + }; }); const dispatchWithReceiptEffect = Effect.fn("orchestrationV2.dispatch.withReceipt")(function* ( @@ -3954,26 +4031,53 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies OrchestratorV2DispatchResult; } - const storedEvents = yield* dispatchOnce(command); - const sequence = lastSequence(storedEvents); - if (sequence === 0) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: "Command produced no stored events.", - }); - } + const plan = yield* dispatchOnce(command).pipe( + Effect.flatMap((planned) => + planned.events.length > 0 + ? Effect.succeed(planned) + : Effect.fail( + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Command produced no domain events.", + }), + ), + ), + Effect.catch((cause) => + Effect.gen(function* () { + const rejectedAt = yield* DateTime.now; + yield* eventSink + .commitRejectedCommand({ + commandId: command.commandId, + threadId: commandThreadId(command), + commandType: command.type, + rejectedAt, + error: cause instanceof Error ? cause.message : String(cause), + }) + .pipe( + Effect.mapError( + (receiptCause) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: receiptCause, + }), + ), + ); + return yield* cause; + }), + ), + ); - const acceptedAt = storedEvents.at(-1)?.event.occurredAt ?? (yield* DateTime.now); - yield* commandReceipts - .upsert({ + const acceptedAt = plan.events.at(-1)?.occurredAt ?? (yield* DateTime.now); + const committed = yield* eventSink + .commitCommand({ commandId: command.commandId, threadId: commandThreadId(command), commandType: command.type, acceptedAt, - resultSequence: sequence, - status: "accepted", - error: null, + events: plan.events, + effects: plan.effects, }) .pipe( Effect.mapError( @@ -3986,9 +4090,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + if (committed.receipt.status === "rejected") { + return yield* new OrchestratorCommandPreviouslyRejectedError({ + commandId: command.commandId, + commandType: command.type, + detail: committed.receipt.error ?? "Previously rejected.", + }); + } + + // The receipt and outbox rows are already committed here. Draining makes + // direct callers deterministic; the daemon remains responsible for work + // left behind by a crash between commit and this wake-up. + yield* effectWorker.drain(100).pipe( + Effect.mapError( + (cause) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause, + }), + ), + ); + return { - sequence, - storedEvents, + sequence: committed.receipt.resultSequence, + storedEvents: committed.storedEvents, } satisfies OrchestratorV2DispatchResult; }); @@ -4023,6 +4149,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projectionStore .getThreadProjection(threadId) .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), + getThreadSnapshot: (threadId) => + projectionStore + .getThreadSnapshot(threadId) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), getShellSnapshot: () => projectionStore.getShellSnapshot().pipe( Effect.mapError( @@ -4045,6 +4175,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), ), + streamStoredEventsFrom: (input) => + eventSink.stream(input).pipe( + Stream.mapError( + (cause) => + new OrchestratorDomainEventStreamError({ + cause, + }), + ), + ), streamDomainEvents: eventSink.stream().pipe( Stream.map((stored) => stored.event), Stream.mapError( @@ -4065,11 +4204,14 @@ export const layer: Layer.Layer< | CommandReceiptStoreV2 | ContextHandoffServiceV2 | EventSinkV2 + | OrchestrationEffectWorkerV2 | IdAllocatorV2 + | ProviderAdapterRegistryV2 | ProviderSessionManagerV2 + | ProviderSwitchServiceV2 | ProjectionStoreV2 - | RunExecutionServiceV2 | RuntimePolicyV2 + | ThreadForkServiceV2 > = Layer.effect(OrchestratorV2, makeOrchestrator()); export const layerUnavailable: Layer.Layer = Layer.succeed( @@ -4090,6 +4232,13 @@ export const layerUnavailable: Layer.Layer = Layer.succeed( cause: "Orchestration V2 live runtime is not configured.", }), ), + getThreadSnapshot: (threadId) => + Effect.fail( + new OrchestratorProjectionError({ + threadId, + cause: "Orchestration V2 live runtime is not configured.", + }), + ), getShellSnapshot: () => Effect.fail( new OrchestratorProjectionError({ @@ -4109,6 +4258,12 @@ export const layerUnavailable: Layer.Layer = Layer.succeed( cause: "Orchestration V2 live runtime is not configured.", }), ), + streamStoredEventsFrom: () => + Stream.fail( + new OrchestratorDomainEventStreamError({ + cause: "Orchestration V2 live runtime is not configured.", + }), + ), streamDomainEvents: Stream.fail( new OrchestratorDomainEventStreamError({ cause: "Orchestration V2 live runtime is not configured.", diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts new file mode 100644 index 0000000000..91ebe25336 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts @@ -0,0 +1,271 @@ +import { + type OrchestrationV2StoredEvent, + type OrchestrationV2ThreadProjection, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { EventStoreV2 } from "./EventStore.ts"; +import { + applyToProjection, + emptyProjection, + ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + ProjectionStoreV2, +} from "./ProjectionStore.ts"; + +export interface ProjectionVerificationV2 { + readonly valid: boolean; + readonly schemaVersion: number; + readonly expectedSequence: number; + readonly projectionSequence: number; + readonly differingThreadIds: ReadonlyArray; + readonly missingThreadIds: ReadonlyArray; + readonly unexpectedThreadIds: ReadonlyArray; +} + +export class ProjectionMaintenanceError extends Schema.TaggedErrorClass()( + "ProjectionMaintenanceError", + { + operation: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface ProjectionMaintenanceV2Shape { + readonly verify: Effect.Effect; + readonly rebuild: Effect.Effect; +} + +export class ProjectionMaintenanceV2 extends Context.Service< + ProjectionMaintenanceV2, + ProjectionMaintenanceV2Shape +>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {} + +type ProjectionMetadataRow = { + readonly schema_version: number; + readonly last_sequence: number; +}; + +function sortedProjection(projection: OrchestrationV2ThreadProjection): unknown { + const sortById = (values: ReadonlyArray) => + values.toSorted((left, right) => left.id.localeCompare(right.id)); + return { + ...projection, + runs: sortById(projection.runs), + attempts: sortById(projection.attempts), + nodes: sortById(projection.nodes), + subagents: sortById(projection.subagents), + providerSessions: sortById(projection.providerSessions), + providerThreads: sortById(projection.providerThreads), + providerTurns: sortById(projection.providerTurns), + runtimeRequests: sortById(projection.runtimeRequests), + messages: sortById(projection.messages), + plans: sortById(projection.plans), + turnItems: sortById(projection.turnItems), + checkpointScopes: sortById(projection.checkpointScopes), + checkpoints: sortById(projection.checkpoints), + contextHandoffs: sortById(projection.contextHandoffs), + contextTransfers: sortById(projection.contextTransfers), + // This is a derived lineage view. Its source entities are compared above. + visibleTurnItems: [], + }; +} + +function stableStringify(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(stableStringify).join(",")}]`; + } + if (typeof value === "object" && value !== null) { + const record = value as Record; + return `{${Object.keys(record) + .toSorted() + .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`) + .join(",")}}`; + } + return JSON.stringify(value); +} + +export const layer: Layer.Layer< + ProjectionMaintenanceV2, + never, + EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient +> = Layer.effect( + ProjectionMaintenanceV2, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const eventStore = yield* EventStoreV2; + const projectionStore = yield* ProjectionStoreV2; + + const readAllEvents = Effect.gen(function* () { + const events: Array = []; + const pageSize = 500; + let afterSequence = 0; + while (true) { + const page = yield* eventStore.read({ afterSequence, limit: pageSize }).pipe( + Stream.runCollect, + Effect.map((chunk) => Array.from(chunk)), + ); + events.push(...page); + if (page.length < pageSize) { + break; + } + afterSequence = page.at(-1)?.sequence ?? afterSequence; + } + return events; + }); + + const expectedProjections = (events: ReadonlyArray) => { + const projections = new Map(); + for (const stored of events) { + const event = stored.event; + if (event.type === "thread.created") { + projections.set(event.threadId, emptyProjection(event)); + continue; + } + const current = projections.get(event.threadId); + if (current !== undefined) { + projections.set(event.threadId, applyToProjection(current, event)); + } + } + return projections; + }; + + const verify = Effect.gen(function* () { + const events = yield* readAllEvents; + const expected = expectedProjections(events); + const projectionRows = yield* sql<{ readonly thread_id: string }>` + SELECT thread_id + FROM orchestration_v2_projection_threads + ORDER BY thread_id ASC + `; + const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id)); + const expectedIds = [...expected.keys()].toSorted((left, right) => left.localeCompare(right)); + const actualSet = new Set(actualIds); + const expectedSet = new Set(expectedIds); + const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId)); + const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId)); + const differingThreadIds: Array = []; + for (const threadId of expectedIds) { + if (!actualSet.has(threadId)) { + continue; + } + const actual = yield* projectionStore.getThreadProjection(threadId); + const expectedProjection = expected.get(threadId); + if ( + expectedProjection === undefined || + stableStringify(sortedProjection(actual)) !== + stableStringify(sortedProjection(expectedProjection)) + ) { + differingThreadIds.push(threadId); + } + } + const metadata = yield* sql` + SELECT schema_version, last_sequence + FROM orchestration_v2_projection_metadata + WHERE projection_name = 'thread-projections' + LIMIT 1 + `; + const expectedSequence = events.at(-1)?.sequence ?? 0; + const schemaVersion = metadata[0]?.schema_version ?? 0; + const projectionSequence = metadata[0]?.last_sequence ?? 0; + return { + valid: + schemaVersion === ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION && + projectionSequence === expectedSequence && + missingThreadIds.length === 0 && + unexpectedThreadIds.length === 0 && + differingThreadIds.length === 0, + schemaVersion, + expectedSequence, + projectionSequence, + differingThreadIds, + missingThreadIds, + unexpectedThreadIds, + } satisfies ProjectionVerificationV2; + }); + + const rebuild = Effect.gen(function* () { + const events = yield* readAllEvents; + yield* sql.withTransaction( + Effect.gen(function* () { + yield* sql`DELETE FROM orchestration_v2_projection_context_transfers`; + yield* sql`DELETE FROM orchestration_v2_projection_context_handoffs`; + yield* sql`DELETE FROM orchestration_v2_projection_checkpoints`; + yield* sql`DELETE FROM orchestration_v2_projection_checkpoint_scopes`; + yield* sql`DELETE FROM orchestration_v2_projection_turn_items`; + yield* sql`DELETE FROM orchestration_v2_projection_plans`; + yield* sql`DELETE FROM orchestration_v2_projection_messages`; + yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`; + yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`; + yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`; + yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`; + yield* sql`DELETE FROM orchestration_v2_projection_subagents`; + yield* sql`DELETE FROM orchestration_v2_projection_nodes`; + yield* sql`DELETE FROM orchestration_v2_projection_run_attempts`; + yield* sql`DELETE FROM orchestration_v2_projection_runs`; + yield* sql`DELETE FROM orchestration_v2_projection_threads`; + yield* sql`DELETE FROM orchestration_v2_turn_item_positions`; + + for (const stored of events) { + yield* projectionStore.apply(stored.event); + if (stored.event.type === "turn-item.updated") { + yield* sql` + INSERT INTO orchestration_v2_turn_item_positions ( + thread_id, + turn_item_id, + ordinal + ) + VALUES ( + ${stored.event.threadId}, + ${stored.event.payload.id}, + ${stored.event.payload.ordinal} + ) + ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET + ordinal = excluded.ordinal + `; + } + } + const now = DateTime.formatIso(yield* DateTime.now); + const lastSequence = events.at(-1)?.sequence ?? 0; + yield* sql` + INSERT INTO orchestration_v2_projection_metadata ( + projection_name, + schema_version, + last_sequence, + updated_at + ) + VALUES ( + 'thread-projections', + ${ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION}, + ${lastSequence}, + ${now} + ) + ON CONFLICT(projection_name) DO UPDATE SET + schema_version = excluded.schema_version, + last_sequence = excluded.last_sequence, + updated_at = excluded.updated_at + `; + }), + ); + return yield* verify; + }); + + const mapError = + (operation: string) => + (effect: Effect.Effect) => + effect.pipe( + Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })), + ); + + return ProjectionMaintenanceV2.of({ + verify: mapError("verify")(verify), + rebuild: mapError("rebuild")(rebuild), + }); + }), +); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 1d55cf9ee8..812ebafb68 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -5,6 +5,7 @@ import { type ModelSelection, NodeId, ProjectId, + ProviderDriverKind, ProviderInstanceId, ProviderThreadId, ProviderTurnId, @@ -30,6 +31,8 @@ const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", } satisfies ModelSelection; +const driver = ProviderDriverKind.make("codex"); +const providerInstanceId = modelSelection.instanceId; const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); it.layer(TestLayer)("ProjectionStoreV2", (it) => { @@ -53,11 +56,8 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { id: threadId, projectId, title: "Projection shell", - defaultProvider: "codex", - modelSelection: { - provider: "codex", - model: "gpt-5.4", - }, + providerInstanceId, + modelSelection: modelSelection, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -177,7 +177,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { id: threadId, projectId, title: "Projection rollback prune", - defaultProvider: "codex", + providerInstanceId, modelSelection, runtimeMode: "full-access", interactionMode: "default", @@ -200,11 +200,12 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { id: EventId.make("event:projection-rollback-prune:provider-thread"), type: "provider-thread.updated", threadId, - provider: "codex", + driver, occurredAt: now, payload: { id: providerThreadId, - provider: "codex", + driver, + providerInstanceId, providerSessionId: null, appThreadId: threadId, ownerNodeId: null, @@ -225,13 +226,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: runId, threadId, ordinal: 1, - provider: "codex", + providerInstanceId, modelSelection, providerThreadId, userMessageId, @@ -251,14 +252,14 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: attemptId, runId, attemptOrdinal: 1, rootNodeId, - provider: "codex", + providerInstanceId, providerThreadId, providerTurnId, reason: "initial", @@ -273,7 +274,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: rootNodeId, @@ -299,7 +300,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: assistantNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: assistantNodeId, @@ -325,7 +326,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: providerTurnId, @@ -345,7 +346,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { createdBy: "user", @@ -368,7 +369,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: assistantNodeId, - provider: "codex", + driver, occurredAt: now, payload: { createdBy: "agent", @@ -391,7 +392,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { createdBy: "user", @@ -423,7 +424,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: assistantNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: assistantTurnItemId, @@ -452,13 +453,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: runId, threadId, ordinal: 1, - provider: "codex", + providerInstanceId, modelSelection, providerThreadId, userMessageId, @@ -478,7 +479,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId, runId, nodeId: rootNodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: rootNodeId, @@ -548,7 +549,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { id: sourceThreadId, projectId, title: "Projection fork source rollback source", - defaultProvider: "codex", + providerInstanceId, modelSelection, runtimeMode: "full-access", interactionMode: "default", @@ -578,7 +579,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { id: targetThreadId, projectId, title: "Projection fork source rollback target", - defaultProvider: "codex", + providerInstanceId, modelSelection, runtimeMode: "full-access", interactionMode: "default", @@ -612,13 +613,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId: sourceThreadId, runId, nodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: runId, threadId: sourceThreadId, ordinal, - provider: "codex", + providerInstanceId, modelSelection, providerThreadId: sourceProviderThreadId, userMessageId: MessageId.make( @@ -640,7 +641,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId: sourceThreadId, runId, nodeId, - provider: "codex", + driver, occurredAt: now, payload: { createdBy: "user", @@ -672,7 +673,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId: sourceThreadId, runId, nodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: TurnItemId.make(`turn-item:projection-fork-source-rollback:assistant:${ordinal}`), @@ -711,13 +712,13 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { threadId: sourceThreadId, runId: sourceRun2Id, nodeId: sourceRun2NodeId, - provider: "codex", + driver, occurredAt: now, payload: { id: sourceRun2Id, threadId: sourceThreadId, ordinal: 2, - provider: "codex", + providerInstanceId, modelSelection, providerThreadId: sourceProviderThreadId, userMessageId: MessageId.make("message:projection-fork-source-rollback:user:2"), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index abeccf2570..78b4de020f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -106,12 +106,22 @@ export interface ProjectionStoreV2Shape { readonly getThreadProjection: ( threadId: ThreadId, ) => Effect.Effect; + readonly getThreadSnapshot: (threadId: ThreadId) => Effect.Effect< + { + readonly schemaVersion: number; + readonly snapshotSequence: number; + readonly projection: OrchestrationV2ThreadProjection; + }, + ProjectionStoreV2Error + >; } export class ProjectionStoreV2 extends Context.Service()( "t3/orchestration-v2/ProjectionStore/ProjectionStoreV2", ) {} +export const ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION = 1; + function upsertById(items: ReadonlyArray, next: T): Array { const index = items.findIndex((item) => item.id === next.id); if (index === -1) { @@ -154,11 +164,23 @@ export function applyToProjection( ): OrchestrationV2ThreadProjection { const base = { ...projection, + thread: { + ...projection.thread, + updatedAt: event.occurredAt, + }, updatedAt: event.occurredAt, }; switch (event.type) { case "thread.created": + case "thread.archived": + case "thread.unarchived": + case "thread.deleted": + case "thread.metadata-updated": + case "thread.runtime-mode-updated": + case "thread.interaction-mode-updated": + case "thread.model-selection-updated": + case "thread.provider-switched": return { ...base, thread: event.payload, @@ -230,6 +252,8 @@ export function applyToProjection( ...base, checkpoints: upsertById(base.checkpoints, event.payload), }; + case "checkpoint.rollback-requested": + return base; case "context-handoff.updated": return { ...base, @@ -253,6 +277,9 @@ type ShellThreadRow = { readonly payload_json: string; readonly latest_run_id: string | null; readonly latest_run_status: string | null; + readonly active_run_id: string | null; + readonly pending_request_payload_json: string | null; + readonly latest_message_payload_json: string | null; readonly item_count: number; }; @@ -587,32 +614,77 @@ export function threadShellFromProjection( projection: OrchestrationV2ThreadProjection, ): OrchestrationV2ThreadShell { const latestRun = projection.runs.at(-1) ?? null; + const activeRun = + projection.runs + .filter(isBlockingRunForShell) + .toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null; + const pendingRuntimeRequest = + projection.runtimeRequests + .filter((request) => request.status === "pending") + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt), + )[0] ?? null; + const latestVisibleMessage = + projection.messages.toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + )[0] ?? null; return { createdBy: projection.thread.createdBy, creationSource: projection.thread.creationSource, id: projection.thread.id, projectId: projection.thread.projectId, title: projection.thread.title, - defaultProvider: projection.thread.defaultProvider, + providerInstanceId: projection.thread.providerInstanceId, modelSelection: projection.thread.modelSelection, runtimeMode: projection.thread.runtimeMode, interactionMode: projection.thread.interactionMode, + branch: projection.thread.branch, + worktreePath: projection.thread.worktreePath, lineage: projection.thread.lineage, forkedFrom: projection.thread.forkedFrom, activeProviderThreadId: projection.thread.activeProviderThreadId, latestRunId: latestRun?.id ?? null, + activeRunId: activeRun?.id ?? null, status: latestRun?.status ?? "idle", + pendingRuntimeRequest: + pendingRuntimeRequest === null + ? null + : { + id: pendingRuntimeRequest.id, + kind: pendingRuntimeRequest.kind, + createdAt: pendingRuntimeRequest.createdAt, + }, + latestVisibleMessage: + latestVisibleMessage === null + ? null + : { + id: latestVisibleMessage.id, + role: latestVisibleMessage.role, + text: latestVisibleMessage.text, + updatedAt: latestVisibleMessage.updatedAt, + }, itemCount: activeLocalTurnItems(projection).length, visibleItemCount: projection.visibleTurnItems.length, createdAt: projection.thread.createdAt, updatedAt: projection.updatedAt, + archivedAt: projection.thread.archivedAt, + deletedAt: projection.thread.deletedAt, }; } +function isBlockingRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean { + return run.status === "starting" || run.status === "running" || run.status === "waiting"; +} + type ShellThreadState = { readonly thread: OrchestrationV2ThreadProjection["thread"]; readonly latestRunId: RunId | null; readonly latestRunStatus: OrchestrationV2ShellThreadStatus; + readonly activeRunId: RunId | null; + readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null; + readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null; readonly itemCount: number; readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"]; readonly runOrdinalById: ReadonlyMap; @@ -710,19 +782,41 @@ function shellFromState(input: { id: input.state.thread.id, projectId: input.state.thread.projectId, title: input.state.thread.title, - defaultProvider: input.state.thread.defaultProvider, + providerInstanceId: input.state.thread.providerInstanceId, modelSelection: input.state.thread.modelSelection, runtimeMode: input.state.thread.runtimeMode, interactionMode: input.state.thread.interactionMode, + branch: input.state.thread.branch, + worktreePath: input.state.thread.worktreePath, lineage: input.state.thread.lineage, forkedFrom: input.state.thread.forkedFrom, activeProviderThreadId: input.state.thread.activeProviderThreadId, latestRunId: input.state.latestRunId, + activeRunId: input.state.activeRunId, status: input.state.latestRunStatus, + pendingRuntimeRequest: + input.state.pendingRuntimeRequest === null + ? null + : { + id: input.state.pendingRuntimeRequest.id, + kind: input.state.pendingRuntimeRequest.kind, + createdAt: input.state.pendingRuntimeRequest.createdAt, + }, + latestVisibleMessage: + input.state.latestVisibleMessage === null + ? null + : { + id: input.state.latestVisibleMessage.id, + role: input.state.latestVisibleMessage.role, + text: input.state.latestVisibleMessage.text, + updatedAt: input.state.latestVisibleMessage.updatedAt, + }, itemCount: input.state.itemCount, visibleItemCount: input.visibleItemCount, createdAt: input.state.thread.createdAt, updatedAt: input.state.updatedAt, + archivedAt: input.state.thread.archivedAt, + deletedAt: input.state.thread.deletedAt, }; } @@ -734,7 +828,15 @@ export const layer: Layer.Layer = const apply: ProjectionStoreV2Shape["apply"] = (event) => Effect.gen(function* () { switch (event.type) { - case "thread.created": { + case "thread.created": + case "thread.archived": + case "thread.unarchived": + case "thread.deleted": + case "thread.metadata-updated": + case "thread.runtime-mode-updated": + case "thread.interaction-mode-updated": + case "thread.model-selection-updated": + case "thread.provider-switched": { const payloadJson = yield* encodeThreadPayload(event.payload); const payload = parseEncodedPayload(payloadJson); yield* sql` @@ -743,6 +845,7 @@ export const layer: Layer.Layer = project_id, title, default_provider, + provider_instance_id, runtime_mode, interaction_mode, active_provider_thread_id, @@ -756,7 +859,8 @@ export const layer: Layer.Layer = ${event.payload.id}, ${event.payload.projectId}, ${event.payload.title}, - ${event.payload.defaultProvider}, + ${event.payload.providerInstanceId}, + ${event.payload.providerInstanceId}, ${event.payload.runtimeMode}, ${event.payload.interactionMode}, ${event.payload.activeProviderThreadId}, @@ -771,6 +875,7 @@ export const layer: Layer.Layer = project_id = excluded.project_id, title = excluded.title, default_provider = excluded.default_provider, + provider_instance_id = excluded.provider_instance_id, runtime_mode = excluded.runtime_mode, interaction_mode = excluded.interaction_mode, active_provider_thread_id = excluded.active_provider_thread_id, @@ -792,6 +897,7 @@ export const layer: Layer.Layer = thread_id, ordinal, provider, + provider_instance_id, provider_thread_id, status, requested_at, @@ -802,7 +908,8 @@ export const layer: Layer.Layer = ${event.payload.id}, ${event.payload.threadId}, ${event.payload.ordinal}, - ${event.payload.provider}, + ${event.payload.providerInstanceId}, + ${event.payload.providerInstanceId}, ${event.payload.providerThreadId}, ${event.payload.status}, ${stringField(payload, "requestedAt")}, @@ -814,6 +921,7 @@ export const layer: Layer.Layer = thread_id = excluded.thread_id, ordinal = excluded.ordinal, provider = excluded.provider, + provider_instance_id = excluded.provider_instance_id, provider_thread_id = excluded.provider_thread_id, status = excluded.status, requested_at = excluded.requested_at, @@ -833,6 +941,7 @@ export const layer: Layer.Layer = attempt_ordinal, root_node_id, provider, + provider_instance_id, provider_thread_id, provider_turn_id, status, @@ -844,7 +953,8 @@ export const layer: Layer.Layer = ${event.payload.runId}, ${event.payload.attemptOrdinal}, ${event.payload.rootNodeId}, - ${event.payload.provider}, + ${event.payload.providerInstanceId}, + ${event.payload.providerInstanceId}, ${event.payload.providerThreadId}, ${event.payload.providerTurnId}, ${event.payload.status}, @@ -857,6 +967,7 @@ export const layer: Layer.Layer = attempt_ordinal = excluded.attempt_ordinal, root_node_id = excluded.root_node_id, provider = excluded.provider, + provider_instance_id = excluded.provider_instance_id, provider_thread_id = excluded.provider_thread_id, provider_turn_id = excluded.provider_turn_id, status = excluded.status, @@ -928,6 +1039,8 @@ export const layer: Layer.Layer = run_id, parent_node_id, provider, + driver, + provider_instance_id, provider_thread_id, child_thread_id, origin, @@ -942,7 +1055,9 @@ export const layer: Layer.Layer = ${event.payload.threadId}, ${event.payload.runId}, ${event.payload.parentNodeId}, - ${event.payload.provider}, + ${event.payload.providerInstanceId}, + ${event.payload.driver}, + ${event.payload.providerInstanceId}, ${event.payload.providerThreadId}, ${event.payload.childThreadId}, ${event.payload.origin}, @@ -958,6 +1073,8 @@ export const layer: Layer.Layer = run_id = excluded.run_id, parent_node_id = excluded.parent_node_id, provider = excluded.provider, + driver = excluded.driver, + provider_instance_id = excluded.provider_instance_id, provider_thread_id = excluded.provider_thread_id, child_thread_id = excluded.child_thread_id, origin = excluded.origin, @@ -977,6 +1094,8 @@ export const layer: Layer.Layer = provider_session_id, thread_id, provider, + driver, + provider_instance_id, status, model, updated_at, @@ -985,7 +1104,9 @@ export const layer: Layer.Layer = VALUES ( ${event.payload.id}, ${event.threadId}, - ${event.payload.provider}, + ${event.payload.providerInstanceId}, + ${event.payload.driver}, + ${event.payload.providerInstanceId}, ${event.payload.status}, ${event.payload.model}, ${stringField(payload, "updatedAt")}, @@ -995,6 +1116,8 @@ export const layer: Layer.Layer = DO UPDATE SET thread_id = excluded.thread_id, provider = excluded.provider, + driver = excluded.driver, + provider_instance_id = excluded.provider_instance_id, status = excluded.status, model = excluded.model, updated_at = excluded.updated_at, @@ -1011,6 +1134,8 @@ export const layer: Layer.Layer = thread_id, owner_node_id, provider, + driver, + provider_instance_id, provider_session_id, status, first_run_ordinal, @@ -1022,7 +1147,9 @@ export const layer: Layer.Layer = ${event.payload.id}, ${event.payload.appThreadId}, ${event.payload.ownerNodeId}, - ${event.payload.provider}, + ${event.payload.providerInstanceId}, + ${event.payload.driver}, + ${event.payload.providerInstanceId}, ${event.payload.providerSessionId}, ${event.payload.status}, ${event.payload.firstRunOrdinal}, @@ -1035,6 +1162,8 @@ export const layer: Layer.Layer = thread_id = excluded.thread_id, owner_node_id = excluded.owner_node_id, provider = excluded.provider, + driver = excluded.driver, + provider_instance_id = excluded.provider_instance_id, provider_session_id = excluded.provider_session_id, status = excluded.status, first_run_ordinal = excluded.first_run_ordinal, @@ -1360,6 +1489,8 @@ export const layer: Layer.Layer = `; break; } + case "checkpoint.rollback-requested": + break; case "context-handoff.updated": { const payloadJson = yield* encodeContextHandoffPayload(event.payload); const payload = parseEncodedPayload(payloadJson); @@ -1410,6 +1541,8 @@ export const layer: Layer.Layer = status, source_provider, target_provider, + source_provider_instance_id, + target_provider_instance_id, updated_at, payload_json ) @@ -1420,8 +1553,10 @@ export const layer: Layer.Layer = ${event.payload.targetRunId}, ${event.payload.type}, ${event.payload.status}, - ${event.payload.sourceProvider}, - ${event.payload.targetProvider}, + ${event.payload.sourceProviderInstanceId}, + ${event.payload.targetProviderInstanceId}, + ${event.payload.sourceProviderInstanceId}, + ${event.payload.targetProviderInstanceId}, ${stringField(payload, "updatedAt")}, ${payloadJson} ) @@ -1434,12 +1569,46 @@ export const layer: Layer.Layer = status = excluded.status, source_provider = excluded.source_provider, target_provider = excluded.target_provider, + source_provider_instance_id = excluded.source_provider_instance_id, + target_provider_instance_id = excluded.target_provider_instance_id, updated_at = excluded.updated_at, payload_json = excluded.payload_json `; break; } } + + if ( + event.type !== "thread.created" && + event.type !== "thread.archived" && + event.type !== "thread.unarchived" && + event.type !== "thread.deleted" && + event.type !== "thread.metadata-updated" && + event.type !== "thread.runtime-mode-updated" && + event.type !== "thread.interaction-mode-updated" && + event.type !== "thread.model-selection-updated" && + event.type !== "thread.provider-switched" + ) { + const rows = yield* sql` + SELECT payload_json + FROM orchestration_v2_projection_threads + WHERE thread_id = ${event.threadId} + LIMIT 1 + `; + const row = rows[0]; + if (row !== undefined) { + const thread = yield* decodeThreadPayload(row.payload_json); + const updatedThread = { ...thread, updatedAt: event.occurredAt }; + const payloadJson = yield* encodeThreadPayload(updatedThread); + yield* sql` + UPDATE orchestration_v2_projection_threads + SET + updated_at = ${stringField(parseEncodedPayload(payloadJson), "updatedAt")}, + payload_json = ${payloadJson} + WHERE thread_id = ${event.threadId} + `; + } + } }).pipe( Effect.mapError( (cause) => @@ -1575,13 +1744,13 @@ export const layer: Layer.Layer = SELECT payload_json FROM orchestration_v2_projection_context_handoffs WHERE thread_id = ${threadId} - ORDER BY updated_at ASC, context_handoff_id ASC + ORDER BY rowid ASC `, sql` SELECT payload_json FROM orchestration_v2_projection_context_transfers WHERE source_thread_id = ${threadId} OR target_thread_id = ${threadId} - ORDER BY updated_at ASC, context_transfer_id ASC + ORDER BY rowid ASC `, ]); @@ -1678,10 +1847,38 @@ export const layer: Layer.Layer = const getThreadProjection: ProjectionStoreV2Shape["getThreadProjection"] = (threadId) => readProjection(threadId, new Set()); + const getThreadSnapshot: ProjectionStoreV2Shape["getThreadSnapshot"] = (threadId) => + sql + .withTransaction( + Effect.gen(function* () { + const projection = yield* getThreadProjection(threadId); + const rows = yield* sql<{ readonly snapshot_sequence: number | null }>` + SELECT MAX(sequence) AS snapshot_sequence + FROM orchestration_v2_events + WHERE thread_id = ${threadId} + `; + return { + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + snapshotSequence: rows[0]?.snapshot_sequence ?? 0, + projection, + }; + }), + ) + .pipe( + Effect.mapError((cause) => + Schema.is(ProjectionStoreThreadNotFoundError)(cause) || + Schema.is(ProjectionStoreReadError)(cause) + ? cause + : new ProjectionStoreReadError({ threadId, cause }), + ), + ); + const getShellSnapshot: ProjectionStoreV2Shape["getShellSnapshot"] = () => - Effect.gen(function* () { - const [threadRows, runRows, itemCountRows] = yield* Effect.all([ - sql` + sql + .withTransaction( + Effect.gen(function* () { + const [threadRows, runRows, itemCountRows, sequenceRows] = yield* Effect.all([ + sql` SELECT t.thread_id, t.payload_json, @@ -1699,6 +1896,29 @@ export const layer: Layer.Layer = ORDER BY r.ordinal DESC, r.run_id DESC LIMIT 1 ) AS latest_run_status, + ( + SELECT r.run_id + FROM orchestration_v2_projection_runs r + WHERE r.thread_id = t.thread_id + AND r.status IN ('starting', 'running', 'waiting') + ORDER BY r.ordinal DESC, r.run_id DESC + LIMIT 1 + ) AS active_run_id, + ( + SELECT request.payload_json + FROM orchestration_v2_projection_runtime_requests request + WHERE request.thread_id = t.thread_id + AND request.status = 'pending' + ORDER BY request.created_at DESC, request.runtime_request_id DESC + LIMIT 1 + ) AS pending_request_payload_json, + ( + SELECT message.payload_json + FROM orchestration_v2_projection_messages message + WHERE message.thread_id = t.thread_id + ORDER BY message.updated_at DESC, message.message_id DESC + LIMIT 1 + ) AS latest_message_payload_json, ( SELECT COUNT(*) FROM orchestration_v2_projection_turn_items i @@ -1711,80 +1931,102 @@ export const layer: Layer.Layer = WHERE t.deleted_at IS NULL ORDER BY t.updated_at ASC, t.thread_id ASC `, - sql` + sql` SELECT thread_id, run_id, ordinal FROM orchestration_v2_projection_runs `, - sql` + sql` SELECT thread_id, run_id, COUNT(*) AS item_count FROM orchestration_v2_projection_turn_items WHERE run_id IS NOT NULL GROUP BY thread_id, run_id `, - ]); + sql<{ readonly snapshot_sequence: number | null }>` + SELECT MAX(sequence) AS snapshot_sequence + FROM orchestration_v2_events + `, + ]); - const runOrdinalsByThreadId = new Map>(); - for (const row of runRows) { - const threadId = ThreadId.make(row.thread_id); - const runId = RunId.make(row.run_id); - const existing = runOrdinalsByThreadId.get(threadId) ?? new Map(); - existing.set(runId, row.ordinal); - runOrdinalsByThreadId.set(threadId, existing); - } + const runOrdinalsByThreadId = new Map>(); + for (const row of runRows) { + const threadId = ThreadId.make(row.thread_id); + const runId = RunId.make(row.run_id); + const existing = runOrdinalsByThreadId.get(threadId) ?? new Map(); + existing.set(runId, row.ordinal); + runOrdinalsByThreadId.set(threadId, existing); + } - const itemCountsByThreadId = new Map>(); - for (const row of itemCountRows) { - const threadId = ThreadId.make(row.thread_id); - const runId = RunId.make(row.run_id); - const existing = itemCountsByThreadId.get(threadId) ?? new Map(); - existing.set(runId, row.item_count); - itemCountsByThreadId.set(threadId, existing); - } + const itemCountsByThreadId = new Map>(); + for (const row of itemCountRows) { + const threadId = ThreadId.make(row.thread_id); + const runId = RunId.make(row.run_id); + const existing = itemCountsByThreadId.get(threadId) ?? new Map(); + existing.set(runId, row.item_count); + itemCountsByThreadId.set(threadId, existing); + } - const states = yield* Effect.forEach(threadRows, (row) => - decodeThreadPayload(row.payload_json).pipe( - Effect.map( - (thread): ShellThreadState => ({ - thread, - latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id), - latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status), - itemCount: row.item_count, - updatedAt: thread.updatedAt, - runOrdinalById: - runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(), - itemCountByRunId: - itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(), + const states = yield* Effect.forEach(threadRows, (row) => + Effect.gen(function* () { + const thread = yield* decodeThreadPayload(row.payload_json); + const pendingRuntimeRequest = + row.pending_request_payload_json === null + ? null + : yield* decodeRuntimeRequestPayload(row.pending_request_payload_json); + const latestVisibleMessage = + row.latest_message_payload_json === null + ? null + : yield* decodeMessagePayload(row.latest_message_payload_json); + return { + thread, + latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id), + latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status), + activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id), + pendingRuntimeRequest, + latestVisibleMessage, + itemCount: row.item_count, + updatedAt: thread.updatedAt, + runOrdinalById: + runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(), + itemCountByRunId: + itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(), + } satisfies ShellThreadState; + }), + ); + const statesByThreadId = new Map(states.map((state) => [state.thread.id, state])); + + const shells = states.map((state) => + shellFromState({ + state, + visibleItemCount: visibleItemCountForShell({ + threadId: state.thread.id, + statesByThreadId, + }), + }), + ); + + return { + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + snapshotSequence: sequenceRows[0]?.snapshot_sequence ?? 0, + threads: shells.filter((thread) => thread.archivedAt === null), + archivedThreads: shells.filter((thread) => thread.archivedAt !== null), + }; + }), + ) + .pipe( + Effect.mapError( + (cause) => + new ProjectionStoreReadError({ + threadId: ThreadId.make("thread:shell"), + cause, }), - ), ), ); - const statesByThreadId = new Map(states.map((state) => [state.thread.id, state])); - - return { - threads: states.map((state) => - shellFromState({ - state, - visibleItemCount: visibleItemCountForShell({ - threadId: state.thread.id, - statesByThreadId, - }), - }), - ), - }; - }).pipe( - Effect.mapError( - (cause) => - new ProjectionStoreReadError({ - threadId: ThreadId.make("thread:shell"), - cause, - }), - ), - ); return { apply, getShellSnapshot, getThreadProjection, + getThreadSnapshot, } satisfies ProjectionStoreV2Shape; }), ); @@ -1793,6 +2035,7 @@ export const layerMemory: Layer.Layer = Layer.effect( ProjectionStoreV2, Effect.gen(function* () { const projections = yield* Ref.make(new Map()); + const sequence = yield* Ref.make(0); const service: ProjectionStoreV2Shape = { apply: (event) => @@ -1820,6 +2063,7 @@ export const layerMemory: Layer.Layer = Layer.effect( if (result) { return yield* result; } + yield* Ref.update(sequence, (current) => current + 1); }), getShellSnapshot: () => Effect.gen(function* () { @@ -1831,7 +2075,13 @@ export const layerMemory: Layer.Layer = Layer.effect( (threadId) => service.getThreadProjection(threadId).pipe(Effect.map(threadShellFromProjection)), ); - return { threads: shells }; + const visible = shells.filter((thread) => thread.deletedAt === null); + return { + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + snapshotSequence: yield* Ref.get(sequence), + threads: visible.filter((thread) => thread.archivedAt === null), + archivedThreads: visible.filter((thread) => thread.archivedAt !== null), + }; }), getThreadProjection: (threadId) => Effect.gen(function* () { @@ -1866,6 +2116,18 @@ export const layerMemory: Layer.Layer = Layer.effect( } return projection; }), + getThreadSnapshot: (threadId) => + service.getThreadProjection(threadId).pipe( + Effect.flatMap((projection) => + Ref.get(sequence).pipe( + Effect.map((snapshotSequence) => ({ + schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, + snapshotSequence, + projection, + })), + ), + ), + ), }; return service; diff --git a/apps/server/src/orchestration-v2/ProviderAdapter.ts b/apps/server/src/orchestration-v2/ProviderAdapter.ts index febfc41c89..b54cf5c1d6 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapter.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapter.ts @@ -18,7 +18,8 @@ import { OrchestrationV2TurnItem, ProviderApprovalDecision, ProviderInteractionMode, - ProviderKind, + ProviderDriverKind, + ProviderInstanceId, ProviderUserInputAnswers, ProviderSessionId, ProviderThreadId, @@ -67,59 +68,59 @@ export type ProviderAdapterV2SessionStatus = typeof ProviderAdapterV2SessionStat export const ProviderAdapterV2Event = Schema.Union([ Schema.Struct({ type: Schema.Literal("app_thread.created"), - provider: ProviderKind, + driver: ProviderDriverKind, appThread: OrchestrationV2AppThread, }), Schema.Struct({ type: Schema.Literal("provider_session.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, providerSession: OrchestrationV2ProviderSession, }), Schema.Struct({ type: Schema.Literal("provider_thread.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, providerThread: OrchestrationV2ProviderThread, }), Schema.Struct({ type: Schema.Literal("provider_turn.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, threadId: Schema.optional(ThreadId), providerTurn: OrchestrationV2ProviderTurn, }), Schema.Struct({ type: Schema.Literal("node.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, node: OrchestrationV2ExecutionNode, }), Schema.Struct({ type: Schema.Literal("subagent.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, subagent: OrchestrationV2Subagent, }), Schema.Struct({ type: Schema.Literal("message.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, message: OrchestrationV2ConversationMessage, }), Schema.Struct({ type: Schema.Literal("turn_item.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, turnItem: OrchestrationV2TurnItem, }), Schema.Struct({ type: Schema.Literal("runtime_request.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, threadId: Schema.optional(ThreadId), runtimeRequest: OrchestrationV2RuntimeRequest, }), Schema.Struct({ type: Schema.Literal("plan.updated"), - provider: ProviderKind, + driver: ProviderDriverKind, plan: OrchestrationV2PlanArtifact, }), Schema.Struct({ type: Schema.Literal("turn.terminal"), - provider: ProviderKind, + driver: ProviderDriverKind, providerTurnId: ProviderTurnId, status: Schema.Literals(["completed", "interrupted", "failed", "cancelled"]), }), @@ -129,112 +130,112 @@ export type ProviderAdapterV2Event = typeof ProviderAdapterV2Event.Type; export class ProviderAdapterCapabilitiesError extends Schema.TaggedErrorClass()( "ProviderAdapterCapabilitiesError", { - provider: ProviderKind, + driver: ProviderDriverKind, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to read ${this.provider} provider capabilities.`; + return `Failed to read ${this.driver} provider capabilities.`; } } export class ProviderAdapterOpenSessionError extends Schema.TaggedErrorClass()( "ProviderAdapterOpenSessionError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerSessionId: ProviderSessionId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to open ${this.provider} provider session ${this.providerSessionId}.`; + return `Failed to open ${this.driver} provider session ${this.providerSessionId}.`; } } export class ProviderAdapterCloseSessionError extends Schema.TaggedErrorClass()( "ProviderAdapterCloseSessionError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerSessionId: ProviderSessionId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to close ${this.provider} provider session ${this.providerSessionId}.`; + return `Failed to close ${this.driver} provider session ${this.providerSessionId}.`; } } export class ProviderAdapterResumeThreadError extends Schema.TaggedErrorClass()( "ProviderAdapterResumeThreadError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to resume ${this.provider} provider thread ${this.providerThreadId}.`; + return `Failed to resume ${this.driver} provider thread ${this.providerThreadId}.`; } } export class ProviderAdapterEnsureThreadError extends Schema.TaggedErrorClass()( "ProviderAdapterEnsureThreadError", { - provider: ProviderKind, + driver: ProviderDriverKind, threadId: ThreadId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to ensure ${this.provider} provider thread for app thread ${this.threadId}.`; + return `Failed to ensure ${this.driver} provider thread for app thread ${this.threadId}.`; } } export class ProviderAdapterReadThreadSnapshotError extends Schema.TaggedErrorClass()( "ProviderAdapterReadThreadSnapshotError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerThreadId: ProviderThreadId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to read ${this.provider} provider thread snapshot ${this.providerThreadId}.`; + return `Failed to read ${this.driver} provider thread snapshot ${this.providerThreadId}.`; } } export class ProviderAdapterRollbackThreadError extends Schema.TaggedErrorClass()( "ProviderAdapterRollbackThreadError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerThreadId: ProviderThreadId, checkpointId: Schema.optional(CheckpointId), cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to roll back ${this.provider} provider thread ${this.providerThreadId}.`; + return `Failed to roll back ${this.driver} provider thread ${this.providerThreadId}.`; } } export class ProviderAdapterForkThreadError extends Schema.TaggedErrorClass()( "ProviderAdapterForkThreadError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerThreadId: ProviderThreadId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to fork ${this.provider} provider thread ${this.providerThreadId}.`; + return `Failed to fork ${this.driver} provider thread ${this.providerThreadId}.`; } } export class ProviderAdapterTurnStartError extends Schema.TaggedErrorClass()( "ProviderAdapterTurnStartError", { - provider: ProviderKind, + driver: ProviderDriverKind, threadId: ThreadId, providerThreadId: ProviderThreadId, runId: RunId, @@ -242,86 +243,86 @@ export class ProviderAdapterTurnStartError extends Schema.TaggedErrorClass()( "ProviderAdapterSteerRunUnsupportedError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerThreadId: ProviderThreadId, }, ) { override get message(): string { - return `${this.provider} provider thread ${this.providerThreadId} does not support active-run steering.`; + return `${this.driver} provider thread ${this.providerThreadId} does not support active-run steering.`; } } export class ProviderAdapterSteerRunError extends Schema.TaggedErrorClass()( "ProviderAdapterSteerRunError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerThreadId: ProviderThreadId, providerTurnId: ProviderTurnId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to steer active run ${this.providerTurnId} on ${this.provider} provider thread ${this.providerThreadId}.`; + return `Failed to steer active run ${this.providerTurnId} on ${this.driver} provider thread ${this.providerThreadId}.`; } } export class ProviderAdapterInterruptError extends Schema.TaggedErrorClass()( "ProviderAdapterInterruptError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerThreadId: ProviderThreadId, providerTurnId: ProviderTurnId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to interrupt ${this.provider} provider turn ${this.providerTurnId}.`; + return `Failed to interrupt ${this.driver} provider turn ${this.providerTurnId}.`; } } export class ProviderAdapterRuntimeRequestResponseError extends Schema.TaggedErrorClass()( "ProviderAdapterRuntimeRequestResponseError", { - provider: ProviderKind, + driver: ProviderDriverKind, requestId: RuntimeRequestId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to respond to ${this.provider} runtime request ${this.requestId}.`; + return `Failed to respond to ${this.driver} runtime request ${this.requestId}.`; } } export class ProviderAdapterEventStreamError extends Schema.TaggedErrorClass()( "ProviderAdapterEventStreamError", { - provider: ProviderKind, + driver: ProviderDriverKind, providerSessionId: ProviderSessionId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed while streaming ${this.provider} provider session ${this.providerSessionId} events.`; + return `Failed while streaming ${this.driver} provider session ${this.providerSessionId} events.`; } } export class ProviderAdapterProtocolError extends Schema.TaggedErrorClass()( "ProviderAdapterProtocolError", { - provider: ProviderKind, + driver: ProviderDriverKind, detail: Schema.String, payload: Schema.optional(Schema.Unknown), }, ) { override get message(): string { - return `${this.provider} provider protocol error: ${this.detail}.`; + return `${this.driver} provider protocol error: ${this.detail}.`; } } @@ -434,7 +435,8 @@ export interface ProviderAdapterV2ForkThreadInput { } export interface ProviderAdapterV2SessionRuntime { - readonly provider: ProviderKind; + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; readonly providerSessionId: ProviderSessionId; readonly providerSession: OrchestrationV2ProviderSession; readonly rawEvents: Stream.Stream; @@ -469,7 +471,8 @@ export interface ProviderAdapterV2SessionRuntime { } export interface ProviderAdapterV2Shape { - readonly provider: ProviderKind; + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; readonly getCapabilities: () => Effect.Effect< OrchestrationV2ProviderCapabilities, ProviderAdapterV2Error diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts index d0fee1fc0e..c78a4679ba 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts @@ -1,177 +1,69 @@ import { assert, it } from "@effect/vitest"; -import { - ProviderDriverKind, - ProviderInstanceId, - type OrchestrationV2ProviderCapabilities, -} from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; -import { ServerSettingsService } from "../serverSettings.ts"; -import type { ProviderAdapterDriver } from "./ProviderAdapterDriver.ts"; +import type { ProviderInstance } from "../provider/ProviderDriver.ts"; +import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts"; +import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import { - makeDriverLayerFromSettings, + layerFromProviderInstanceRegistry, ProviderAdapterRegistryV2, } from "./ProviderAdapterRegistry.ts"; -const capabilities = { - sessions: { - supportsMultipleProviderThreadsPerSession: false, - supportsModelSwitchInSession: false, - supportsProviderSwitchingViaHandoff: false, - supportsRuntimeModeSwitchInSession: false, - pendingRequestsSurviveRestart: false, - }, - threads: { - canCreateEmptyThread: false, - canReadThreadSnapshot: false, - canRollbackThread: false, - canForkThread: false, - canForkFromTurn: false, - canForkFromSubagentThread: false, - exposesNativeThreadId: false, - }, - turns: { - exposesNativeTurnId: false, - emitsTurnStarted: false, - emitsTurnCompleted: false, - supportsInterrupt: false, - supportsActiveSteering: false, - supportsSteeringByInterruptRestart: false, - supportsQueuedMessages: false, - terminalStatusQuality: "weak", - }, - streaming: { - streamsAssistantText: false, - streamsReasoning: false, - streamsToolOutput: false, - streamsPlanText: false, - emitsMessageCompleted: false, - }, - tools: { - exposesToolItemIds: false, - emitsToolStarted: false, - emitsToolCompleted: false, - emitsToolOutput: false, - supportsMcpTools: false, - supportsDynamicToolCallbacks: false, - }, - approvals: { - supportsCommandApproval: false, - supportsFileReadApproval: false, - supportsFileChangeApproval: false, - supportsApplyPatchApproval: false, - approvalsHaveNativeRequestIds: false, - approvalCallbacksAreLiveOnly: false, - approvalsCanOriginateFromSubagents: false, - }, - planning: { - emitsPlanUpdated: false, - emitsTodoList: false, - emitsProposedPlan: false, - supportsStructuredQuestions: false, - planDeltasHaveItemIds: false, - }, - subagents: { - supportsSubagents: false, - exposesSubagentThreadIds: false, - emitsSubagentLifecycle: false, - canWaitForSubagents: false, - canCloseSubagents: false, - canForkSubagentThread: false, - }, - context: { - acceptsSystemContext: false, - acceptsDeveloperContext: false, - acceptsSyntheticUserContext: false, - canGenerateSummaries: false, - canConsumeHandoffSummaries: false, - supportsDeltaHandoff: false, - supportsFullThreadHandoff: false, - maxRecommendedHandoffChars: null, - }, - checkpointing: { - appCanCheckpointFilesystem: false, - supportsNestedCheckpointScopes: false, - providerCanRollbackConversation: false, - providerRollbackReturnsSnapshot: false, - providerCanReadConversationSnapshot: false, - }, - identity: { - nativeThreadIds: "none", - nativeTurnIds: "none", - nativeItemIds: "none", - nativeRequestIds: "none", - }, -} satisfies OrchestrationV2ProviderCapabilities; +const driver = ProviderDriverKind.make("codex"); +const personalId = ProviderInstanceId.make("codex_personal"); +const workId = ProviderInstanceId.make("codex_work"); -const FakeConfig = Schema.Struct({}); -type FakeConfig = typeof FakeConfig.Type; +const makeAdapter = (instanceId: ProviderInstanceId): ProviderAdapterV2Shape => + ({ + instanceId, + driver, + getCapabilities: () => Effect.die("capabilities are not used by this registry test"), + openSession: () => Effect.die("sessions are not used by this registry test"), + }) as ProviderAdapterV2Shape; -function makeFakeDriver(driverKind: ProviderDriverKind): ProviderAdapterDriver { - return { - driverKind, - configSchema: FakeConfig, - defaultConfig: () => ({}), - create: ({ instanceId }) => - Effect.succeed({ - instanceId, - provider: driverKind, - getCapabilities: () => Effect.succeed(capabilities), - openSession: () => Effect.die("fake adapter does not open sessions"), - }), - }; -} - -const codexDriver = ProviderDriverKind.make("codex"); -const claudeDriver = ProviderDriverKind.make("claudeAgent"); -const codexWork = ProviderInstanceId.make("codex_work"); -const claudeWork = ProviderInstanceId.make("claude_work"); -const TestSettingsLayer = ServerSettingsService.layerTest({ - providerInstances: { - [codexWork]: { driver: codexDriver, config: {} }, - [claudeWork]: { driver: claudeDriver, config: {} }, +const makeInstance = ( + instanceId: ProviderInstanceId, + orchestrationAdapter: ProviderAdapterV2Shape, +): ProviderInstance => ({ + instanceId, + driverKind: driver, + continuationIdentity: { + driverKind: driver, + continuationKey: `codex:test:${instanceId}`, }, + displayName: String(instanceId), + enabled: true, + snapshot: {} as ProviderInstance["snapshot"], + adapter: {} as ProviderInstance["adapter"], + orchestrationAdapter, + textGeneration: {} as ProviderInstance["textGeneration"], }); -const TestLayer = makeDriverLayerFromSettings({ - drivers: [makeFakeDriver(codexDriver), makeFakeDriver(claudeDriver)], -}).pipe(Layer.provideMerge(TestSettingsLayer)); -it.effect("builds one V2 adapter per configured provider instance", () => +const personalAdapter = makeAdapter(personalId); +const workAdapter = makeAdapter(workId); +const instances = [ + makeInstance(personalId, personalAdapter), + makeInstance(workId, workAdapter), +] as const; +const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(instances.find((instance) => instance.instanceId === instanceId)), + listInstances: Effect.succeed(instances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.never, +}); +const TestLayer = layerFromProviderInstanceRegistry.pipe(Layer.provide(instanceRegistryLayer)); + +it.effect("routes two configured instances of the same driver independently", () => Effect.gen(function* () { const registry = yield* ProviderAdapterRegistryV2; - const instances = yield* registry.list(); - const codexWorkAdapter = yield* registry.get(codexWork); - const claudeWorkAdapter = yield* registry.get(claudeWork); - assert.deepEqual(instances, [ - codexWork, - claudeWork, - ProviderInstanceId.make("codex"), - ProviderInstanceId.make("claudeAgent"), - ]); - assert.equal(codexWorkAdapter.instanceId, codexWork); - assert.equal(claudeWorkAdapter.instanceId, claudeWork); - }).pipe(Effect.provide(TestLayer)), -); - -it.effect("resolves provider instances added after the V2 registry was constructed", () => - Effect.gen(function* () { - const registry = yield* ProviderAdapterRegistryV2; - const settings = yield* ServerSettingsService; - const codexAfterStart = ProviderInstanceId.make("codex_after_start"); - - yield* settings.updateSettings({ - providerInstances: { - [codexAfterStart]: { driver: codexDriver, config: {} }, - }, - }); - - const adapter = yield* registry.get(codexAfterStart); - const instances = yield* registry.list(); - - assert.equal(adapter.instanceId, codexAfterStart); - assert.isTrue(instances.includes(codexAfterStart)); + assert.strictEqual(yield* registry.get(personalId), personalAdapter); + assert.strictEqual(yield* registry.get(workId), workAdapter); + assert.deepEqual(yield* registry.list(), [personalId, workId]); }).pipe(Effect.provide(TestLayer)), ); diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts index 4ed42a728e..af734588e6 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts @@ -1,23 +1,21 @@ import { - defaultInstanceIdForDriver, - ProviderDriverKind as ProviderDriverKindSchema, ProviderInstanceId, type ProviderDriverKind, type ProviderInstanceConfig, type ProviderInstanceConfigMap, - type ServerSettings, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; -import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; -import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import * as Semaphore from "effect/Semaphore"; import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; +import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts"; +import { + ProviderAdapterDriverCreateError, + type AnyProviderAdapterDriver, +} from "./ProviderAdapterDriver.ts"; import { ProviderAdapterV2, type ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass()( @@ -49,6 +47,41 @@ export class ProviderAdapterRegistryV2 extends Context.Service< ProviderAdapterRegistryV2Shape >()("t3/orchestration-v2/ProviderAdapterRegistry/ProviderAdapterRegistryV2") {} +/** + * Production facade over the canonical provider-instance registry. Adapter + * lookup stays dynamic so instance hot reloads and removals are visible + * without maintaining a second settings watcher or instance map. + */ +export const layerFromProviderInstanceRegistry: Layer.Layer< + ProviderAdapterRegistryV2, + never, + ProviderInstanceRegistry +> = Layer.effect( + ProviderAdapterRegistryV2, + Effect.gen(function* () { + const instances = yield* ProviderInstanceRegistry; + return ProviderAdapterRegistryV2.of({ + get: (instanceId) => + instances + .getInstance(instanceId) + .pipe( + Effect.flatMap((instance) => + instance === undefined + ? new ProviderAdapterRegistryLookupError({ instanceId }) + : Effect.succeed(instance.orchestrationAdapter), + ), + ), + list: () => + instances.listInstances.pipe( + Effect.map((available) => available.map((instance) => instance.instanceId)), + ), + }); + }), +); + +export const ProviderAdapterRegistryBuildError = Schema.Union([ProviderAdapterDriverCreateError]); +export type ProviderAdapterRegistryBuildError = typeof ProviderAdapterRegistryBuildError.Type; + function makeRegistry( adapters: ReadonlyArray, ): ProviderAdapterRegistryV2Shape { @@ -89,35 +122,6 @@ export function makeSingleLayer( return makeLayer([adapter]); } -export function deriveProviderAdapterInstanceConfigMap(input: { - readonly settings: ServerSettings; - readonly drivers: ReadonlyArray>; -}): ProviderInstanceConfigMap { - const merged: Record = { - ...input.settings.providerInstances, - }; - - for (const driver of input.drivers) { - const instanceId = defaultInstanceIdForDriver(driver.driverKind); - if (instanceId in merged) { - continue; - } - - const legacyKey = driver.driverKind as keyof ServerSettings["providers"]; - const legacyConfig = input.settings.providers[legacyKey]; - if (legacyConfig === undefined) { - continue; - } - - merged[instanceId] = { - driver: driver.driverKind, - config: legacyConfig, - }; - } - - return merged as ProviderInstanceConfigMap; -} - const decodedConfigEnabled = (config: unknown): boolean | undefined => { if (!config || typeof config !== "object" || globalThis.Array.isArray(config)) { return undefined; @@ -132,17 +136,6 @@ interface LiveAdapterEntry { readonly entry: ProviderInstanceConfig; } -const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => - Equal.equals(a, b); - -const makeSettingsReadError = (cause: unknown): ProviderAdapterDriverCreateError => - new ProviderAdapterDriverCreateError({ - driver: ProviderDriverKindSchema.make("settings"), - instanceId: ProviderInstanceId.make("settings"), - detail: "Failed to read server settings before building provider adapters.", - cause, - }); - function makeDriversById( drivers: ReadonlyArray>, ): ReadonlyMap> { @@ -244,9 +237,6 @@ const buildAdaptersFromConfigMap = Effect.fn("ProviderAdapterRegistry.buildAdapt }, ); -const closeAdapterEntry = (entry: LiveAdapterEntry): Effect.Effect => - Scope.close(entry.scope, Exit.void).pipe(Effect.ignore); - export function makeRegistryFromConfigMap(input: { readonly drivers: ReadonlyArray>; readonly configMap: ProviderInstanceConfigMap; @@ -274,169 +264,6 @@ export function makeDriverLayer(input: { ) as Layer.Layer; } -export function makeDriverLayerFromSettings(input: { - readonly drivers: ReadonlyArray>; -}): Layer.Layer< - ProviderAdapterRegistryV2, - ProviderAdapterRegistryBuildError, - R | ServerSettingsService -> { - return Layer.effect( - ProviderAdapterRegistryV2, - Effect.gen(function* () { - const settingsService = yield* ServerSettingsService; - const parentScope = yield* Effect.scope; - const driverContext = yield* Effect.context(); - const settings = yield* settingsService.getSettings.pipe( - Effect.mapError((cause) => makeSettingsReadError(cause)), - ); - const configMap = deriveProviderAdapterInstanceConfigMap({ - settings, - drivers: input.drivers, - }); - const initialAdapters = yield* buildAdaptersFromConfigMap({ - drivers: input.drivers, - configMap, - parentScope, - }); - const adaptersRef = yield* Ref.make(initialAdapters); - const reconcileSemaphore = yield* Semaphore.make(1); - const driversById = makeDriversById(input.drivers); - - const reconcileConfigMapWithR = Effect.fn("ProviderAdapterRegistry.reconcileConfigMap")( - function* ( - nextConfigMap: ProviderInstanceConfigMap, - ): Effect.fn.Return { - const previous = yield* Ref.get(adaptersRef); - const nextEntries = new Map(); - const staleEntries: Array = []; - const nextIds = new Set(); - - for (const [rawInstanceId, entry] of Object.entries(nextConfigMap)) { - const instanceId = ProviderInstanceId.make(rawInstanceId); - nextIds.add(instanceId); - - if (!driversById.has(entry.driver)) { - yield* Effect.logWarning( - "Skipping orchestration-v2 provider adapter with unknown driver", - { - instanceId, - driver: entry.driver, - }, - ); - continue; - } - - const existing = previous.get(instanceId); - if (existing !== undefined && entryEqual(existing.entry, entry)) { - nextEntries.set(instanceId, existing); - continue; - } - - const nextEntry = yield* createAdapterEntryFromConfigEntry({ - driversById, - parentScope, - instanceId, - entry, - }); - nextEntries.set(instanceId, nextEntry); - if (existing !== undefined) { - staleEntries.push(existing); - } - } - - for (const [instanceId, existing] of previous) { - if (!nextIds.has(instanceId)) { - staleEntries.push(existing); - } - } - - yield* Ref.set(adaptersRef, nextEntries); - for (const entry of staleEntries) { - yield* closeAdapterEntry(entry); - } - }, - ); - const reconcileConfigMap = (nextConfigMap: ProviderInstanceConfigMap) => - reconcileConfigMapWithR(nextConfigMap).pipe(Effect.provideContext(driverContext)); - - const refreshFromSettings = Effect.fn("ProviderAdapterRegistry.refreshFromSettings")( - function* (): Effect.fn.Return { - const latestSettings = yield* settingsService.getSettings.pipe( - Effect.mapError((cause) => makeSettingsReadError(cause)), - ); - yield* reconcileConfigMap( - deriveProviderAdapterInstanceConfigMap({ - settings: latestSettings, - drivers: input.drivers, - }), - ); - }, - ); - - yield* settingsService.streamChanges.pipe( - Stream.runForEach((nextSettings) => - reconcileSemaphore.withPermits(1)( - reconcileConfigMap( - deriveProviderAdapterInstanceConfigMap({ - settings: nextSettings, - drivers: input.drivers, - }), - ).pipe( - Effect.catchCause((cause) => - Effect.logError("Orchestration-v2 provider adapter registry reconcile failed", { - cause, - }), - ), - ), - ), - ), - Effect.forkScoped, - ); - - const refreshAndGet = Effect.fn("ProviderAdapterRegistry.refreshAndGet")(function* ( - instanceId: ProviderInstanceId, - ): Effect.fn.Return { - return yield* reconcileSemaphore.withPermits(1)( - Effect.gen(function* () { - const cached = (yield* Ref.get(adaptersRef)).get(instanceId); - if (cached !== undefined) { - return cached.adapter; - } - - yield* refreshFromSettings(); - const refreshed = (yield* Ref.get(adaptersRef)).get(instanceId); - if (refreshed === undefined) { - return yield* new ProviderAdapterRegistryLookupError({ instanceId }); - } - return refreshed.adapter; - }), - ); - }); - - const get = Effect.fn("ProviderAdapterRegistry.get")(function* ( - instanceId: ProviderInstanceId, - ): Effect.fn.Return { - const cached = (yield* Ref.get(adaptersRef)).get(instanceId); - if (cached !== undefined) { - return cached.adapter; - } - return yield* refreshAndGet(instanceId); - }); - - return ProviderAdapterRegistryV2.of({ - get, - list: () => - Ref.get(adaptersRef).pipe( - Effect.map((adapters) => - Array.from(adapters.values()).map((entry) => entry.adapter.instanceId), - ), - ), - } satisfies ProviderAdapterRegistryV2Shape); - }), - ); -} - export const layerFromProviderAdapter: Layer.Layer< ProviderAdapterRegistryV2, never, diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 6ec87f697a..49555e28c8 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -6,6 +6,8 @@ import { type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, type OrchestrationV2ProviderThread, + ProviderDriverKind, + ProviderInstanceId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -43,6 +45,11 @@ const TestLayer = Layer.mergeAll( Layer.provide(Layer.mergeAll(TestStoresLayer, TestEventSinkLayer, idAllocatorLayer)), ), ); +const modelSelection = { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", +} satisfies ModelSelection; +const CODEX_DRIVER = ProviderDriverKind.make("codex"); function threadCreatedEvent( now: DateTime.Utc, @@ -57,7 +64,7 @@ function threadCreatedEvent( projectId, }); const providerThreadId = idAllocator.derive.providerThread({ - provider: "codex", + driver: CODEX_DRIVER, nativeThreadId: "native-thread", }); const thread: OrchestrationV2AppThread = { @@ -66,11 +73,8 @@ function threadCreatedEvent( id: threadId, projectId, title: "Provider event ingestor", - defaultProvider: "codex", - modelSelection: { - provider: "codex", - model: "gpt-5.4", - }, + providerInstanceId: modelSelection.instanceId, + modelSelection: modelSelection, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -111,20 +115,21 @@ layer("ProviderEventIngestorV2", (it) => { const idAllocator = yield* IdAllocatorV2; const threadEvent = yield* threadCreatedEvent(now); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId: threadEvent.threadId, }); const providerThread: OrchestrationV2ProviderThread = { id: idAllocator.derive.providerThread({ - provider: "codex", + driver: CODEX_DRIVER, nativeThreadId: "native-thread", }), - provider: "codex", + driver: CODEX_DRIVER, + providerInstanceId: modelSelection.instanceId, providerSessionId, appThreadId: threadEvent.threadId, ownerNodeId: null, nativeThreadRef: { - provider: "codex", + driver: CODEX_DRIVER, nativeId: "native-thread", strength: "strong", }, @@ -141,10 +146,11 @@ layer("ProviderEventIngestorV2", (it) => { yield* eventSink.write({ events: [threadEvent] }); const storedEvents = yield* ingestor.ingestNormalized({ providerSessionId, + providerInstanceId: modelSelection.instanceId, threadId: threadEvent.threadId, event: { type: "provider_thread.updated", - provider: "codex", + driver: CODEX_DRIVER, providerThread, }, }); @@ -194,17 +200,18 @@ layer("ProviderEventIngestorV2", (it) => { projectId, }); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); const normalized = yield* ingestor.normalize({ providerSessionId, + providerInstanceId: modelSelection.instanceId, threadId, event: { type: "turn.terminal", - provider: "codex", + driver: CODEX_DRIVER, providerTurnId: idAllocator.derive.providerTurn({ - provider: "codex", + driver: CODEX_DRIVER, nativeTurnId: "native-turn", }), status: "completed", @@ -225,7 +232,7 @@ layer("ProviderEventIngestorV2", (it) => { throw new Error("Expected a thread.created fixture event"); } const childThreadId = idAllocator.derive.threadFromProviderThread({ - provider: "codex", + driver: CODEX_DRIVER, nativeThreadId: "native-subagent-thread", }); const childRootNodeId = NodeId.make("node:subagent-root"); @@ -245,25 +252,27 @@ layer("ProviderEventIngestorV2", (it) => { }, }; const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId: rootEvent.threadId, }); const threadEvents = yield* ingestor.normalize({ providerSessionId, + providerInstanceId: modelSelection.instanceId, threadId: rootEvent.threadId, event: { type: "app_thread.created", - provider: "codex", + driver: CODEX_DRIVER, appThread: childThread, }, }); const messageEvents = yield* ingestor.normalize({ providerSessionId, + providerInstanceId: modelSelection.instanceId, threadId: rootEvent.threadId, event: { type: "message.updated", - provider: "codex", + driver: CODEX_DRIVER, message: { createdBy: "agent", creationSource: "provider", diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index d9e60edc3b..7f40457c90 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -3,6 +3,7 @@ import { CommandId, OrchestrationV2DomainEvent, OrchestrationV2StoredEvent, + ProviderInstanceId, ProviderSessionId, RawEventId, RunId, @@ -54,6 +55,7 @@ export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.T export interface ProviderEventIngestorV2Shape { readonly normalize: (input: { readonly providerSessionId: ProviderSessionId; + readonly providerInstanceId: ProviderInstanceId; readonly commandId?: CommandId; readonly threadId: ThreadId; readonly runId?: RunId; @@ -63,6 +65,7 @@ export interface ProviderEventIngestorV2Shape { }) => Effect.Effect, ProviderEventIngestorV2Error>; readonly ingestNormalized: (input: { readonly providerSessionId: ProviderSessionId; + readonly providerInstanceId: ProviderInstanceId; readonly commandId?: CommandId; readonly threadId: ThreadId; readonly runId?: RunId; @@ -91,6 +94,7 @@ export const layer: Layer.Layer Effect.succeed(CodexCapabilities), openSession: (input) => Effect.gen(function* () { @@ -228,14 +234,15 @@ function makeProviderAdapter( ); return { - provider: "codex", + instanceId: ProviderInstanceId.make("codex"), + driver: CODEX_DRIVER, providerSessionId: input.providerSessionId, providerSession: session, rawEvents: Stream.empty, events: options.failEventStream ? Stream.fail( new ProviderAdapterEventStreamError({ - provider: "codex", + driver: CODEX_DRIVER, providerSessionId: input.providerSessionId, cause: "process exited", }), @@ -306,7 +313,7 @@ function makePendingRuntimeRequestEvents(input: { }) { return Effect.gen(function* () { const requestId = yield* input.idAllocator.allocate.runtimeRequest({ - provider: "codex", + driver: CODEX_DRIVER, nativeRequestId: "pending-approval", }); const nodeId = input.idAllocator.derive.approvalNode({ requestId }); @@ -332,7 +339,7 @@ function makePendingRuntimeRequestEvents(input: { nodeId, providerTurnId: null, nativeRequestRef: { - provider: "codex" as const, + driver: CODEX_DRIVER, nativeId: "pending-approval", strength: "strong" as const, }, @@ -373,7 +380,7 @@ function makePendingRuntimeRequestEvents(input: { type: "node.updated" as const, threadId: input.threadId, nodeId, - provider: "codex" as const, + driver: CODEX_DRIVER, occurredAt: input.now, payload: node, }, @@ -385,7 +392,7 @@ function makePendingRuntimeRequestEvents(input: { type: "runtime-request.updated" as const, threadId: input.threadId, nodeId, - provider: "codex" as const, + driver: CODEX_DRIVER, occurredAt: input.now, payload: request, }, @@ -397,7 +404,7 @@ function makePendingRuntimeRequestEvents(input: { type: "turn-item.updated" as const, threadId: input.threadId, nodeId, - provider: "codex" as const, + driver: CODEX_DRIVER, occurredAt: input.now, payload: turnItem, }, @@ -415,7 +422,7 @@ it.effect("ProviderSessionManagerV2 releases live sessions when its layer shuts const now = yield* DateTime.now; const threadId = ThreadId.make("thread-provider-session-manager-shutdown"); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); @@ -463,7 +470,7 @@ it.effect( const now = yield* DateTime.now; const threadId = ThreadId.make("thread-provider-session-manager-mcp"); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); @@ -522,7 +529,7 @@ it.effect("ProviderSessionManagerV2 releases idle sessions without sweeping all projectId, }); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); @@ -572,7 +579,7 @@ it.effect( projectId, }); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); const providerThread = makeProviderThread({ @@ -585,7 +592,7 @@ it.effect( const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }); const rootNodeId = idAllocator.derive.rootNode({ runId }); const providerTurnId = idAllocator.derive.providerTurn({ - provider: "codex", + driver: CODEX_DRIVER, nativeTurnId: "native-turn", }); @@ -628,7 +635,7 @@ it.effect( assert.isDefined(queue); yield* Queue.offer(queue!, { type: "turn.terminal", - provider: "codex", + driver: CODEX_DRIVER, providerTurnId, status: "completed", }); @@ -663,7 +670,7 @@ it.effect("ProviderSessionManagerV2 uses the same release path for runtime failu projectId, }); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); @@ -713,7 +720,7 @@ it.effect("ProviderSessionManagerV2 releases sessions when provider event stream projectId, }); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); @@ -767,7 +774,7 @@ it.effect("ProviderSessionManagerV2 marks pending runtime requests non-live on r projectId, }); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId, }); const providerThread = makeProviderThread({ @@ -841,7 +848,7 @@ it.effect( projectId, }); const providerSessionId = yield* idAllocator.allocate.providerSession({ - provider: "codex", + providerInstanceId: modelSelection.instanceId, threadId: firstThreadId, }); const firstProviderThread = makeProviderThread({ @@ -859,11 +866,11 @@ it.effect( const firstRunId = idAllocator.derive.run({ threadId: firstThreadId, ordinal: 1 }); const secondRunId = idAllocator.derive.run({ threadId: secondThreadId, ordinal: 1 }); const firstProviderTurnId = idAllocator.derive.providerTurn({ - provider: "codex", + driver: CODEX_DRIVER, nativeTurnId: "native-turn-a", }); const secondProviderTurnId = idAllocator.derive.providerTurn({ - provider: "codex", + driver: CODEX_DRIVER, nativeTurnId: "native-turn-b", }); @@ -934,7 +941,7 @@ it.effect( assert.isDefined(queue); yield* Queue.offer(queue!, { type: "turn.terminal", - provider: "codex", + driver: CODEX_DRIVER, providerTurnId: firstProviderTurnId, status: "completed", }); @@ -944,7 +951,7 @@ it.effect( yield* Queue.offer(queue!, { type: "turn.terminal", - provider: "codex", + driver: CODEX_DRIVER, providerTurnId: secondProviderTurnId, status: "completed", }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index e459d669e5..076350e4d1 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -250,7 +250,7 @@ export const layerWithOptions = ( }), type: "provider-session.updated", threadId, - provider: input.entry.runtime.provider, + driver: input.entry.runtime.driver, occurredAt: now, payload, } satisfies OrchestrationV2DomainEvent; @@ -291,7 +291,7 @@ export const layerWithOptions = ( type: "runtime-request.updated", threadId, nodeId: request.nodeId, - provider: input.entry.runtime.provider, + driver: input.entry.runtime.driver, occurredAt: now, payload: { ...request, @@ -315,7 +315,7 @@ export const layerWithOptions = ( threadId, ...(requestNode.runId === null ? {} : { runId: requestNode.runId }), nodeId: requestNode.id, - provider: input.entry.runtime.provider, + driver: input.entry.runtime.driver, occurredAt: now, payload: { ...requestNode, @@ -338,7 +338,7 @@ export const layerWithOptions = ( threadId, ...(turnItem.runId === null ? {} : { runId: turnItem.runId }), ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }), - provider: input.entry.runtime.provider, + driver: input.entry.runtime.driver, occurredAt: now, payload: { ...turnItem, @@ -426,7 +426,7 @@ export const layerWithOptions = ( cancelIdleFiber: false, }).pipe( Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.provider-session.idle-release-failed", { + Effect.logWarning("orchestration-v2.driver-session.idle-release-failed", { providerSessionId: input.providerSessionId, cause, }), @@ -578,7 +578,7 @@ export const layerWithOptions = ( ) => activity.pipe( Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.provider-session.activity-failed", { + Effect.logWarning("orchestration-v2.driver-session.activity-failed", { providerSessionId, cause, }), @@ -661,7 +661,7 @@ export const layerWithOptions = ( reason: "server_shutdown", }).pipe( Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.provider-session.shutdown-release-failed", { + Effect.logWarning("orchestration-v2.driver-session.shutdown-release-failed", { providerSessionId: entry.runtime.providerSessionId, cause, }), diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.ts index 422d45fd2d..a5598f2c84 100644 --- a/apps/server/src/orchestration-v2/ProviderSwitchService.ts +++ b/apps/server/src/orchestration-v2/ProviderSwitchService.ts @@ -1,78 +1,87 @@ import { ModelSelection, - OrchestrationV2ContextHandoff, OrchestrationV2ThreadProjection, + ProviderSessionId, ProviderThreadId, - RunId, ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import * as Schema from "effect/Schema"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; -export const ProviderSwitchStrategyV2 = Schema.Literals([ - "resume_with_delta_handoff", - "resume_with_full_handoff", - "new_thread_with_full_handoff", -]); -export type ProviderSwitchStrategyV2 = typeof ProviderSwitchStrategyV2.Type; - -export const ProviderSwitchPlanV2 = Schema.Struct({ - strategy: ProviderSwitchStrategyV2, - targetProviderThreadId: Schema.NullOr(ProviderThreadId), - handoff: Schema.NullOr(OrchestrationV2ContextHandoff), -}); -export type ProviderSwitchPlanV2 = typeof ProviderSwitchPlanV2.Type; +export interface ProviderSwitchPlanV2 { + readonly instanceChanged: boolean; + readonly modelChanged: boolean; + readonly targetProviderThreadId: ProviderThreadId | null; + readonly releaseProviderSessionIds: ReadonlyArray; +} export class ProviderSwitchPlanError extends Schema.TaggedErrorClass()( "ProviderSwitchPlanError", { threadId: ThreadId, - targetRunId: RunId, - targetProvider: Schema.String, + targetProviderInstanceId: Schema.String, cause: Schema.optional(Schema.Defect()), }, -) { - override get message(): string { - return `Failed to plan provider switch to ${this.targetProvider} for run ${this.targetRunId}.`; - } -} - -export class ProviderSwitchApplyError extends Schema.TaggedErrorClass()( - "ProviderSwitchApplyError", - { - threadId: ThreadId, - targetRunId: RunId, - strategy: ProviderSwitchStrategyV2, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Failed to apply provider switch strategy ${this.strategy} for run ${this.targetRunId}.`; - } -} - -export const ProviderSwitchServiceV2Error = Schema.Union([ - ProviderSwitchPlanError, - ProviderSwitchApplyError, -]); -export type ProviderSwitchServiceV2Error = typeof ProviderSwitchServiceV2Error.Type; +) {} export interface ProviderSwitchServiceV2Shape { readonly plan: (input: { readonly projection: OrchestrationV2ThreadProjection; - readonly targetRunId: RunId; readonly targetModelSelection: ModelSelection; - }) => Effect.Effect; - readonly apply: (input: { - readonly projection: OrchestrationV2ThreadProjection; - readonly targetRunId: RunId; - readonly targetModelSelection: ModelSelection; - readonly plan: ProviderSwitchPlanV2; - }) => Effect.Effect; + }) => Effect.Effect; } export class ProviderSwitchServiceV2 extends Context.Service< ProviderSwitchServiceV2, ProviderSwitchServiceV2Shape >()("t3/orchestration-v2/ProviderSwitchService/ProviderSwitchServiceV2") {} + +export const layer: Layer.Layer = Layer.succeed( + ProviderSwitchServiceV2, + ProviderSwitchServiceV2.of({ + plan: ({ projection, targetModelSelection }) => + Effect.sync(() => { + const current = projection.thread.modelSelection; + const instanceChanged = current.instanceId !== targetModelSelection.instanceId; + const modelChanged = current.model !== targetModelSelection.model; + const targetProviderThread = projection.providerThreads + .filter( + (thread) => + thread.appThreadId === projection.thread.id && + thread.ownerNodeId === null && + thread.providerInstanceId === targetModelSelection.instanceId, + ) + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + )[0]; + const releaseProviderSessionIds = projection.providerSessions + .filter((session) => { + if (session.status === "stopped" || session.status === "error") return false; + if (instanceChanged) { + return session.providerInstanceId !== targetModelSelection.instanceId; + } + return modelChanged && !session.capabilities.sessions.supportsModelSwitchInSession; + }) + .map((session) => session.id); + return { + instanceChanged, + modelChanged, + targetProviderThreadId: targetProviderThread?.id ?? null, + releaseProviderSessionIds, + }; + }).pipe( + Effect.mapError( + (cause) => + new ProviderSwitchPlanError({ + threadId: projection.thread.id, + targetProviderInstanceId: targetModelSelection.instanceId, + cause, + }), + ), + ), + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts new file mode 100644 index 0000000000..87b7df5438 --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -0,0 +1,236 @@ +import { + MessageId, + ProviderSessionId, + ProviderThreadId, + ProviderTurnId, + RunAttemptId, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; + +const yieldToRuntime = Effect.yieldNow.pipe( + Effect.andThen( + Effect.promise( + () => + new Promise((resolve) => { + setImmediate(resolve); + }), + ), + ), +); + +export class ProviderTurnControlError extends Schema.TaggedErrorClass()( + "ProviderTurnControlError", + { + threadId: ThreadId, + operation: Schema.Literals(["interrupt", "restart", "steer"]), + providerTurnId: ProviderTurnId, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface ProviderTurnControlServiceV2Shape { + readonly interrupt: (input: { + readonly threadId: ThreadId; + readonly providerSessionId: ProviderSessionId; + readonly providerThreadId: ProviderThreadId; + readonly providerTurnId: ProviderTurnId; + }) => Effect.Effect; + readonly steer: (input: { + readonly threadId: ThreadId; + readonly providerSessionId: ProviderSessionId; + readonly providerThreadId: ProviderThreadId; + readonly providerTurnId: ProviderTurnId; + readonly messageId: MessageId; + }) => Effect.Effect; + readonly interruptAndAwaitTerminal: (input: { + readonly threadId: ThreadId; + readonly providerSessionId: ProviderSessionId; + readonly providerThreadId: ProviderThreadId; + readonly providerTurnId: ProviderTurnId; + readonly interruptedAttemptId: RunAttemptId; + }) => Effect.Effect; +} + +export class ProviderTurnControlServiceV2 extends Context.Service< + ProviderTurnControlServiceV2, + ProviderTurnControlServiceV2Shape +>()("t3/orchestration-v2/ProviderTurnControlService/ProviderTurnControlServiceV2") {} + +export const layer: Layer.Layer< + ProviderTurnControlServiceV2, + never, + ProjectionStoreV2 | ProviderSessionManagerV2 +> = Layer.effect( + ProviderTurnControlServiceV2, + Effect.gen(function* () { + const projections = yield* ProjectionStoreV2; + const sessions = yield* ProviderSessionManagerV2; + + const load = (input: { + readonly threadId: ThreadId; + readonly providerSessionId: ProviderSessionId; + readonly providerThreadId: ProviderThreadId; + readonly providerTurnId: ProviderTurnId; + readonly operation: "interrupt" | "restart" | "steer"; + }) => + Effect.gen(function* () { + const projection = yield* projections.getThreadProjection(input.threadId); + const providerThread = projection.providerThreads.find( + (candidate) => candidate.id === input.providerThreadId, + ); + const providerTurn = projection.providerTurns.find( + (candidate) => candidate.id === input.providerTurnId, + ); + if ( + providerThread === undefined || + providerTurn === undefined || + providerThread.providerSessionId !== input.providerSessionId || + providerTurn.providerThreadId !== providerThread.id + ) { + return yield* new ProviderTurnControlError({ + threadId: input.threadId, + operation: input.operation, + providerTurnId: input.providerTurnId, + cause: "The recorded provider execution target is no longer valid.", + }); + } + if (providerTurn.status !== "running") { + return { projection, providerThread, providerTurn, session: Option.none() }; + } + const session = yield* sessions.get(input.providerSessionId); + if (Option.isNone(session)) { + return yield* new ProviderTurnControlError({ + threadId: input.threadId, + operation: input.operation, + providerTurnId: input.providerTurnId, + cause: `Provider session ${input.providerSessionId} is not active.`, + }); + } + return { projection, providerThread, providerTurn, session }; + }); + + return ProviderTurnControlServiceV2.of({ + interrupt: (input) => + Effect.gen(function* () { + const loaded = yield* load({ ...input, operation: "interrupt" }); + if (Option.isNone(loaded.session)) return; + yield* loaded.session.value.interruptTurn({ + providerThread: loaded.providerThread, + providerTurnId: loaded.providerTurn.id, + }); + }).pipe( + Effect.mapError((cause) => + Schema.is(ProviderTurnControlError)(cause) + ? cause + : new ProviderTurnControlError({ + threadId: input.threadId, + operation: "interrupt", + providerTurnId: input.providerTurnId, + cause, + }), + ), + ), + interruptAndAwaitTerminal: (input) => + Effect.gen(function* () { + const loaded = yield* load({ ...input, operation: "restart" }); + if (Option.isSome(loaded.session)) { + yield* loaded.session.value.interruptTurn({ + providerThread: loaded.providerThread, + providerTurnId: loaded.providerTurn.id, + }); + } + + for (let remaining = 1_000; remaining > 0; remaining -= 1) { + const projection = yield* projections.getThreadProjection(input.threadId); + const providerTurn = projection.providerTurns.find( + (candidate) => candidate.id === input.providerTurnId, + ); + const attempt = projection.attempts.find( + (candidate) => candidate.id === input.interruptedAttemptId, + ); + if ( + providerTurn !== undefined && + providerTurn.status !== "running" && + attempt !== undefined && + attempt.status !== "running" + ) { + return; + } + // Provider terminal events are projected on a detached ingestion + // fiber. Yield through the Node event loop instead of sleeping on + // Effect's clock so deterministic runtimes cannot deadlock a + // command that is waiting for that projection. + yield* yieldToRuntime; + } + return yield* new ProviderTurnControlError({ + threadId: input.threadId, + operation: "restart", + providerTurnId: input.providerTurnId, + cause: `Provider turn ${input.providerTurnId} did not terminalize before restart.`, + }); + }).pipe( + Effect.mapError((cause) => + Schema.is(ProviderTurnControlError)(cause) + ? cause + : new ProviderTurnControlError({ + threadId: input.threadId, + operation: "restart", + providerTurnId: input.providerTurnId, + cause, + }), + ), + ), + steer: (input) => + Effect.gen(function* () { + const loaded = yield* load({ ...input, operation: "steer" }); + if (Option.isNone(loaded.session)) return; + const message = loaded.projection.messages.find( + (candidate) => candidate.id === input.messageId, + ); + const run = loaded.projection.runs.find( + (candidate) => candidate.activeAttemptId === loaded.providerTurn.runAttemptId, + ); + if (message === undefined || run === undefined) { + return yield* new ProviderTurnControlError({ + threadId: input.threadId, + operation: "steer", + providerTurnId: input.providerTurnId, + cause: "The persisted steering message or target run is missing.", + }); + } + yield* loaded.session.value.steerTurn({ + threadId: input.threadId, + runId: run.id, + providerThread: loaded.providerThread, + providerTurnId: loaded.providerTurn.id, + message: { + messageId: message.id, + text: message.text, + attachments: message.attachments, + createdBy: message.createdBy, + creationSource: message.creationSource, + }, + }); + }).pipe( + Effect.mapError((cause) => + Schema.is(ProviderTurnControlError)(cause) + ? cause + : new ProviderTurnControlError({ + threadId: input.threadId, + operation: "steer", + providerTurnId: input.providerTurnId, + cause, + }), + ), + ), + }); + }), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts new file mode 100644 index 0000000000..b175f0ff3f --- /dev/null +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -0,0 +1,339 @@ +import { + CommandId, + type OrchestrationV2DomainEvent, + type OrchestrationV2ExecutionNode, + type OrchestrationV2ProviderThread, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { EventSinkV2 } from "./EventSink.ts"; +import { providerMessageWithContextHandoffs } from "./ContextHandoffService.ts"; +import { IdAllocatorV2 } from "./IdAllocator.ts"; +import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; +import { RunExecutionServiceV2 } from "./RunExecutionService.ts"; +import { RuntimePolicyV2 } from "./RuntimePolicy.ts"; + +export class ProviderTurnStartError extends Schema.TaggedErrorClass()( + "ProviderTurnStartError", + { + runId: RunId, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface ProviderTurnStartServiceV2Shape { + readonly start: (input: { + readonly threadId: ThreadId; + readonly runId: RunId; + }) => Effect.Effect; +} + +export class ProviderTurnStartServiceV2 extends Context.Service< + ProviderTurnStartServiceV2, + ProviderTurnStartServiceV2Shape +>()("t3/orchestration-v2/ProviderTurnStartService/ProviderTurnStartServiceV2") {} + +export const layer: Layer.Layer< + ProviderTurnStartServiceV2, + never, + | EventSinkV2 + | IdAllocatorV2 + | ProjectionStoreV2 + | ProviderSessionManagerV2 + | RunExecutionServiceV2 + | RuntimePolicyV2 +> = Layer.effect( + ProviderTurnStartServiceV2, + Effect.gen(function* () { + const eventSink = yield* EventSinkV2; + const idAllocator = yield* IdAllocatorV2; + const projectionStore = yield* ProjectionStoreV2; + const providerSessions = yield* ProviderSessionManagerV2; + const runExecution = yield* RunExecutionServiceV2; + const runtimePolicy = yield* RuntimePolicyV2; + + const start = Effect.fn("orchestrationV2.providerTurnStart.start")(function* (input: { + readonly threadId: ThreadId; + readonly runId: RunId; + }) { + const { runId } = input; + const projection = yield* projectionStore.getThreadProjection(input.threadId); + const run = projection.runs.find((candidate) => candidate.id === runId); + if (run === undefined) { + return yield* new ProviderTurnStartError({ runId, cause: `Run ${runId} was not found.` }); + } + if (run.status !== "starting") { + // The effect is idempotent once the run has advanced or terminalized. + return; + } + const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId); + const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId); + const providerThread = projection.providerThreads.find( + (candidate) => candidate.id === run.providerThreadId, + ); + const message = projection.messages.find((candidate) => candidate.id === run.userMessageId); + const checkpointScope = projection.checkpointScopes.find( + (candidate) => candidate.id === rootNode?.checkpointScopeId, + ); + const handoffs = projection.contextHandoffs.filter( + (handoff) => handoff.targetRunId === run.id && handoff.status === "ready", + ); + const nativeForkTransfer = projection.contextTransfers.find( + (transfer) => + transfer.type === "fork" && + transfer.targetThreadId === input.threadId && + transfer.targetRunId === run.id && + transfer.status === "pending" && + transfer.resolution === null, + ); + if ( + rootNode === undefined || + attempt === undefined || + providerThread === undefined || + providerThread.providerSessionId === null || + message === undefined || + checkpointScope === undefined + ) { + return yield* new ProviderTurnStartError({ + runId, + cause: `Run ${runId} is missing its execution projection state.`, + }); + } + const providerSessionId = providerThread.providerSessionId; + + const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ + thread: projection.thread, + modelSelection: run.modelSelection, + }); + const existingSessionProjection = projection.providerSessions.find( + (candidate) => candidate.id === providerSessionId, + ); + const activeSession = yield* providerSessions.get(providerSessionId); + const session = yield* providerSessions.open({ + threadId: projection.thread.id, + providerSessionId, + modelSelection: run.modelSelection, + runtimePolicy: resolvedRuntimePolicy, + ...(existingSessionProjection === undefined + ? {} + : { resumeFromSession: existingSessionProjection }), + }); + const loadedProviderThread = yield* Effect.gen(function* () { + if (nativeForkTransfer !== undefined) { + const sourceProjection = yield* projectionStore.getThreadProjection( + nativeForkTransfer.sourceThreadId, + ); + const sourceRun = sourceProjection.runs.find( + (candidate) => candidate.id === nativeForkTransfer.sourcePoint.runId, + ); + const sourceProviderThread = sourceProjection.providerThreads.find( + (candidate) => candidate.id === sourceRun?.providerThreadId, + ); + const sourceAttempt = sourceProjection.attempts.find( + (candidate) => candidate.id === sourceRun?.activeAttemptId, + ); + const sourceProviderTurn = sourceProjection.providerTurns.find( + (candidate) => + candidate.id === sourceAttempt?.providerTurnId || + candidate.runAttemptId === sourceAttempt?.id, + ); + if (sourceRun === undefined || sourceProviderThread === undefined) { + return yield* new ProviderTurnStartError({ + runId, + cause: `Native fork transfer ${nativeForkTransfer.id} has no source provider execution.`, + }); + } + return yield* session.forkThread({ + sourceProviderThread, + sourceProviderTurns: sourceProjection.providerTurns, + targetThreadId: projection.thread.id, + ...(sourceProviderTurn === undefined ? {} : { providerTurnId: sourceProviderTurn.id }), + }); + } + return providerThread.nativeThreadRef === null + ? yield* session.ensureThread({ + threadId: projection.thread.id, + modelSelection: run.modelSelection, + runtimePolicy: resolvedRuntimePolicy, + providerSessionId, + }) + : Option.isSome(activeSession) + ? providerThread + : yield* session.resumeThread({ providerThread }); + }); + const now = yield* DateTime.now; + const runningProviderThread: OrchestrationV2ProviderThread = { + ...loadedProviderThread, + id: providerThread.id, + driver: session.driver, + providerInstanceId: run.providerInstanceId, + providerSessionId, + appThreadId: projection.thread.id, + ownerNodeId: providerThread.ownerNodeId, + firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal, + lastRunOrdinal: run.ordinal, + handoffIds: providerThread.handoffIds, + forkedFrom: providerThread.forkedFrom, + status: "active", + createdAt: providerThread.createdAt, + updatedAt: now, + }; + const runningRun: OrchestrationV2Run = { + ...run, + status: "running", + startedAt: now, + }; + const runningAttempt: OrchestrationV2RunAttempt = { + ...attempt, + status: "running", + startedAt: now, + }; + const runningRootNode: OrchestrationV2ExecutionNode = { + ...rootNode, + status: "running", + startedAt: now, + }; + const events: Array = [ + { + id: yield* idAllocator.allocate.event({ + threadId: projection.thread.id, + providerSessionId, + }), + type: "provider-session.updated", + threadId: projection.thread.id, + driver: session.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: session.providerSession, + }, + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "provider-thread.updated", + threadId: projection.thread.id, + driver: session.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: runningProviderThread, + }, + ...(nativeForkTransfer === undefined || runningProviderThread.nativeThreadRef === null + ? [] + : [ + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "context-transfer.updated" as const, + threadId: projection.thread.id, + runId: run.id, + driver: session.driver, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + ...nativeForkTransfer, + targetProviderInstanceId: run.providerInstanceId, + targetRunId: run.id, + status: "consumed" as const, + resolution: { + strategy: "native_fork" as const, + providerThreadRef: runningProviderThread.nativeThreadRef, + }, + error: null, + updatedAt: now, + consumedAt: now, + }, + }, + ]), + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "run.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: runningRun, + }, + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "run-attempt.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: runningAttempt, + }, + { + id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }), + type: "node.updated", + threadId: projection.thread.id, + runId: run.id, + nodeId: rootNode.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: runningRootNode, + }, + ]; + yield* eventSink.write({ events }); + yield* runExecution.startRootRun({ + commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), + appThread: projection.thread, + providerSessionId, + session, + run: runningRun, + rootNode: runningRootNode, + checkpointScope, + providerThread: runningProviderThread, + attempt: runningAttempt, + attemptId: attempt.id, + providerTurnOrdinal: + Math.max( + 0, + ...projection.providerTurns + .filter((turn) => turn.providerThreadId === providerThread.id) + .map((turn) => turn.ordinal), + ) + 1, + shouldFinalizeRun: () => + projectionStore.getThreadProjection(projection.thread.id).pipe( + Effect.map( + (current) => + current.runs.find((candidate) => candidate.id === run.id)?.activeAttemptId === + attempt.id, + ), + Effect.catchCause(() => Effect.succeed(false)), + ), + message: { + messageId: message.id, + text: + handoffs.length === 0 + ? message.text + : providerMessageWithContextHandoffs({ handoffs, userText: message.text }), + attachments: message.attachments, + createdBy: message.createdBy, + creationSource: message.creationSource, + }, + modelSelection: run.modelSelection, + runtimePolicy: resolvedRuntimePolicy, + }); + }); + + return ProviderTurnStartServiceV2.of({ + start: (input) => + start(input).pipe( + Effect.mapError((cause) => + Schema.is(ProviderTurnStartError)(cause) + ? cause + : new ProviderTurnStartError({ runId: input.runId, cause }), + ), + ), + }); + }), +); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index fd7119fb7b..bbc61b9612 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -2,7 +2,6 @@ import { CommandId, type ModelSelection, type OrchestrationV2AppThread, - type OrchestrationV2Checkpoint, type OrchestrationV2CheckpointScope, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderThread, @@ -150,7 +149,6 @@ export const layer: Layer.Layer< OrchestrationV2Run["status"], "completed" | "interrupted" | "failed" | "cancelled" >; - readonly runtimePolicy: ProviderAdapterV2RuntimePolicy; }) => Effect.gen(function* () { const completedAt = yield* DateTime.now; @@ -162,43 +160,43 @@ export const layer: Layer.Layer< const shouldFinalizeRun = input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun(); if (!shouldFinalizeRun) { - yield* eventSink.write({ - events: [ - { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), - type: "run-attempt.updated" as const, - threadId: input.run.threadId, - runId: input.run.id, - nodeId: input.rootNode.id, - provider: input.run.provider, - occurredAt: completedAt, - payload: finalizedAttempt, - }, - ], - }); + // A newer attempt already owns the run and the command that created + // it terminalized this attempt as superseded. Preserve that domain + // status while retaining the provider's interruption artifact. + if (input.status === "interrupted") { + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), + type: "turn-item.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: makeInterruptResultTurnItem({ + idAllocator, + run: input.run, + rootNode: input.rootNode, + providerThread: input.providerThread, + completedAt, + }), + }, + ], + }); + } return; } - const checkpoint = - input.status === "completed" - ? yield* checkpointService.capture({ - scope: input.checkpointScope, - runId: input.run.id, - nodeId: input.rootNode.id, - ordinalWithinScope: input.run.ordinal, - appRunOrdinal: input.run.ordinal, - capturedAt: completedAt, - }) - : null; + const persistedStatus = input.status === "completed" ? "waiting" : input.status; const finalizedRun: OrchestrationV2Run = { ...input.run, - status: input.status, - completedAt, - checkpointId: checkpoint?.id ?? input.run.checkpointId, + status: persistedStatus, + completedAt: input.status === "completed" ? null : completedAt, }; const finalizedRootNode: OrchestrationV2ExecutionNode = { ...input.rootNode, - status: input.status, - completedAt, + status: persistedStatus, + completedAt: input.status === "completed" ? null : completedAt, checkpointScopeId: input.checkpointScope.id, }; const finalizedProviderThread: OrchestrationV2ProviderThread = { @@ -211,7 +209,25 @@ export const layer: Layer.Layer< const providerThreadEventId = yield* idAllocator.allocate.event({ threadId: input.run.threadId, }); - yield* eventSink.write({ + const checkpointCaptureCommandId = CommandId.make( + `command:effect:checkpoint.capture:${input.run.id}`, + ); + yield* eventSink.writeWithEffects({ + effects: + input.status === "completed" + ? [ + { + id: `effect:checkpoint.capture:${input.run.id}`, + commandId: checkpointCaptureCommandId, + threadId: input.run.threadId, + request: { + type: "checkpoint.capture" as const, + runId: input.run.id, + scopeId: input.checkpointScope.id, + }, + }, + ] + : [], events: [ ...(finalizedAttempt === null ? [] @@ -222,42 +238,11 @@ export const layer: Layer.Layer< threadId: input.run.threadId, runId: input.run.id, nodeId: input.rootNode.id, - provider: input.run.provider, + providerInstanceId: input.run.providerInstanceId, occurredAt: completedAt, payload: finalizedAttempt, }, ]), - ...(checkpoint === null - ? [] - : [ - { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), - type: "checkpoint.captured" as const, - threadId: input.run.threadId, - runId: input.run.id, - nodeId: input.rootNode.id, - provider: input.run.provider, - occurredAt: completedAt, - payload: checkpoint, - }, - { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), - type: "turn-item.updated" as const, - threadId: input.run.threadId, - runId: input.run.id, - nodeId: input.rootNode.id, - provider: input.run.provider, - occurredAt: completedAt, - payload: makeCheckpointTurnItem({ - idAllocator, - run: input.run, - rootNode: input.rootNode, - providerThread: input.providerThread, - checkpoint, - completedAt, - }), - }, - ]), ...(input.status === "interrupted" ? [ { @@ -266,7 +251,7 @@ export const layer: Layer.Layer< threadId: input.run.threadId, runId: input.run.id, nodeId: input.rootNode.id, - provider: input.run.provider, + providerInstanceId: input.run.providerInstanceId, occurredAt: completedAt, payload: makeInterruptResultTurnItem({ idAllocator, @@ -284,7 +269,7 @@ export const layer: Layer.Layer< threadId: input.run.threadId, runId: input.run.id, nodeId: input.rootNode.id, - provider: input.run.provider, + providerInstanceId: input.run.providerInstanceId, occurredAt: completedAt, payload: finalizedRun, }, @@ -294,7 +279,7 @@ export const layer: Layer.Layer< threadId: input.run.threadId, runId: input.run.id, nodeId: input.rootNode.id, - provider: input.run.provider, + providerInstanceId: input.run.providerInstanceId, occurredAt: completedAt, payload: finalizedRootNode, }, @@ -302,7 +287,7 @@ export const layer: Layer.Layer< id: providerThreadEventId, type: "provider-thread.updated", threadId: input.run.threadId, - provider: input.run.provider, + providerInstanceId: input.run.providerInstanceId, occurredAt: completedAt, payload: finalizedProviderThread, }, @@ -336,6 +321,7 @@ export const layer: Layer.Layer< if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) { yield* providerEventIngestor.ingestNormalized({ providerSessionId: input.providerSessionId, + providerInstanceId: input.run.providerInstanceId, threadId: input.run.threadId, runId: input.run.id, nodeId: input.rootNode.id, @@ -370,7 +356,6 @@ export const layer: Layer.Layer< ? {} : { shouldFinalizeRun: input.shouldFinalizeRun }), status, - runtimePolicy: input.runtimePolicy, }).pipe( Effect.mapError( (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), @@ -379,7 +364,11 @@ export const layer: Layer.Layer< }), ), Effect.catchCause((cause) => - Ref.get(latestProviderThread).pipe( + Effect.logWarning("orchestration V2 provider event ingestion failed", { + runId: input.run.id, + cause, + }).pipe( + Effect.andThen(Ref.get(latestProviderThread)), Effect.flatMap((providerThread) => writeFinalRunEvents({ run: input.run, @@ -391,7 +380,6 @@ export const layer: Layer.Layer< ? {} : { shouldFinalizeRun: input.shouldFinalizeRun }), status: "failed", - runtimePolicy: input.runtimePolicy, }), ), Effect.mapError( @@ -438,7 +426,11 @@ export const layer: Layer.Layer< }) .pipe( Effect.catchCause((cause) => - Fiber.interrupt(providerEventFiber).pipe( + Effect.logError("orchestration V2 provider turn start failed", { + runId: input.run.id, + cause, + }).pipe( + Effect.andThen(Fiber.interrupt(providerEventFiber)), Effect.andThen(Ref.get(latestProviderThread)), Effect.flatMap((providerThread) => writeFinalRunEvents({ @@ -451,7 +443,6 @@ export const layer: Layer.Layer< ? {} : { shouldFinalizeRun: input.shouldFinalizeRun }), status: "failed", - runtimePolicy: input.runtimePolicy, }), ), Effect.mapError( @@ -470,39 +461,6 @@ export const layer: Layer.Layer< }), ); -function makeCheckpointTurnItem(input: { - readonly idAllocator: IdAllocatorV2Shape; - readonly run: OrchestrationV2Run; - readonly rootNode: OrchestrationV2ExecutionNode; - readonly providerThread: OrchestrationV2ProviderThread; - readonly checkpoint: OrchestrationV2Checkpoint; - readonly completedAt: DateTime.Utc; -}): OrchestrationV2TurnItem { - return { - id: input.idAllocator.derive.turnItemFromProviderItem({ - provider: input.run.provider, - nativeItemId: `checkpoint:${input.checkpoint.id}`, - }), - threadId: input.run.threadId, - runId: input.run.id, - nodeId: input.rootNode.id, - providerThreadId: input.providerThread.id, - providerTurnId: input.rootNode.providerTurnId, - nativeItemRef: null, - parentItemId: null, - ordinal: input.run.ordinal * 100 + 99, - status: "completed", - title: null, - startedAt: input.completedAt, - completedAt: input.completedAt, - updatedAt: input.completedAt, - type: "checkpoint", - checkpointId: input.checkpoint.id, - scopeId: input.checkpoint.scopeId, - files: input.checkpoint.files, - }; -} - function makeInterruptResultTurnItem(input: { readonly idAllocator: IdAllocatorV2Shape; readonly run: OrchestrationV2Run; diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.ts b/apps/server/src/orchestration-v2/RuntimePolicy.ts index d1e971d055..8132bc8b53 100644 --- a/apps/server/src/orchestration-v2/RuntimePolicy.ts +++ b/apps/server/src/orchestration-v2/RuntimePolicy.ts @@ -1,4 +1,4 @@ -import { ModelSelection, OrchestrationV2AppThread, ProviderKind } from "@t3tools/contracts"; +import { ModelSelection, OrchestrationV2AppThread, ProviderDriverKind } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -15,12 +15,12 @@ import { export class RuntimePolicyResolveError extends Schema.TaggedErrorClass()( "RuntimePolicyResolveError", { - provider: ProviderKind, + driver: ProviderDriverKind, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to resolve runtime policy for ${this.provider}.`; + return `Failed to resolve runtime policy for ${this.driver}.`; } } diff --git a/apps/server/src/orchestration-v2/RuntimeRequestService.ts b/apps/server/src/orchestration-v2/RuntimeRequestService.ts index ccbc74dc46..00bcb47d3d 100644 --- a/apps/server/src/orchestration-v2/RuntimeRequestService.ts +++ b/apps/server/src/orchestration-v2/RuntimeRequestService.ts @@ -1,75 +1,101 @@ import { - NodeId, - OrchestrationV2RuntimeRequest, ProviderApprovalDecision, + ProviderSessionId, ProviderUserInputAnswers, RuntimeRequestId, ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import type * as Effect from "effect/Effect"; -export class RuntimeRequestOpenError extends Schema.TaggedErrorClass()( - "RuntimeRequestOpenError", - { - requestId: RuntimeRequestId, - nodeId: NodeId, - kind: Schema.String, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Failed to open runtime request ${this.requestId} (${this.kind}).`; - } -} +import { ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; -export class RuntimeRequestNotFoundError extends Schema.TaggedErrorClass()( - "RuntimeRequestNotFoundError", - { - threadId: ThreadId, - requestId: RuntimeRequestId, - }, -) { - override get message(): string { - return `Runtime request ${this.requestId} was not found in thread ${this.threadId}.`; - } -} - -export class RuntimeRequestRespondError extends Schema.TaggedErrorClass()( - "RuntimeRequestRespondError", +export class RuntimeRequestResponseExecutionError extends Schema.TaggedErrorClass()( + "RuntimeRequestResponseExecutionError", { threadId: ThreadId, requestId: RuntimeRequestId, cause: Schema.optional(Schema.Defect()), }, -) { - override get message(): string { - return `Failed to respond to runtime request ${this.requestId} in thread ${this.threadId}.`; - } -} - -export const RuntimeRequestServiceV2Error = Schema.Union([ - RuntimeRequestOpenError, - RuntimeRequestNotFoundError, - RuntimeRequestRespondError, -]); -export type RuntimeRequestServiceV2Error = typeof RuntimeRequestServiceV2Error.Type; +) {} export interface RuntimeRequestServiceV2Shape { - readonly open: ( - request: OrchestrationV2RuntimeRequest, - ) => Effect.Effect; readonly respond: (input: { readonly threadId: ThreadId; + readonly providerSessionId: ProviderSessionId; readonly requestId: RuntimeRequestId; readonly decision?: ProviderApprovalDecision; readonly answers?: ProviderUserInputAnswers; - readonly response?: unknown; - }) => Effect.Effect; + }) => Effect.Effect; } export class RuntimeRequestServiceV2 extends Context.Service< RuntimeRequestServiceV2, RuntimeRequestServiceV2Shape >()("t3/orchestration-v2/RuntimeRequestService/RuntimeRequestServiceV2") {} + +export const layer: Layer.Layer< + RuntimeRequestServiceV2, + never, + ProjectionStoreV2 | ProviderSessionManagerV2 +> = Layer.effect( + RuntimeRequestServiceV2, + Effect.gen(function* () { + const projections = yield* ProjectionStoreV2; + const sessions = yield* ProviderSessionManagerV2; + + return RuntimeRequestServiceV2.of({ + respond: (input) => + Effect.gen(function* () { + const projection = yield* projections.getThreadProjection(input.threadId); + const request = projection.runtimeRequests.find( + (candidate) => candidate.id === input.requestId, + ); + if (request === undefined) { + return yield* new RuntimeRequestResponseExecutionError({ + threadId: input.threadId, + requestId: input.requestId, + cause: "The runtime request no longer exists.", + }); + } + if ( + request.responseCapability.type !== "live" || + request.responseCapability.providerSessionId !== input.providerSessionId + ) { + return yield* new RuntimeRequestResponseExecutionError({ + threadId: input.threadId, + requestId: input.requestId, + cause: "The runtime request is not resumable on the recorded provider session.", + }); + } + const session = yield* sessions.get(input.providerSessionId); + if (Option.isNone(session)) { + return yield* new RuntimeRequestResponseExecutionError({ + threadId: input.threadId, + requestId: input.requestId, + cause: `Provider session ${input.providerSessionId} is not active.`, + }); + } + yield* session.value.respondToRuntimeRequest({ + requestId: input.requestId, + ...(input.decision === undefined ? {} : { decision: input.decision }), + ...(input.answers === undefined ? {} : { answers: input.answers }), + }); + }).pipe( + Effect.mapError((cause) => + Schema.is(RuntimeRequestResponseExecutionError)(cause) + ? cause + : new RuntimeRequestResponseExecutionError({ + threadId: input.threadId, + requestId: input.requestId, + cause, + }), + ), + ), + }); + }), +); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts new file mode 100644 index 0000000000..528415a7ed --- /dev/null +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -0,0 +1,43 @@ +import type { + OrchestrationV2ShellSnapshot, + OrchestrationV2ShellStreamItem, + OrchestrationV2StoredEvent, +} from "@t3tools/contracts"; + +/** Converts a committed event and its resulting shell snapshot into one delta. */ +export function shellStreamItemFromSnapshot(input: { + readonly stored: OrchestrationV2StoredEvent; + readonly snapshot: OrchestrationV2ShellSnapshot; +}): Exclude { + const active = input.snapshot.threads.find((thread) => thread.id === input.stored.event.threadId); + if (active !== undefined) { + return { + kind: "thread.updated", + sequence: input.stored.sequence, + location: "active", + thread: active, + }; + } + + const archived = input.snapshot.archivedThreads.find( + (thread) => thread.id === input.stored.event.threadId, + ); + if (archived !== undefined) { + return { + kind: "thread.updated", + sequence: input.stored.sequence, + location: "archive", + thread: archived, + }; + } + + return { + kind: "thread.removed", + sequence: input.stored.sequence, + location: + input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null + ? "archive" + : "active", + threadId: input.stored.event.threadId, + }; +} diff --git a/apps/server/src/orchestration-v2/SubagentProjection.ts b/apps/server/src/orchestration-v2/SubagentProjection.ts index 2f1a0a2a0e..d2bec48536 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.ts @@ -55,7 +55,7 @@ export function makeSubagentChildThread(input: { creationSource: input.creationSource, id: input.childThreadId, title: input.title, - defaultProvider: input.providerInstanceId, + providerInstanceId: input.providerInstanceId, modelSelection: input.modelSelection, activeProviderThreadId: input.activeProviderThreadId, lineage: { diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index 24b4e328a7..9527c5040b 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.ts @@ -1,58 +1,111 @@ import { + ContextTransferId, + OrchestrationV2Actor, OrchestrationV2AppThread, - OrchestrationV2ThreadForkSourcePoint, + OrchestrationV2ContextSourcePoint, + OrchestrationV2ContextTransfer, + OrchestrationV2CreationSource, + OrchestrationV2ProviderThread, + OrchestrationV2Run, + OrchestrationV2ThreadProjection, ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import type * as Effect from "effect/Effect"; + +export interface ThreadForkPlanV2 { + readonly targetThread: OrchestrationV2AppThread; + readonly transfer: OrchestrationV2ContextTransfer; +} export class ThreadForkPlanError extends Schema.TaggedErrorClass()( "ThreadForkPlanError", { + sourceThreadId: ThreadId, targetThreadId: ThreadId, - sourcePoint: OrchestrationV2ThreadForkSourcePoint, cause: Schema.optional(Schema.Defect()), }, -) { - override get message(): string { - return `Failed to plan fork into thread ${this.targetThreadId}.`; - } -} - -export class ThreadForkApplyError extends Schema.TaggedErrorClass()( - "ThreadForkApplyError", - { - targetThreadId: ThreadId, - sourcePoint: OrchestrationV2ThreadForkSourcePoint, - cause: Schema.optional(Schema.Defect()), - }, -) { - override get message(): string { - return `Failed to apply fork into thread ${this.targetThreadId}.`; - } -} - -export const ThreadForkServiceV2Error = Schema.Union([ThreadForkPlanError, ThreadForkApplyError]); -export type ThreadForkServiceV2Error = typeof ThreadForkServiceV2Error.Type; - -export interface ThreadForkPlanV2 { - readonly sourcePoint: OrchestrationV2ThreadForkSourcePoint; - readonly targetThreadId: ThreadId; - readonly targetThread: OrchestrationV2AppThread; -} +) {} export interface ThreadForkServiceV2Shape { readonly plan: (input: { - readonly sourcePoint: OrchestrationV2ThreadForkSourcePoint; + readonly sourceProjection: OrchestrationV2ThreadProjection; + readonly sourceRun: OrchestrationV2Run; + readonly sourceProviderThread: OrchestrationV2ProviderThread | undefined; + readonly canonicalSourcePoint: OrchestrationV2ContextSourcePoint; + readonly transferId: ContextTransferId; readonly targetThreadId: ThreadId; - }) => Effect.Effect; - readonly apply: ( - plan: ThreadForkPlanV2, - ) => Effect.Effect; + readonly title?: string; + readonly createdBy: OrchestrationV2Actor; + readonly creationSource: OrchestrationV2CreationSource; + readonly createdAt: DateTime.Utc; + }) => Effect.Effect; } export class ThreadForkServiceV2 extends Context.Service< ThreadForkServiceV2, ThreadForkServiceV2Shape >()("t3/orchestration-v2/ThreadForkService/ThreadForkServiceV2") {} + +export const layer: Layer.Layer = Layer.succeed( + ThreadForkServiceV2, + ThreadForkServiceV2.of({ + plan: (input) => + Effect.gen(function* () { + if (input.sourceRun.status !== "completed") { + return yield* new ThreadForkPlanError({ + sourceThreadId: input.sourceProjection.thread.id, + targetThreadId: input.targetThreadId, + cause: `Fork source run ${input.sourceRun.id} is ${input.sourceRun.status}.`, + }); + } + const targetThread: OrchestrationV2AppThread = { + ...input.sourceProjection.thread, + createdBy: input.createdBy, + creationSource: input.creationSource, + id: input.targetThreadId, + title: input.title ?? `${input.sourceProjection.thread.title} fork`, + activeProviderThreadId: null, + lineage: { + parentThreadId: input.sourceProjection.thread.id, + relationshipToParent: "fork", + rootThreadId: input.sourceProjection.thread.lineage.rootThreadId, + }, + forkedFrom: { + type: "run", + threadId: input.sourceProjection.thread.id, + runId: input.sourceRun.id, + }, + createdAt: input.createdAt, + updatedAt: input.createdAt, + archivedAt: null, + deletedAt: null, + }; + const transfer: OrchestrationV2ContextTransfer = { + id: input.transferId, + type: "fork", + sourceThreadId: input.sourceProjection.thread.id, + targetThreadId: input.targetThreadId, + sourcePoint: input.canonicalSourcePoint, + basePoint: null, + sourceProviderInstanceId: input.sourceRun.providerInstanceId, + targetProviderInstanceId: null, + targetRunId: null, + status: "pending", + resolution: null, + createdBy: input.createdBy, + error: + input.sourceProviderThread?.nativeThreadRef?.strength === "strong" + ? null + : "Source provider thread does not expose a strong native thread ref.", + createdAt: input.createdAt, + updatedAt: input.createdAt, + consumedAt: null, + }; + return { targetThread, transfer }; + }), + }), +); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 70df70d1a8..5805778a1a 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -138,6 +138,7 @@ export interface ThreadManagementServiceShape { readonly getThreadProjection: ( threadId: ThreadId, ) => Effect.Effect; + readonly getThreadSnapshot: OrchestratorV2["Service"]["getThreadSnapshot"]; readonly getProjectThread: (input: { readonly projectId: ProjectId; readonly threadId: ThreadId; @@ -158,6 +159,7 @@ export interface ThreadManagementServiceShape { ) => Effect.Effect; readonly getThreadEventSequence: OrchestratorV2["Service"]["getThreadEventSequence"]; readonly streamStoredEvents: OrchestratorV2["Service"]["streamStoredEvents"]; + readonly streamStoredEventsFrom: OrchestratorV2["Service"]["streamStoredEventsFrom"]; readonly streamDomainEvents: OrchestratorV2["Service"]["streamDomainEvents"]; } @@ -442,6 +444,7 @@ const make = Effect.gen(function* () { return ThreadManagementService.of({ dispatch: orchestrator.dispatch, getThreadProjection: orchestrator.getThreadProjection, + getThreadSnapshot: orchestrator.getThreadSnapshot, getProjectThread, getShellSnapshot: orchestrator.getShellSnapshot, listProjectThreads, @@ -450,6 +453,7 @@ const make = Effect.gen(function* () { interruptThread, getThreadEventSequence: orchestrator.getThreadEventSequence, streamStoredEvents: orchestrator.streamStoredEvents, + streamStoredEventsFrom: orchestrator.streamStoredEventsFrom, streamDomainEvents: orchestrator.streamDomainEvents, }); }); diff --git a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts new file mode 100644 index 0000000000..6f8993ae25 --- /dev/null +++ b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts @@ -0,0 +1,105 @@ +import { OrchestrationV2TurnItem, RunId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export class TurnItemPositionStoreError extends Schema.TaggedErrorClass()( + "TurnItemPositionStoreError", + { + threadId: ThreadId, + turnItemId: TurnItemId, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export interface TurnItemPositionStoreV2Shape { + readonly allocate: (input: { + readonly threadId: ThreadId; + readonly turnItemId: TurnItemId; + readonly runId: RunId | null; + readonly runOrdinal?: number; + }) => Effect.Effect; + readonly normalize: ( + item: OrchestrationV2TurnItem, + runOrdinal?: number, + ) => Effect.Effect; +} + +export class TurnItemPositionStoreV2 extends Context.Service< + TurnItemPositionStoreV2, + TurnItemPositionStoreV2Shape +>()("t3/orchestration-v2/TurnItemPositionStore/TurnItemPositionStoreV2") {} + +export const layer: Layer.Layer = Layer.effect( + TurnItemPositionStoreV2, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const allocate: TurnItemPositionStoreV2Shape["allocate"] = ({ + threadId, + turnItemId, + runId, + runOrdinal: suppliedRunOrdinal, + }) => + Effect.gen(function* () { + const runRows = + runId === null + ? [] + : yield* sql<{ readonly ordinal: number }>` + SELECT ordinal + FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND run_id = ${runId} + LIMIT 1 + `; + const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null; + const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000; + const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999; + yield* sql` + INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal) + SELECT + ${threadId}, + ${turnItemId}, + COALESCE(MAX(ordinal), ${lowerBound}) + 1 + FROM orchestration_v2_turn_item_positions + WHERE thread_id = ${threadId} + AND ordinal >= ${lowerBound} + AND ordinal <= ${upperBound} + ON CONFLICT(thread_id, turn_item_id) DO NOTHING + `; + const rows = yield* sql<{ readonly ordinal: number }>` + SELECT ordinal + FROM orchestration_v2_turn_item_positions + WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId} + LIMIT 1 + `; + const ordinal = rows[0]?.ordinal; + if (ordinal === undefined) { + return yield* new TurnItemPositionStoreError({ + threadId, + turnItemId, + cause: "Position allocation returned no row.", + }); + } + return ordinal; + }).pipe( + Effect.mapError((cause) => + Schema.is(TurnItemPositionStoreError)(cause) + ? cause + : new TurnItemPositionStoreError({ threadId, turnItemId, cause }), + ), + ); + + return TurnItemPositionStoreV2.of({ + allocate, + normalize: (item, runOrdinal) => + allocate({ + threadId: item.threadId, + turnItemId: item.id, + runId: item.runId, + ...(runOrdinal === undefined ? {} : { runOrdinal }), + }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal }))), + }); + }), +); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index d84b02d787..ea514e2582 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4,19 +4,27 @@ import { CommandId, type ModelSelection, ProjectId, + ProviderDriverKind, ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts"; import { ServerConfig } from "../config.ts"; import { GitCoreLive } from "../git/Layers/GitCore.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import { ServerSettingsService } from "../serverSettings.ts"; +import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts"; +import type { ProviderInstance } from "../provider/ProviderDriver.ts"; +import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; import { OrchestratorV2 } from "./Orchestrator.ts"; +import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import { OrchestrationV2LayerLive } from "./runtimeLayer.ts"; +import { shellStreamItemFromSnapshot } from "./ShellStream.ts"; const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-orchestration-v2-runtime-layer-", @@ -32,11 +40,43 @@ const CheckpointStoreTestLayer = CheckpointStoreLive.pipe( Layer.provide(NodeServices.layer), ); +const driver = ProviderDriverKind.make("codex"); +const orchestrationAdapter = { + instanceId: modelSelection.instanceId, + driver, + getCapabilities: () => Effect.die("capabilities are not used by lifecycle tests"), + openSession: () => Effect.die("sessions are not used by lifecycle tests"), +} as ProviderAdapterV2Shape; +const providerInstance = { + instanceId: modelSelection.instanceId, + driverKind: driver, + continuationIdentity: { + driverKind: driver, + continuationKey: "codex:test", + }, + displayName: "Codex test", + enabled: true, + snapshot: {} as ProviderInstance["snapshot"], + adapter: {} as ProviderInstance["adapter"], + orchestrationAdapter, + textGeneration: {} as ProviderInstance["textGeneration"], +} satisfies ProviderInstance; + +const TestProviderInstanceRegistry = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(instanceId === providerInstance.instanceId ? providerInstance : undefined), + listInstances: Effect.succeed([providerInstance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.never, +}); + const TestLayer = OrchestrationV2LayerLive.pipe( Layer.provide(SqlitePersistenceMemory), Layer.provide(CheckpointStoreTestLayer), Layer.provide(ServerConfigLayer), Layer.provide(ServerSettingsService.layerTest()), + Layer.provide(TestProviderInstanceRegistry), Layer.provide(NodeServices.layer), ); @@ -70,8 +110,139 @@ it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => { assert.equal(result.sequence, 1); assert.equal(projection.thread.id, threadId); assert.equal(projection.thread.projectId, projectId); - assert.equal(projection.thread.defaultProvider, "codex"); + assert.equal(projection.thread.providerInstanceId, "codex"); assert.deepEqual(projection.runs, []); }), ); + + it.effect("applies lifecycle commands idempotently and emits archive/removal shell deltas", () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-lifecycle-thread"); + const create = { + type: "thread.create" as const, + createdBy: "user" as const, + creationSource: "web" as const, + commandId: CommandId.make("runtime-layer-lifecycle-create"), + threadId, + projectId: ProjectId.make("runtime-layer-lifecycle-project"), + title: "Lifecycle thread", + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + }; + + const firstCreate = yield* orchestrator.dispatch(create); + const retriedCreate = yield* orchestrator.dispatch(create); + assert.equal(retriedCreate.sequence, firstCreate.sequence); + assert.lengthOf(retriedCreate.storedEvents, 1); + + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("runtime-layer-lifecycle-metadata"), + threadId, + title: "Renamed lifecycle thread", + branch: "feature/v2", + worktreePath: "/tmp/t3-v2-worktree", + }); + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("runtime-layer-lifecycle-runtime"), + threadId, + runtimeMode: "approval-required", + }); + yield* orchestrator.dispatch({ + type: "thread.interaction-mode.set", + commandId: CommandId.make("runtime-layer-lifecycle-interaction"), + threadId, + interactionMode: "plan", + }); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("runtime-layer-lifecycle-model"), + threadId, + modelSelection: { ...modelSelection, model: "gpt-5.5" }, + }); + + const archive = yield* orchestrator.dispatch({ + type: "thread.archive", + commandId: CommandId.make("runtime-layer-lifecycle-archive"), + threadId, + }); + const archivedShell = yield* orchestrator.getShellSnapshot(); + assert.notInclude( + archivedShell.threads.map((thread) => thread.id), + threadId, + ); + assert.include( + archivedShell.archivedThreads.map((thread) => thread.id), + threadId, + ); + assert.deepEqual( + shellStreamItemFromSnapshot({ + stored: archive.storedEvents[0]!, + snapshot: archivedShell, + }), + { + kind: "thread.updated", + sequence: archive.sequence, + location: "archive", + thread: archivedShell.archivedThreads[0]!, + }, + ); + + const remove = yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("runtime-layer-lifecycle-delete"), + threadId, + }); + const deletedShell = yield* orchestrator.getShellSnapshot(); + assert.notInclude( + deletedShell.threads.map((thread) => thread.id), + threadId, + ); + assert.notInclude( + deletedShell.archivedThreads.map((thread) => thread.id), + threadId, + ); + assert.deepEqual( + shellStreamItemFromSnapshot({ stored: remove.storedEvents[0]!, snapshot: deletedShell }), + { + kind: "thread.removed", + sequence: remove.sequence, + location: "archive", + threadId, + }, + ); + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.thread.title, "Renamed lifecycle thread"); + assert.equal(projection.thread.branch, "feature/v2"); + assert.equal(projection.thread.worktreePath, "/tmp/t3-v2-worktree"); + assert.equal(projection.thread.runtimeMode, "approval-required"); + assert.equal(projection.thread.interactionMode, "plan"); + assert.equal(projection.thread.modelSelection.model, "gpt-5.5"); + assert.isNotNull(projection.thread.archivedAt); + assert.isNotNull(projection.thread.deletedAt); + }), + ); + + it.effect("persists rejected command receipts across retries", () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const command = { + type: "thread.archive" as const, + commandId: CommandId.make("runtime-layer-rejected-command"), + threadId: ThreadId.make("runtime-layer-missing-thread"), + }; + + const first = yield* orchestrator.dispatch(command).pipe(Effect.flip); + const retry = yield* orchestrator.dispatch(command).pipe(Effect.flip); + + assert.equal(first._tag, "OrchestratorProjectionError"); + assert.equal(retry._tag, "OrchestratorCommandPreviouslyRejectedError"); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index bdb49ef70b..058958c20d 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,31 +1,45 @@ import * as Layer from "effect/Layer"; -import { FetchHttpClient } from "effect/unstable/http"; - -import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts"; -import { claudeAgentSdkQueryRunnerLiveLayer } from "./Adapters/ClaudeAdapterV2.ts"; -import { codexAppServerClientFactoryFromSettingsLayer } from "./Adapters/CodexAdapterV2.ts"; -import { cursorAgentSdkRunnerLiveLayer } from "./Adapters/CursorAgentSdk.ts"; -import { BUILT_IN_PROVIDER_ADAPTER_DRIVERS_V2 } from "./builtInProviderAdapterDrivers.ts"; +import { layer as checkpointCaptureServiceLayer } from "./CheckpointCaptureService.ts"; import { layer as checkpointServiceLayer } from "./CheckpointService.ts"; +import { layer as checkpointRollbackServiceLayer } from "./CheckpointRollbackService.ts"; import { layer as commandPolicyLayer } from "./CommandPolicy.ts"; import { layer as commandReceiptStoreLayer } from "./CommandReceiptStore.ts"; import { layer as contextHandoffServiceLayer } from "./ContextHandoffService.ts"; -import { layer as eventSinkLayer } from "./EventSink.ts"; +import { layer as effectOutboxLayer } from "./EffectOutbox.ts"; +import { + daemonLayer as effectWorkerDaemonLayer, + executorLayer as effectExecutorLayer, + layer as effectWorkerLayer, +} from "./EffectWorker.ts"; +import { layerFromStores as eventSinkLayer } from "./EventSink.ts"; import { layer as eventStoreLayer } from "./EventStore.ts"; import { layer as idAllocatorLayer } from "./IdAllocator.ts"; import { layer as orchestratorLayer } from "./Orchestrator.ts"; import { layer as projectionStoreLayer } from "./ProjectionStore.ts"; -import { ProviderAdapterV2 } from "./ProviderAdapter.ts"; -import { makeLayerEffect as providerAdapterRegistryLayerFromEffect } from "./ProviderAdapterRegistry.ts"; +import { layer as projectionMaintenanceLayer } from "./ProjectionMaintenance.ts"; +import { layerFromProviderInstanceRegistry as providerAdapterRegistryLayerFromProviderInstances } from "./ProviderAdapterRegistry.ts"; import { layer as providerEventIngestorLayer } from "./ProviderEventIngestor.ts"; import { layer as providerSessionManagerLayer } from "./ProviderSessionManager.ts"; +import { layer as providerSwitchServiceLayer } from "./ProviderSwitchService.ts"; +import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlService.ts"; +import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts"; import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts"; import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts"; +import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts"; import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts"; +import { layer as threadForkServiceLayer } from "./ThreadForkService.ts"; +import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts"; -const storesLayer = Layer.merge(eventStoreLayer, projectionStoreLayer); +const storesLayer = Layer.mergeAll( + eventStoreLayer, + projectionStoreLayer, + commandReceiptStoreLayer, + effectOutboxLayer, + turnItemPositionStoreLayer, +); const eventSinkProvided = eventSinkLayer.pipe(Layer.provide(storesLayer)); +const projectionMaintenanceProvided = projectionMaintenanceLayer.pipe(Layer.provide(storesLayer)); const commandReceiptStoreProvided = commandReceiptStoreLayer; @@ -38,18 +52,7 @@ const contextHandoffServiceProvided = contextHandoffServiceLayer.pipe( Layer.provide(idAllocatorLayer), ); -const codexAdapterProvided = codexAdapterLayer.pipe( - Layer.provide(codexAppServerClientFactoryFromSettingsLayer), - Layer.provide(idAllocatorLayer), -); - -const claudeAdapterProvided = claudeAdapterLayer.pipe( - Layer.provide(claudeAgentSdkQueryRunnerLiveLayer), - Layer.provide(cursorAgentSdkRunnerLiveLayer), - Layer.provide(OpenCodeRuntimeLive), - Layer.provide(FetchHttpClient.layer), - Layer.provide(idAllocatorLayer), -); +const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromProviderInstances; const providerAdapterRegistryProvided = providerAdapterRegistryLayerFromEffect( Effect.all([ @@ -80,6 +83,67 @@ const runExecutionServiceProvided = runExecutionServiceLayer.pipe( ), ); +const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + eventSinkProvided, + idAllocatorLayer, + projectionStoreLayer, + providerSessionManagerProvided, + runExecutionServiceProvided, + runtimePolicyLayer, + ), + ), +); + +const providerTurnControlServiceProvided = providerTurnControlServiceLayer.pipe( + Layer.provide(Layer.merge(projectionStoreLayer, providerSessionManagerProvided)), +); +const runtimeRequestServiceProvided = runtimeRequestServiceLayer.pipe( + Layer.provide(Layer.merge(projectionStoreLayer, providerSessionManagerProvided)), +); +const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + checkpointServiceProvided, + eventSinkProvided, + idAllocatorLayer, + projectionStoreLayer, + providerSessionManagerProvided, + runtimePolicyLayer, + ), + ), +); +const checkpointCaptureServiceProvided = checkpointCaptureServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + checkpointServiceProvided, + eventSinkProvided, + idAllocatorLayer, + projectionStoreLayer, + ), + ), +); + +const effectExecutorProvided = effectExecutorLayer.pipe( + Layer.provide( + Layer.mergeAll( + checkpointCaptureServiceProvided, + checkpointRollbackServiceProvided, + providerSessionManagerProvided, + providerTurnControlServiceProvided, + providerTurnStartServiceProvided, + runtimeRequestServiceProvided, + ), + ), +); +const effectWorkerProvided = effectWorkerLayer.pipe( + Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)), +); +const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe( + Layer.provide(effectWorkerProvided), +); + const orchestratorProvided = orchestratorLayer.pipe( Layer.provide( Layer.mergeAll( @@ -87,18 +151,24 @@ const orchestratorProvided = orchestratorLayer.pipe( commandPolicyLayer, storesLayer, eventSinkProvided, + effectWorkerProvided, commandReceiptStoreProvided, contextHandoffServiceProvided, idAllocatorLayer, + providerAdapterRegistryProvided, providerEventIngestorProvided, runtimePolicyLayer, providerSessionManagerProvided, + providerSwitchServiceLayer, runExecutionServiceProvided, + threadForkServiceLayer, ), ), ); -export const OrchestrationV2LayerLive = Layer.merge( +export const OrchestrationV2LayerLive = Layer.mergeAll( orchestratorProvided, threadManagementServiceLayer.pipe(Layer.provide(orchestratorProvided)), + effectWorkerDaemonProvided, + projectionMaintenanceProvided, ); diff --git a/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts index 032bf46990..3f2ea0d8af 100644 --- a/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts @@ -37,7 +37,7 @@ const readTranscript = Effect.fn("readClaudeReplayFixture")(function* (file: URL function claudeFixture(name: string) { const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((entry) => entry.name === name); - const provider = fixture?.providers.find((entry) => entry.provider === "claudeAgent"); + const provider = fixture?.providers.find((entry) => entry.driver === "claudeAgent"); if (fixture === undefined || provider === undefined) { throw new Error(`Missing ${name}/claudeAgent replay fixture.`); } @@ -144,7 +144,7 @@ describe("Claude Agent SDK replay fixtures", () => { for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) { for (const provider of fixture.providers) { - if (provider.provider !== "claudeAgent") { + if (provider.driver !== "claudeAgent") { continue; } diff --git a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts index 5e198927d6..55a0906297 100644 --- a/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts @@ -31,7 +31,7 @@ type ProtocolReplayEntry = Extract< const CODEX_REPLAY_FIXTURES = ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) => fixture.providers - .filter((provider) => provider.provider === "codex") + .filter((provider) => provider.driver === "codex") .map((provider) => ({ scenario: fixture.name, transcriptFile: provider.transcriptFile, diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts index 3839d6c4bc..a82947ba95 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts @@ -1,6 +1,6 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { OrchestrationV2Command } from "@t3tools/contracts"; +import { OrchestrationV2Command, ProviderInstanceId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; @@ -35,7 +35,7 @@ describe("orchestrator replay fixture contract", () => { for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) { assert.isAtLeast(fixture.providers.length, 1, `${fixture.name} must have providers`); assertUnique( - fixture.providers.map((provider) => provider.provider), + fixture.providers.map((provider) => provider.driver), `${fixture.name} provider variants`, ); @@ -44,25 +44,29 @@ describe("orchestrator replay fixture contract", () => { const materialized = yield* materializeFixtureInput({ scenario: fixture.name, fixtureInput: fixture.buildInput(), + driver: provider.driver, modelSelection: provider.modelSelection, }).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime); const firstCommand = materialized.commands[0]; assert.equal(transcript.scenario, fixture.name); - if (provider.provider === "acpRegistry") { + if (provider.driver === "acpRegistry") { assert.include( ["acpRegistry", "grok"], transcript.provider, "ACP Registry may retarget protocol-standard Grok ACP evidence", ); } else { - assert.equal(transcript.provider, provider.provider); + assert.equal(transcript.provider, provider.driver); } - assert.equal(provider.modelSelection.instanceId, provider.provider); + assert.equal( + provider.modelSelection.instanceId, + ProviderInstanceId.make(provider.driver), + ); assert.isDefined(materialized.projectionThreadIds[0]); assert.equal(firstCommand?.type, "thread.create"); if (firstCommand?.type !== "thread.create") { - throw new Error(`${fixture.name}/${provider.provider} must start with thread.create`); + throw new Error(`${fixture.name}/${provider.driver} must start with thread.create`); } assert.equal(firstCommand.threadId, materialized.projectionThreadIds[0]); assert.equal(materialized.commands.length, fixture.buildInput().steps.length + 1); @@ -71,7 +75,7 @@ describe("orchestrator replay fixture contract", () => { assertUnique( materialized.commands.map((command) => command.commandId), - `${fixture.name}/${provider.provider} command IDs`, + `${fixture.name}/${provider.driver} command IDs`, ); for (const command of materialized.commands) { @@ -86,7 +90,7 @@ describe("orchestrator replay fixture contract", () => { (step.type === "respond_to_next_runtime_request" && step.commandId === command.commandId), ), - `${fixture.name}/${provider.provider} command ${command.commandId} must appear in the timeline`, + `${fixture.name}/${provider.driver} command ${command.commandId} must appear in the timeline`, ); } } @@ -97,7 +101,7 @@ describe("orchestrator replay fixture contract", () => { it.effect("keeps Codex fixture transcripts at the codex app-server boundary", () => Effect.gen(function* () { for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) { - for (const provider of fixture.providers.filter((entry) => entry.provider === "codex")) { + for (const provider of fixture.providers.filter((entry) => entry.driver === "codex")) { const transcript = yield* readTranscript(provider.transcriptFile); const first = transcript.entries[0]; const last = transcript.entries.at(-1); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts index ebebfb67f3..a0c1a4dd76 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts @@ -55,26 +55,27 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < >(input: { readonly fixtureName: string; readonly buildInput: () => OrchestratorFixtureInput; - readonly provider: ProviderOrchestratorReplayVariant; + readonly driver: ProviderOrchestratorReplayVariant; readonly harness: OrchestratorV2ProviderReplayHarness; readonly enableAssistantStreaming?: boolean; }) { - const rawTranscript = yield* readTranscript(input.provider.transcriptFile); + const rawTranscript = yield* readTranscript(input.driver.transcriptFile); const transcript = yield* input.harness.decodeTranscript(rawTranscript); const workspace = yield* checkpointWorkspace(input.fixtureName); const materialized = yield* materializeFixtureInput({ scenario: input.fixtureName, fixtureInput: input.buildInput(), - modelSelection: input.provider.modelSelection, + driver: input.driver.driver, + modelSelection: input.driver.modelSelection, }).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime); const scenario = { - name: `${input.fixtureName}/${input.provider.provider}`, + name: `${input.fixtureName}/${input.driver.driver}`, transcript, commands: materialized.commands, steps: materialized.steps, projectionThreadIds: materialized.projectionThreadIds, runtimePolicyOverride: { - ...input.provider.runtimePolicyOverride, + ...input.driver.runtimePolicyOverride, cwd: workspace, }, }; @@ -82,8 +83,7 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness, { enableAssistantStreaming: input.enableAssistantStreaming ?? false, }).pipe(provideDeterministicTestRuntime); - - input.provider.assertOutput(result, transcript); + input.driver.assertOutput(result, transcript); if (input.enableAssistantStreaming !== true) { assert.isFalse( result.domainEvents.some(isStreamingAssistantEvent), @@ -95,17 +95,17 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < const projection = result.projections.get(projectionThreadId); assert.isDefined(projection); const latestRun = projection.runs.at(-1); - assert.deepEqual(latestRun?.modelSelection, input.provider.modelSelection); + assert.deepEqual(latestRun?.modelSelection, input.driver.modelSelection); return result; }); function runFixtureProviderWithRegisteredHarness(input: { readonly fixtureName: string; readonly buildInput: () => OrchestratorFixtureInput; - readonly provider: ProviderOrchestratorReplayVariant; + readonly driver: ProviderOrchestratorReplayVariant; readonly enableAssistantStreaming?: boolean; }) { - switch (input.provider.provider) { + switch (input.driver.driver) { case "codex": return runFixtureProvider({ ...input, @@ -138,7 +138,7 @@ function runFixtureProviderWithRegisteredHarness(input: { }).pipe(Effect.mapError(normalizeTestError), Effect.scoped); default: return Effect.die( - new Error(`No replay harness registered for provider ${input.provider.provider}.`), + new Error(`No replay harness registered for provider ${input.driver.driver}.`), ); } } @@ -147,12 +147,12 @@ describe("orchestrator replay fixtures", () => { for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) { for (const provider of fixture.providers) { it.effect( - `runs ${fixture.name}/${provider.provider} through OrchestratorV2 using deterministic replay`, + `runs ${fixture.name}/${provider.driver} through OrchestratorV2 using deterministic replay`, () => runFixtureProviderWithRegisteredHarness({ fixtureName: fixture.name, buildInput: fixture.buildInput, - provider, + driver: provider, }), ); } @@ -162,21 +162,21 @@ describe("orchestrator replay fixtures", () => { (fixture) => fixture.name === "message_steering", ); const cursorSteeringProvider = steeringFixture?.providers.find( - (provider) => provider.provider === "cursor", + (provider) => provider.driver === "cursor", ); if (cursorSteeringProvider !== undefined) { it.effect("executes explicit Cursor restart_active through the recorded SDK boundary", () => runFixtureProviderWithRegisteredHarness({ fixtureName: "message_steering", buildInput: messageRestartInput, - provider: cursorSteeringProvider, + driver: cursorSteeringProvider, }), ); } const simpleFixture = ORCHESTRATOR_REPLAY_FIXTURES.find((fixture) => fixture.name === "simple"); const simpleCursorProvider = simpleFixture?.providers.find( - (provider) => provider.provider === "cursor", + (provider) => provider.driver === "cursor", ); if (simpleFixture !== undefined && simpleCursorProvider !== undefined) { it.effect("streams Cursor assistant artifacts only when streaming is enabled", () => @@ -184,7 +184,7 @@ describe("orchestrator replay fixtures", () => { const result = yield* runFixtureProviderWithRegisteredHarness({ fixtureName: "simple-cursor-streaming", buildInput: simpleFixture.buildInput, - provider: simpleCursorProvider, + driver: simpleCursorProvider, enableAssistantStreaming: true, }); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts index 85243bd0fe..ad7cbc662f 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts @@ -6,6 +6,7 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as CodexReplay from "effect-codex-app-server/replay"; +import { ProviderDriverKind } from "@t3tools/contracts"; import { CodexOrchestratorReplayHarness, @@ -103,6 +104,7 @@ const runCursorRecovery = Effect.fn("runCursorRecovery")(function* (input: { { type: "message", text: PROVIDER_THREAD_RESUME_SECOND_PROMPT }, ], }, + driver: ProviderDriverKind.make("cursor"), modelSelection: CURSOR_MODEL_SELECTION, }); const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } = @@ -196,6 +198,7 @@ describe("orchestrator replay recovery", () => { { type: "message", text: PROVIDER_THREAD_RESUME_SECOND_PROMPT }, ], }, + driver: ProviderDriverKind.make("codex"), modelSelection: CODEX_MODEL_SELECTION, }); const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } = diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 3c06b6eb37..d3cf0bb060 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -92,6 +92,14 @@ export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass { switch (command.type) { case "thread.create": + case "thread.archive": + case "thread.unarchive": + case "thread.delete": + case "thread.metadata.update": + case "thread.runtime-mode.set": + case "thread.interaction-mode.set": + case "thread.model-selection.set": + case "provider-session.release": case "message.dispatch": case "run.interrupt": case "queued-message.promote-to-steer": @@ -213,9 +221,10 @@ export function runOrchestratorV2Scenario( return request; } if (attemptsRemaining <= 0) { + const runState = projection.runs.map((run) => `${run.id}:${run.status}`).join(","); return yield* new OrchestratorV2ScenarioStepError({ scenario: scenario.name, - step: `respond_to_next_runtime_request:${threadId}`, + step: `respond_to_next_runtime_request:${threadId}:runs=${runState}:providerTurns=${projection.providerTurns.length}`, }); } yield* yieldToRuntime; @@ -232,9 +241,17 @@ export function runOrchestratorV2Scenario( return; } if (attemptsRemaining <= 0) { + const activeRuns = projection.runs + .filter((run) => ["queued", "starting", "running", "waiting"].includes(run.status)) + .map((run) => `${run.id}:${run.status}`) + .join(","); + const pendingRequests = projection.runtimeRequests + .filter((request) => request.status === "pending") + .map((request) => `${request.id}:${request.kind}`) + .join(","); return yield* new OrchestratorV2ScenarioStepError({ scenario: scenario.name, - step: `await_thread_idle:${threadId}`, + step: `await_thread_idle:${threadId}:runs=${activeRuns}:requests=${pendingRequests}`, }); } yield* yieldToRuntime; diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 533d030aa3..ff6a4b43a8 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -1,5 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import type { ProviderKind, ProviderReplayTranscript } from "@t3tools/contracts"; +import type { ProviderDriverKind, ProviderReplayTranscript } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -16,11 +16,19 @@ import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../../vcs/VcsProcess.ts"; +import { layer as checkpointCaptureServiceLayer } from "../CheckpointCaptureService.ts"; import { layer as checkpointServiceLayer } from "../CheckpointService.ts"; +import { layer as checkpointRollbackServiceLayer } from "../CheckpointRollbackService.ts"; import { layer as commandPolicyLayer } from "../CommandPolicy.ts"; import { layer as commandReceiptStoreLayer } from "../CommandReceiptStore.ts"; import { layer as contextHandoffServiceLayer } from "../ContextHandoffService.ts"; -import { layer as eventSinkLayer } from "../EventSink.ts"; +import { layer as effectOutboxLayer } from "../EffectOutbox.ts"; +import { + daemonLayer as effectWorkerDaemonLayer, + executorLayer as effectExecutorLayer, + layer as effectWorkerLayer, +} from "../EffectWorker.ts"; +import { layerFromStores as eventSinkLayer } from "../EventSink.ts"; import { layer as eventStoreLayer } from "../EventStore.ts"; import { layer as idAllocatorLayer } from "../IdAllocator.ts"; import { layer as orchestratorLayer } from "../Orchestrator.ts"; @@ -29,12 +37,18 @@ import type { OrchestratorV2, OrchestratorV2Error } from "../Orchestrator.ts"; import { ProviderAdapterRegistryV2 } from "../ProviderAdapterRegistry.ts"; import { layer as providerEventIngestorLayer } from "../ProviderEventIngestor.ts"; import { layer as providerSessionManagerLayer } from "../ProviderSessionManager.ts"; +import { layer as providerSwitchServiceLayer } from "../ProviderSwitchService.ts"; +import { layer as providerTurnControlServiceLayer } from "../ProviderTurnControlService.ts"; +import { layer as providerTurnStartServiceLayer } from "../ProviderTurnStartService.ts"; import { layer as runExecutionServiceLayer } from "../RunExecutionService.ts"; import { layer as runtimePolicyLayer, layerWithOverride as runtimePolicyLayerWithOverride, type RuntimePolicyV2Override, } from "../RuntimePolicy.ts"; +import { layer as turnItemPositionStoreLayer } from "../TurnItemPositionStore.ts"; +import { layer as runtimeRequestServiceLayer } from "../RuntimeRequestService.ts"; +import { layer as threadForkServiceLayer } from "../ThreadForkService.ts"; import { runOrchestratorV2Scenario, type OrchestratorV2ScenarioStepError, @@ -133,7 +147,7 @@ export interface OrchestratorV2ProviderReplayHarness< Transcript extends ProviderReplayTranscript = ProviderReplayTranscript, Error = never, > { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly decodeTranscript: ( transcript: ProviderReplayTranscript, ) => Effect.Effect; @@ -213,9 +227,13 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( const serverSettingsLayer = ServerSettingsService.layerTest({ enableAssistantStreaming: options.enableAssistantStreaming ?? false, }).pipe(Layer.orDie); - const storesLayer = Layer.merge(eventStoreLayer, projectionStoreLayer).pipe( - Layer.provide(databaseLayer), - ); + const storesLayer = Layer.mergeAll( + eventStoreLayer, + projectionStoreLayer, + commandReceiptStoreLayer, + effectOutboxLayer, + turnItemPositionStoreLayer, + ).pipe(Layer.provide(databaseLayer)); const eventSinkProvided = eventSinkLayer.pipe( Layer.provide(Layer.mergeAll(storesLayer, databaseLayer)), ); @@ -258,17 +276,75 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( ), ), ); - return orchestratorLayer.pipe( + const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + eventSinkProvided, + idAllocatorLayer, + storesLayer, + providerSessionManagerProvided, + runExecutionServiceProvided, + runtimeLayer, + ), + ), + ); + const providerTurnControlServiceProvided = providerTurnControlServiceLayer.pipe( + Layer.provide(Layer.merge(storesLayer, providerSessionManagerProvided)), + ); + const runtimeRequestServiceProvided = runtimeRequestServiceLayer.pipe( + Layer.provide(Layer.merge(storesLayer, providerSessionManagerProvided)), + ); + const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe( + Layer.provide( + Layer.mergeAll( + checkpointServiceProvided, + eventSinkProvided, + idAllocatorLayer, + storesLayer, + providerSessionManagerProvided, + runtimeLayer, + ), + ), + ); + const checkpointCaptureServiceProvided = checkpointCaptureServiceLayer.pipe( + Layer.provide( + Layer.mergeAll(checkpointServiceProvided, eventSinkProvided, idAllocatorLayer, storesLayer), + ), + ); + const effectExecutorProvided = effectExecutorLayer.pipe( + Layer.provide( + Layer.mergeAll( + checkpointCaptureServiceProvided, + checkpointRollbackServiceProvided, + providerSessionManagerProvided, + providerTurnControlServiceProvided, + providerTurnStartServiceProvided, + runtimeRequestServiceProvided, + ), + ), + ); + const effectWorkerProvided = effectWorkerLayer.pipe( + Layer.provide(Layer.merge(storesLayer, effectExecutorProvided)), + ); + const effectWorkerDaemonProvided = effectWorkerDaemonLayer.pipe( + Layer.provide(effectWorkerProvided), + ); + const orchestratorProvided = orchestratorLayer.pipe( Layer.provide( Layer.mergeAll( checkpointServiceProvided, commandPolicyLayer, contextHandoffServiceProvided, + effectWorkerProvided, persistenceLayer, + registryLayer, runtimeLayer, providerSessionManagerProvided, + providerSwitchServiceLayer, runExecutionServiceProvided, + threadForkServiceLayer, ), ), ); + return Layer.merge(orchestratorProvided, effectWorkerDaemonProvided); } diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 2063af6454..53b7318ec5 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -13,7 +13,7 @@ import { ProviderTurnId, ThreadId, TurnItemId, - type ProviderKind, + ProviderDriverKind, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -44,21 +44,24 @@ const projectId = ProjectId.make("project:provider-switch"); const firstPrompt = "Respond with exactly: codex before switch"; const claudePrompt = "Respond with exactly: claude switched response"; const returnPrompt = "Respond with exactly: codex after return"; +const CODEX_DRIVER = ProviderDriverKind.make("codex"); +const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent"); +const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); interface CapturedTurn { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly threadId: ThreadId; readonly providerThreadId: ProviderThreadId; readonly text: string; } -function unimplemented(provider: ProviderKind, detail: string) { - return Effect.fail(new ProviderAdapterProtocolError({ provider, detail })); +function unimplemented(driver: ProviderDriverKind, detail: string) { + return Effect.fail(new ProviderAdapterProtocolError({ driver, detail })); } function makeTestAdapter(input: { readonly instanceId: ProviderInstanceId; - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly capabilities: OrchestrationV2ProviderCapabilities; readonly modelSelection: ModelSelection; readonly responseByRunOrdinal: Readonly>; @@ -67,7 +70,7 @@ function makeTestAdapter(input: { }): ProviderAdapterV2Shape { return { instanceId: input.instanceId, - provider: input.provider, + driver: input.driver, getCapabilities: () => Effect.succeed(input.capabilities), openSession: (sessionInput) => Effect.gen(function* () { @@ -75,7 +78,8 @@ function makeTestAdapter(input: { const now = yield* DateTime.now; const providerSession: OrchestrationV2ProviderSession = { id: sessionInput.providerSessionId, - provider: input.provider, + driver: input.driver, + providerInstanceId: input.instanceId, status: "ready", cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(), model: input.modelSelection.model, @@ -87,7 +91,7 @@ function makeTestAdapter(input: { return { instanceId: input.instanceId, - provider: input.provider, + driver: input.driver, providerSessionId: sessionInput.providerSessionId, providerSession, rawEvents: Stream.empty, @@ -95,15 +99,16 @@ function makeTestAdapter(input: { ensureThread: (threadInput) => Effect.gen(function* () { const createdAt = yield* DateTime.now; - const nativeThreadId = `${input.provider}:${threadInput.threadId}`; + const nativeThreadId = `${input.driver}:${threadInput.threadId}`; return { id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`), - provider: input.provider, + driver: input.driver, + providerInstanceId: input.instanceId, providerSessionId: sessionInput.providerSessionId, appThreadId: threadInput.threadId, ownerNodeId: null, nativeThreadRef: { - provider: input.provider, + driver: input.driver, nativeId: nativeThreadId, strength: "strong", }, @@ -124,7 +129,7 @@ function makeTestAdapter(input: { yield* Ref.update(input.capturedTurns, (turns) => [ ...turns, { - provider: input.provider, + driver: input.driver, threadId: turnInput.threadId, providerThreadId: turnInput.providerThread.id, text: turnInput.message.text, @@ -132,23 +137,23 @@ function makeTestAdapter(input: { ]); const eventTime = yield* DateTime.now; const providerTurnId = ProviderTurnId.make( - `provider-turn:${input.provider}:${turnInput.threadId}:${turnInput.runOrdinal}`, + `provider-turn:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}`, ); const response = input.responseByThreadId?.[turnInput.threadId]?.[turnInput.runOrdinal] ?? input.responseByRunOrdinal[turnInput.runOrdinal] ?? - `${input.provider} response for run ${turnInput.runOrdinal}`; + `${input.driver} response for run ${turnInput.runOrdinal}`; const providerEvents: ReadonlyArray = [ { type: "provider_turn.updated", - provider: input.provider, + driver: input.driver, providerTurn: { id: providerTurnId, providerThreadId: turnInput.providerThread.id, nodeId: turnInput.rootNodeId, runAttemptId: turnInput.attemptId, nativeTurnRef: { - provider: input.provider, + driver: input.driver, nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`, strength: "strong", }, @@ -160,10 +165,10 @@ function makeTestAdapter(input: { }, { type: "turn_item.updated", - provider: input.provider, + driver: input.driver, turnItem: { id: TurnItemId.make( - `turn-item:${input.provider}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`, + `turn-item:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`, ), threadId: turnInput.threadId, runId: turnInput.runId, @@ -180,7 +185,7 @@ function makeTestAdapter(input: { updatedAt: eventTime, type: "assistant_message", messageId: MessageId.make( - `message:${input.provider}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`, + `message:${input.driver}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`, ), text: response, streaming: false, @@ -188,7 +193,7 @@ function makeTestAdapter(input: { }, { type: "turn.terminal", - provider: input.provider, + driver: input.driver, providerTurnId, status: "completed", }, @@ -201,11 +206,11 @@ function makeTestAdapter(input: { interruptTurn: () => Effect.void, respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => - unimplemented(input.provider, "readThreadSnapshot unused in provider switch test"), + unimplemented(input.driver, "readThreadSnapshot unused in provider switch test"), rollbackThread: () => - unimplemented(input.provider, "rollbackThread unused in provider switch test"), + unimplemented(input.driver, "rollbackThread unused in provider switch test"), forkThread: () => - unimplemented(input.provider, "forkThread unused in provider switch test"), + unimplemented(input.driver, "forkThread unused in provider switch test"), }; }), }; @@ -238,7 +243,7 @@ describe("orchestration v2 provider switching", () => { const registryLayer = makeProviderAdapterRegistryLayer([ makeTestAdapter({ instanceId: ProviderInstanceId.make("codex"), - provider: "codex", + driver: CODEX_DRIVER, capabilities: CodexProviderCapabilitiesV2, modelSelection: CODEX_MODEL_SELECTION, responseByRunOrdinal: { @@ -249,7 +254,7 @@ describe("orchestration v2 provider switching", () => { }), makeTestAdapter({ instanceId: ProviderInstanceId.make("claudeAgent"), - provider: "claudeAgent", + driver: CLAUDE_DRIVER, capabilities: ClaudeProviderCapabilitiesV2, modelSelection: CLAUDE_MODEL_SELECTION, responseByRunOrdinal: { 2: "claude switched response" }, @@ -340,7 +345,7 @@ describe("orchestration v2 provider switching", () => { const turns = yield* Ref.get(capturedTurns); assert.deepEqual( - projection.runs.map((run) => [run.provider, run.status]), + projection.runs.map((run) => [run.providerInstanceId, run.status]), [ ["codex", "completed"], ["claudeAgent", "completed"], @@ -373,7 +378,7 @@ describe("orchestration v2 provider switching", () => { ); assert.deepEqual( projection.providerThreads.map((providerThread) => [ - providerThread.provider, + providerThread.driver, providerThread.status, providerThread.handoffIds.length, ]), @@ -407,7 +412,7 @@ describe("orchestration v2 provider switching", () => { const registryLayer = makeProviderAdapterRegistryLayer([ makeTestAdapter({ instanceId: ProviderInstanceId.make("codex"), - provider: "codex", + driver: CODEX_DRIVER, capabilities: CodexProviderCapabilitiesV2, modelSelection: CODEX_MODEL_SELECTION, responseByRunOrdinal: { 1: "The release color is violet." }, @@ -415,7 +420,7 @@ describe("orchestration v2 provider switching", () => { }), makeTestAdapter({ instanceId: ProviderInstanceId.make("claudeAgent"), - provider: "claudeAgent", + driver: CLAUDE_DRIVER, capabilities: ClaudeProviderCapabilitiesV2, modelSelection: CLAUDE_MODEL_SELECTION, responseByRunOrdinal: { 1: "I will remember violet." }, @@ -504,11 +509,11 @@ describe("orchestration v2 provider switching", () => { const targetTurn = turns.find((turn) => turn.threadId === targetThreadId); assert.deepEqual( - targetProjection.runs.map((run) => [run.provider, run.status]), + targetProjection.runs.map((run) => [run.providerInstanceId, run.status]), [["codex", "completed"]], ); assert.lengthOf(targetProjection.providerThreads, 1); - assert.equal(targetProjection.providerThreads[0]?.provider, "codex"); + assert.equal(targetProjection.providerThreads[0]?.driver, "codex"); assert.isNull(targetProjection.providerThreads[0]?.forkedFrom); assert.deepEqual( targetProjection.contextTransfers.map((transfer) => [ @@ -547,7 +552,7 @@ describe("orchestration v2 provider switching", () => { const registryLayer = makeProviderAdapterRegistryLayer([ makeTestAdapter({ instanceId: ProviderInstanceId.make("cursor"), - provider: "cursor", + driver: CURSOR_DRIVER, capabilities: CursorProviderCapabilitiesV2, modelSelection: CURSOR_MODEL_SELECTION, responseByRunOrdinal: {}, @@ -640,11 +645,11 @@ describe("orchestration v2 provider switching", () => { const targetTurn = turns.find((turn) => turn.threadId === targetThreadId); assert.deepEqual( - targetProjection.runs.map((run) => [run.provider, run.status]), + targetProjection.runs.map((run) => [run.providerInstanceId, run.status]), [["cursor", "completed"]], ); assert.lengthOf(targetProjection.providerThreads, 1); - assert.equal(targetProjection.providerThreads[0]?.provider, "cursor"); + assert.equal(targetProjection.providerThreads[0]?.driver, "cursor"); assert.isNull(targetProjection.providerThreads[0]?.forkedFrom); assert.deepEqual( targetProjection.contextTransfers.map((transfer) => [ @@ -680,7 +685,7 @@ describe("orchestration v2 provider switching", () => { const registryLayer = makeProviderAdapterRegistryLayer([ makeTestAdapter({ instanceId: ProviderInstanceId.make("codex"), - provider: "codex", + driver: CODEX_DRIVER, capabilities: CodexProviderCapabilitiesV2, modelSelection: CODEX_MODEL_SELECTION, responseByRunOrdinal: {}, @@ -697,7 +702,7 @@ describe("orchestration v2 provider switching", () => { }), makeTestAdapter({ instanceId: ProviderInstanceId.make("claudeAgent"), - provider: "claudeAgent", + driver: CLAUDE_DRIVER, capabilities: ClaudeProviderCapabilitiesV2, modelSelection: CLAUDE_MODEL_SELECTION, responseByRunOrdinal: { 2: "I will remember violet." }, @@ -822,7 +827,7 @@ describe("orchestration v2 provider switching", () => { ); const turns = yield* Ref.get(capturedTurns); const mergedTurn = turns.findLast( - (turn) => turn.threadId === sourceThreadId && turn.provider === "codex", + (turn) => turn.threadId === sourceThreadId && turn.driver === "codex", ); const mergeTransfer = projection.contextTransfers.find( (transfer) => transfer.type === "merge_back", @@ -840,9 +845,120 @@ describe("orchestration v2 provider switching", () => { assert.include(mergedTurn.text, mergePrompt); assert.isDefined(mergeTransfer); assert.equal(mergeTransfer.status, "consumed"); - assert.equal(mergeTransfer.targetProvider, "codex"); + assert.equal(mergeTransfer.targetProviderInstanceId, "codex"); assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context"); }), ), ); + + it.live("routes two custom instances of the same driver independently", () => + Effect.scoped( + Effect.gen(function* () { + const personalThreadId = ThreadId.make("thread:custom-codex-personal"); + const workThreadId = ThreadId.make("thread:custom-codex-work"); + const personalSelection = { + instanceId: ProviderInstanceId.make("codex_personal"), + model: "gpt-5.4", + } satisfies ModelSelection; + const workSelection = { + instanceId: ProviderInstanceId.make("codex_work"), + model: "gpt-5.4", + } satisfies ModelSelection; + const cwd = yield* checkpointWorkspace("custom-codex-instances"); + const capturedTurns = yield* Ref.make>([]); + const registryLayer = makeProviderAdapterRegistryLayer([ + makeTestAdapter({ + instanceId: personalSelection.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: personalSelection, + responseByRunOrdinal: { 1: "personal response" }, + capturedTurns, + }), + makeTestAdapter({ + instanceId: workSelection.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: workSelection, + responseByRunOrdinal: { 1: "work response" }, + capturedTurns, + }), + ]); + + const [personal, work] = yield* Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + for (const [targetThreadId, selection, suffix] of [ + [personalThreadId, personalSelection, "personal"], + [workThreadId, workSelection, "work"], + ] as const) { + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:custom-codex:${suffix}:create`), + threadId: targetThreadId, + projectId, + title: `Custom Codex ${suffix}`, + modelSelection: selection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:custom-codex:${suffix}:message`), + threadId: targetThreadId, + messageId: MessageId.make(`message:custom-codex:${suffix}`), + text: `${suffix} prompt`, + attachments: [], + modelSelection: selection, + dispatchMode: { type: "start_immediately" }, + }); + yield* waitForIdle(targetThreadId); + } + return yield* Effect.all([ + orchestrator.getThreadProjection(personalThreadId), + orchestrator.getThreadProjection(workThreadId), + ]); + }).pipe( + Effect.provide( + makeOrchestratorV2ReplayLayerWithRegistry( + { + name: "custom-codex-instances", + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + registryLayer, + ), + ), + ); + + assert.equal(personal.runs[0]?.providerInstanceId, personalSelection.instanceId); + assert.equal( + personal.providerSessions[0]?.providerInstanceId, + personalSelection.instanceId, + ); + assert.equal(work.runs[0]?.providerInstanceId, workSelection.instanceId); + assert.equal(work.providerSessions[0]?.providerInstanceId, workSelection.instanceId); + assert.notEqual(personal.providerSessions[0]?.id, work.providerSessions[0]?.id); + assert.deepEqual( + (yield* Ref.get(capturedTurns)).map((turn) => [turn.threadId, turn.text]), + [ + [personalThreadId, "personal prompt"], + [workThreadId, "work prompt"], + ], + ); + }), + ), + ); }); diff --git a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts index de2d3c9136..b1e0c91f3d 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts @@ -548,19 +548,15 @@ describe("orchestration V2 thread fork", () => { event.threadId === materialized.targetThreadId && event.type === "provider-session.updated", ); + const targetRunCreatedIndex = result.domainEvents.findIndex( + (event) => event.threadId === materialized.targetThreadId && event.type === "run.created", + ); assert.isAtLeast(transferCreatedIndex, 0); assert.isAbove(targetProviderSessionIndex, transferCreatedIndex); - assert.isEmpty( - result.domainEvents - .slice(0, targetProviderSessionIndex) - .filter((event) => event.threadId === materialized.targetThreadId) - .filter( - (event) => - event.type === "provider-session.updated" || - event.type === "provider-thread.updated" || - event.type === "run.created", - ), - "thread.fork must not eagerly create provider runtime state for the target thread", + assert.isAbove( + targetProviderSessionIndex, + targetRunCreatedIndex, + "provider runtime state must be materialized only after the target run commits", ); const forkEvents = result.domainEvents.filter( diff --git a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts index e05212c3b3..736428f9c3 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts @@ -8,7 +8,7 @@ import { type OrchestrationV2ThreadProjection, ProjectId, ProviderInstanceId, - type ProviderKind, + ProviderDriverKind, type ProviderReplayTranscript, ThreadId, } from "@t3tools/contracts"; @@ -53,30 +53,30 @@ const SECOND_SIBLING_MERGE_USER_TEXT = "Retain the second transferred marker for later. Respond with exactly: second merge delta stored"; interface ProviderVariant { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly modelSelection: ModelSelection; } const PROVIDERS: ReadonlyArray = [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), modelSelection: CODEX_MODEL_SELECTION, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), modelSelection: CLAUDE_MODEL_SELECTION, }, ]; -function transcriptPath(scenario: string, provider: ProviderKind): string { - const fileName = provider === "codex" ? "codex_transcript.ndjson" : "claude_transcript.ndjson"; +function transcriptPath(scenario: string, driver: ProviderDriverKind): string { + const fileName = driver === "codex" ? "codex_transcript.ndjson" : "claude_transcript.ndjson"; return `${import.meta.dirname}/fixtures/${scenario}/${fileName}`; } -function readTranscript(scenario: string, provider: ProviderKind) { +function readTranscript(scenario: string, driver: ProviderDriverKind) { return Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const text = yield* fs.readFileString(transcriptPath(scenario, provider)); + const text = yield* fs.readFileString(transcriptPath(scenario, driver)); return yield* decodeProviderReplayNdjson(text); }); } @@ -200,24 +200,24 @@ function makeCreateCommand(input: { describe("orchestration V2 merge-back provider replay", () => { for (const variant of PROVIDERS) { - it.effect(`merges one fork delta back into the original ${variant.provider} thread`, () => + it.effect(`merges one fork delta back into the original ${variant.driver} thread`, () => Effect.gen(function* () { - const rawTranscript = yield* readTranscript("thread_merge_back_continue", variant.provider); + const rawTranscript = yield* readTranscript("thread_merge_back_continue", variant.driver); const materialized = yield* Effect.gen(function* () { const ids = yield* IdAllocatorV2; const projectId = yield* ids.allocate.project({ - fixtureName: `thread-merge-back-${variant.provider}`, + fixtureName: `thread-merge-back-${variant.driver}`, }); const sourceThreadId = yield* ids.allocate.thread({ - fixtureName: `thread-merge-back-${variant.provider}-source`, + fixtureName: `thread-merge-back-${variant.driver}-source`, projectId, }); - const forkThreadId = ThreadId.make(`thread-merge-back-${variant.provider}-fork`); + const forkThreadId = ThreadId.make(`thread-merge-back-${variant.driver}-fork`); const forkRunId = ids.derive.run({ threadId: forkThreadId, ordinal: 1 }); const commands = [ makeCreateCommand({ commandId: yield* ids.allocate.command({ - fixtureName: `thread-merge-back-${variant.provider}`, + fixtureName: `thread-merge-back-${variant.driver}`, commandName: "create", }), threadId: sourceThreadId, @@ -229,11 +229,11 @@ describe("orchestration V2 merge-back provider replay", () => { createdBy: "user", creationSource: "web", commandId: yield* ids.allocate.command({ - fixtureName: `thread-merge-back-${variant.provider}`, + fixtureName: `thread-merge-back-${variant.driver}`, commandName: "source", }), threadId: sourceThreadId, - messageId: MessageId.make(`message-merge-source-${variant.provider}`), + messageId: MessageId.make(`message-merge-source-${variant.driver}`), text: THREAD_MERGE_BACK_SOURCE_PROMPT, attachments: [], modelSelection: variant.modelSelection, @@ -243,7 +243,7 @@ describe("orchestration V2 merge-back provider replay", () => { type: "thread.fork", createdBy: "user", creationSource: "web", - commandId: CommandId.make(`command-merge-fork-${variant.provider}`), + commandId: CommandId.make(`command-merge-fork-${variant.driver}`), sourceThreadId, targetThreadId: forkThreadId, sourcePoint: { type: "latest_stable" }, @@ -254,11 +254,11 @@ describe("orchestration V2 merge-back provider replay", () => { createdBy: "user", creationSource: "web", commandId: yield* ids.allocate.command({ - fixtureName: `thread-merge-back-${variant.provider}`, + fixtureName: `thread-merge-back-${variant.driver}`, commandName: "fork-delta", }), threadId: forkThreadId, - messageId: MessageId.make(`message-merge-fork-${variant.provider}`), + messageId: MessageId.make(`message-merge-fork-${variant.driver}`), text: THREAD_MERGE_BACK_FORK_PROMPT, attachments: [], modelSelection: variant.modelSelection, @@ -268,7 +268,7 @@ describe("orchestration V2 merge-back provider replay", () => { type: "thread.merge_back", createdBy: "user", creationSource: "web", - commandId: CommandId.make(`command-merge-back-${variant.provider}`), + commandId: CommandId.make(`command-merge-back-${variant.driver}`), sourceThreadId: forkThreadId, targetThreadId: sourceThreadId, sourcePoint: { type: "run", runId: forkRunId }, @@ -278,11 +278,11 @@ describe("orchestration V2 merge-back provider replay", () => { createdBy: "user", creationSource: "web", commandId: yield* ids.allocate.command({ - fixtureName: `thread-merge-back-${variant.provider}`, + fixtureName: `thread-merge-back-${variant.driver}`, commandName: "consume-merge", }), threadId: sourceThreadId, - messageId: MessageId.make(`message-consume-merge-${variant.provider}`), + messageId: MessageId.make(`message-consume-merge-${variant.driver}`), text: MERGE_BACK_USER_TEXT, attachments: [], modelSelection: variant.modelSelection, @@ -293,11 +293,11 @@ describe("orchestration V2 merge-back provider replay", () => { createdBy: "user", creationSource: "web", commandId: yield* ids.allocate.command({ - fixtureName: `thread-merge-back-${variant.provider}`, + fixtureName: `thread-merge-back-${variant.driver}`, commandName: "recall", }), threadId: sourceThreadId, - messageId: MessageId.make(`message-merge-recall-${variant.provider}`), + messageId: MessageId.make(`message-merge-recall-${variant.driver}`), text: THREAD_MERGE_BACK_RECALL_PROMPT, attachments: [], modelSelection: variant.modelSelection, @@ -317,7 +317,7 @@ describe("orchestration V2 merge-back provider replay", () => { [THREAD_MERGE_BACK_HANDOFF_PROMPT, generatedProviderMessage], ]); const cwd = yield* Effect.acquireRelease( - Effect.promise(() => makeCheckpointWorkspace(`merge-back-${variant.provider}`)), + Effect.promise(() => makeCheckpointWorkspace(`merge-back-${variant.driver}`)), (directory) => Effect.service(FileSystem.FileSystem).pipe( Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), @@ -325,7 +325,7 @@ describe("orchestration V2 merge-back provider replay", () => { ), ); const scenario = { - name: `thread_merge_back_continue/${variant.provider}`, + name: `thread_merge_back_continue/${variant.driver}`, commands: materialized.commands, steps: [ { type: "dispatch" as const, command: materialized.commands[0]!, await: true }, @@ -345,7 +345,7 @@ describe("orchestration V2 merge-back provider replay", () => { runtimePolicyOverride: { cwd }, }; const result = - variant.provider === "codex" + variant.driver === "codex" ? yield* runOrchestratorV2ProviderReplayScenario( { ...scenario, @@ -392,12 +392,12 @@ describe("orchestration V2 merge-back provider replay", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect(`merges two sibling fork deltas into the original ${variant.provider} thread`, () => + it.effect(`merges two sibling fork deltas into the original ${variant.driver} thread`, () => Effect.gen(function* () { - const rawTranscript = yield* readTranscript("thread_merge_back_siblings", variant.provider); + const rawTranscript = yield* readTranscript("thread_merge_back_siblings", variant.driver); const materialized = yield* Effect.gen(function* () { const ids = yield* IdAllocatorV2; - const fixtureName = `thread-merge-back-siblings-${variant.provider}`; + const fixtureName = `thread-merge-back-siblings-${variant.driver}`; const projectId = yield* ids.allocate.project({ fixtureName }); const sourceThreadId = yield* ids.allocate.thread({ fixtureName: `${fixtureName}-source`, @@ -559,7 +559,7 @@ describe("orchestration V2 merge-back provider replay", () => { ], ]); const cwd = yield* Effect.acquireRelease( - Effect.promise(() => makeCheckpointWorkspace(`merge-back-siblings-${variant.provider}`)), + Effect.promise(() => makeCheckpointWorkspace(`merge-back-siblings-${variant.driver}`)), (directory) => Effect.service(FileSystem.FileSystem).pipe( Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), @@ -587,7 +587,7 @@ describe("orchestration V2 merge-back provider replay", () => { { type: "await_thread_idle" as const, threadId: materialized.sourceThreadId }, ]; const scenario = { - name: `thread_merge_back_siblings/${variant.provider}`, + name: `thread_merge_back_siblings/${variant.driver}`, commands: materialized.commands, steps, projectionThreadIds: [ @@ -598,7 +598,7 @@ describe("orchestration V2 merge-back provider replay", () => { runtimePolicyOverride: { cwd }, }; const result = - variant.provider === "codex" + variant.driver === "codex" ? yield* runOrchestratorV2ProviderReplayScenario( { ...scenario, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts index 13569cfc3f..ba29043da6 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts @@ -1,3 +1,5 @@ +import { ProviderDriverKind } from "@t3tools/contracts"; + import { assertClaudeMessageSteeringOutput } from "./message_steering/claude_output.ts"; import { assertMessageSteeringOutput } from "./message_steering/codex_output.ts"; import { assertCursorMessageSteeringOutput } from "./message_steering/cursor_output.ts"; @@ -76,14 +78,14 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: planQuestionsInput, providers: [ { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertPlanQuestionsOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./acp_elicitation/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, @@ -96,37 +98,37 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: simpleInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./simple/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, assertOutput: assertSimpleOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./simple/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertSimpleClaudeOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./simple/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertSimpleOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, assertOutput: assertSimpleOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./simple/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, assertOutput: assertSimpleOutput, }, { - provider: "opencode", + driver: ProviderDriverKind.make("opencode"), transcriptFile: new URL("./simple/opencode_transcript.ndjson", import.meta.url), modelSelection: OPENCODE_MODEL_SELECTION, assertOutput: assertSimpleOutput, @@ -138,28 +140,28 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: toolCallReadOnlyInput, providers: [ { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./tool_call_read_only/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertToolCallReadOnlyClaudeOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./tool_call_read_only/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertToolCallReadOnlyCursorOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertToolCallReadOnlyCursorOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./tool_call_read_only/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, @@ -172,7 +174,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: toolCallReadOnlyOnRequestInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL( "./tool_call_read_only_on_request/codex_transcript.ndjson", import.meta.url, @@ -182,7 +184,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ assertOutput: assertToolCallReadOnlyOnRequestOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL( "./tool_call_read_only_on_request/claude_transcript.ndjson", import.meta.url, @@ -192,7 +194,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ assertOutput: assertToolCallReadOnlyOnRequestClaudeOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL( "./tool_call_read_only_on_request/grok_transcript.ndjson", import.meta.url, @@ -202,7 +204,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ assertOutput: assertToolCallReadOnlyOnRequestOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL( "./tool_call_read_only_on_request/grok_transcript.ndjson", import.meta.url, @@ -218,7 +220,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: toolCallWorkspaceNeverInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL( "./tool_call_workspace_never/codex_transcript.ndjson", import.meta.url, @@ -228,7 +230,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ assertOutput: assertToolCallWorkspaceNeverOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL( "./tool_call_workspace_never/claude_transcript.ndjson", import.meta.url, @@ -244,7 +246,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: toolCallRestrictedGranularInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL( "./tool_call_restricted_granular/codex_transcript.ndjson", import.meta.url, @@ -254,7 +256,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ assertOutput: assertToolCallRestrictedGranularOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL( "./tool_call_restricted_granular/claude_transcript.ndjson", import.meta.url, @@ -270,20 +272,20 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: subagentInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./subagent/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY, assertOutput: assertSubagentOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./subagent/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertClaudeSubagentOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./subagent/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, @@ -296,7 +298,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: subagentContinueInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./subagent_continue/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, assertOutput: assertSubagentContinueOutput, @@ -308,7 +310,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: openCodeSubagentInput, providers: [ { - provider: "opencode", + driver: ProviderDriverKind.make("opencode"), transcriptFile: new URL("./opencode_subagent/opencode_transcript.ndjson", import.meta.url), modelSelection: OPENCODE_MODEL_SELECTION, assertOutput: assertOpenCodeSubagentOutput, @@ -320,31 +322,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: multiTurnInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./multi_turn/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, assertOutput: assertMultiTurnOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./multi_turn/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertMultiTurnClaudeOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./multi_turn/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertMultiTurnOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, assertOutput: assertMultiTurnOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./multi_turn/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, assertOutput: assertMultiTurnOutput, @@ -356,7 +358,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: multiTurnInput, providers: [ { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./multi_turn_restart/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertMultiTurnClaudeOutput, @@ -368,31 +370,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: queuedTurnInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./queued_turn/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, assertOutput: assertQueuedTurnOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./queued_turn/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertQueuedTurnOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./queued_turn/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertQueuedTurnOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, assertOutput: assertQueuedTurnOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./queued_turn/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, assertOutput: assertQueuedTurnOutput, @@ -404,27 +406,27 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: todoListInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./todo_list/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertTodoListOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./todo_list/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertTodoListCursorOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, assertOutput: assertTodoListGrokOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./todo_list/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, assertOutput: assertTodoListGrokOutput, @@ -436,13 +438,13 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: webSearchInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./web_search/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, assertOutput: assertWebSearchOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./web_search/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertClaudeWebSearchOutput, @@ -454,21 +456,21 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: planQuestionsInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./plan_questions/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertPlanQuestionsOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./plan_questions/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertPlanQuestionsOutput, }, { - provider: "opencode", + driver: ProviderDriverKind.make("opencode"), transcriptFile: new URL("./plan_questions/opencode_transcript.ndjson", import.meta.url), modelSelection: OPENCODE_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, @@ -481,14 +483,14 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: proposedPlanInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./proposed_plan/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, assertOutput: assertProposedPlanOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./proposed_plan/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, runtimePolicyOverride: READ_ONLY_NEVER_POLICY, @@ -501,31 +503,31 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: messageSteeringInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./message_steering/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, assertOutput: assertMessageSteeringOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./message_steering/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertClaudeMessageSteeringOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL("./message_steering/cursor_transcript.ndjson", import.meta.url), modelSelection: CURSOR_MODEL_SELECTION, assertOutput: assertCursorMessageSteeringOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, assertOutput: assertGrokMessageSteeringOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./message_steering/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, assertOutput: assertGrokMessageSteeringOutput, @@ -537,35 +539,35 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: turnInterruptInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./turn_interrupt/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, runtimePolicyOverride: WORKSPACE_NEVER_POLICY, assertOutput: assertTurnInterruptOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./turn_interrupt/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, runtimePolicyOverride: WORKSPACE_NEVER_POLICY, assertOutput: assertTurnInterruptClaudeOutput, }, { - provider: "grok", + driver: ProviderDriverKind.make("grok"), transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url), modelSelection: GROK_MODEL_SELECTION, runtimePolicyOverride: WORKSPACE_NEVER_POLICY, assertOutput: assertTurnInterruptOutput, }, { - provider: "acpRegistry", + driver: ProviderDriverKind.make("acpRegistry"), transcriptFile: new URL("./turn_interrupt/grok_transcript.ndjson", import.meta.url), modelSelection: ACP_REGISTRY_MODEL_SELECTION, runtimePolicyOverride: WORKSPACE_NEVER_POLICY, assertOutput: assertTurnInterruptOutput, }, { - provider: "opencode", + driver: ProviderDriverKind.make("opencode"), transcriptFile: new URL("./turn_interrupt/opencode_transcript.ndjson", import.meta.url), modelSelection: OPENCODE_MODEL_SELECTION, runtimePolicyOverride: WORKSPACE_NEVER_POLICY, @@ -578,7 +580,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: turnInterruptMidToolInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL( "./turn_interrupt_mid_tool/codex_transcript.ndjson", import.meta.url, @@ -588,7 +590,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ assertOutput: assertTurnInterruptMidToolCodexOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL( "./turn_interrupt_mid_tool/claude_transcript.ndjson", import.meta.url, @@ -598,7 +600,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ assertOutput: assertTurnInterruptMidToolClaudeOutput, }, { - provider: "cursor", + driver: ProviderDriverKind.make("cursor"), transcriptFile: new URL( "./turn_interrupt_mid_tool/cursor_transcript.ndjson", import.meta.url, @@ -614,7 +616,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: turnInterruptRestartInput, providers: [ { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL( "./turn_interrupt_restart/claude_transcript.ndjson", import.meta.url, @@ -630,13 +632,13 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [ buildInput: threadRollbackInput, providers: [ { - provider: "codex", + driver: ProviderDriverKind.make("codex"), transcriptFile: new URL("./thread_rollback/codex_transcript.ndjson", import.meta.url), modelSelection: CODEX_MODEL_SELECTION, assertOutput: assertThreadRollbackOutput, }, { - provider: "claudeAgent", + driver: ProviderDriverKind.make("claudeAgent"), transcriptFile: new URL("./thread_rollback/claude_transcript.ndjson", import.meta.url), modelSelection: CLAUDE_MODEL_SELECTION, assertOutput: assertClaudeThreadRollbackOutput, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts index e50f12bad8..c6ea4f4b86 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode_subagent/output.ts @@ -36,7 +36,7 @@ export function assertOpenCodeSubagentOutput( assert.isDefined(subagent); assert.equal(subagent.origin, "provider_native"); assert.equal(subagent.createdBy, "agent"); - assert.equal(subagent.provider, "opencode"); + assert.equal(subagent.driver, "opencode"); assert.equal(subagent.status, "completed"); assert.equal(subagent.prompt, "Respond exactly CHILD_OK."); assert.include(subagent.result ?? "", "CHILD_OK"); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson index dbe439433b..df39632263 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/proposed_plan/codex_transcript.ndjson @@ -96,7 +96,7 @@ {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"call_A9NEOfTYCCXkUPLqxfWsCNE5","command":"/bin/zsh -lc \"cat package.json && printf '\\\\n--- protocol ---\\\\n' && sed -n '1,220p' src/protocol.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"24242","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"read","command":"cat package.json","name":"package.json","path":"package.json"},{"type":"read","command":"sed -n '1,220p' src/protocol.ts","name":"protocol.ts","path":"src/protocol.ts"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"commandExecution","id":"call_yp787C983Bb0Klnj9F8zRBDd","command":"/bin/zsh -lc \"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts && printf '\\\\n--- sample fixture ---\\\\n' && sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"80213","source":"unifiedExecStartup","status":"inProgress","commandActions":[{"type":"read","command":"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts","name":"codex-app-server-mock-peer.ts","path":"test/fixtures/codex-app-server-mock-peer.ts"},{"type":"read","command":"sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson","name":"simple.ndjson","path":"test/fixtures/codex-app-server-probes/simple.ndjson"}],"aggregatedOutput":null,"exitCode":null,"durationMs":null},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_A9NEOfTYCCXkUPLqxfWsCNE5","command":"/bin/zsh -lc \"cat package.json && printf '\\\\n--- protocol ---\\\\n' && sed -n '1,220p' src/protocol.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"24242","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"cat package.json","name":"package.json","path":"package.json"},{"type":"read","command":"sed -n '1,220p' src/protocol.ts","name":"protocol.ts","path":"src/protocol.ts"}],"aggregatedOutput":"{\n \"name\": \"effect-codex-app-server\",\n \"private\": true,\n \"type\": \"module\",\n \"exports\": {\n \"./client\": {\n \"types\": \"./src/client.ts\",\n \"import\": \"./src/client.ts\"\n },\n \"./schema\": {\n \"types\": \"./src/schema.ts\",\n \"import\": \"./src/schema.ts\"\n },\n \"./rpc\": {\n \"types\": \"./src/rpc.ts\",\n \"import\": \"./src/rpc.ts\"\n },\n \"./protocol\": {\n \"types\": \"./src/protocol.ts\",\n \"import\": \"./src/protocol.ts\"\n },\n \"./replay\": {\n \"types\": \"./src/replay.ts\",\n \"import\": \"./src/replay.ts\"\n },\n \"./errors\": {\n \"types\": \"./src/errors.ts\",\n \"import\": \"./src/errors.ts\"\n }\n },\n \"scripts\": {\n \"dev\": \"tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --watch --clean\",\n \"build\": \"tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --clean\",\n \"prepare\": \"effect-language-service patch\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"generate\": \"bun run scripts/generate.ts\",\n \"probe\": \"bun run test/examples/codex-app-server-probe.ts\"\n },\n \"dependencies\": {\n \"effect\": \"catalog:\"\n },\n \"devDependencies\": {\n \"@effect/language-service\": \"catalog:\",\n \"@effect/openapi-generator\": \"catalog:\",\n \"@effect/platform-node\": \"catalog:\",\n \"@effect/vitest\": \"catalog:\",\n \"tsdown\": \"catalog:\",\n \"typescript\": \"catalog:\",\n \"vitest\": \"catalog:\"\n }\n}\n\n--- protocol ---\nimport * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as CodexError from \"./errors.ts\";\nimport { JsonRpcId, JsonRpcResponseEnvelope } from \"./_internal/shared.ts\";\n\nexport interface CodexAppServerProtocolLogEvent {\n readonly direction: \"incoming\" | \"outgoing\";\n readonly stage: \"raw\" | \"decoded\" | \"decode_failed\";\n readonly payload: unknown;\n}\n\nexport interface CodexAppServerIncomingNotification {\n readonly method: string;\n readonly params?: unknown;\n}\n\nexport interface CodexAppServerIncomingRequest {\n readonly id: string | number;\n readonly method: string;\n readonly params?: unknown;\n}\n\nexport interface CodexAppServerPatchedProtocolOptions {\n readonly stdio: Stdio.Stdio;\n readonly terminationError?: Effect.Effect;\n readonly logIncoming?: boolean;\n readonly logOutgoing?: boolean;\n readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect;\n readonly onNotification?: (\n notification: CodexAppServerIncomingNotification,\n ) => Effect.Effect;\n readonly onRequest?: (\n request: CodexAppServerIncomingRequest,\n ) => Effect.Effect;\n readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect;\n}\n\nexport interface CodexAppServerPatchedProtocol {\n readonly incomingNotifications: Stream.Stream;\n readonly incomingRequests: Stream.Stream;\n readonly request: (\n method: string,\n payload?: unknown,\n ) => Effect.Effect;\n readonly notify: (\n method: string,\n payload?: unknown,\n ) => Effect.Effect;\n readonly respond: (\n requestId: string | number,\n result: unknown,\n ) => Effect.Effect;\n readonly respondError: (\n requestId: string | number,\n error: CodexError.CodexAppServerRequestError,\n ) => Effect.Effect;\n}\n\nfunction isObject(value: unknown): value is Record {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {\n if (!isObject(value) || typeof value.method !== \"string\") {\n return false;\n }\n return Schema.is(JsonRpcId)(value.id);\n}\n\nfunction isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {\n return isObject(value) && typeof value.method === \"string\" && !(\"id\" in value);\n}\n\nfunction isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {\n return Schema.is(JsonRpcResponseEnvelope)(value);\n}\n\nconst encodeWireMessage = (\n message: Record,\n): Effect.Effect =>\n Effect.try({\n try: () => `${JSON.stringify(message)}\\n`,\n catch: (cause) =>\n new CodexError.CodexAppServerProtocolParseError({\n detail: \"Failed to encode Codex App Server message\",\n cause,\n }),\n });\n\nconst normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError =>\n Schema.is(CodexError.CodexAppServerError)(error)\n ? error\n : new CodexError.CodexAppServerTransportError({\n detail,\n cause: error,\n });\n\nconst toProtocolMessage = (\n requestId: string | number,\n fields: {\n readonly result?: unknown;\n readonly error?: CodexError.CodexAppServerProtocolErrorShape;\n },\n): { readonly [key: string]: unknown } => ({\n id: requestId,\n ...(fields.result !== undefined ? { result: fields.result } : {}),\n ...(fields.error !== undefined ? { error: fields.error } : {}),\n});\n\nexport const makeCodexAppServerPatchedProtocol = Effect.fn(\"makeCodexAppServerPatchedProtocol\")(\n function* (\n options: CodexAppServerPatchedProtocolOptions,\n ): Effect.fn.Return {\n const outgoing = yield* Queue.unbounded>();\n const incomingNotifications = yield* Queue.unbounded();\n const incomingRequests = yield* Queue.unbounded();\n const pending = yield* Ref.make(\n new Map>(),\n );\n const nextRequestId = yield* Ref.make(1);\n const remainder = yield* Ref.make(\"\");\n const terminationHandled = yield* Ref.make(false);\n\n const logProtocol = (event: CodexAppServerProtocolLogEvent) => {\n if (event.direction === \"incoming\" && !options.logIncoming) {\n return Effect.void;\n }\n if (event.direction === \"outgoing\" && !options.logOutgoing) {\n return Effect.void;\n }\n return (\n options.logger?.(event) ??\n Effect.logDebug(\"Codex App Server protocol event\").pipe(Effect.annotateLogs({ event }))\n );\n };\n\n const failAllPending = (error: CodexError.CodexAppServerError) =>\n Ref.get(pending).pipe(\n Effect.flatMap((current) =>\n Effect.forEach([...current.values()], (deferred) => Deferred.fail(deferred, error), {\n discard: true,\n }),\n ),\n Effect.andThen(Ref.set(pending, new Map())),\n );\n\n const handleTermination = (classify: () => Effect.Effect) =>\n Ref.modify(terminationHandled, (handled) => {\n if (handled) {\n return [Effect.void, true] as const;\n }\n return [\n Effect.gen(function* () {\n const error = yield* classify();\n yield* failAllPending(error);\n yield* Queue.end(outgoing);\n if (options.onTermination) {\n yield* options.onTermination(error);\n }\n }),\n true,\n ] as const;\n }).pipe(Effect.flatten);\n\n const offerOutgoing = (message: Record) =>\n Effect.gen(function* () {\n yield* logProtocol({\n direction: \"outgoing\",\n stage: \"decoded\",\n payload: message,\n });\n const encoded = yield* encodeWireMessage(message);\n yield* logProtocol({\n direction: \"outgoing\",\n stage: \"raw\",\n payload: encoded,\n });\n yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);\n });\n\n const removePending = (requestId: string) =>\n Ref.update(pending, (current) => {\n if (!current.has(requestId)) {\n return current;\n }\n const next = new Map(current);\n next.delete(requestId);\n return next;\n });\n\n const resolvePending = (\n requestId: string,\n handler: (\n deferred: Deferred.Deferred,\n ) => Effect.Effect,\n ) =>\n Ref.modify(pending, (current) => {\n const deferred = current.get(requestId);\n if (!deferred) {\n return [Effect.void, current] as const;\n }\n const next = new Map(current);\n next.delete(requestId);\n return [handler(deferred), next] as const;\n }).pipe(Effect.flatten);\n\n const respond = (requestId: string | number, result: unknown) =>\n offerOutgoing(toProtocolMessage(requestId, { result }));\n\n const respondError = (\n requestId: string | number,\n error: CodexError.CodexAppServerRequestError,\n","exitCode":0,"durationMs":0},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} -{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_0B2ieGRdMDXmQA8peWORTcTz","command":"/bin/zsh -lc \"sed -n '1,220p' src/replay.ts && printf '\\\\n--- replay.test ---\\\\n' && sed -n '1,240p' src/replay.test.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"16103","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"sed -n '1,220p' src/replay.ts","name":"replay.ts","path":"src/replay.ts"},{"type":"read","command":"sed -n '1,240p' src/replay.test.ts","name":"replay.test.ts","path":"src/replay.test.ts"}],"aggregatedOutput":"import * as Cause from \"effect/Cause\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport { CodexAppServerClient } from \"./client.ts\";\nimport * as CodexClient from \"./client.ts\";\nimport * as CodexError from \"./errors.ts\";\n\nexport const CodexAppServerReplayEntry = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"expect_outbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n }),\n Schema.Struct({\n type: Schema.Literal(\"emit_inbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n afterMs: Schema.optional(Schema.Number),\n }),\n Schema.Struct({\n type: Schema.Literal(\"runtime_exit\"),\n status: Schema.Literals([\"success\", \"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n }),\n]);\nexport type CodexAppServerReplayEntry = typeof CodexAppServerReplayEntry.Type;\n\nexport const CodexAppServerReplayTranscript = Schema.Struct({\n provider: Schema.Literal(\"codex\"),\n protocol: Schema.Literal(\"codex.app-server\"),\n version: Schema.String,\n scenario: Schema.String,\n metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n entries: Schema.Array(CodexAppServerReplayEntry),\n});\nexport type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;\n\nexport class CodexAppServerReplayJsonParseError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayJsonParseError\",\n {\n scenario: Schema.String,\n line: Schema.String,\n cause: Schema.Defect,\n },\n) {\n override get message(): string {\n return `Failed to parse outbound Codex app-server replay frame for scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayExhaustedError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayExhaustedError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Codex app-server replay transcript exhausted before outbound frame ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayUnexpectedOutboundError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayUnexpectedOutboundError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n expectedType: Schema.String,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Unexpected outbound Codex app-server frame at replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayFrameMismatchError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayFrameMismatchError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n label: Schema.optional(Schema.String),\n expected: Schema.Unknown,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Outbound Codex app-server frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayRuntimeExitError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayRuntimeExitError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n status: Schema.Literals([\"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n },\n) {\n override get message(): string {\n return `Codex app-server replay exited with status ${this.status} at cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayIncompleteError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayIncompleteError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n remaining: Schema.Number,\n },\n) {\n override get message(): string {\n return `Codex app-server replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`;\n }\n}\n\nexport const CodexAppServerReplayError = Schema.Union([\n CodexAppServerReplayJsonParseError,\n CodexAppServerReplayExhaustedError,\n CodexAppServerReplayUnexpectedOutboundError,\n CodexAppServerReplayFrameMismatchError,\n CodexAppServerReplayRuntimeExitError,\n CodexAppServerReplayIncompleteError,\n]);\nexport type CodexAppServerReplayError = typeof CodexAppServerReplayError.Type;\n\nexport interface CodexAppServerReplayState {\n readonly cursor: number;\n readonly failure: CodexAppServerReplayError | null;\n}\n\nexport interface CodexAppServerReplayDriver {\n readonly transcript: CodexAppServerReplayTranscript;\n readonly state: Ref.Ref;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const record = value as Record;\n return `{${Object.keys(record)\n .toSorted()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\nfunction normalizeReplayFrame(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(normalizeReplayFrame);\n }\n\n const record = value as Record;\n const normalized = Object.fromEntries(\n Object.entries(record).map(([key, entry]) => [key, normalizeReplayFrame(entry)]),\n );\n\n if (\n normalized.method === \"initialize\" &&\n typeof normalized.params === \"object\" &&\n normalized.params !== null\n ) {\n const params = normalized.params as Record;\n if (typeof params.clientInfo === \"object\" && params.clientInfo !== null) {\n normalized.params = {\n ...params,\n clientInfo: {\n ...(params.clientInfo as Record),\n version: \"\",\n },\n };\n }\n }\n\n return normalized;\n}\n\nfunction sameFrame(left: unknown, right: unknown): boolean {\n return (\n stableStringify(normalizeReplayFrame(left)) === stableStringify(normalizeReplayFrame(right))\n );\n}\n\nfunction encodeInboundFrame(frame: unknown): Uint8Array {\n return encoder.encode(`${JSON.stringify(frame)}\\n`);\n}\n\nfunction replayTransportError(\n transcript: CodexAppServerReplayTranscript,\n error: CodexAppServerReplayError,\n): CodexError.CodexAppServerTransportError {\n return new CodexError.CodexAppServerTransportError({\n detail: error.message,\n cause: error,\n });\n}\n\nexport function layerReplay(\n transcript: CodexAppServerReplayTranscript,\n): Layer.Layer {\n\n--- replay.test ---\nimport * as Exit from \"effect/Exit\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\n\nimport { assert, it } from \"@effect/vitest\";\n\nimport * as CodexClient from \"./client.ts\";\nimport * as CodexError from \"./errors.ts\";\nimport * as CodexReplay from \"./replay.ts\";\n\nconst initializeParams = {\n clientInfo: {\n name: \"effect-codex-app-server-test\",\n title: \"Effect Codex App Server Test\",\n version: \"0.0.0\",\n },\n capabilities: {\n experimentalApi: true,\n optOutNotificationMethods: null,\n },\n} as const;\n\nconst initializeResponse = {\n userAgent: \"replay-codex-app-server\",\n codexHome: \"/tmp/codex-home\",\n platformFamily: \"unix\",\n platformOs: \"macos\",\n} as const;\n\nfunction buildContext(transcript: CodexReplay.CodexAppServerReplayTranscript) {\n return Effect.gen(function* () {\n const scope = yield* Scope.make();\n const context = yield* Layer.buildWithScope(CodexReplay.layerReplay(transcript), scope);\n return { context, scope };\n });\n}\n\nit.effect(\"replays Codex app-server frames through the real client protocol\", () =>\n Effect.gen(function* () {\n const { context, scope } = yield* buildContext({\n provider: \"codex\",\n protocol: \"codex.app-server\",\n version: \"test\",\n scenario: \"initialize\",\n entries: [\n {\n type: \"expect_outbound\",\n label: \"initialize\",\n frame: {\n id: 1,\n method: \"initialize\",\n params: {\n ...initializeParams,\n clientInfo: {\n ...initializeParams.clientInfo,\n version: \"older-fixture-version\",\n },\n },\n },\n },\n {\n type: \"emit_inbound\",\n label: \"initialize\",\n frame: {\n id: 1,\n result: initializeResponse,\n },\n },\n {\n type: \"expect_outbound\",\n label: \"initialized\",\n frame: {\n method: \"initialized\",\n },\n },\n {\n type: \"runtime_exit\",\n status: \"success\",\n },\n ],\n });\n\n yield* Effect.gen(function* () {\n const client = yield* CodexClient.CodexAppServerClient;\n assert.deepEqual(yield* client.request(\"initialize\", initializeParams), initializeResponse);\n yield* client.notify(\"initialized\", undefined);\n }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));\n }),\n);\n\nit.effect(\"fails pending client requests with a schema-serializable replay mismatch\", () =>\n Effect.gen(function* () {\n const { context, scope } = yield* buildContext({\n provider: \"codex\",\n protocol: \"codex.app-server\",\n version: \"test\",\n scenario: \"mismatch\",\n entries: [\n {\n type: \"expect_outbound\",\n label: \"initialize\",\n frame: {\n id: 1,\n method: \"initialize\",\n params: initializeParams,\n },\n },\n {\n type: \"runtime_exit\",\n status: \"success\",\n },\n ],\n });\n\n const error = yield* Effect.gen(function* () {\n const client = yield* CodexClient.CodexAppServerClient;\n return yield* client.request(\"account/read\", {});\n }).pipe(Effect.provide(context), Effect.flip, Effect.ensuring(Scope.close(scope, Exit.void)));\n\n assert.equal(error._tag, \"CodexAppServerTransportError\");\n if (!Schema.is(CodexError.CodexAppServerTransportError)(error)) {\n throw new Error(\"Expected transport error.\");\n }\n\n const replayError = Schema.decodeUnknownSync(CodexReplay.CodexAppServerReplayError)(\n error.cause,\n );\n const encoded = Schema.encodeUnknownSync(CodexReplay.CodexAppServerReplayError)(replayError);\n\n assert.equal(encoded._tag, \"CodexAppServerReplayFrameMismatchError\");\n if (encoded._tag !== \"CodexAppServerReplayFrameMismatchError\") {\n throw new Error(\"Expected frame mismatch error.\");\n }\n assert.equal(encoded.scenario, \"mismatch\");\n assert.equal(encoded.cursor, 0);\n assert.deepEqual(encoded.actual, {\n id: 1,\n method: \"account/read\",\n params: {},\n });\n }),\n);\n","exitCode":0,"durationMs":0},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} +{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_0B2ieGRdMDXmQA8peWORTcTz","command":"/bin/zsh -lc \"sed -n '1,220p' src/replay.ts && printf '\\\\n--- replay.test ---\\\\n' && sed -n '1,240p' src/replay.test.ts\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"16103","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"sed -n '1,220p' src/replay.ts","name":"replay.ts","path":"src/replay.ts"},{"type":"read","command":"sed -n '1,240p' src/replay.test.ts","name":"replay.test.ts","path":"src/replay.test.ts"}],"aggregatedOutput":"import * as Cause from \"effect/Cause\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport { CodexAppServerClient } from \"./client.ts\";\nimport * as CodexClient from \"./client.ts\";\nimport * as CodexError from \"./errors.ts\";\n\nexport const CodexAppServerReplayEntry = Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"expect_outbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n }),\n Schema.Struct({\n type: Schema.Literal(\"emit_inbound\"),\n label: Schema.optional(Schema.String),\n frame: Schema.Unknown,\n afterMs: Schema.optional(Schema.Number),\n }),\n Schema.Struct({\n type: Schema.Literal(\"runtime_exit\"),\n status: Schema.Literals([\"success\", \"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n }),\n]);\nexport type CodexAppServerReplayEntry = typeof CodexAppServerReplayEntry.Type;\n\nexport const CodexAppServerReplayTranscript = Schema.Struct({\n driver: Schema.Literal(\"codex\"),\n protocol: Schema.Literal(\"codex.app-server\"),\n version: Schema.String,\n scenario: Schema.String,\n metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n entries: Schema.Array(CodexAppServerReplayEntry),\n});\nexport type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;\n\nexport class CodexAppServerReplayJsonParseError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayJsonParseError\",\n {\n scenario: Schema.String,\n line: Schema.String,\n cause: Schema.Defect,\n },\n) {\n override get message(): string {\n return `Failed to parse outbound Codex app-server replay frame for scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayExhaustedError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayExhaustedError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Codex app-server replay transcript exhausted before outbound frame ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayUnexpectedOutboundError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayUnexpectedOutboundError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n expectedType: Schema.String,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Unexpected outbound Codex app-server frame at replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayFrameMismatchError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayFrameMismatchError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n label: Schema.optional(Schema.String),\n expected: Schema.Unknown,\n actual: Schema.Unknown,\n },\n) {\n override get message(): string {\n return `Outbound Codex app-server frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayRuntimeExitError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayRuntimeExitError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n status: Schema.Literals([\"error\", \"cancelled\"]),\n error: Schema.optional(Schema.Unknown),\n },\n) {\n override get message(): string {\n return `Codex app-server replay exited with status ${this.status} at cursor ${this.cursor} in scenario ${this.scenario}.`;\n }\n}\n\nexport class CodexAppServerReplayIncompleteError extends Schema.TaggedErrorClass()(\n \"CodexAppServerReplayIncompleteError\",\n {\n scenario: Schema.String,\n cursor: Schema.Number,\n remaining: Schema.Number,\n },\n) {\n override get message(): string {\n return `Codex app-server replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`;\n }\n}\n\nexport const CodexAppServerReplayError = Schema.Union([\n CodexAppServerReplayJsonParseError,\n CodexAppServerReplayExhaustedError,\n CodexAppServerReplayUnexpectedOutboundError,\n CodexAppServerReplayFrameMismatchError,\n CodexAppServerReplayRuntimeExitError,\n CodexAppServerReplayIncompleteError,\n]);\nexport type CodexAppServerReplayError = typeof CodexAppServerReplayError.Type;\n\nexport interface CodexAppServerReplayState {\n readonly cursor: number;\n readonly failure: CodexAppServerReplayError | null;\n}\n\nexport interface CodexAppServerReplayDriver {\n readonly transcript: CodexAppServerReplayTranscript;\n readonly state: Ref.Ref;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n if (typeof value === \"object\" && value !== null) {\n const record = value as Record;\n return `{${Object.keys(record)\n .toSorted()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\nfunction normalizeReplayFrame(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(normalizeReplayFrame);\n }\n\n const record = value as Record;\n const normalized = Object.fromEntries(\n Object.entries(record).map(([key, entry]) => [key, normalizeReplayFrame(entry)]),\n );\n\n if (\n normalized.method === \"initialize\" &&\n typeof normalized.params === \"object\" &&\n normalized.params !== null\n ) {\n const params = normalized.params as Record;\n if (typeof params.clientInfo === \"object\" && params.clientInfo !== null) {\n normalized.params = {\n ...params,\n clientInfo: {\n ...(params.clientInfo as Record),\n version: \"\",\n },\n };\n }\n }\n\n return normalized;\n}\n\nfunction sameFrame(left: unknown, right: unknown): boolean {\n return (\n stableStringify(normalizeReplayFrame(left)) === stableStringify(normalizeReplayFrame(right))\n );\n}\n\nfunction encodeInboundFrame(frame: unknown): Uint8Array {\n return encoder.encode(`${JSON.stringify(frame)}\\n`);\n}\n\nfunction replayTransportError(\n transcript: CodexAppServerReplayTranscript,\n error: CodexAppServerReplayError,\n): CodexError.CodexAppServerTransportError {\n return new CodexError.CodexAppServerTransportError({\n detail: error.message,\n cause: error,\n });\n}\n\nexport function layerReplay(\n transcript: CodexAppServerReplayTranscript,\n): Layer.Layer {\n\n--- replay.test ---\nimport * as Exit from \"effect/Exit\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\n\nimport { assert, it } from \"@effect/vitest\";\n\nimport * as CodexClient from \"./client.ts\";\nimport * as CodexError from \"./errors.ts\";\nimport * as CodexReplay from \"./replay.ts\";\n\nconst initializeParams = {\n clientInfo: {\n name: \"effect-codex-app-server-test\",\n title: \"Effect Codex App Server Test\",\n version: \"0.0.0\",\n },\n capabilities: {\n experimentalApi: true,\n optOutNotificationMethods: null,\n },\n} as const;\n\nconst initializeResponse = {\n userAgent: \"replay-codex-app-server\",\n codexHome: \"/tmp/codex-home\",\n platformFamily: \"unix\",\n platformOs: \"macos\",\n} as const;\n\nfunction buildContext(transcript: CodexReplay.CodexAppServerReplayTranscript) {\n return Effect.gen(function* () {\n const scope = yield* Scope.make();\n const context = yield* Layer.buildWithScope(CodexReplay.layerReplay(transcript), scope);\n return { context, scope };\n });\n}\n\nit.effect(\"replays Codex app-server frames through the real client protocol\", () =>\n Effect.gen(function* () {\n const { context, scope } = yield* buildContext({\n driver: \"codex\",\n protocol: \"codex.app-server\",\n version: \"test\",\n scenario: \"initialize\",\n entries: [\n {\n type: \"expect_outbound\",\n label: \"initialize\",\n frame: {\n id: 1,\n method: \"initialize\",\n params: {\n ...initializeParams,\n clientInfo: {\n ...initializeParams.clientInfo,\n version: \"older-fixture-version\",\n },\n },\n },\n },\n {\n type: \"emit_inbound\",\n label: \"initialize\",\n frame: {\n id: 1,\n result: initializeResponse,\n },\n },\n {\n type: \"expect_outbound\",\n label: \"initialized\",\n frame: {\n method: \"initialized\",\n },\n },\n {\n type: \"runtime_exit\",\n status: \"success\",\n },\n ],\n });\n\n yield* Effect.gen(function* () {\n const client = yield* CodexClient.CodexAppServerClient;\n assert.deepEqual(yield* client.request(\"initialize\", initializeParams), initializeResponse);\n yield* client.notify(\"initialized\", undefined);\n }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));\n }),\n);\n\nit.effect(\"fails pending client requests with a schema-serializable replay mismatch\", () =>\n Effect.gen(function* () {\n const { context, scope } = yield* buildContext({\n driver: \"codex\",\n protocol: \"codex.app-server\",\n version: \"test\",\n scenario: \"mismatch\",\n entries: [\n {\n type: \"expect_outbound\",\n label: \"initialize\",\n frame: {\n id: 1,\n method: \"initialize\",\n params: initializeParams,\n },\n },\n {\n type: \"runtime_exit\",\n status: \"success\",\n },\n ],\n });\n\n const error = yield* Effect.gen(function* () {\n const client = yield* CodexClient.CodexAppServerClient;\n return yield* client.request(\"account/read\", {});\n }).pipe(Effect.provide(context), Effect.flip, Effect.ensuring(Scope.close(scope, Exit.void)));\n\n assert.equal(error._tag, \"CodexAppServerTransportError\");\n if (!Schema.is(CodexError.CodexAppServerTransportError)(error)) {\n throw new Error(\"Expected transport error.\");\n }\n\n const replayError = Schema.decodeUnknownSync(CodexReplay.CodexAppServerReplayError)(\n error.cause,\n );\n const encoded = Schema.encodeUnknownSync(CodexReplay.CodexAppServerReplayError)(replayError);\n\n assert.equal(encoded._tag, \"CodexAppServerReplayFrameMismatchError\");\n if (encoded._tag !== \"CodexAppServerReplayFrameMismatchError\") {\n throw new Error(\"Expected frame mismatch error.\");\n }\n assert.equal(encoded.scenario, \"mismatch\");\n assert.equal(encoded.cursor, 0);\n assert.deepEqual(encoded.actual, {\n id: 1,\n method: \"account/read\",\n params: {},\n });\n }),\n);\n","exitCode":0,"durationMs":0},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"call_yp787C983Bb0Klnj9F8zRBDd","command":"/bin/zsh -lc \"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts && printf '\\\\n--- sample fixture ---\\\\n' && sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson\"","cwd":"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server","processId":"80213","source":"unifiedExecStartup","status":"completed","commandActions":[{"type":"read","command":"sed -n '1,220p' test/fixtures/codex-app-server-mock-peer.ts","name":"codex-app-server-mock-peer.ts","path":"test/fixtures/codex-app-server-mock-peer.ts"},{"type":"read","command":"sed -n '1,80p' test/fixtures/codex-app-server-probes/simple.ndjson","name":"simple.ndjson","path":"test/fixtures/codex-app-server-probes/simple.ndjson"}],"aggregatedOutput":"let nextServerRequestId = 10_000;\nlet pendingSkillsListRequestId: number | string | null = null;\nlet pendingUserInputRequestId: number | null = null;\n\nconst writeMessage = (message: unknown) => {\n process.stdout.write(`${JSON.stringify(message)}\\n`);\n};\n\nconst respond = (id: number | string, result: unknown) => {\n writeMessage({ id, result });\n};\n\nconst respondError = (id: number | string, code: number, message: string) => {\n writeMessage({\n id,\n error: {\n code,\n message,\n },\n });\n};\n\nconst sendRequest = (method: string, params: unknown) => {\n const id = nextServerRequestId++;\n writeMessage({ id, method, params });\n return id;\n};\n\nconst handleMethod = (message: Record) => {\n const method = message.method;\n if (typeof method !== \"string\") {\n return;\n }\n\n switch (method) {\n case \"initialize\": {\n respond(message.id as number | string, {\n userAgent: \"mock-codex-app-server\",\n codexHome: process.cwd(),\n platformFamily: process.platform === \"win32\" ? \"windows\" : \"unix\",\n platformOs: process.platform === \"darwin\" ? \"macos\" : process.platform,\n });\n return;\n }\n case \"initialized\": {\n writeMessage({\n method: \"item/agentMessage/delta\",\n params: {\n delta: \"Mock server is ready.\",\n itemId: \"item-1\",\n threadId: \"thread-1\",\n turnId: \"turn-1\",\n },\n });\n return;\n }\n case \"account/read\": {\n respond(message.id as number | string, {\n account: {\n type: \"chatgpt\",\n email: \"mock@example.com\",\n planType: \"plus\",\n },\n requiresOpenaiAuth: false,\n });\n return;\n }\n case \"skills/list\": {\n pendingSkillsListRequestId = message.id as number | string;\n pendingUserInputRequestId = sendRequest(\"item/tool/requestUserInput\", {\n itemId: \"item-approval-1\",\n threadId: \"thread-1\",\n turnId: \"turn-1\",\n questions: [\n {\n id: \"approved\",\n header: \"Approve\",\n question: \"Continue with the mock skills request?\",\n options: [\n {\n label: \"yes\",\n description: \"Approve the request\",\n },\n ],\n },\n ],\n });\n return;\n }\n default: {\n if (message.id !== undefined) {\n respondError(message.id as number | string, -32601, `Unhandled request: ${method}`);\n }\n }\n }\n};\n\nconst handleResponse = (message: Record) => {\n if (message.id !== pendingUserInputRequestId) {\n return;\n }\n\n pendingUserInputRequestId = null;\n\n respond(pendingSkillsListRequestId!, {\n data: [\n {\n cwd: process.cwd(),\n errors: [],\n skills: [],\n },\n ],\n });\n pendingSkillsListRequestId = null;\n};\n\nlet remainder = \"\";\n\nprocess.stdin.setEncoding(\"utf8\");\nprocess.stdin.on(\"data\", (chunk) => {\n remainder += chunk;\n const lines = remainder.split(\"\\n\");\n remainder = lines.pop() ?? \"\";\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n continue;\n }\n\n const message = JSON.parse(trimmed) as Record;\n if (\"method\" in message) {\n handleMethod(message);\n continue;\n }\n if (\"id\" in message) {\n handleResponse(message);\n }\n }\n});\n\nprocess.stdin.on(\"end\", () => {\n process.exit(0);\n});\n\n--- sample fixture ---\n{\"type\":\"transcript_start\",\"provider\":\"codex\",\"protocol\":\"codex.app-server\",\"version\":\"0.120.0\",\"scenario\":\"simple\",\"metadata\":{\"source\":\"codex-app-server-probe\",\"fileName\":\"simple.ndjson\",\"description\":\"One thread and one turn with a deterministic text-only response.\"}}\n{\"type\":\"expect_outbound\",\"label\":\"initialize\",\"frame\":{\"id\":1,\"method\":\"initialize\",\"params\":{\"capabilities\":{\"experimentalApi\":true,\"optOutNotificationMethods\":null},\"clientInfo\":{\"name\":\"effect-codex-app-server-probe\",\"title\":\"Effect Codex App Server Probe\",\"version\":\"0.0.0\"}}}}\n{\"type\":\"emit_inbound\",\"label\":\"initialize\",\"frame\":{\"id\":1,\"result\":{\"userAgent\":\"effect-codex-app-server-probe/0.120.0 (Mac OS 26.4.1; arm64) dumb (effect-codex-app-server-probe; 0.0.0)\",\"codexHome\":\"/Users/julius/.codex\",\"platformFamily\":\"unix\",\"platformOs\":\"macos\"}}}\n{\"type\":\"expect_outbound\",\"label\":\"initialized\",\"frame\":{\"method\":\"initialized\"}}\n{\"type\":\"expect_outbound\",\"label\":\"thread/start\",\"frame\":{\"id\":2,\"method\":\"thread/start\",\"params\":{}}}\n{\"type\":\"emit_inbound\",\"label\":\"thread/start\",\"frame\":{\"id\":2,\"result\":{\"thread\":{\"id\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"forkedFromId\":null,\"preview\":\"\",\"ephemeral\":false,\"modelProvider\":\"openai\",\"createdAt\":1776725627,\"updatedAt\":1776725627,\"status\":{\"type\":\"idle\"},\"path\":\"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T15-53-47-019dad19-92e1-7460-8c82-034802b2a6cc.jsonl\",\"cwd\":\"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server\",\"cliVersion\":\"0.120.0\",\"source\":\"vscode\",\"agentNickname\":null,\"agentRole\":null,\"gitInfo\":null,\"name\":null,\"turns\":[]},\"model\":\"gpt-5.4\",\"modelProvider\":\"openai\",\"serviceTier\":\"fast\",\"cwd\":\"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server\",\"approvalPolicy\":\"on-request\",\"approvalsReviewer\":\"user\",\"sandbox\":{\"type\":\"workspaceWrite\",\"writableRoots\":[\"/Users/julius/.codex/memories\"],\"readOnlyAccess\":{\"type\":\"fullAccess\"},\"networkAccess\":false,\"excludeTmpdirEnvVar\":false,\"excludeSlashTmp\":false},\"reasoningEffort\":\"xhigh\"}}}\n{\"type\":\"expect_outbound\",\"label\":\"turn/start\",\"frame\":{\"id\":3,\"method\":\"turn/start\",\"params\":{\"input\":[{\"text\":\"Respond with the following text: fixture simple ok\",\"type\":\"text\"}],\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"thread/started\",\"frame\":{\"method\":\"thread/started\",\"params\":{\"thread\":{\"id\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"forkedFromId\":null,\"preview\":\"\",\"ephemeral\":false,\"modelProvider\":\"openai\",\"createdAt\":1776725627,\"updatedAt\":1776725627,\"status\":{\"type\":\"idle\"},\"path\":\"/Users/julius/.codex/sessions/2026/04/20/rollout-2026-04-20T15-53-47-019dad19-92e1-7460-8c82-034802b2a6cc.jsonl\",\"cwd\":\"/Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/packages/effect-codex-app-server\",\"cliVersion\":\"0.120.0\",\"source\":\"vscode\",\"agentNickname\":null,\"agentRole\":null,\"gitInfo\":null,\"name\":null,\"turns\":[]}}}}\n{\"type\":\"emit_inbound\",\"label\":\"deprecationNotice\",\"frame\":{\"method\":\"deprecationNotice\",\"params\":{\"summary\":\"`[features].collab` is deprecated. Use `[features].multi_agent` instead.\",\"details\":\"Enable it with `--enable multi_agent` or `[features].multi_agent` in config.toml. See https://developers.openai.com/codex/config-basic#feature-flags for details.\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"mcpServer/startupStatus/updated\",\"frame\":{\"method\":\"mcpServer/startupStatus/updated\",\"params\":{\"name\":\"codex_apps\",\"status\":\"starting\",\"error\":null}}}\n{\"type\":\"emit_inbound\",\"label\":\"mcpServer/startupStatus/updated\",\"frame\":{\"method\":\"mcpServer/startupStatus/updated\",\"params\":{\"name\":\"uidotsh\",\"status\":\"starting\",\"error\":null}}}\n{\"type\":\"emit_inbound\",\"label\":\"turn/start\",\"frame\":{\"id\":3,\"result\":{\"turn\":{\"id\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\",\"items\":[],\"status\":\"inProgress\",\"error\":null,\"startedAt\":null,\"completedAt\":null,\"durationMs\":null}}}}\n{\"type\":\"emit_inbound\",\"label\":\"thread/status/changed\",\"frame\":{\"method\":\"thread/status/changed\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"status\":{\"type\":\"active\",\"activeFlags\":[]}}}}\n{\"type\":\"emit_inbound\",\"label\":\"turn/started\",\"frame\":{\"method\":\"turn/started\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turn\":{\"id\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\",\"items\":[],\"status\":\"inProgress\",\"error\":null,\"startedAt\":1776725627,\"completedAt\":null,\"durationMs\":null}}}}\n{\"type\":\"emit_inbound\",\"label\":\"mcpServer/startupStatus/updated\",\"frame\":{\"method\":\"mcpServer/startupStatus/updated\",\"params\":{\"name\":\"codex_apps\",\"status\":\"ready\",\"error\":null}}}\n{\"type\":\"emit_inbound\",\"label\":\"mcpServer/startupStatus/updated\",\"frame\":{\"method\":\"mcpServer/startupStatus/updated\",\"params\":{\"name\":\"uidotsh\",\"status\":\"ready\",\"error\":null}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/started\",\"frame\":{\"method\":\"item/started\",\"params\":{\"item\":{\"type\":\"userMessage\",\"id\":\"28c8a871-c12e-4d6a-af88-7a53c03b748e\",\"content\":[{\"type\":\"text\",\"text\":\"Respond with the following text: fixture simple ok\",\"text_elements\":[]}]},\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/completed\",\"frame\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"type\":\"userMessage\",\"id\":\"28c8a871-c12e-4d6a-af88-7a53c03b748e\",\"content\":[{\"type\":\"text\",\"text\":\"Respond with the following text: fixture simple ok\",\"text_elements\":[]}]},\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"account/rateLimits/updated\",\"frame\":{\"method\":\"account/rateLimits/updated\",\"params\":{\"rateLimits\":{\"limitId\":\"codex\",\"limitName\":null,\"primary\":{\"usedPercent\":0,\"windowDurationMins\":300,\"resetsAt\":1776738279},\"secondary\":{\"usedPercent\":34,\"windowDurationMins\":10080,\"resetsAt\":1776893129},\"credits\":null,\"planType\":\"pro\"}}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/started\",\"frame\":{\"method\":\"item/started\",\"params\":{\"item\":{\"type\":\"reasoning\",\"id\":\"rs_0e6f3b2a309a10b40169e6ae80f20c819bbe4ad96641fe124e\",\"summary\":[],\"content\":[]},\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/completed\",\"frame\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"type\":\"reasoning\",\"id\":\"rs_0e6f3b2a309a10b40169e6ae80f20c819bbe4ad96641fe124e\",\"summary\":[],\"content\":[]},\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/started\",\"frame\":{\"method\":\"item/started\",\"params\":{\"item\":{\"type\":\"agentMessage\",\"id\":\"msg_0e6f3b2a309a10b40169e6ae814a88819bb76ddc2495f25a5a\",\"text\":\"\",\"phase\":\"final_answer\",\"memoryCitation\":null},\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/agentMessage/delta\",\"frame\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\",\"itemId\":\"msg_0e6f3b2a309a10b40169e6ae814a88819bb76ddc2495f25a5a\",\"delta\":\"fixture\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/agentMessage/delta\",\"frame\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\",\"itemId\":\"msg_0e6f3b2a309a10b40169e6ae814a88819bb76ddc2495f25a5a\",\"delta\":\" simple\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/agentMessage/delta\",\"frame\":{\"method\":\"item/agentMessage/delta\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\",\"itemId\":\"msg_0e6f3b2a309a10b40169e6ae814a88819bb76ddc2495f25a5a\",\"delta\":\" ok\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"item/completed\",\"frame\":{\"method\":\"item/completed\",\"params\":{\"item\":{\"type\":\"agentMessage\",\"id\":\"msg_0e6f3b2a309a10b40169e6ae814a88819bb76ddc2495f25a5a\",\"text\":\"fixture simple ok\",\"phase\":\"final_answer\",\"memoryCitation\":null},\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\"}}}\n{\"type\":\"emit_inbound\",\"label\":\"thread/tokenUsage/updated\",\"frame\":{\"method\":\"thread/tokenUsage/updated\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turnId\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\",\"tokenUsage\":{\"total\":{\"totalTokens\":28263,\"inputTokens\":28223,\"cachedInputTokens\":28032,\"outputTokens\":40,\"reasoningOutputTokens\":31},\"last\":{\"totalTokens\":28263,\"inputTokens\":28223,\"cachedInputTokens\":28032,\"outputTokens\":40,\"reasoningOutputTokens\":31},\"modelContextWindow\":258400}}}}\n{\"type\":\"emit_inbound\",\"label\":\"account/rateLimits/updated\",\"frame\":{\"method\":\"account/rateLimits/updated\",\"params\":{\"rateLimits\":{\"limitId\":\"codex\",\"limitName\":null,\"primary\":{\"usedPercent\":0,\"windowDurationMins\":300,\"resetsAt\":1776738279},\"secondary\":{\"usedPercent\":34,\"windowDurationMins\":10080,\"resetsAt\":1776893129},\"credits\":null,\"planType\":\"pro\"}}}}\n{\"type\":\"emit_inbound\",\"label\":\"thread/status/changed\",\"frame\":{\"method\":\"thread/status/changed\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"status\":{\"type\":\"idle\"}}}}\n{\"type\":\"emit_inbound\",\"label\":\"turn/completed\",\"frame\":{\"method\":\"turn/completed\",\"params\":{\"threadId\":\"019dad19-92e1-7460-8c82-034802b2a6cc\",\"turn\":{\"id\":\"019dad19-92ef-7e13-b919-c01c6abf3d0c\",\"items\":[],\"status\":\"completed\",\"error\":null,\"startedAt\":1776725627,\"completedAt\":1776725633,\"durationMs\":5852}}}}\n{\"type\":\"runtime_exit\",\"status\":\"success\"}\n","exitCode":0,"durationMs":0},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} {"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"reasoning","id":"rs_0b2955d3a75fd8630169e7fab1e01481999f57bbddc11af4b5","summary":[],"content":[]},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} {"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"reasoning","id":"rs_0b2955d3a75fd8630169e7fab1e01481999f57bbddc11af4b5","summary":[],"content":[]},"threadId":"019db22b-08cd-7e12-b967-cf6ab32dd408","turnId":"019db22b-08d6-7bb3-9b7d-2ae5b8661a04"}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts index ae96b122ad..5379158a4c 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts @@ -12,8 +12,9 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, type OrchestrationV2UserMessageInputIntent, - type ProviderKind, + ProviderInstanceId, type ProviderInteractionMode, + type ProviderDriverKind, type ProviderReplayTranscript, type ProviderUserInputAnswers, } from "@t3tools/contracts"; @@ -196,7 +197,7 @@ export interface OrchestratorFixtureInput { } export interface ProviderOrchestratorReplayVariant { - readonly provider: ProviderKind; + readonly driver: ProviderDriverKind; readonly transcriptFile: URL; readonly modelSelection: ModelSelection; readonly runtimePolicyOverride?: RuntimePolicyV2Override; @@ -355,6 +356,7 @@ export function dispatchMessageCommand(input: { export function materializeFixtureInput(input: { readonly scenario: string; readonly fixtureInput: OrchestratorFixtureInput; + readonly driver: ProviderDriverKind; readonly modelSelection: ModelSelection; }): Effect.Effect { return Effect.gen(function* () { @@ -483,7 +485,7 @@ export function materializeFixtureInput(input: { }), threadId: ids.threadId, requestId: yield* idAllocator.allocate.runtimeRequest({ - provider: input.modelSelection.provider, + driver: input.driver, nativeRequestId: `fixture-placeholder-${messageIndex}`, }), answers: step.answers, @@ -509,7 +511,7 @@ export function materializeFixtureInput(input: { }), threadId: ids.threadId, requestId: yield* idAllocator.allocate.runtimeRequest({ - provider: input.modelSelection.provider, + driver: input.driver, nativeRequestId: `fixture-placeholder-${messageIndex}`, }), decision: step.decision ?? "accept", @@ -679,7 +681,10 @@ export function assertBaseProjection(input: { }) { const projection = projectionFor(input.result, input.transcript.scenario); - assert.equal(projection.thread.defaultProvider, input.transcript.provider); + assert.equal( + projection.thread.providerInstanceId, + ProviderInstanceId.make(input.transcript.provider), + ); assert.lengthOf(projection.runs, input.runCount); assert.isAtLeast(projection.providerThreads.length, 1); assert.isAtLeast( diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_output.ts index 54d42092fc..d2db4ac5c9 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/claude_output.ts @@ -69,7 +69,7 @@ export function assertClaudeSubagentOutput( for (const subagent of projection.subagents) { assert.equal(subagent.origin, "provider_native"); assert.equal(subagent.createdBy, "agent"); - assert.equal(subagent.provider, "claudeAgent"); + assert.equal(subagent.driver, "claudeAgent"); assert.equal(subagent.status, "completed"); assert.isNull(subagent.providerThreadId); assert.isNotNull(subagent.childThreadId); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_output.ts index 6c2cbfc47e..143b9bd900 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/codex_output.ts @@ -63,7 +63,7 @@ export function assertSubagentOutput( for (const subagent of projection.subagents) { assert.equal(subagent.origin, "provider_native"); assert.equal(subagent.createdBy, "agent"); - assert.equal(subagent.provider, "codex"); + assert.equal(subagent.driver, "codex"); assert.isNotNull(subagent.childThreadId); assert.isNotNull(subagent.providerThreadId); assert.isNotNull(subagent.nativeTaskRef); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts index d882367591..d152df55e8 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts @@ -63,7 +63,7 @@ export function assertCursorSubagentOutput( for (const subagent of projection.subagents) { assert.equal(subagent.origin, "provider_native"); assert.equal(subagent.createdBy, "agent"); - assert.equal(subagent.provider, "cursor"); + assert.equal(subagent.driver, "cursor"); assert.isNull(subagent.providerThreadId); assert.isNotNull(subagent.childThreadId); assert.isNotNull(subagent.nativeTaskRef); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index aea8a626cc..1a2724e009 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -47,6 +47,7 @@ import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts"; import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts"; import Migration0033 from "./Migrations/033_OrchestrationV2.ts"; import Migration0034 from "./Migrations/034_OrchestrationV2Subagents.ts"; +import Migration0035 from "./Migrations/035_OrchestrationV2Foundation.ts"; /** * Migration loader with all migrations defined inline. @@ -93,6 +94,7 @@ export const migrationEntries = [ [32, "AuthPairingProofKeyThumbprint", Migration0032], [33, "OrchestrationV2", Migration0033], [34, "OrchestrationV2Subagents", Migration0034], + [35, "OrchestrationV2Foundation", Migration0035], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/035_OrchestrationV2Foundation.ts b/apps/server/src/persistence/Migrations/035_OrchestrationV2Foundation.ts new file mode 100644 index 0000000000..8c333707af --- /dev/null +++ b/apps/server/src/persistence/Migrations/035_OrchestrationV2Foundation.ts @@ -0,0 +1,172 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +/** + * Production-facing V2 persistence additions. + * + * The original V2 schema used a single `provider` column for both configured + * instance routing and driver identity. Keep those columns in place for + * migration compatibility. They remain write-through shadows where the old + * schema declared them NOT NULL; all V2 reads and indexes use the explicit + * columns added here. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN driver TEXT`; + yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_events + SET + driver = provider, + provider_instance_id = COALESCE( + json_extract(payload_json, '$.providerInstanceId'), + provider + ) + `; + yield* sql`CREATE INDEX orchestration_v2_events_instance_sequence_idx ON orchestration_v2_events(provider_instance_id, sequence)`; + + yield* sql`ALTER TABLE orchestration_v2_projection_threads ADD COLUMN provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_projection_threads + SET provider_instance_id = COALESCE( + json_extract(payload_json, '$.providerInstanceId'), + default_provider + ) + `; + + yield* sql`ALTER TABLE orchestration_v2_projection_runs ADD COLUMN provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_projection_runs + SET provider_instance_id = COALESCE( + json_extract(payload_json, '$.providerInstanceId'), + provider + ) + `; + + yield* sql`ALTER TABLE orchestration_v2_projection_run_attempts ADD COLUMN provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_projection_run_attempts + SET provider_instance_id = COALESCE( + json_extract(payload_json, '$.providerInstanceId'), + provider + ) + `; + + yield* sql`ALTER TABLE orchestration_v2_projection_provider_sessions ADD COLUMN driver TEXT`; + yield* sql`ALTER TABLE orchestration_v2_projection_provider_sessions ADD COLUMN provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_projection_provider_sessions + SET + driver = COALESCE(json_extract(payload_json, '$.driver'), provider), + provider_instance_id = COALESCE( + json_extract(payload_json, '$.providerInstanceId'), + provider + ) + `; + yield* sql`CREATE INDEX orchestration_v2_projection_provider_sessions_instance_status_idx ON orchestration_v2_projection_provider_sessions(provider_instance_id, status)`; + + yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN driver TEXT`; + yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_projection_provider_threads + SET + driver = COALESCE(json_extract(payload_json, '$.driver'), provider), + provider_instance_id = COALESCE( + json_extract(payload_json, '$.providerInstanceId'), + provider + ) + `; + yield* sql`CREATE INDEX orchestration_v2_projection_provider_threads_instance_status_idx ON orchestration_v2_projection_provider_threads(provider_instance_id, status)`; + + yield* sql`ALTER TABLE orchestration_v2_projection_subagents ADD COLUMN driver TEXT`; + yield* sql`ALTER TABLE orchestration_v2_projection_subagents ADD COLUMN provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_projection_subagents + SET + driver = json_extract(payload_json, '$.driver'), + provider_instance_id = COALESCE( + json_extract(payload_json, '$.providerInstanceId'), + provider + ) + `; + + yield* sql`ALTER TABLE orchestration_v2_projection_context_transfers ADD COLUMN source_provider_instance_id TEXT`; + yield* sql`ALTER TABLE orchestration_v2_projection_context_transfers ADD COLUMN target_provider_instance_id TEXT`; + yield* sql` + UPDATE orchestration_v2_projection_context_transfers + SET + source_provider_instance_id = COALESCE( + json_extract(payload_json, '$.sourceProviderInstanceId'), + source_provider + ), + target_provider_instance_id = COALESCE( + json_extract(payload_json, '$.targetProviderInstanceId'), + target_provider + ) + `; + + yield* sql` + CREATE TABLE orchestration_v2_effect_outbox ( + effect_id TEXT PRIMARY KEY, + command_id TEXT NOT NULL, + thread_id TEXT NOT NULL, + effect_type TEXT NOT NULL, + payload_json TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'succeeded', 'failed')), + attempt_count INTEGER NOT NULL DEFAULT 0, + available_at TEXT NOT NULL, + lease_owner TEXT, + lease_expires_at TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + completed_at TEXT, + last_error TEXT + ) + `; + yield* sql`CREATE INDEX orchestration_v2_effect_outbox_claim_idx ON orchestration_v2_effect_outbox(status, available_at, lease_expires_at, created_at)`; + yield* sql`CREATE INDEX orchestration_v2_effect_outbox_command_idx ON orchestration_v2_effect_outbox(command_id, effect_id)`; + + yield* sql` + CREATE TABLE orchestration_v2_turn_item_positions ( + thread_id TEXT NOT NULL, + turn_item_id TEXT NOT NULL, + ordinal INTEGER NOT NULL, + PRIMARY KEY (thread_id, turn_item_id), + UNIQUE (thread_id, ordinal) + ) + `; + yield* sql` + INSERT OR IGNORE INTO orchestration_v2_turn_item_positions ( + thread_id, + turn_item_id, + ordinal + ) + SELECT thread_id, turn_item_id, ordinal + FROM orchestration_v2_projection_turn_items + ORDER BY thread_id, ordinal, turn_item_id + `; + + yield* sql` + CREATE TABLE orchestration_v2_projection_metadata ( + projection_name TEXT PRIMARY KEY, + schema_version INTEGER NOT NULL, + last_sequence INTEGER NOT NULL, + updated_at TEXT NOT NULL + ) + `; + yield* sql` + INSERT INTO orchestration_v2_projection_metadata ( + projection_name, + schema_version, + last_sequence, + updated_at + ) + VALUES ( + 'thread-projections', + 1, + COALESCE((SELECT MAX(sequence) FROM orchestration_v2_events), 0), + strftime('%Y-%m-%dT%H:%M:%fZ', 'now') + ) + `; +}); diff --git a/apps/server/src/provider/Drivers/AcpRegistryDriver.ts b/apps/server/src/provider/Drivers/AcpRegistryDriver.ts new file mode 100644 index 0000000000..682c85dde9 --- /dev/null +++ b/apps/server/src/provider/Drivers/AcpRegistryDriver.ts @@ -0,0 +1,171 @@ +import { + AcpRegistrySettings, + ProviderDriverKind, + TextGenerationError, + type ServerProvider, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { + AcpRegistryAdapterV2Driver, + type AcpRegistryAdapterV2DriverEnv, +} from "../../orchestration-v2/Adapters/AcpRegistryAdapterV2.ts"; +import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts"; +import { ProviderAdapterRequestError, ProviderDriverError } from "../Errors.ts"; +import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts"; +import { + defaultProviderContinuationIdentity, + type ProviderDriver, + type ProviderInstance, +} from "../ProviderDriver.ts"; + +const DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); +const decodeSettings = Schema.decodeSync(AcpRegistrySettings); + +const unsupportedLegacyCall = (operation: string) => + Effect.fail( + new ProviderAdapterRequestError({ + provider: DRIVER_KIND, + method: operation, + detail: "ACP Registry instances are available through orchestration V2 only.", + }), + ); + +const makeLegacyAdapter = (): ProviderInstance["adapter"] => ({ + provider: DRIVER_KIND, + capabilities: { sessionModelSwitch: "unsupported" }, + startSession: () => unsupportedLegacyCall("startSession"), + sendTurn: () => unsupportedLegacyCall("sendTurn"), + interruptTurn: () => unsupportedLegacyCall("interruptTurn"), + respondToRequest: () => unsupportedLegacyCall("respondToRequest"), + respondToUserInput: () => unsupportedLegacyCall("respondToUserInput"), + stopSession: () => Effect.void, + listSessions: () => Effect.succeed([]), + hasSession: () => Effect.succeed(false), + readThread: () => unsupportedLegacyCall("readThread"), + rollbackThread: () => unsupportedLegacyCall("rollbackThread"), + stopAll: () => Effect.void, + streamEvents: Stream.empty, +}); + +const makeUnsupportedTextGeneration = (): TextGenerationShape => { + const unsupported = (operation: string) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "ACP Registry instances do not provide application text generation.", + }), + ); + return { + generateCommitMessage: () => unsupported("generateCommitMessage"), + generatePrContent: () => unsupported("generatePrContent"), + generateBranchName: () => unsupported("generateBranchName"), + generateThreadTitle: () => unsupported("generateThreadTitle"), + }; +}; + +const makeSnapshot = (input: { + readonly instanceId: ProviderInstance["instanceId"]; + readonly displayName: string | undefined; + readonly accentColor: string | undefined; + readonly enabled: boolean; + readonly settings: AcpRegistrySettings; + readonly continuationKey: string; + readonly checkedAt: string; +}): ServerProvider => { + const modelIds = Array.from(new Set(["default", ...input.settings.customModels])); + return { + instanceId: input.instanceId, + driver: DRIVER_KIND, + ...(input.displayName ? { displayName: input.displayName } : {}), + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + continuation: { groupKey: input.continuationKey }, + enabled: input.enabled, + installed: true, + version: null, + status: input.enabled ? "ready" : "disabled", + auth: { status: "unknown" }, + checkedAt: input.checkedAt, + models: modelIds.map((model) => ({ + slug: model, + name: model, + isCustom: model !== "default", + capabilities: null, + })), + slashCommands: [], + skills: [], + }; +}; + +export type AcpRegistryDriverEnv = AcpRegistryAdapterV2DriverEnv; + +/** Canonical provider-instance wrapper for ACP Registry orchestration adapters. */ +export const AcpRegistryDriver: ProviderDriver = { + driverKind: DRIVER_KIND, + metadata: { + displayName: "ACP Registry", + supportsMultipleInstances: true, + }, + configSchema: AcpRegistrySettings, + defaultConfig: () => decodeSettings({}), + create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + Effect.gen(function* () { + const continuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER_KIND, + instanceId, + }); + const checkedAt = DateTime.formatIso(yield* DateTime.now); + const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build ACP Registry orchestration adapter.", + cause, + }), + ), + ); + const currentSnapshot = () => + makeSnapshot({ + instanceId, + displayName, + accentColor, + enabled, + settings: config, + continuationKey: continuationIdentity.continuationKey, + checkedAt, + }); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity, + displayName, + accentColor, + enabled, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: DRIVER_KIND, + packageName: null, + }), + getSnapshot: Effect.sync(currentSnapshot), + refresh: Effect.sync(currentSnapshot), + streamChanges: Stream.empty, + }, + adapter: makeLegacyAdapter(), + orchestrationAdapter, + textGeneration: makeUnsupportedTextGeneration(), + } satisfies ProviderInstance; + }), +}; diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index e099d52e51..daec0a4018 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -26,7 +26,10 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts"; import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { + ClaudeAdapterV2Driver, + type ClaudeAdapterV2DriverEnv, +} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts"; import { @@ -82,7 +85,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({ }); export type ClaudeDriverEnv = - | BackgroundPolicy.BackgroundPolicy + | ClaudeAdapterV2DriverEnv | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem @@ -149,6 +152,24 @@ export const ClaudeDriver: ProviderDriver = { ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), }; const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions); + const orchestrationAdapter = yield* ClaudeAdapterV2Driver.create({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build Claude orchestration adapter.", + cause, + }), + ), + ); const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv); // Per-instance capabilities cache: keyed on binary + resolved HOME so @@ -215,6 +236,7 @@ export const ClaudeDriver: ProviderDriver = { enabled, snapshot, adapter, + orchestrationAdapter, textGeneration, } satisfies ProviderInstance; }), diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 15d7a1ff02..66f6d9670b 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -33,7 +33,10 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts"; import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { + CodexAdapterV2Driver, + type CodexAdapterV2DriverEnv, +} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; import { makeCodexAdapter } from "../Layers/CodexAdapter.ts"; import { checkCodexProviderStatus, makePendingCodexProvider } from "../Layers/CodexProvider.ts"; @@ -73,7 +76,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({ * registered driver and the runtime satisfies them once. */ export type CodexDriverEnv = - | BackgroundPolicy.BackgroundPolicy + | CodexAdapterV2DriverEnv | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem @@ -160,6 +163,24 @@ export const CodexDriver: ProviderDriver = { environment: processEnv, ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), }); + const orchestrationAdapter = yield* CodexAdapterV2Driver.create({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build Codex orchestration adapter.", + cause, + }), + ), + ); const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv); // Build a managed snapshot whose settings never change — mutations come @@ -207,6 +228,7 @@ export const CodexDriver: ProviderDriver = { enabled, snapshot, adapter, + orchestrationAdapter, textGeneration, } satisfies ProviderInstance; }), diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts index 964819844e..802b280843 100644 --- a/apps/server/src/provider/Drivers/CursorDriver.ts +++ b/apps/server/src/provider/Drivers/CursorDriver.ts @@ -24,6 +24,10 @@ import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts"; +import { + CursorAdapterV2Driver, + type CursorAdapterV2DriverEnv, +} from "../../orchestration-v2/Adapters/CursorAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; import { makeCursorAdapter } from "../Layers/CursorAdapter.ts"; import { @@ -66,7 +70,7 @@ const UPDATE: ProviderMaintenanceCapabilitiesResolver = { }; export type CursorDriverEnv = - | BackgroundPolicy.BackgroundPolicy + | CursorAdapterV2DriverEnv | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem @@ -131,6 +135,24 @@ export const CursorDriver: ProviderDriver = { ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), instanceId, }); + const orchestrationAdapter = yield* CursorAdapterV2Driver.create({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build Cursor orchestration adapter.", + cause, + }), + ), + ); const textGeneration = yield* makeCursorTextGeneration(effectiveConfig, processEnv); const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe( @@ -183,6 +205,7 @@ export const CursorDriver: ProviderDriver = { enabled, snapshot, adapter, + orchestrationAdapter, textGeneration, } satisfies ProviderInstance; }), diff --git a/apps/server/src/provider/Drivers/GrokDriver.ts b/apps/server/src/provider/Drivers/GrokDriver.ts index 112f110131..149ea429d6 100644 --- a/apps/server/src/provider/Drivers/GrokDriver.ts +++ b/apps/server/src/provider/Drivers/GrokDriver.ts @@ -11,6 +11,10 @@ import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts"; +import { + GrokAdapterV2Driver, + type GrokAdapterV2DriverEnv, +} from "../../orchestration-v2/Adapters/GrokAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; import { makeGrokAdapter } from "../Layers/GrokAdapter.ts"; import { @@ -48,7 +52,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver( ); export type GrokDriverEnv = - | BackgroundPolicy.BackgroundPolicy + | GrokAdapterV2DriverEnv | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem @@ -111,6 +115,24 @@ export const GrokDriver: ProviderDriver = { ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), instanceId, }); + const orchestrationAdapter = yield* GrokAdapterV2Driver.create({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build Grok orchestration adapter.", + cause, + }), + ), + ); const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv); const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe( @@ -157,6 +179,7 @@ export const GrokDriver: ProviderDriver = { enabled, snapshot, adapter, + orchestrationAdapter, textGeneration, } satisfies ProviderInstance; }), diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts index a01e414f81..3a6ba24178 100644 --- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts +++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts @@ -24,7 +24,10 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts"; import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; +import { + OpenCodeAdapterV2Driver, + type OpenCodeAdapterV2DriverEnv, +} from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts"; import { ProviderDriverError } from "../Errors.ts"; import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts"; import { @@ -77,7 +80,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({ }); export type OpenCodeDriverEnv = - | BackgroundPolicy.BackgroundPolicy + | OpenCodeAdapterV2DriverEnv | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem @@ -141,6 +144,24 @@ export const OpenCodeDriver: ProviderDriver environment: processEnv, ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), }); + const orchestrationAdapter = yield* OpenCodeAdapterV2Driver.create({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build OpenCode orchestration adapter.", + cause, + }), + ), + ); const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv); const checkProvider = checkOpenCodeProviderStatus( @@ -188,6 +209,7 @@ export const OpenCodeDriver: ProviderDriver enabled, snapshot, adapter, + orchestrationAdapter, textGeneration, } satisfies ProviderInstance; }), diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts index 26f28c1dd7..e36ed52d4a 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts @@ -96,19 +96,60 @@ const fakeCursorAdapter: CursorAdapterShape = { streamEvents: Stream.empty, }; -const layer = it.layer( - Layer.mergeAll( - Layer.provide( - ProviderAdapterRegistryLive, - Layer.mergeAll( - Layer.succeed(CodexAdapter, fakeCodexAdapter), - Layer.succeed(ClaudeAdapter, fakeClaudeAdapter), - Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter), - Layer.succeed(CursorAdapter, fakeCursorAdapter), - ), - ), - NodeServices.layer, - ), +// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry — +// it walks `listInstances` once at boot and surfaces the default-instance +// adapter keyed by its driver kind. To test the facade we supply four fake +// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so +// they pass the default-instance filter. +const makeFakeInstance = ( + driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode", + adapter: ProviderInstance["adapter"], +): ProviderInstance => { + const driverKind = ProviderDriverKind.make(driverKindString); + return { + instanceId: defaultInstanceIdForDriver(driverKind), + driverKind, + continuationIdentity: { + driverKind, + continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`, + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: driverKind, + packageName: null, + }), + getSnapshot: Effect.succeed({} as unknown as ServerProvider), + refresh: Effect.succeed({} as unknown as ServerProvider), + streamChanges: Stream.empty, + }, + adapter, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as unknown as TextGenerationShape, + }; +}; + +const fakeInstances: ReadonlyArray = [ + makeFakeInstance("codex", fakeCodexAdapter), + makeFakeInstance("claudeAgent", fakeClaudeAdapter), + makeFakeInstance("opencode", fakeOpenCodeAdapter), + makeFakeInstance("cursor", fakeCursorAdapter), +]; + +const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)), + listInstances: Effect.succeed(fakeInstances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + // Tests never drive changes through this fake; acquire a throwaway + // subscription on an unused PubSub so the shape is satisfied. + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => PubSub.subscribe(pubsub)), +}); + +const layer = Layer.mergeAll( + Layer.provide(ProviderAdapterRegistryLive, fakeInstanceRegistryLayer), NodeServices.layer, ); diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts index 0fd88b4262..0b28cd1bbe 100644 --- a/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryHydration.ts @@ -56,6 +56,14 @@ import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "../builtInDrivers.ts"; import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts"; import { ProviderInstanceRegistryMutator } from "../Services/ProviderInstanceRegistryMutator.ts"; import { ProviderInstanceRegistryMutableLayer } from "./ProviderInstanceRegistryLive.ts"; +import { + type ProviderOrchestrationAdapterInfrastructure, + ProviderOrchestrationAdapterInfrastructureLive, +} from "./ProviderOrchestrationAdapterInfrastructure.ts"; + +type ProviderInstanceRegistryHydrationEnv = + | Exclude + | ServerSettingsService; /** * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot. @@ -152,7 +160,7 @@ const SettingsWatcherLive = Layer.effectDiscard( export const ProviderInstanceRegistryHydrationLive: Layer.Layer< ProviderInstanceRegistry, never, - BuiltInDriversEnv | ServerSettingsService + ProviderInstanceRegistryHydrationEnv > = Layer.unwrap( Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; @@ -167,8 +175,8 @@ export const ProviderInstanceRegistryHydrationLive: Layer.Layer< const mutableLayer = ProviderInstanceRegistryMutableLayer({ drivers: BUILT_IN_DRIVERS, configMap: initialConfigMap, - }); + }).pipe(Layer.provide(ProviderOrchestrationAdapterInfrastructureLive)); return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer)); }), -) as Layer.Layer; +) as Layer.Layer; diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts index dcc3ac0b5d..f0b8fd46dc 100644 --- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts @@ -43,14 +43,16 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http"; import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import type { BuiltInDriversEnv } from "../builtInDrivers.ts"; import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts"; -import { CodexDriver } from "../Drivers/CodexDriver.ts"; +import { CodexDriver, type CodexDriverEnv } from "../Drivers/CodexDriver.ts"; import { CursorDriver } from "../Drivers/CursorDriver.ts"; import { GrokDriver } from "../Drivers/GrokDriver.ts"; import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts"; import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts"; import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts"; import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts"; +import { ProviderOrchestrationAdapterInfrastructureLive } from "./ProviderOrchestrationAdapterInfrastructure.ts"; const TestHttpClientLive = Layer.succeed( HttpClient.HttpClient, @@ -139,15 +141,19 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => { // `NodeServices.layer` through `Layer.provideMerge` to satisfy that // dependency while still surfacing NodeServices to the test body (the // codex driver's `create` yields `ChildProcessSpawner` directly). - const testLayer = ServerConfig.layerTest(process.cwd(), { + const baseLayer = ServerConfig.layerTest(process.cwd(), { prefix: "provider-instance-registry-test", }).pipe( Layer.provideMerge(NodeServices.layer), Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(TestHttpClientLive), + Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); + const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe( + Layer.provideMerge(baseLayer), + ); it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () => Effect.gen(function* () { @@ -178,7 +184,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => { }, }; - const { registry } = yield* makeProviderInstanceRegistry({ + const { registry } = yield* makeProviderInstanceRegistry({ drivers: [CodexDriver], configMap, }); @@ -244,7 +250,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => { }, }; - const { registry } = yield* makeProviderInstanceRegistry({ + const { registry } = yield* makeProviderInstanceRegistry({ drivers: [CodexDriver], configMap, }); @@ -278,15 +284,19 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => { // surfaced; that merged layer then provides `ServerConfig.layerTest`'s // `FileSystem` dep while keeping everything else surfaced to the test. const infraLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer)); - const testLayer = ServerConfig.layerTest(process.cwd(), { + const baseLayer = ServerConfig.layerTest(process.cwd(), { prefix: "provider-instance-registry-all-drivers-test", }).pipe( Layer.provideMerge(infraLayer), Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(TestHttpClientLive), + Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), ); + const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe( + Layer.provideMerge(baseLayer), + ); it.live("boots one instance of every shipped driver from a single config map", () => Effect.gen(function* () { @@ -338,7 +348,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => { }, }; - const { registry } = yield* makeProviderInstanceRegistry({ + const { registry } = yield* makeProviderInstanceRegistry({ drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver], configMap, }); diff --git a/apps/server/src/provider/Layers/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/Layers/ProviderOrchestrationAdapterInfrastructure.ts new file mode 100644 index 0000000000..bf34ea3065 --- /dev/null +++ b/apps/server/src/provider/Layers/ProviderOrchestrationAdapterInfrastructure.ts @@ -0,0 +1,29 @@ +import * as Layer from "effect/Layer"; + +import { + ClaudeAgentSdkQueryRunner, + claudeAgentSdkQueryRunnerLiveLayer, +} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import { + CodexAppServerClientFactory, + codexAppServerClientFactoryFromSettingsLayer, +} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import { + CursorAgentSdkRunner, + cursorAgentSdkRunnerLiveLayer, +} from "../../orchestration-v2/Adapters/CursorAgentSdk.ts"; +import { IdAllocatorV2, layer as idAllocatorLayer } from "../../orchestration-v2/IdAllocator.ts"; + +export type ProviderOrchestrationAdapterInfrastructure = + | ClaudeAgentSdkQueryRunner + | CodexAppServerClientFactory + | CursorAgentSdkRunner + | IdAllocatorV2; + +/** Infrastructure shared by the V2 adapters materialized inside provider instances. */ +export const ProviderOrchestrationAdapterInfrastructureLive = Layer.mergeAll( + claudeAgentSdkQueryRunnerLiveLayer, + codexAppServerClientFactoryFromSettingsLayer, + cursorAgentSdkRunnerLiveLayer, + idAllocatorLayer, +); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index a57a38e30f..6d1196446e 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -659,6 +659,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( streamChanges: Stream.empty, }, adapter: {} as ProviderInstance["adapter"], + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; const instanceRegistryLayer = Layer.succeed( @@ -701,6 +702,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( streamChanges: Stream.fromPubSub(changes), }, adapter: {} as ProviderInstance["adapter"], + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], } satisfies ProviderInstance; const instanceRegistryLayer = Layer.succeed( @@ -733,7 +735,435 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( yield* Effect.gen(function* () { const registry = yield* ProviderRegistry; - assert.strictEqual(spawnCount > 0, true); + const config = yield* ServerConfig; + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: cursorInstanceId, + }); + + assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [ + ...initialProvider.models, + ]); + yield* PubSub.publish(changes, refreshedProvider); + + let cachedProvider = yield* readProviderStatusCache(filePath); + for ( + let attempt = 0; + attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt; + attempt += 1 + ) { + yield* TestClock.adjust("10 millis"); + yield* Effect.yieldNow; + cachedProvider = yield* readProviderStatusCache(filePath); + } + + assert.deepStrictEqual(cachedProvider, { + ...refreshedProvider, + models: [...initialProvider.models], + }); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it.effect("returns the cached provider list when a manual refresh fails", () => + Effect.gen(function* () { + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const cachedProvider = { + instanceId: codexInstanceId, + driver: codexDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-29T10:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const instance = { + instanceId: codexInstanceId, + driverKind: codexDriver, + continuationIdentity: { + driverKind: codexDriver, + continuationKey: "codex:instance:codex", + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: codexDriver, + packageName: null, + }), + getSnapshot: Effect.succeed(cachedProvider), + refresh: Effect.die(new Error("simulated refresh failure")), + streamChanges: Stream.empty, + }, + adapter: {} as ProviderInstance["adapter"], + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Effect.succeed(instanceId === codexInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-refresh-failure-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + + assert.deepStrictEqual(yield* registry.getProviders, [cachedProvider]); + assert.deepStrictEqual(yield* registry.refresh(codexDriver), [cachedProvider]); + assert.deepStrictEqual(yield* registry.refreshInstance(codexInstanceId), [ + cachedProvider, + ]); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + it.effect("keeps consuming registry changes after one sync fails", () => + Effect.gen(function* () { + const codexDriver = ProviderDriverKind.make("codex"); + const codexInstanceId = ProviderInstanceId.make("codex"); + const claudeDriver = ProviderDriverKind.make("claudeAgent"); + const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); + const codexProvider = { + instanceId: codexInstanceId, + driver: codexDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-29T10:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const claudeProvider = { + instanceId: claudeInstanceId, + driver: claudeDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-29T10:01:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const makeInstance = (provider: ServerProvider): ProviderInstance => ({ + instanceId: provider.instanceId, + driverKind: provider.driver, + continuationIdentity: { + driverKind: provider.driver, + continuationKey: `${provider.driver}:instance:${provider.instanceId}`, + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: provider.driver, + packageName: null, + }), + getSnapshot: Effect.succeed(provider), + refresh: Effect.succeed(provider), + streamChanges: Stream.empty, + }, + adapter: {} as ProviderInstance["adapter"], + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }); + const codexInstance = makeInstance(codexProvider); + const claudeInstance = makeInstance(claudeProvider); + const changes = yield* PubSub.unbounded(); + const instancesRef = yield* Ref.make>([codexInstance]); + const failNextList = yield* Ref.make(false); + const wait = () => Effect.yieldNow; + const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, { + getInstance: (instanceId) => + Ref.get(instancesRef).pipe( + Effect.map((instances) => + instances.find((instance) => instance.instanceId === instanceId), + ), + ), + listInstances: Effect.gen(function* () { + const shouldFail = yield* Ref.get(failNextList); + if (shouldFail) { + yield* Ref.set(failNextList, false); + return yield* Effect.die(new Error("simulated registry list failure")); + } + return yield* Ref.get(instancesRef); + }), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-sync-failure-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + assert.deepStrictEqual(yield* registry.getProviders, [codexProvider]); + + yield* Ref.set(failNextList, true); + yield* PubSub.publish(changes, undefined); + + yield* Ref.set(instancesRef, [codexInstance, claudeInstance]); + yield* PubSub.publish(changes, undefined); + + let providers = yield* registry.getProviders; + for ( + let attempt = 0; + attempt < 50 && + !providers.some((provider) => provider.instanceId === claudeInstanceId); + attempt += 1 + ) { + yield* wait(); + providers = yield* registry.getProviders; + } + + assert.deepStrictEqual( + providers.map((provider) => provider.instanceId).toSorted(), + [codexInstanceId, claudeInstanceId].toSorted(), + ); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + // This test intentionally avoids `mockCommandSpawnerLayer` so the real + // `probeCodexAppServerProvider` path runs — including the full + // `codex app-server` RPC handshake via `CodexClient.layerChildProcess`. + // We point `binaryPath` at a name that cannot exist on any machine so + // the real `ChildProcessSpawner` deterministically returns ENOENT; the + // probe wraps that as `CodexAppServerSpawnError` and + // `checkCodexProviderStatus` turns it into the user-visible "not + // installed" error snapshot. If the aggregator's `syncLiveSources` + // breaks — the `codex_personal`-never-probes bug we are guarding + // against — that snapshot never lands in `getProviders` and the + // assertions below fail. + it.effect("propagates real Codex probe failures to the aggregator at boot", () => + Effect.gen(function* () { + const missingBinary = `t3code_codex_missing_`; + const serverSettings = yield* makeMutableServerSettingsService( + decodeServerSettings( + deepMerge(encodedDefaultServerSettings, { + providers: { + // Disable every built-in probe that would otherwise spawn + // on the CI host. `enabled: false` short-circuits each + // driver's probe *before* it touches the spawner, so the + // test environment stays isolated from the dev + // machine's PATH. + codex: { enabled: false }, + claudeAgent: { enabled: false }, + cursor: { enabled: false }, + grok: { enabled: false }, + opencode: { enabled: false }, + }, + // `providerInstances` keys are branded `ProviderInstanceId`; + // the branded index signature rejects plain string literals + // at the TS level even though the runtime schema happily + // accepts + decodes them. Cast the patch to `unknown` so + // the `Schema.decodeSync` below does the real validation. + providerInstances: { + // Matches the shape the user had in `.t3/dev/settings.json` + // when the bug was reported: a custom enabled Codex instance + // pointing at a binary the server has to actually spawn. + codex_personal: { + driver: "codex", + displayName: "Codex Personal", + enabled: true, + config: { + binaryPath: missingBinary, + homePath: `/tmp/${missingBinary}_home`, + }, + }, + } as unknown as ContractServerSettings["providerInstances"], + }), + ), + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), + Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-", + }), + ), + Layer.provideMerge(TestHttpClientLive), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + Layer.provideMerge(OpenCodeRuntimeLive), + // NO spawner mock — `ChildProcessSpawner` is supplied by the + // outer `NodeServices.layer` on `it.layer(...)` and will + // genuinely spawn a subprocess. The missing-binary ENOENT is + // what exercises the same failure mode as a misconfigured + // production `binaryPath`. + ); + const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( + Scope.provide(scope), + ); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + let providers = yield* registry.getProviders; + for ( + let attempts = 0; + attempts < 50 && + providers.find((provider) => provider.instanceId === "codex_personal")?.status !== + "error"; + attempts += 1 + ) { + yield* Effect.yieldNow; + providers = yield* registry.getProviders; + } + const codexPersonal = providers.find( + (provider) => provider.instanceId === "codex_personal", + ); + assert.notStrictEqual( + codexPersonal, + undefined, + `Expected the aggregator to know about codex_personal; instead saw: ${providers + .map((provider) => provider.instanceId) + .join(", ")}`, + ); + assert.strictEqual( + codexPersonal?.status, + "error", + "Real Codex probe against a missing binary should surface as 'error' in the aggregator", + ); + assert.strictEqual(codexPersonal?.installed, false); + assert.strictEqual( + codexPersonal?.message, + "Codex CLI (`codex`) is not installed or not on PATH.", + ); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + + // Guards the second half of the reported bug: changing + // `providers.codex.binaryPath` in settings must tear down the live + // instance and rebuild it so a fresh probe runs with the new binary. + // This test drives the real settings stream → registry reconcile → + // aggregator sync pipeline and asserts that `getProviders` reflects + // the new background probe's outcome. + // + it.effect("re-probes when settings change the codex binaryPath", () => + Effect.gen(function* () { + const firstMissing = `t3code_codex_first_`; + const secondMissing = `t3code_codex_second_`; + const spawnedCommands: Array = []; + const serverSettings = yield* makeMutableServerSettingsService( + decodeServerSettings( + deepMerge(encodedDefaultServerSettings, { + providers: { + codex: { enabled: true, binaryPath: firstMissing }, + claudeAgent: { enabled: false }, + cursor: { enabled: false }, + grok: { enabled: false }, + opencode: { enabled: false }, + }, + }), + ), + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const providerRegistryLayer = ProviderRegistryLive.pipe( + Layer.provideMerge(ProviderInstanceRegistryHydrationLive), + Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-", + }), + ), + Layer.provideMerge(TestHttpClientLive), + Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)), + Layer.provideMerge(OpenCodeRuntimeLive), + Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) => + ChildProcessSpawner.make((command) => { + spawnedCommands.push((command as { readonly command: string }).command); + return spawner.spawn(command); + }), + ), + Layer.provideMerge(NodeServices.layer), + ); + const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( + Scope.provide(scope), + ); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry; + // Boot-time probe: the default codex instance is enabled with + // `firstMissing`, so the real spawner yields ENOENT and the + // snapshot should be `status: "error"`. + let initialProviders = yield* registry.getProviders; + for ( + let attempts = 0; + attempts < 50 && + initialProviders.find((provider) => provider.instanceId === "codex")?.status !== + "error"; + attempts += 1 + ) { + yield* TestClock.adjust("10 millis"); + yield* Effect.yieldNow; + initialProviders = yield* registry.getProviders; + } + const initialCodex = initialProviders.find( + (provider) => provider.instanceId === "codex", + ); + assert.strictEqual(initialCodex?.status, "error"); + assert.strictEqual(initialCodex?.installed, false); + assert.deepStrictEqual(spawnedCommands, [firstMissing]); + + // Drive a settings change. The Hydration layer's + // `SettingsWatcherLive` consumes this via `streamChanges`, + // calls `reconcile`, which rebuilds the codex instance (the + // envelope changed because `binaryPath` differs → `entryEqual` + // is false). The registry's `Stream.runForEach( + // instanceRegistry.streamChanges, () => syncLiveSources)` + // fires `syncLiveSources`, which subscribes and launches a fresh + // background refresh on the rebuilt instance. + yield* serverSettings.updateSettings({ + providers: { + codex: { enabled: true, binaryPath: secondMissing }, + }, + }); + + // Poll until the injected process boundary observes the new + // executable. This verifies the public settings-to-probe behavior + // without depending on timestamps assigned by TestClock. const refreshed = yield* Effect.gen(function* () { for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) { const providers = yield* registry.getProviders; diff --git a/apps/server/src/provider/ProviderDriver.ts b/apps/server/src/provider/ProviderDriver.ts index c738882c23..359da392f8 100644 --- a/apps/server/src/provider/ProviderDriver.ts +++ b/apps/server/src/provider/ProviderDriver.ts @@ -30,7 +30,8 @@ import type * as Effect from "effect/Effect"; import type * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; -import type * as TextGeneration from "../textGeneration/TextGeneration.ts"; +import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts"; +import type { ProviderAdapterV2Shape } from "../orchestration-v2/ProviderAdapter.ts"; import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts"; import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts"; import type { ServerProviderShape } from "./Services/ServerProvider.ts"; @@ -70,7 +71,8 @@ export interface ProviderInstance { readonly enabled: boolean; readonly snapshot: ServerProviderShape; readonly adapter: ProviderAdapterShape; - readonly textGeneration: TextGeneration.TextGeneration["Service"]; + readonly orchestrationAdapter: ProviderAdapterV2Shape; + readonly textGeneration: TextGenerationShape; } export interface ProviderContinuationIdentity { diff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts index 791a96e1da..bbff99705d 100644 --- a/apps/server/src/provider/builtInDrivers.ts +++ b/apps/server/src/provider/builtInDrivers.ts @@ -20,6 +20,7 @@ * * @module provider/builtInDrivers */ +import { AcpRegistryDriver, type AcpRegistryDriverEnv } from "./Drivers/AcpRegistryDriver.ts"; import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts"; import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts"; import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts"; @@ -33,6 +34,7 @@ import type { AnyProviderDriver } from "./ProviderDriver.ts"; * layer must provide every service in this union. */ export type BuiltInDriversEnv = + | AcpRegistryDriverEnv | ClaudeDriverEnv | CodexDriverEnv | CursorDriverEnv @@ -50,4 +52,5 @@ export const BUILT_IN_DRIVERS: ReadonlyArray new OrchestrationV2GetThreadProjectionError({ @@ -983,37 +985,29 @@ const makeWsRpcLayer = ( }), ), ); - const snapshotSequence = yield* threadManagement - .getThreadEventSequence(input.threadId) + const { projection, snapshotSequence } = snapshot; + + const liveStream = threadManagement + .streamStoredEventsFrom({ + threadId: input.threadId, + afterSequence: snapshotSequence, + }) .pipe( - Effect.mapError( + Stream.map((stored) => ({ + kind: "event" as const, + sequence: stored.sequence, + event: stored.event, + })), + Stream.mapError( (cause) => new OrchestrationV2GetThreadProjectionError({ threadId: input.threadId, - message: `Failed to load orchestration V2 sequence for thread ${input.threadId}`, + message: `Failed while streaming orchestration V2 thread ${input.threadId}`, cause, }), ), ); - const liveStream = threadManagement.streamStoredEvents.pipe( - Stream.filter((stored) => stored.event.threadId === input.threadId), - Stream.filter((stored) => stored.sequence > snapshotSequence), - Stream.map((stored) => ({ - kind: "event" as const, - sequence: stored.sequence, - event: stored.event, - })), - Stream.mapError( - (cause) => - new OrchestrationV2GetThreadProjectionError({ - threadId: input.threadId, - message: `Failed while streaming orchestration V2 thread ${input.threadId}`, - cause, - }), - ), - ); - return Stream.concat( Stream.make({ kind: "snapshot" as const, @@ -1037,35 +1031,31 @@ const makeWsRpcLayer = ( ), ); - const liveStream = threadManagement.streamDomainEvents.pipe( - Stream.mapEffect((event) => - threadManagement.getShellSnapshot().pipe( - Effect.map( - (nextSnapshot) => - nextSnapshot.threads.find((thread) => thread.id === event.threadId) ?? null, - ), - Effect.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: `Failed while streaming orchestration V2 shell thread ${event.threadId}`, - cause, - }), + const liveStream = threadManagement + .streamStoredEventsFrom({ afterSequence: snapshot.snapshotSequence }) + .pipe( + Stream.mapEffect((stored) => + threadManagement.getShellSnapshot().pipe( + Effect.map((nextSnapshot) => + shellStreamItemFromSnapshot({ stored, snapshot: nextSnapshot }), + ), + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: `Failed while streaming orchestration V2 shell thread ${stored.event.threadId}`, + cause, + }), + ), ), ), - ), - Stream.filter((thread): thread is OrchestrationV2ThreadShell => thread !== null), - Stream.map((thread) => ({ - kind: "thread.updated" as const, - thread, - })), - Stream.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: "Failed while streaming orchestration V2 shell", - cause, - }), - ), - ); + Stream.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed while streaming orchestration V2 shell", + cause, + }), + ), + ); return Stream.concat( Stream.make({ diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx index 79fab8361c..f9cd46a7c2 100644 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ b/apps/web/src/routes/debug.orchestration-v2.tsx @@ -676,7 +676,7 @@ function buildStreamTimeline(logEntries: ReadonlyArray): ReadonlyArray title: event.type, subtitle: compactId(event.threadId), sequence: value.sequence, - status: stringifyShort(payload.status) ?? stringifyShort(event.provider) ?? "received", + status: stringifyShort(payload.status) ?? stringifyShort(event.driver) ?? "received", body: readText(payload, ["text", "title", "detail", "markdown"]), raw: value, }; @@ -1721,7 +1721,16 @@ function OrchestrationV2DebugRoute() { unsubscribeRef.current = null; }, []); - useEffect(() => clearSubscription, [clearSubscription]); + setShellThreadsById((current) => { + const next = new Map(current); + if (item.kind === "thread.removed") { + next.delete(item.threadId); + return next; + } + next.set(item.thread.id, item.thread); + return next; + }); + }, [shellSubscription.data]); useEffect(() => { shellUnsubscribeRef.current = api.subscribeShell((item) => { @@ -3296,7 +3305,8 @@ function workLogRowContent(item: OrchestrationV2TurnItem): WorkLogRowContent { glyph: "⇄", label: "Handoff", preview: - clipOneLine(item.summary, 120) ?? `${item.fromProviders.join(", ")} → ${item.toProvider}`, + clipOneLine(item.summary, 120) ?? + `${item.fromProviderInstanceIds.join(", ")} → ${item.toProviderInstanceId}`, tone: "muted", }; case "fork": @@ -3749,7 +3759,10 @@ function ChatItem(props: { return ( diff --git a/packages/contracts/src/chatAttachment.ts b/packages/contracts/src/chatAttachment.ts new file mode 100644 index 0000000000..5d1f28d583 --- /dev/null +++ b/packages/contracts/src/chatAttachment.ts @@ -0,0 +1,41 @@ +import * as Schema from "effect/Schema"; + +import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000; +export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8; +export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024; +const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000; +const CHAT_ATTACHMENT_ID_MAX_CHARS = 128; + +export const ChatAttachmentId = TrimmedNonEmptyString.check( + Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS), + Schema.isPattern(/^[a-z0-9_-]+$/i), +); +export type ChatAttachmentId = typeof ChatAttachmentId.Type; + +export const ChatImageAttachment = Schema.Struct({ + type: Schema.Literal("image"), + id: ChatAttachmentId, + name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)), + sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)), +}); +export type ChatImageAttachment = typeof ChatImageAttachment.Type; + +export const UploadChatImageAttachment = Schema.Struct({ + type: Schema.Literal("image"), + name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)), + sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)), + dataUrl: TrimmedNonEmptyString.check( + Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS), + ), +}); +export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type; + +export const ChatAttachment = Schema.Union([ChatImageAttachment]); +export type ChatAttachment = typeof ChatAttachment.Type; + +export const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]); +export type UploadChatAttachment = typeof UploadChatAttachment.Type; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index f8143ab792..10225eae6a 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -11,6 +11,9 @@ export * from "./terminal.ts"; export * from "./provider.ts"; export * from "./providerInstance.ts"; export * from "./providerRuntime.ts"; +export * from "./providerPolicy.ts"; +export * from "./modelSelection.ts"; +export * from "./chatAttachment.ts"; export * from "./model.ts"; export * from "./keybindings.ts"; export * from "./server.ts"; diff --git a/packages/contracts/src/modelSelection.ts b/packages/contracts/src/modelSelection.ts new file mode 100644 index 0000000000..a131111a78 --- /dev/null +++ b/packages/contracts/src/modelSelection.ts @@ -0,0 +1,63 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SchemaTransformation from "effect/SchemaTransformation"; + +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ProviderOptionSelections } from "./model.ts"; +import { ProviderInstanceId } from "./providerInstance.ts"; + +/** + * Selection of a model on a configured provider instance. + * + * `instanceId` is the routing key. The provider driver, credentials, + * environment, and continuation identity are resolved by the provider + * instance registry rather than encoded into the selection itself. + */ +const ModelSelectionWire = Schema.Struct({ + instanceId: ProviderInstanceId, + model: TrimmedNonEmptyString, + options: Schema.optionalKey(ProviderOptionSelections), +}); + +const ModelSelectionSource = Schema.Struct({ + provider: Schema.optional(Schema.Unknown), + instanceId: Schema.optional(Schema.Unknown), + model: Schema.Unknown, + options: Schema.optional(Schema.Unknown), +}); + +/** + * The decoder still accepts the historical `{ provider, model }` shape while + * V1 persistence remains readable. Runtime code only receives the canonical + * instance-based representation. + */ +export const ModelSelection = ModelSelectionSource.pipe( + Schema.decodeTo( + ModelSelectionWire, + SchemaTransformation.transformOrFail({ + decode: (raw) => { + const instanceIdSource = + raw.instanceId !== undefined + ? raw.instanceId + : typeof raw.provider === "string" + ? raw.provider + : undefined; + const base: Record = { + instanceId: instanceIdSource, + model: raw.model, + }; + if (raw.options !== undefined) base.options = raw.options; + return Effect.succeed(base as typeof ModelSelectionWire.Encoded); + }, + encode: (value) => { + const base: Record = { + instanceId: value.instanceId, + model: value.model, + }; + if (value.options !== undefined) base.options = value.options; + return Effect.succeed(base as typeof ModelSelectionSource.Encoded); + }, + }), + ), +); +export type ModelSelection = typeof ModelSelection.Type; diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index ecf7afa061..d844c43a03 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -3,9 +3,6 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { - DEFAULT_PROVIDER_INTERACTION_MODE, - DEFAULT_RUNTIME_MODE, - ModelSelection, OrchestrationCommand, OrchestrationEvent, OrchestrationGetFullThreadDiffInput, @@ -24,6 +21,8 @@ import { ThreadTurnDiff, ThreadTurnStartRequestedPayload, } from "./orchestration.ts"; +import { ModelSelection } from "./modelSelection.ts"; +import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "./providerPolicy.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; const decodeTurnDiffInput = Schema.decodeUnknownEffect(OrchestrationGetTurnDiffInput); diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 51357633ac..3a057fb240 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -2,9 +2,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as SchemaIssue from "effect/SchemaIssue"; -import * as SchemaTransformation from "effect/SchemaTransformation"; import * as Struct from "effect/Struct"; -import { ProviderOptionSelections } from "./model.ts"; import { RepositoryIdentity } from "./environment.ts"; import { ApprovalRequestId, @@ -21,6 +19,16 @@ import { TrimmedString, TurnId, } from "./baseSchemas.ts"; +import { ChatAttachment, UploadChatAttachment } from "./chatAttachment.ts"; +import { ModelSelection } from "./modelSelection.ts"; +import { + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + ProviderApprovalDecision, + ProviderInteractionMode, + ProviderUserInputAnswers, + RuntimeMode, +} from "./providerPolicy.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; export const ORCHESTRATION_WS_METHODS = { @@ -33,155 +41,10 @@ export const ORCHESTRATION_WS_METHODS = { subscribeThread: "orchestration.subscribeThread", } as const; -export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor", "opencode"]); -export type ProviderKind = typeof ProviderKind.Type; -export const ProviderApprovalPolicy = Schema.Literals([ - "untrusted", - "on-failure", - "on-request", - "never", -]); -export type ProviderApprovalPolicy = typeof ProviderApprovalPolicy.Type; -export const ProviderSandboxMode = Schema.Literals([ - "read-only", - "workspace-write", - "danger-full-access", -]); -export type ProviderSandboxMode = typeof ProviderSandboxMode.Type; - -/** - * `ModelSelection` — selection of a model on a configured provider instance. - * - * The routing key is `instanceId` (a user-defined slug identifying one - * configured provider instance). Drivers, credentials, working-directory - * bindings, and any other per-instance state are recovered from the - * runtime registry via the instance id. - * - * Wire legacy: persisted selections produced before the driver/instance - * split carried a `provider: ` field instead. The schema absorbs - * that shape via a pre-decoding transform — `{provider, model}` is promoted - * to `{instanceId: defaultInstanceIdForDriver(provider), model}`. No - * post-decode compatibility code lives in the runtime; the transform is the - * only compat surface. - */ -const ModelSelectionWire = Schema.Struct({ - instanceId: ProviderInstanceId, - model: TrimmedNonEmptyString, - options: Schema.optionalKey(ProviderOptionSelections), -}); - -// Source shape for persisted legacy payloads. Fields are typed as -// `Schema.Unknown` so malformed drafts still make it into the transform and -// fail validation through the target schema (with proper error messages) -// rather than at the source-struct layer where the error is less actionable. -const ModelSelectionSource = Schema.Struct({ - provider: Schema.optional(Schema.Unknown), - instanceId: Schema.optional(Schema.Unknown), - model: Schema.Unknown, - options: Schema.optional(Schema.Unknown), -}); - -export const ModelSelection = ModelSelectionSource.pipe( - Schema.decodeTo( - ModelSelectionWire, - SchemaTransformation.transformOrFail({ - decode: (raw) => { - // Resolve the routing key: prefer an explicit `instanceId`; fall - // back to promoting the legacy `provider` slug (the canonical - // `defaultInstanceIdForDriver` mapping) so persisted rollout-era - // payloads decode without data loss. The target schema brands the - // string as `ProviderInstanceId`. - const instanceIdSource = - raw.instanceId !== undefined - ? raw.instanceId - : typeof raw.provider === "string" - ? raw.provider - : undefined; - const base: Record = { - instanceId: instanceIdSource, - model: raw.model, - }; - if (raw.options !== undefined) base.options = raw.options; - return Effect.succeed(base as typeof ModelSelectionWire.Encoded); - }, - encode: (value) => { - const base: Record = { - model: value.model, - instanceId: value.instanceId, - }; - if (value.options !== undefined) base.options = value.options; - return Effect.succeed(base as typeof ModelSelectionSource.Encoded); - }, - }), - ), -); -export type ModelSelection = typeof ModelSelection.Type; - -export const RuntimeMode = Schema.Literals([ - "approval-required", - "auto-accept-edits", - "auto", - "full-access", -]); -export type RuntimeMode = typeof RuntimeMode.Type; -export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; -export const ProviderInteractionMode = Schema.Literals(["default", "plan"]); -export type ProviderInteractionMode = typeof ProviderInteractionMode.Type; -export const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = "default"; -export const ProviderRequestKind = Schema.Literals(["command", "file-read", "file-change"]); -export type ProviderRequestKind = typeof ProviderRequestKind.Type; -export const AssistantDeliveryMode = Schema.Literals(["buffered", "streaming"]); -export type AssistantDeliveryMode = typeof AssistantDeliveryMode.Type; -export const ProviderApprovalDecision = Schema.Literals([ - "accept", - "acceptForSession", - "decline", - "cancel", -]); -export type ProviderApprovalDecision = typeof ProviderApprovalDecision.Type; -export const ProviderUserInputAnswers = Schema.Record(Schema.String, Schema.Unknown); -export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type; - -export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000; -export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8; -export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024; -const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000; -const CHAT_ATTACHMENT_ID_MAX_CHARS = 128; // Correlation id is command id by design in this model. export const CorrelationId = CommandId; export type CorrelationId = typeof CorrelationId.Type; -const ChatAttachmentId = TrimmedNonEmptyString.check( - Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS), - Schema.isPattern(/^[a-z0-9_-]+$/i), -); -export type ChatAttachmentId = typeof ChatAttachmentId.Type; - -export const ChatImageAttachment = Schema.Struct({ - type: Schema.Literal("image"), - id: ChatAttachmentId, - name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), - mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)), - sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)), -}); -export type ChatImageAttachment = typeof ChatImageAttachment.Type; - -const UploadChatImageAttachment = Schema.Struct({ - type: Schema.Literal("image"), - name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), - mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)), - sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)), - dataUrl: TrimmedNonEmptyString.check( - Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS), - ), -}); -export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type; - -export const ChatAttachment = Schema.Union([ChatImageAttachment]); -export type ChatAttachment = typeof ChatAttachment.Type; -const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]); -export type UploadChatAttachment = typeof UploadChatAttachment.Type; - export const ProjectScriptIcon = Schema.Literals([ "play", "test", diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index b6da4789f0..598e7e2325 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -108,7 +108,7 @@ describe("orchestration V2 contracts", () => { id: "run-1", threadId: "thread-1", ordinal: 1, - provider: "codex", + providerInstanceId: "codex", modelSelection: { instanceId: "codex", model: "gpt-5.4", @@ -128,6 +128,9 @@ describe("orchestration V2 contracts", () => { expect(command.commandId).toBe(CommandId.make("command-1")); expect(event.id).toBe(EventId.make("event-1")); + if (event.type !== "run.created") { + throw new Error(`Expected run.created, received ${event.type}.`); + } expect(event.payload.id).toBe(RunId.make("run-1")); }); @@ -199,7 +202,7 @@ describe("orchestration V2 contracts", () => { nodeId: "node-file-change-1", providerThreadId: "provider-thread-1", providerTurnId: "provider-turn-1", - nativeItemRef: { provider: "codex", nativeId: "item-file-change-1", strength: "strong" }, + nativeItemRef: { driver: "codex", nativeId: "item-file-change-1", strength: "strong" }, parentItemId: null, ordinal: 3, status: "completed", @@ -220,7 +223,7 @@ describe("orchestration V2 contracts", () => { nodeId: "node-dynamic-1", providerThreadId: "provider-thread-1", providerTurnId: "provider-turn-1", - nativeItemRef: { provider: "codex", nativeId: "item-dynamic-1", strength: "strong" }, + nativeItemRef: { driver: "codex", nativeId: "item-dynamic-1", strength: "strong" }, parentItemId: null, ordinal: 4, status: "completed", @@ -250,11 +253,12 @@ describe("orchestration V2 contracts", () => { parentNodeId: "node-root-1", origin: "provider_native", createdBy: "agent", - provider: "codex", + driver: "codex", + providerInstanceId: "codex", providerThreadId: "provider-thread-subagent-1", childThreadId: null, nativeTaskRef: { - provider: "codex", + driver: "codex", nativeId: "native-task-1", strength: "strong", }, @@ -282,7 +286,8 @@ describe("orchestration V2 contracts", () => { title: subagent.title, subagentId: subagent.id, origin: subagent.origin, - provider: subagent.provider, + driver: subagent.driver, + providerInstanceId: subagent.providerInstanceId, childThreadId: subagent.childThreadId, prompt: subagent.prompt, result: subagent.result, @@ -304,8 +309,8 @@ describe("orchestration V2 contracts", () => { id: "thread-1", projectId: "project-1", title: "Thread", - defaultProvider: "codex", - modelSelection: { provider: "codex", model: "gpt-5-codex" }, + providerInstanceId: "codex", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -341,7 +346,7 @@ describe("orchestration V2 contracts", () => { nodeId: "node-command-1", providerThreadId: "provider-thread-1", providerTurnId: "provider-turn-1", - nativeItemRef: { provider: "codex", nativeId: "item-command-1", strength: "strong" }, + nativeItemRef: { driver: "codex", nativeId: "item-command-1", strength: "strong" }, parentItemId: null, ordinal: 1, status: "completed", @@ -354,6 +359,34 @@ describe("orchestration V2 contracts", () => { updatedAt: now, }, ], + visibleTurnItems: [ + { + position: 0, + visibility: "local", + sourceThreadId: "thread-1", + sourceItemId: "turn-item-command-1", + item: { + id: "turn-item-command-1", + type: "command_execution", + threadId: "thread-1", + runId: "run-1", + nodeId: "node-command-1", + providerThreadId: "provider-thread-1", + providerTurnId: "provider-turn-1", + nativeItemRef: { driver: "codex", nativeId: "item-command-1", strength: "strong" }, + parentItemId: null, + ordinal: 1, + status: "completed", + title: "Ran command", + input: "bun typecheck", + output: "Tasks: 10 successful", + exitCode: 0, + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + ], checkpointScopes: [], checkpoints: [], contextHandoffs: [], @@ -378,7 +411,7 @@ describe("orchestration V2 contracts", () => { ordinal: 5, status: "running", title: "Compacting context...", - provider: "codex", + driver: "codex", beforeTokenCount: 180000, startedAt: now, completedAt: null, @@ -400,8 +433,8 @@ describe("orchestration V2 contracts", () => { contextHandoffId: "handoff-1", fromProviderThreadIds: ["provider-thread-codex-1"], toProviderThreadId: "provider-thread-claude-1", - fromProviders: ["codex"], - toProvider: "claudeAgent", + fromProviderInstanceIds: ["codex"], + toProviderInstanceId: "claudeAgent", strategy: "delta_since_target_last_seen", summary: "Codex completed the setup work.", startedAt: now, @@ -434,7 +467,7 @@ describe("orchestration V2 contracts", () => { if (handoff.type !== "handoff") { throw new Error("expected handoff"); } - expect(handoff.toProvider).toBe("claudeAgent"); + expect(handoff.toProviderInstanceId).toBe("claudeAgent"); expect(fork.type).toBe("fork"); }); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index dc9963f908..0f9a994158 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -25,16 +25,17 @@ import { TrimmedNonEmptyString, TurnItemId, } from "./baseSchemas.ts"; +import { ChatAttachment } from "./chatAttachment.ts"; +import { ModelSelection } from "./modelSelection.ts"; import { - ChatAttachment, - ModelSelection, ProviderApprovalDecision, ProviderInteractionMode, ProviderKind, ProviderRequestKind, ProviderUserInputAnswers, RuntimeMode, -} from "./orchestration.ts"; +} from "./providerPolicy.ts"; +import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; export const OrchestrationV2Actor = Schema.Literals(["user", "agent", "system"]); export type OrchestrationV2Actor = typeof OrchestrationV2Actor.Type; @@ -57,7 +58,7 @@ export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type; export const OrchestrationV2ProviderRef = Schema.Struct({ - provider: ProviderKind, + driver: ProviderDriverKind, nativeId: Schema.NullOr(TrimmedNonEmptyString), strength: OrchestrationV2NativeRefStrength, fingerprint: Schema.optional(TrimmedNonEmptyString), @@ -130,8 +131,8 @@ export const OrchestrationV2ContextTransfer = Schema.Struct({ targetThreadId: ThreadId, sourcePoint: OrchestrationV2ContextSourcePoint, basePoint: Schema.NullOr(OrchestrationV2ContextSourcePoint), - sourceProvider: Schema.NullOr(ProviderKind), - targetProvider: Schema.NullOr(ProviderKind), + sourceProviderInstanceId: Schema.NullOr(ProviderInstanceId), + targetProviderInstanceId: Schema.NullOr(ProviderInstanceId), targetRunId: Schema.NullOr(RunId), status: Schema.Literals([ "pending", @@ -281,7 +282,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ id: ThreadId, projectId: ProjectId, title: TrimmedNonEmptyString, - defaultProvider: ProviderKind, + providerInstanceId: ProviderInstanceId, modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, @@ -324,7 +325,7 @@ export const OrchestrationV2Run = Schema.Struct({ id: RunId, threadId: ThreadId, ordinal: PositiveInt, - provider: ProviderKind, + providerInstanceId: ProviderInstanceId, modelSelection: ModelSelection, providerThreadId: Schema.NullOr(ProviderThreadId), userMessageId: MessageId, @@ -351,7 +352,7 @@ export const OrchestrationV2RunAttempt = Schema.Struct({ runId: RunId, attemptOrdinal: PositiveInt, rootNodeId: NodeId, - provider: ProviderKind, + providerInstanceId: ProviderInstanceId, providerThreadId: ProviderThreadId, providerTurnId: Schema.NullOr(ProviderTurnId), reason: Schema.Literals(["initial", "steering_restart", "retry", "provider_recovery"]), @@ -416,7 +417,8 @@ export const OrchestrationV2Subagent = Schema.Struct({ parentNodeId: NodeId, origin: Schema.Literals(["provider_native", "app_owned"]), createdBy: OrchestrationV2Actor, - provider: ProviderKind, + driver: ProviderDriverKind, + providerInstanceId: ProviderInstanceId, providerThreadId: Schema.NullOr(ProviderThreadId), childThreadId: Schema.NullOr(ThreadId), nativeTaskRef: Schema.NullOr(OrchestrationV2ProviderRef), @@ -456,7 +458,8 @@ export type OrchestrationV2CheckpointScope = typeof OrchestrationV2CheckpointSco export const OrchestrationV2ProviderSession = Schema.Struct({ id: ProviderSessionId, - provider: ProviderKind, + driver: ProviderDriverKind, + providerInstanceId: ProviderInstanceId, status: Schema.Literals(["starting", "ready", "running", "waiting", "stopped", "error"]), cwd: TrimmedNonEmptyString, model: Schema.NullOr(TrimmedNonEmptyString), @@ -469,7 +472,8 @@ export type OrchestrationV2ProviderSession = typeof OrchestrationV2ProviderSessi export const OrchestrationV2ProviderThread = Schema.Struct({ id: ProviderThreadId, - provider: ProviderKind, + driver: ProviderDriverKind, + providerInstanceId: ProviderInstanceId, providerSessionId: Schema.NullOr(ProviderSessionId), appThreadId: Schema.NullOr(ThreadId), ownerNodeId: Schema.NullOr(NodeId), @@ -512,7 +516,7 @@ export const OrchestrationV2ContextHandoff = Schema.Struct({ status: Schema.Literals(["pending", "ready", "failed", "superseded"]), summaryMessageId: Schema.NullOr(MessageId), summaryText: Schema.String, - createdByProvider: Schema.NullOr(ProviderKind), + createdByProviderInstanceId: Schema.NullOr(ProviderInstanceId), createdAt: Schema.DateTimeUtc, updatedAt: Schema.DateTimeUtc, }); @@ -639,6 +643,14 @@ export const OrchestrationV2Checkpoint = Schema.Struct({ }); export type OrchestrationV2Checkpoint = typeof OrchestrationV2Checkpoint.Type; +export const OrchestrationV2CheckpointRollbackRequest = Schema.Struct({ + scopeId: CheckpointScopeId, + checkpointId: CheckpointId, + requestedAt: Schema.DateTimeUtc, +}); +export type OrchestrationV2CheckpointRollbackRequest = + typeof OrchestrationV2CheckpointRollbackRequest.Type; + export const OrchestrationV2TurnItemStatus = Schema.Literals([ "pending", "running", @@ -790,7 +802,7 @@ export const OrchestrationV2TurnItem = Schema.Union([ Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, type: Schema.Literal("compaction"), - provider: Schema.NullOr(ProviderKind), + driver: Schema.NullOr(ProviderDriverKind), summary: Schema.optional(Schema.String), beforeTokenCount: Schema.optional(NonNegativeInt), afterTokenCount: Schema.optional(NonNegativeInt), @@ -801,8 +813,8 @@ export const OrchestrationV2TurnItem = Schema.Union([ contextHandoffId: ContextHandoffId, fromProviderThreadIds: Schema.Array(ProviderThreadId), toProviderThreadId: ProviderThreadId, - fromProviders: Schema.Array(ProviderKind), - toProvider: ProviderKind, + fromProviderInstanceIds: Schema.Array(ProviderInstanceId), + toProviderInstanceId: ProviderInstanceId, strategy: Schema.Literals([ "delta_since_target_last_seen", "fork_delta_summary", @@ -832,7 +844,8 @@ export const OrchestrationV2TurnItem = Schema.Union([ type: Schema.Literal("subagent"), subagentId: NodeId, origin: Schema.Literals(["provider_native", "app_owned"]), - provider: ProviderKind, + driver: ProviderDriverKind, + providerInstanceId: ProviderInstanceId, childThreadId: Schema.NullOr(ThreadId), prompt: Schema.String, result: Schema.NullOr(Schema.String), @@ -858,7 +871,8 @@ export type OrchestrationV2ProjectedTurnItem = typeof OrchestrationV2ProjectedTu export const OrchestrationV2RawProviderEvent = Schema.Struct({ id: RawEventId, - provider: ProviderKind, + driver: ProviderDriverKind, + providerInstanceId: ProviderInstanceId, providerSessionId: ProviderSessionId, sequence: PositiveInt, direction: Schema.Literals(["incoming", "outgoing"]), @@ -875,7 +889,8 @@ const OrchestrationV2EventBase = Schema.Struct({ threadId: ThreadId, runId: Schema.optional(RunId), nodeId: Schema.optional(NodeId), - provider: Schema.optional(ProviderKind), + driver: Schema.optional(ProviderDriverKind), + providerInstanceId: Schema.optional(ProviderInstanceId), rawEventId: Schema.optional(RawEventId), occurredAt: Schema.DateTimeUtc, }); @@ -886,6 +901,20 @@ export const OrchestrationV2DomainEvent = Schema.Union([ type: Schema.Literal("thread.created"), payload: OrchestrationV2AppThread, }), + Schema.Struct({ + ...OrchestrationV2EventBase.fields, + type: Schema.Literals([ + "thread.archived", + "thread.unarchived", + "thread.deleted", + "thread.metadata-updated", + "thread.runtime-mode-updated", + "thread.interaction-mode-updated", + "thread.model-selection-updated", + "thread.provider-switched", + ]), + payload: OrchestrationV2AppThread, + }), Schema.Struct({ ...OrchestrationV2EventBase.fields, type: Schema.Literal("run.created"), @@ -961,6 +990,11 @@ export const OrchestrationV2DomainEvent = Schema.Union([ type: Schema.Literal("checkpoint.captured"), payload: OrchestrationV2Checkpoint, }), + Schema.Struct({ + ...OrchestrationV2EventBase.fields, + type: Schema.Literal("checkpoint.rollback-requested"), + payload: OrchestrationV2CheckpointRollbackRequest, + }), Schema.Struct({ ...OrchestrationV2EventBase.fields, type: Schema.Literal("context-handoff.updated"), @@ -1007,29 +1041,56 @@ export const OrchestrationV2ShellThreadStatus = Schema.Union([ ]); export type OrchestrationV2ShellThreadStatus = typeof OrchestrationV2ShellThreadStatus.Type; +export const OrchestrationV2PendingRuntimeRequestSummary = Schema.Struct({ + id: RuntimeRequestId, + kind: OrchestrationV2RuntimeRequest.fields.kind, + createdAt: Schema.DateTimeUtc, +}); +export type OrchestrationV2PendingRuntimeRequestSummary = + typeof OrchestrationV2PendingRuntimeRequestSummary.Type; + +export const OrchestrationV2LatestVisibleMessageSummary = Schema.Struct({ + id: MessageId, + role: OrchestrationV2ConversationMessage.fields.role, + text: Schema.String, + updatedAt: Schema.DateTimeUtc, +}); +export type OrchestrationV2LatestVisibleMessageSummary = + typeof OrchestrationV2LatestVisibleMessageSummary.Type; + export const OrchestrationV2ThreadShell = Schema.Struct({ ...OrchestrationV2CreationFields, id: ThreadId, projectId: ProjectId, title: Schema.String, - defaultProvider: ProviderKind, + providerInstanceId: ProviderInstanceId, modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, + branch: Schema.NullOr(TrimmedNonEmptyString), + worktreePath: Schema.NullOr(TrimmedNonEmptyString), lineage: OrchestrationV2AppThreadLineage, forkedFrom: Schema.NullOr(OrchestrationV2AppThread.fields.forkedFrom), activeProviderThreadId: Schema.NullOr(ProviderThreadId), latestRunId: Schema.NullOr(RunId), + activeRunId: Schema.NullOr(RunId), status: OrchestrationV2ShellThreadStatus, + pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary), + latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary), itemCount: NonNegativeInt, visibleItemCount: NonNegativeInt, createdAt: Schema.DateTimeUtc, updatedAt: Schema.DateTimeUtc, + archivedAt: Schema.NullOr(Schema.DateTimeUtc), + deletedAt: Schema.NullOr(Schema.DateTimeUtc), }); export type OrchestrationV2ThreadShell = typeof OrchestrationV2ThreadShell.Type; export const OrchestrationV2ShellSnapshot = Schema.Struct({ + schemaVersion: PositiveInt, + snapshotSequence: NonNegativeInt, threads: Schema.Array(OrchestrationV2ThreadShell), + archivedThreads: Schema.Array(OrchestrationV2ThreadShell), }); export type OrchestrationV2ShellSnapshot = typeof OrchestrationV2ShellSnapshot.Type; @@ -1040,8 +1101,16 @@ export const OrchestrationV2ShellStreamItem = Schema.Union([ }), Schema.Struct({ kind: Schema.Literal("thread.updated"), + sequence: NonNegativeInt, + location: Schema.Literals(["active", "archive"]), thread: OrchestrationV2ThreadShell, }), + Schema.Struct({ + kind: Schema.Literal("thread.removed"), + sequence: NonNegativeInt, + location: Schema.Literals(["active", "archive"]), + threadId: ThreadId, + }), ]); export type OrchestrationV2ShellStreamItem = typeof OrchestrationV2ShellStreamItem.Type; @@ -1170,6 +1239,12 @@ export const OrchestrationV2CheckpointJson = OrchestrationV2Checkpoint.mapFields })); export type OrchestrationV2CheckpointJson = typeof OrchestrationV2CheckpointJson.Type; +export const OrchestrationV2CheckpointRollbackRequestJson = + OrchestrationV2CheckpointRollbackRequest.mapFields((fields) => ({ + ...fields, + requestedAt: Schema.DateTimeUtcFromString, + })); + const OrchestrationV2TurnItemJsonBaseFields = { ...OrchestrationV2TurnItemBaseFields, startedAt: Schema.NullOr(Schema.DateTimeUtcFromString), @@ -1276,7 +1351,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, type: Schema.Literal("compaction"), - provider: Schema.NullOr(ProviderKind), + driver: Schema.NullOr(ProviderDriverKind), summary: Schema.optional(Schema.String), beforeTokenCount: Schema.optional(NonNegativeInt), afterTokenCount: Schema.optional(NonNegativeInt), @@ -1287,8 +1362,8 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ contextHandoffId: ContextHandoffId, fromProviderThreadIds: Schema.Array(ProviderThreadId), toProviderThreadId: ProviderThreadId, - fromProviders: Schema.Array(ProviderKind), - toProvider: ProviderKind, + fromProviderInstanceIds: Schema.Array(ProviderInstanceId), + toProviderInstanceId: ProviderInstanceId, strategy: Schema.Literals([ "delta_since_target_last_seen", "fork_delta_summary", @@ -1318,7 +1393,8 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ type: Schema.Literal("subagent"), subagentId: NodeId, origin: Schema.Literals(["provider_native", "app_owned"]), - provider: ProviderKind, + driver: ProviderDriverKind, + providerInstanceId: ProviderInstanceId, childThreadId: Schema.NullOr(ThreadId), prompt: Schema.String, result: Schema.NullOr(Schema.String), @@ -1352,6 +1428,20 @@ export const OrchestrationV2DomainEventJson = Schema.Union([ type: Schema.Literal("thread.created"), payload: OrchestrationV2AppThreadJson, }), + Schema.Struct({ + ...OrchestrationV2JsonEventBaseFields, + type: Schema.Literals([ + "thread.archived", + "thread.unarchived", + "thread.deleted", + "thread.metadata-updated", + "thread.runtime-mode-updated", + "thread.interaction-mode-updated", + "thread.model-selection-updated", + "thread.provider-switched", + ]), + payload: OrchestrationV2AppThreadJson, + }), Schema.Struct({ ...OrchestrationV2JsonEventBaseFields, type: Schema.Literal("run.created"), @@ -1427,6 +1517,11 @@ export const OrchestrationV2DomainEventJson = Schema.Union([ type: Schema.Literal("checkpoint.captured"), payload: OrchestrationV2CheckpointJson, }), + Schema.Struct({ + ...OrchestrationV2JsonEventBaseFields, + type: Schema.Literal("checkpoint.rollback-requested"), + payload: OrchestrationV2CheckpointRollbackRequestJson, + }), Schema.Struct({ ...OrchestrationV2JsonEventBaseFields, type: Schema.Literal("context-handoff.updated"), @@ -1466,6 +1561,54 @@ export const OrchestrationV2Command = Schema.Union([ branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), }), + Schema.Struct({ + type: Schema.Literal("thread.archive"), + commandId: CommandId, + threadId: ThreadId, + }), + Schema.Struct({ + type: Schema.Literal("thread.unarchive"), + commandId: CommandId, + threadId: ThreadId, + }), + Schema.Struct({ + type: Schema.Literal("thread.delete"), + commandId: CommandId, + threadId: ThreadId, + }), + Schema.Struct({ + type: Schema.Literal("thread.metadata.update"), + commandId: CommandId, + threadId: ThreadId, + title: Schema.optional(TrimmedNonEmptyString), + branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + }), + Schema.Struct({ + type: Schema.Literal("thread.runtime-mode.set"), + commandId: CommandId, + threadId: ThreadId, + runtimeMode: RuntimeMode, + }), + Schema.Struct({ + type: Schema.Literal("thread.interaction-mode.set"), + commandId: CommandId, + threadId: ThreadId, + interactionMode: ProviderInteractionMode, + }), + Schema.Struct({ + type: Schema.Literal("thread.model-selection.set"), + commandId: CommandId, + threadId: ThreadId, + modelSelection: ModelSelection, + }), + Schema.Struct({ + type: Schema.Literal("provider-session.release"), + commandId: CommandId, + threadId: ThreadId, + providerSessionId: ProviderSessionId, + reason: Schema.optional(Schema.String), + }), Schema.Struct({ type: Schema.Literal("message.dispatch"), ...OrchestrationV2CreationFields, @@ -1555,7 +1698,6 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("provider.switch"), commandId: CommandId, threadId: ThreadId, - provider: ProviderKind, modelSelection: ModelSelection, }), ]); @@ -1668,7 +1810,7 @@ export const ProviderReplayEntry = Schema.Union([ export type ProviderReplayEntry = typeof ProviderReplayEntry.Type; export const ProviderReplayTranscript = Schema.Struct({ - provider: ProviderKind, + provider: TrimmedNonEmptyString, protocol: TrimmedNonEmptyString, version: TrimmedNonEmptyString, scenario: TrimmedNonEmptyString, @@ -1679,7 +1821,7 @@ export type ProviderReplayTranscript = typeof ProviderReplayTranscript.Type; export const ProviderReplayTranscriptHeader = Schema.Struct({ type: Schema.Literal("transcript_start"), - provider: ProviderKind, + provider: TrimmedNonEmptyString, protocol: TrimmedNonEmptyString, version: TrimmedNonEmptyString, scenario: TrimmedNonEmptyString, diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index f096f27835..5ec92d5903 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -13,7 +13,7 @@ import { TrimmedNonEmptyString, TurnItemId, } from "./baseSchemas.ts"; -import { ProviderInteractionMode, RuntimeMode } from "./orchestration.ts"; +import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts"; import { OrchestrationV2Actor, OrchestrationV2CreationSource, diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 94fb007a7b..ce078a944f 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -9,10 +9,12 @@ import { TurnId, } from "./baseSchemas.ts"; import { - ChatAttachment, - ModelSelection, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, + ChatAttachment, +} from "./chatAttachment.ts"; +import { ModelSelection } from "./modelSelection.ts"; +import { ProviderApprovalDecision, ProviderApprovalPolicy, ProviderInteractionMode, @@ -20,7 +22,7 @@ import { ProviderSandboxMode, ProviderUserInputAnswers, RuntimeMode, -} from "./orchestration.ts"; +} from "./providerPolicy.ts"; import { ProviderInstanceId, ProviderDriverKind } from "./providerInstance.ts"; const ProviderSessionStatus = Schema.Literals([ diff --git a/packages/contracts/src/providerPolicy.ts b/packages/contracts/src/providerPolicy.ts new file mode 100644 index 0000000000..a738aa43a5 --- /dev/null +++ b/packages/contracts/src/providerPolicy.ts @@ -0,0 +1,45 @@ +import * as Schema from "effect/Schema"; + +export const ProviderApprovalPolicy = Schema.Literals([ + "untrusted", + "on-failure", + "on-request", + "never", +]); +export type ProviderApprovalPolicy = typeof ProviderApprovalPolicy.Type; + +export const ProviderSandboxMode = Schema.Literals([ + "read-only", + "workspace-write", + "danger-full-access", +]); +export type ProviderSandboxMode = typeof ProviderSandboxMode.Type; + +export const RuntimeMode = Schema.Literals([ + "approval-required", + "auto-accept-edits", + "full-access", +]); +export type RuntimeMode = typeof RuntimeMode.Type; +export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; + +export const ProviderInteractionMode = Schema.Literals(["default", "plan"]); +export type ProviderInteractionMode = typeof ProviderInteractionMode.Type; +export const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = "default"; + +export const ProviderRequestKind = Schema.Literals(["command", "file-read", "file-change"]); +export type ProviderRequestKind = typeof ProviderRequestKind.Type; + +export const AssistantDeliveryMode = Schema.Literals(["buffered", "streaming"]); +export type AssistantDeliveryMode = typeof AssistantDeliveryMode.Type; + +export const ProviderApprovalDecision = Schema.Literals([ + "accept", + "acceptForSession", + "decline", + "cancel", +]); +export type ProviderApprovalDecision = typeof ProviderApprovalDecision.Type; + +export const ProviderUserInputAnswers = Schema.Record(Schema.String, Schema.Unknown); +export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 33c8f3aeff..8f9fe40ba6 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -3,8 +3,8 @@ import * as Duration from "effect/Duration"; import * as Schema from "effect/Schema"; import * as SchemaTransformation from "effect/SchemaTransformation"; import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts"; -import { DEFAULT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts"; -import { ModelSelection } from "./orchestration.ts"; +import { DEFAULT_GIT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts"; +import { ModelSelection } from "./modelSelection.ts"; import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts"; // ── Client Settings (local-only) ─────────────────────────────── diff --git a/packages/effect-codex-app-server/src/replay.ts b/packages/effect-codex-app-server/src/replay.ts index 451643863c..aef177510a 100644 --- a/packages/effect-codex-app-server/src/replay.ts +++ b/packages/effect-codex-app-server/src/replay.ts @@ -95,7 +95,7 @@ export class CodexAppServerReplayFrameMismatchError extends Schema.TaggedErrorCl }, ) { override get message(): string { - return `Outbound Codex app-server frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}.`; + return `Outbound Codex app-server frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}. Expected ${JSON.stringify(this.expected)}, received ${JSON.stringify(this.actual)}.`; } } @@ -209,6 +209,37 @@ function normalizeReplayFrame(value: unknown): unknown { } } + if ( + normalized.method === "turn/start" && + typeof normalized.params === "object" && + normalized.params !== null + ) { + const params = { ...(normalized.params as Record) }; + if (params.approvalPolicy === "never") { + delete params.approvalPolicy; + } + if ( + typeof params.sandboxPolicy === "object" && + params.sandboxPolicy !== null && + (params.sandboxPolicy as Record).type === "dangerFullAccess" + ) { + delete params.sandboxPolicy; + } + if (typeof params.collaborationMode === "object" && params.collaborationMode !== null) { + const collaborationMode = { + ...(params.collaborationMode as Record), + }; + if (typeof collaborationMode.settings === "object" && collaborationMode.settings !== null) { + collaborationMode.settings = { + ...(collaborationMode.settings as Record), + developer_instructions: "", + }; + } + params.collaborationMode = collaborationMode; + } + normalized.params = params; + } + return normalized; } @@ -218,8 +249,56 @@ function sameFrame(left: unknown, right: unknown): boolean { ); } +function normalizeLegacyInboundFrame(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(normalizeLegacyInboundFrame); + } + if (typeof value !== "object" || value === null) { + return value; + } + const record = value as Record; + const normalized = Object.fromEntries( + Object.entries(record).map(([key, entry]) => [key, normalizeLegacyInboundFrame(entry)]), + ); + if ( + typeof normalized.id === "string" && + normalized.sessionId === undefined && + "modelProvider" in normalized && + "status" in normalized + ) { + normalized.sessionId = normalized.id; + } + if ( + (normalized.method === "item/started" || normalized.method === "item/completed") && + typeof normalized.params === "object" && + normalized.params !== null + ) { + const params = { ...(normalized.params as Record) }; + if (normalized.method === "item/started" && params.startedAtMs === undefined) { + params.startedAtMs = 0; + } + if (normalized.method === "item/completed" && params.completedAtMs === undefined) { + params.completedAtMs = 0; + } + normalized.params = params; + } + if ( + typeof normalized.method === "string" && + normalized.method.endsWith("/requestApproval") && + typeof normalized.params === "object" && + normalized.params !== null + ) { + const params = { ...(normalized.params as Record) }; + if (params.startedAtMs === undefined) { + params.startedAtMs = 0; + } + normalized.params = params; + } + return normalized; +} + function encodeInboundFrame(frame: unknown): Uint8Array { - return encoder.encode(`${JSON.stringify(frame)}\n`); + return encoder.encode(`${JSON.stringify(normalizeLegacyInboundFrame(frame))}\n`); } function replayTransportError(