The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | ModelSelection, |
| 3 | OrchestrationV2ThreadProjection, |
| 4 | ProviderSessionId, |
| 5 | ThreadId, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import { modelSelectionsEqual } from "@t3tools/shared/model"; |
| 8 | import * as Context from "effect/Context"; |
| 9 | import * as DateTime from "effect/DateTime"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Schema from "effect/Schema"; |
| 14 | |
| 15 | import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; |
| 16 | import { |
| 17 | decideProviderSessionTransition, |
| 18 | type ProviderSessionTransition, |
| 19 | } from "./ProviderSessionTransitionPolicy.ts"; |
| 20 | |
| 21 | export interface ProviderSwitchPlanV2 { |
| 22 | readonly instanceChanged: boolean; |
| 23 | readonly releaseProviderSessionIds: ReadonlyArray<ProviderSessionId>; |
| 24 | readonly transition: ProviderSessionTransition; |
| 25 | } |
| 26 | |
| 27 | export class ProviderSwitchPlanError extends Schema.TaggedError<ProviderSwitchPlanError>()( |
| 28 | "ProviderSwitchPlanError", |
| 29 | { |
| 30 | threadId: ThreadId, |
| 31 | targetProviderInstanceId: Schema.String, |
| 32 | cause: Schema.optional(Schema.Defect()), |
| 33 | }, |
| 34 | ) {} |
| 35 | |
| 36 | export interface ProviderSwitchServiceV2Shape { |
| 37 | readonly plan: (input: { |
| 38 | readonly projection: Pick< |
| 39 | OrchestrationV2ThreadProjection, |
| 40 | "thread" | "providerSessions" | "providerThreads" |
| 41 | >; |
| 42 | readonly targetModelSelection: ModelSelection; |
| 43 | }) => Effect.Effect<ProviderSwitchPlanV2, ProviderSwitchPlanError>; |
| 44 | } |
| 45 | |
| 46 | export class ProviderSwitchServiceV2 extends Context.Service< |
| 47 | ProviderSwitchServiceV2, |
| 48 | ProviderSwitchServiceV2Shape |
| 49 | >()("t3/orchestration-v2/ProviderSwitchService/ProviderSwitchServiceV2") {} |
| 50 | |
| 51 | const isLiveProviderSession = ( |
| 52 | session: OrchestrationV2ThreadProjection["providerSessions"][number], |
| 53 | ) => session.status !== "stopped" && session.status !== "error"; |
| 54 | |
| 55 | export const layer: Layer.Layer< |
| 56 | ProviderSwitchServiceV2, |
| 57 | never, |
| 58 | ProviderAdapterRegistry.ProviderAdapterRegistryV2 |
| 59 | > = Layer.effect( |
| 60 | ProviderSwitchServiceV2, |
| 61 | Effect.gen(function* () { |
| 62 | const adapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; |
| 63 | return ProviderSwitchServiceV2.of({ |
| 64 | plan: Effect.fn("ProviderSwitchService.plan")( |
| 65 | function* ({ projection, targetModelSelection }) { |
| 66 | const current = projection.thread.modelSelection; |
| 67 | const instanceChanged = current.instanceId !== targetModelSelection.instanceId; |
| 68 | const getMetadata = (instanceId: typeof current.instanceId) => |
| 69 | adapters.getMetadata !== undefined |
| 70 | ? adapters.getMetadata(instanceId) |
| 71 | : adapters.get(instanceId).pipe( |
| 72 | Effect.flatMap((adapter) => |
| 73 | adapter.getCapabilities().pipe( |
| 74 | Effect.map((capabilities) => ({ |
| 75 | driver: adapter.driver, |
| 76 | continuationKey: `${adapter.driver}:instance:${instanceId}`, |
| 77 | enabled: true, |
| 78 | capabilities, |
| 79 | })), |
| 80 | ), |
| 81 | ), |
| 82 | ); |
| 83 | const currentInstance = yield* Effect.option(getMetadata(current.instanceId)); |
| 84 | const targetInstance = yield* Effect.option(getMetadata(targetModelSelection.instanceId)); |
| 85 | const targetAdapter = yield* Effect.option(adapters.get(targetModelSelection.instanceId)); |
| 86 | const currentSessions = projection.providerSessions |
| 87 | .filter((session) => session.providerInstanceId === current.instanceId) |
| 88 | .toSorted( |
| 89 | (left, right) => |
| 90 | DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), |
| 91 | ); |
| 92 | const currentSession = currentSessions.find(isLiveProviderSession); |
| 93 | const negotiatedCapabilities = |
| 94 | currentSession?.capabilities ?? currentSessions[0]?.capabilities; |
| 95 | const currentProviderThread = projection.providerThreads.find( |
| 96 | (thread) => |
| 97 | thread.id === projection.thread.activeProviderThreadId && |
| 98 | thread.providerInstanceId === current.instanceId && |
| 99 | thread.nativeThreadRef !== null, |
| 100 | ); |
| 101 | const selectionTransition = |
| 102 | current.instanceId === targetModelSelection.instanceId && |
| 103 | !modelSelectionsEqual(current, targetModelSelection) && |
| 104 | Option.isSome(targetAdapter) && |
| 105 | Option.isSome(currentInstance) && |
| 106 | (currentSession !== undefined || currentProviderThread !== undefined) |
| 107 | ? negotiatedCapabilities === undefined |
| 108 | ? // No session record left to switch in place; the next session starts with it. |
| 109 | ({ type: "apply_on_next_turn" } as const) |
| 110 | : yield* targetAdapter.value.planSelectionTransition({ |
| 111 | current, |
| 112 | target: targetModelSelection, |
| 113 | sessionCapabilities: negotiatedCapabilities, |
| 114 | }) |
| 115 | : undefined; |
| 116 | // A selection change keeps the thread where it is. A shared session's cwd is the |
| 117 | // workspace of whichever thread opened it, not a move of this thread. |
| 118 | const workspace = |
| 119 | projection.thread.worktreePath ?? currentSession?.cwd ?? "<unresolved-workspace>"; |
| 120 | const transition = |
| 121 | Option.isNone(targetInstance) || Option.isNone(targetAdapter) |
| 122 | ? ({ |
| 123 | type: "reject", |
| 124 | reason: "The target provider instance is unavailable.", |
| 125 | } as const) |
| 126 | : decideProviderSessionTransition({ |
| 127 | current: |
| 128 | Option.isNone(currentInstance) || |
| 129 | (currentSession === undefined && currentProviderThread === undefined) |
| 130 | ? null |
| 131 | : { |
| 132 | driver: currentInstance.value.driver, |
| 133 | continuationIdentity: { |
| 134 | driverKind: currentInstance.value.driver, |
| 135 | continuationKey: currentInstance.value.continuationKey, |
| 136 | }, |
| 137 | modelSelection: current, |
| 138 | runtimeMode: projection.thread.runtimeMode, |
| 139 | interactionMode: projection.thread.interactionMode, |
| 140 | workspace, |
| 141 | }, |
| 142 | target: { |
| 143 | driver: targetInstance.value.driver, |
| 144 | continuationIdentity: { |
| 145 | driverKind: targetInstance.value.driver, |
| 146 | continuationKey: targetInstance.value.continuationKey, |
| 147 | }, |
| 148 | modelSelection: targetModelSelection, |
| 149 | runtimeMode: projection.thread.runtimeMode, |
| 150 | interactionMode: projection.thread.interactionMode, |
| 151 | workspace, |
| 152 | available: targetInstance.value.enabled, |
| 153 | }, |
| 154 | ...(selectionTransition === undefined ? {} : { selectionTransition }), |
| 155 | }); |
| 156 | if (transition.type === "reject") { |
| 157 | return yield* new ProviderSwitchPlanError({ |
| 158 | threadId: projection.thread.id, |
| 159 | targetProviderInstanceId: targetModelSelection.instanceId, |
| 160 | cause: transition.reason, |
| 161 | }); |
| 162 | } |
| 163 | const releaseProviderSessionIds = projection.providerSessions |
| 164 | .filter((session) => { |
| 165 | if (!isLiveProviderSession(session)) return false; |
| 166 | if (transition.type === "restart_and_resume") { |
| 167 | // Release only the replaced session; peers can serve pooled or delegated bindings. |
| 168 | return session.id === currentSession?.id; |
| 169 | } |
| 170 | if (transition.type === "create_with_handoff") { |
| 171 | return session.providerInstanceId !== targetModelSelection.instanceId; |
| 172 | } |
| 173 | return false; |
| 174 | }) |
| 175 | .map((session) => session.id); |
| 176 | return { |
| 177 | instanceChanged, |
| 178 | releaseProviderSessionIds, |
| 179 | transition, |
| 180 | }; |
| 181 | }, |
| 182 | (effect, { projection, targetModelSelection }) => |
| 183 | effect.pipe( |
| 184 | Effect.mapError( |
| 185 | (cause) => |
| 186 | new ProviderSwitchPlanError({ |
| 187 | threadId: projection.thread.id, |
| 188 | targetProviderInstanceId: targetModelSelection.instanceId, |
| 189 | cause, |
| 190 | }), |
| 191 | ), |
| 192 | ), |
| 193 | ), |
| 194 | }); |
| 195 | }), |
| 196 | ); |