The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | type ChatAttachment, |
| 3 | CommandId, |
| 4 | type OrchestrationV2Command, |
| 5 | OrchestrationV2ProviderCapabilities, |
| 6 | type OrchestrationV2GoalCommand, |
| 7 | type OrchestrationV2ProviderGoalStatus, |
| 8 | type OrchestrationV2Run, |
| 9 | OrchestrationV2ThreadProjection, |
| 10 | ProviderInstanceId, |
| 11 | ThreadId, |
| 12 | } from "@t3tools/contracts"; |
| 13 | import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError"; |
| 14 | import * as Context from "effect/Context"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as Layer from "effect/Layer"; |
| 17 | import * as Schema from "effect/Schema"; |
| 18 | |
| 19 | export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]); |
| 20 | export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type; |
| 21 | |
| 22 | export const ForkExecutionPolicyV2 = Schema.Literals(["native_fork", "portable_context"]); |
| 23 | export type ForkExecutionPolicyV2 = typeof ForkExecutionPolicyV2.Type; |
| 24 | |
| 25 | export const CommandPolicyCapability = Schema.Literals([ |
| 26 | "queued_messages", |
| 27 | "active_steering", |
| 28 | "interrupt", |
| 29 | "interrupt_restart_steering", |
| 30 | "native_fork", |
| 31 | "fork_from_turn", |
| 32 | "rollback", |
| 33 | "rollback_snapshot", |
| 34 | "context_handoff", |
| 35 | "strong_terminal_status", |
| 36 | ]); |
| 37 | export type CommandPolicyCapability = typeof CommandPolicyCapability.Type; |
| 38 | |
| 39 | export class CommandPolicyCapabilityUnsupportedError extends Schema.TaggedError<CommandPolicyCapabilityUnsupportedError>()( |
| 40 | "CommandPolicyCapabilityUnsupportedError", |
| 41 | { |
| 42 | commandId: CommandId, |
| 43 | threadId: ThreadId, |
| 44 | providerInstanceId: ProviderInstanceId, |
| 45 | capability: CommandPolicyCapability, |
| 46 | detail: Schema.String, |
| 47 | }, |
| 48 | ) { |
| 49 | override get message(): string { |
| 50 | return `${this.providerInstanceId} cannot satisfy ${this.capability} for command ${this.commandId}: ${this.detail}`; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | export const CommandPolicyV2Error = Schema.Union([CommandPolicyCapabilityUnsupportedError]); |
| 55 | export type CommandPolicyV2Error = typeof CommandPolicyV2Error.Type; |
| 56 | |
| 57 | type MessageDispatchMode = Extract< |
| 58 | OrchestrationV2Command, |
| 59 | { readonly type: "message.dispatch" } |
| 60 | >["dispatchMode"]; |
| 61 | |
| 62 | /** |
| 63 | * A message that signs a provider account out at turn start, as `providerAuthLogout` does. |
| 64 | * With attachments the same text is an ordinary prompt. |
| 65 | */ |
| 66 | export function isProviderSignOutPrompt(message: { |
| 67 | readonly text: string; |
| 68 | readonly attachments: ReadonlyArray<ChatAttachment>; |
| 69 | }): boolean { |
| 70 | return message.attachments.length === 0 && message.text.trim().toLowerCase() === "/logout"; |
| 71 | } |
| 72 | |
| 73 | export function isNativeMaintenanceCommand(message: { |
| 74 | readonly text: string; |
| 75 | readonly attachments: ReadonlyArray<ChatAttachment>; |
| 76 | readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined; |
| 77 | }): boolean { |
| 78 | return ( |
| 79 | message.attachments.length === 0 && |
| 80 | ["/compact", "/logout"].includes(message.text.trim().toLowerCase()) |
| 81 | ); |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * A goal command sent into active work stops that work when it starts or |
| 86 | * replaces goal work, or ends a goal that is driving the run. |
| 87 | */ |
| 88 | export function goalCommandStopsActiveRun( |
| 89 | command: OrchestrationV2GoalCommand, |
| 90 | goalStatus: OrchestrationV2ProviderGoalStatus | null, |
| 91 | ): boolean { |
| 92 | switch (command.type) { |
| 93 | case "set": |
| 94 | case "resume": |
| 95 | return true; |
| 96 | case "clear": |
| 97 | case "pause": |
| 98 | return goalStatus === "active"; |
| 99 | case "show": |
| 100 | return false; |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | export function resolveMessageDispatchIntent( |
| 105 | projection: OrchestrationV2ThreadProjection, |
| 106 | requestedMode: MessageDispatchMode, |
| 107 | deliveryIntent?: "auto" | "steer" | "restart", |
| 108 | ): MessageDispatchMode { |
| 109 | const mode = resolveDeliveryIntent(projection, requestedMode, deliveryIntent); |
| 110 | if (mode.type !== "steer_active") return mode; |
| 111 | // Compaction and sign-out cannot accept steers; queue follow-ups. |
| 112 | const target = projection.runs.find((run) => run.id === mode.targetRunId); |
| 113 | const targetMessage = projection.messages.find((message) => message.id === target?.userMessageId); |
| 114 | if (targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)) { |
| 115 | return { type: "queue_after_active" }; |
| 116 | } |
| 117 | // A provider that can neither steer nor restart its turn takes the message after the turn. |
| 118 | const turns = |
| 119 | target === undefined || !isActiveRun(target) |
| 120 | ? undefined |
| 121 | : providerTurnCapabilities(projection, target); |
| 122 | return turns !== undefined && !turns.supportsActiveSteering && providerSwitchWaitsForTurn(turns) |
| 123 | ? { type: "queue_after_active" } |
| 124 | : mode; |
| 125 | } |
| 126 | |
| 127 | /** A run that still owns the thread's provider turn. */ |
| 128 | export function isActiveRun(run: OrchestrationV2Run): boolean { |
| 129 | return ( |
| 130 | run.status === "preparing" || |
| 131 | run.status === "starting" || |
| 132 | run.status === "running" || |
| 133 | run.status === "waiting" |
| 134 | ); |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Providers that key forks on native turn ids can only fork a busy source from a turn with one; |
| 139 | * a synthetic or missing boundary would fork the live conversation, including the running turn. |
| 140 | */ |
| 141 | export function canForkBusySourceNatively( |
| 142 | capabilities: OrchestrationV2ProviderCapabilities, |
| 143 | hasNativeTurnBoundary: boolean, |
| 144 | ): boolean { |
| 145 | return ( |
| 146 | capabilities.threads.canForkWhileSourceRunning === true && |
| 147 | (hasNativeTurnBoundary || !capabilities.turns.exposesNativeTurnId) |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | /** The run a follow-up to a finished child binds to: the latest active one, else the last that ran. */ |
| 152 | export function followUpOwnerRun( |
| 153 | runs: ReadonlyArray<OrchestrationV2Run>, |
| 154 | ): OrchestrationV2Run | null { |
| 155 | return ( |
| 156 | runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ?? latestExecutedRun(runs) |
| 157 | ); |
| 158 | } |
| 159 | |
| 160 | /** A provider that cannot restart its turn for new input runs a provider switch after the turn. */ |
| 161 | export function providerSwitchWaitsForTurn( |
| 162 | turns: OrchestrationV2ProviderCapabilities["turns"], |
| 163 | ): boolean { |
| 164 | return ( |
| 165 | turns.supportsQueuedMessages && |
| 166 | !(turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) |
| 167 | ); |
| 168 | } |
| 169 | |
| 170 | export function providerTurnCapabilities( |
| 171 | projection: OrchestrationV2ThreadProjection, |
| 172 | run: OrchestrationV2Run, |
| 173 | ) { |
| 174 | const providerThread = projection.providerThreads.find( |
| 175 | (candidate) => candidate.id === run.providerThreadId, |
| 176 | ); |
| 177 | const providerSession = |
| 178 | providerThread?.providerSessionId == null |
| 179 | ? undefined |
| 180 | : projection.providerSessions.find( |
| 181 | (candidate) => candidate.id === providerThread.providerSessionId, |
| 182 | ); |
| 183 | return providerSession?.capabilities.turns; |
| 184 | } |
| 185 | |
| 186 | function resolveDeliveryIntent( |
| 187 | projection: OrchestrationV2ThreadProjection, |
| 188 | requestedMode: MessageDispatchMode, |
| 189 | deliveryIntent?: "auto" | "steer" | "restart", |
| 190 | ): MessageDispatchMode { |
| 191 | if (deliveryIntent === undefined) return requestedMode; |
| 192 | |
| 193 | const activeRun = projection.runs.findLast(isActiveRun); |
| 194 | if (activeRun === undefined) return { type: "start_immediately" }; |
| 195 | if (deliveryIntent === "steer") { |
| 196 | return { type: "steer_active", targetRunId: activeRun.id }; |
| 197 | } |
| 198 | if (deliveryIntent === "restart") { |
| 199 | return { type: "restart_active", targetRunId: activeRun.id }; |
| 200 | } |
| 201 | // A run can be active before its provider turn starts or after it finishes. |
| 202 | // Queue automatic input in those gaps so steering cannot reject the message. |
| 203 | if ( |
| 204 | activeRun.status === "preparing" || |
| 205 | activeRun.status === "starting" || |
| 206 | !projection.providerTurns.some( |
| 207 | (turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running", |
| 208 | ) |
| 209 | ) { |
| 210 | return { type: "queue_after_active" }; |
| 211 | } |
| 212 | |
| 213 | const capabilities = providerTurnCapabilities(projection, activeRun); |
| 214 | if (capabilities?.supportsActiveSteering === true) { |
| 215 | return { type: "steer_active", targetRunId: activeRun.id }; |
| 216 | } |
| 217 | if (capabilities?.supportsQueuedMessages === true) { |
| 218 | return { type: "queue_after_active" }; |
| 219 | } |
| 220 | if (capabilities?.supportsSteeringByInterruptRestart === true) { |
| 221 | return { type: "restart_active", targetRunId: activeRun.id }; |
| 222 | } |
| 223 | return { type: "queue_after_active" }; |
| 224 | } |
| 225 | |
| 226 | interface CapabilityCheckInput { |
| 227 | readonly commandId: CommandId; |
| 228 | readonly threadId: ThreadId; |
| 229 | readonly providerInstanceId: ProviderInstanceId; |
| 230 | readonly capabilities: OrchestrationV2ProviderCapabilities; |
| 231 | } |
| 232 | |
| 233 | export interface CommandPolicyV2Shape { |
| 234 | readonly ensureQueuedMessages: ( |
| 235 | input: CapabilityCheckInput, |
| 236 | ) => Effect.Effect<void, CommandPolicyV2Error>; |
| 237 | readonly decideSteeringExecution: ( |
| 238 | input: CapabilityCheckInput & { |
| 239 | readonly forceRestart?: boolean; |
| 240 | }, |
| 241 | ) => Effect.Effect<SteeringExecutionPolicyV2, CommandPolicyV2Error>; |
| 242 | readonly ensureInterrupt: ( |
| 243 | input: CapabilityCheckInput, |
| 244 | ) => Effect.Effect<void, CommandPolicyV2Error>; |
| 245 | readonly ensureNativeFork: ( |
| 246 | input: CapabilityCheckInput & { |
| 247 | readonly fromSpecificTurn: boolean; |
| 248 | }, |
| 249 | ) => Effect.Effect<void, CommandPolicyV2Error>; |
| 250 | readonly decideForkExecution: ( |
| 251 | input: CapabilityCheckInput & { |
| 252 | readonly sameProvider: boolean; |
| 253 | readonly hasStrongNativeSource: boolean; |
| 254 | readonly hasNativeTurnBoundary: boolean; |
| 255 | readonly sourceRunStatus: OrchestrationV2Run["status"]; |
| 256 | readonly fromSpecificTurn: boolean; |
| 257 | /** Later source runs are still active. */ |
| 258 | readonly sourceBusy: boolean; |
| 259 | }, |
| 260 | ) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>; |
| 261 | readonly ensureRollback: ( |
| 262 | input: CapabilityCheckInput, |
| 263 | ) => Effect.Effect<void, CommandPolicyV2Error>; |
| 264 | readonly ensureContextHandoff: ( |
| 265 | input: CapabilityCheckInput & { |
| 266 | readonly strategy: "fork_delta_context" | "delta_context" | "full_thread_summary"; |
| 267 | }, |
| 268 | ) => Effect.Effect<void, CommandPolicyV2Error>; |
| 269 | } |
| 270 | |
| 271 | export class CommandPolicyV2 extends Context.Service<CommandPolicyV2, CommandPolicyV2Shape>()( |
| 272 | "t3/orchestration-v2/CommandPolicy/CommandPolicyV2", |
| 273 | ) {} |
| 274 | |
| 275 | function unsupported( |
| 276 | input: CapabilityCheckInput, |
| 277 | capability: CommandPolicyCapability, |
| 278 | detail: string, |
| 279 | ) { |
| 280 | return new CommandPolicyCapabilityUnsupportedError({ |
| 281 | commandId: input.commandId, |
| 282 | threadId: input.threadId, |
| 283 | providerInstanceId: input.providerInstanceId, |
| 284 | capability, |
| 285 | detail, |
| 286 | }); |
| 287 | } |
| 288 | |
| 289 | const ensureQueuedMessages: CommandPolicyV2Shape["ensureQueuedMessages"] = (input) => |
| 290 | input.capabilities.turns.supportsQueuedMessages |
| 291 | ? Effect.void |
| 292 | : Effect.fail( |
| 293 | unsupported( |
| 294 | input, |
| 295 | "queued_messages", |
| 296 | "providerInstanceId does not support app-owned queued turns", |
| 297 | ), |
| 298 | ); |
| 299 | |
| 300 | const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => { |
| 301 | if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) { |
| 302 | return Effect.succeed("active_steering"); |
| 303 | } |
| 304 | if ( |
| 305 | input.capabilities.turns.supportsInterrupt && |
| 306 | input.capabilities.turns.supportsSteeringByInterruptRestart |
| 307 | ) { |
| 308 | return Effect.succeed("interrupt_restart"); |
| 309 | } |
| 310 | return Effect.fail( |
| 311 | unsupported( |
| 312 | input, |
| 313 | input.forceRestart || input.capabilities.turns.supportsInterrupt |
| 314 | ? "interrupt_restart_steering" |
| 315 | : "active_steering", |
| 316 | input.forceRestart |
| 317 | ? "providerInstanceId cannot satisfy a required interrupt-and-restart" |
| 318 | : "providerInstanceId cannot steer active turns directly or by interrupt-and-restart", |
| 319 | ), |
| 320 | ); |
| 321 | }; |
| 322 | |
| 323 | const ensureInterrupt: CommandPolicyV2Shape["ensureInterrupt"] = (input) => |
| 324 | input.capabilities.turns.supportsInterrupt |
| 325 | ? Effect.void |
| 326 | : Effect.fail( |
| 327 | unsupported(input, "interrupt", "providerInstanceId does not support turn interrupts"), |
| 328 | ); |
| 329 | |
| 330 | const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => { |
| 331 | if (!input.capabilities.threads.canForkThread) { |
| 332 | return Effect.fail( |
| 333 | unsupported(input, "native_fork", "providerInstanceId does not support native thread forks"), |
| 334 | ); |
| 335 | } |
| 336 | if (input.fromSpecificTurn && !input.capabilities.threads.canForkFromTurn) { |
| 337 | return Effect.fail( |
| 338 | unsupported( |
| 339 | input, |
| 340 | "fork_from_turn", |
| 341 | "providerInstanceId cannot fork from a specific completed turn", |
| 342 | ), |
| 343 | ); |
| 344 | } |
| 345 | if (input.capabilities.identity.nativeThreadIds !== "strong") { |
| 346 | return Effect.fail( |
| 347 | unsupported( |
| 348 | input, |
| 349 | "native_fork", |
| 350 | "providerInstanceId does not expose strong native thread ids", |
| 351 | ), |
| 352 | ); |
| 353 | } |
| 354 | return Effect.void; |
| 355 | }; |
| 356 | |
| 357 | const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => { |
| 358 | // Without native truncation, the next turn replays the kept conversation as a handoff. |
| 359 | if ( |
| 360 | !input.capabilities.threads.canRollbackThread || |
| 361 | (!input.capabilities.checkpointing.providerCanRollbackConversation && |
| 362 | !input.capabilities.context.canConsumeHandoffSummaries) |
| 363 | ) { |
| 364 | return Effect.fail( |
| 365 | unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"), |
| 366 | ); |
| 367 | } |
| 368 | if (!input.capabilities.checkpointing.providerRollbackReturnsSnapshot) { |
| 369 | return Effect.fail( |
| 370 | unsupported( |
| 371 | input, |
| 372 | "rollback_snapshot", |
| 373 | "rollback must return a providerInstanceId thread snapshot", |
| 374 | ), |
| 375 | ); |
| 376 | } |
| 377 | return Effect.void; |
| 378 | }; |
| 379 | |
| 380 | const ensureContextHandoff: CommandPolicyV2Shape["ensureContextHandoff"] = (input) => { |
| 381 | if (!input.capabilities.context.canConsumeHandoffSummaries) { |
| 382 | return Effect.fail( |
| 383 | unsupported(input, "context_handoff", "providerInstanceId cannot consume handoff summaries"), |
| 384 | ); |
| 385 | } |
| 386 | if (!input.capabilities.context.acceptsSyntheticUserContext) { |
| 387 | return Effect.fail( |
| 388 | unsupported( |
| 389 | input, |
| 390 | "context_handoff", |
| 391 | "providerInstanceId cannot receive synthetic user context", |
| 392 | ), |
| 393 | ); |
| 394 | } |
| 395 | if ( |
| 396 | (input.strategy === "fork_delta_context" || input.strategy === "delta_context") && |
| 397 | !input.capabilities.context.supportsDeltaHandoff |
| 398 | ) { |
| 399 | return Effect.fail( |
| 400 | unsupported(input, "context_handoff", "providerInstanceId does not support delta handoff"), |
| 401 | ); |
| 402 | } |
| 403 | if ( |
| 404 | input.strategy === "full_thread_summary" && |
| 405 | !input.capabilities.context.supportsFullThreadHandoff |
| 406 | ) { |
| 407 | return Effect.fail( |
| 408 | unsupported( |
| 409 | input, |
| 410 | "context_handoff", |
| 411 | "providerInstanceId does not support full-thread handoff", |
| 412 | ), |
| 413 | ); |
| 414 | } |
| 415 | return Effect.void; |
| 416 | }; |
| 417 | |
| 418 | const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input) => { |
| 419 | // Unsuccessful runs may lack native cursors; fork bounded transcripts to exclude later turns. |
| 420 | const canForkNatively = |
| 421 | (input.sourceRunStatus === "completed" || input.sourceRunStatus === "waiting") && |
| 422 | input.sameProvider && |
| 423 | input.hasStrongNativeSource && |
| 424 | (!input.sourceBusy || |
| 425 | canForkBusySourceNatively(input.capabilities, input.hasNativeTurnBoundary)) && |
| 426 | input.capabilities.threads.canForkThread && |
| 427 | (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) && |
| 428 | input.capabilities.identity.nativeThreadIds === "strong"; |
| 429 | |
| 430 | if (canForkNatively) { |
| 431 | return Effect.succeed("native_fork"); |
| 432 | } |
| 433 | |
| 434 | return ensureContextHandoff({ |
| 435 | commandId: input.commandId, |
| 436 | threadId: input.threadId, |
| 437 | providerInstanceId: input.providerInstanceId, |
| 438 | capabilities: input.capabilities, |
| 439 | strategy: "full_thread_summary", |
| 440 | }).pipe(Effect.as("portable_context")); |
| 441 | }; |
| 442 | |
| 443 | export const layer: Layer.Layer<CommandPolicyV2> = Layer.succeed(CommandPolicyV2, { |
| 444 | ensureQueuedMessages, |
| 445 | decideSteeringExecution, |
| 446 | ensureInterrupt, |
| 447 | ensureNativeFork, |
| 448 | decideForkExecution, |
| 449 | ensureRollback, |
| 450 | ensureContextHandoff, |
| 451 | }); |