diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index a50fa929ed04e..709d0af890d10 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -69,10 +69,15 @@ import { agentLaunchInboxError, agentLaunchInboxRouting, withLegacyPeerInboxReason, + orchestrationV2RunFailure, } from "@t3tools/contracts"; import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; -import { latestExecutedRun, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; +import { + latestExecutedRun, + latestRootProviderFailure, + runRanAfter, +} from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; import { @@ -1058,11 +1063,25 @@ function runExecutedModel( : (latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.model ?? null); } +/** A failed run's typed provider error, read from its own error items only. */ +function runFailure( + run: OrchestrationV2Run | undefined, + turnItems: Parameters[1], +) { + const failure = run === undefined ? null : latestRootProviderFailure(run, turnItems); + return run === undefined || failure === null + ? undefined + : orchestrationV2RunFailure(run, failure); +} + function threadRun( projection: Pick, run: OrchestrationV2Run, ): OrchestratorMcpThreadRun { return { + ...(run.providerFailoverOfRunId === undefined + ? {} + : { providerFailoverOfRunId: run.providerFailoverOfRunId }), runId: run.id, ordinal: run.ordinal, status: run.status, @@ -1841,6 +1860,7 @@ const make = Effect.gen(function* () { instanceId: task.providerInstanceId, model: task.model, }; + const latestTerminalFailure = runFailure(terminalRun, childProjection.turnItems); const result = { taskId: task.id, childThreadId: task.childThreadId, @@ -1864,6 +1884,7 @@ const make = Effect.gen(function* () { latestTerminalStatus: terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null, latestTerminalSummary: latestTerminalSummary === derivedResult ? null : latestTerminalSummary, + ...(latestTerminalFailure === undefined ? {} : { latestTerminalFailure }), latestTerminalResultContextTransferId: latestTerminalResultContextTransferId === resultContextTransferId ? null @@ -3482,30 +3503,34 @@ const make = Effect.gen(function* () { const runs = target.runs .toSorted((left, right) => right.ordinal - left.ordinal) .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT); - // Only an agent-created thread's latest run is judged, so a read loads one run's replies and notices. + // Only the latest run is judged, and only when it is an agent's or failed, so a read loads + // one run's replies and notices. const latestRun = runs[0]; - const latestAlert = + const latestRecords = latestRun === undefined || - target.thread.createdBy !== "agent" || + (target.thread.createdBy !== "agent" && latestRun.status !== "failed") || !ThreadManagementService.isTerminalRunStatus(latestRun.status) ? undefined - : subagentResultForRun( - { - ...target, - ...(yield* threadManagement - .getThreadRecords(input.threadId, ["messages", "turnItems"], { - messageRoles: ["assistant"], - messageRunIds: [latestRun.id], - turnItemRunId: latestRun.id, - turnItemTypes: ["assistant_message", "error", "system_notice"], - }) - .pipe(Effect.mapError(threadManagementFailure))), - }, - latestRun, - ).workerAlert; + : yield* threadManagement + .getThreadRecords(input.threadId, ["messages", "turnItems"], { + messageRoles: ["assistant"], + messageRunIds: [latestRun.id], + turnItemRunId: latestRun.id, + turnItemTypes: ["assistant_message", "error", "system_notice"], + }) + .pipe(Effect.mapError(threadManagementFailure)); + const latestAlert = + latestRun === undefined || + latestRecords === undefined || + target.thread.createdBy !== "agent" + ? undefined + : subagentResultForRun({ ...target, ...latestRecords }, latestRun).workerAlert; + const latestFailure = + latestRecords === undefined ? undefined : runFailure(latestRun, latestRecords.turnItems); const recentRuns = runs.map((run) => ({ ...threadRun(target, run), ...(run === latestRun && latestAlert !== undefined ? { workerAlert: latestAlert } : {}), + ...(run === latestRun && latestFailure !== undefined ? { failure: latestFailure } : {}), })); const { items, start } = timelineItemsWithinBudget( { thread, recentRuns, nextPosition: null, hasMore: false, earlierPosition: null }, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 45b0353a88993..80afd4c3da482 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -5248,6 +5248,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload.error.codexErrorInfo, notificationCode, ), + httpStatus: codexErrorHttpStatus(payload.error.codexErrorInfo), }), payload.error, ), @@ -5278,6 +5279,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ? "transport_error" : "provider_error", retryable: true, + httpStatus: codexErrorHttpStatus(payload.error.codexErrorInfo), }), payload.error, ); @@ -6442,6 +6444,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( message: input.failureMessage, code: failureCode, class: failureClass, + httpStatus: codexErrorHttpStatus(input.failureErrorInfo), }), input.failureMessage, ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index a3dbdb3942fea..ad19426ca3c27 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -23,6 +23,7 @@ import { usageLimitBlockedRun, } from "@t3tools/shared/orchestrationV2ThreadError"; import { canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-definitions/registry"; +import { admitProviderFailover } from "./providerFailover.ts"; import { threadPullRequestsOf } from "../sourceControl/threadPullRequests.ts"; import { normalizeThreadPullRequestKey, @@ -1097,6 +1098,7 @@ function carriesDigest( | "restartContinuationOfRunId" | "manualContinuationOfRunId" | "usageLimitContinuationOfRunId" + | "providerFailoverOfRunId" >, message: { readonly text: string; @@ -1109,6 +1111,7 @@ function carriesDigest( run.restartContinuationOfRunId === undefined && run.manualContinuationOfRunId === undefined && run.usageLimitContinuationOfRunId === undefined && + run.providerFailoverOfRunId === undefined && message.idleCompaction === undefined && !isNativeMaintenanceCommand(message) && parseGoalCommand(message) === null @@ -7061,6 +7064,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.manualContinuationOfRunId, command.restartContinuationOfRunId, command.usageLimitContinuationOfRunId, + command.providerFailover?.ofRunId, command.steerFollowUpOfRunId, ...(command.dispatchMode.type === "steer_active" || command.dispatchMode.type === "restart_active" @@ -7122,6 +7126,44 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); return; } + if (command.providerFailover !== undefined) { + const admission = + command.dispatchMode.type === "start_immediately" && command.modelSelection === undefined + ? admitProviderFailover( + command.providerFailover, + projection, + // The command projection keeps only user messages and errors; effects need every item. + (yield* projectionStore + .getThreadRecords(command.threadId, ["turnItems"], { + turnItemRunId: command.providerFailover.ofRunId, + }) + .pipe(mapDispatchError(command))).turnItems, + yield* serverSettings.getSettings.pipe(Effect.orDie), + ) + : null; + if (admission?.type === "duplicate") { + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: yield* DateTime.now, + payload: projection.thread, + }); + return; + } + if (admission?.type !== "admitted") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: + admission?.refusal ?? + "A provider failover starts immediately and takes its model from its candidates.", + }); + } + command = { ...command, modelSelection: admission.target }; + } const activeProviderInstanceId = projection.providerThreads.find( (candidate) => candidate.id === projection.thread.activeProviderThreadId, )?.providerInstanceId; @@ -8116,6 +8158,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.usageLimitContinuationOfRunId === undefined ? {} : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }), + ...(command.providerFailover === undefined + ? {} + : { providerFailoverOfRunId: command.providerFailover.ofRunId }), ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }), ...(freshContext ? { freshContext: true } : {}), ...(command.delivery === undefined ? {} : { delivery: command.delivery }), @@ -8534,6 +8579,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.usageLimitContinuationOfRunId === undefined ? {} : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }), + ...(command.providerFailover === undefined + ? {} + : { providerFailoverOfRunId: command.providerFailover.ofRunId }), ...(dispatchMode.type === "defer_start" && dispatchMode.workspaceStrategy !== undefined ? { workspacePreparation: dispatchMode.workspaceStrategy } : {}), @@ -9346,6 +9394,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.usageLimitContinuationOfRunId === undefined ? {} : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }), + ...(command.providerFailover === undefined + ? {} + : { providerFailoverOfRunId: command.providerFailover.ofRunId }), ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }), ...wakeWorkStartedAt(projection, command), ...(command.delivery === undefined ? {} : { delivery: command.delivery }), diff --git a/apps/server/src/orchestration-v2/providerFailover.ts b/apps/server/src/orchestration-v2/providerFailover.ts new file mode 100644 index 0000000000000..b78abcfc70eb0 --- /dev/null +++ b/apps/server/src/orchestration-v2/providerFailover.ts @@ -0,0 +1,158 @@ +import { + type ModelSelection, + type OrchestrationV2Command, + OrchestrationV2ProviderFailoverRefused, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, + type OrchestrationV2TurnItem, + orchestrationV2RunFailure, + resolveProjectProviderInstanceEnabled, + type ServerSettings, +} from "@t3tools/contracts"; +import { + latestExecutedRun, + latestRootProviderFailure, +} from "@t3tools/shared/orchestrationV2ThreadError"; + +type FailoverRequest = NonNullable< + Extract["providerFailover"] +>; +type Refusal = ConstructorParameters[0]; + +/** + * Items a turn records without acting on anything outside the conversation. Any other item, a + * command, file change, tool call, search, approval or subagent, may have had an effect, so + * replaying the prompt elsewhere could repeat it. + */ +const EFFECT_FREE_ITEM_TYPES: ReadonlySet = new Set([ + "user_message", + "assistant_message", + "reasoning", + "error", + "system_notice", + "run", + "node", + "provider_thread", + "checkpoint", + "compaction", + "handoff", + "notification", + "thread_created", +]); + +// The orchestrator's own workspace setup row, recorded before any provider turn; see Orchestrator.ts. +const WORKSPACE_PREPARATION_INPUT = "Preparing workspace"; + +const mayHaveActed = (item: OrchestrationV2TurnItem) => + !EFFECT_FREE_ITEM_TYPES.has(item.type) && + !( + item.type === "command_execution" && + item.providerTurnId === null && + item.input === WORKSPACE_PREPARATION_INPUT + ); + +const selectionKey = (selection: Pick) => + `${selection.instanceId}\u0000${selection.model}`; + +export type ProviderFailoverAdmission = + | { readonly type: "admitted"; readonly target: ModelSelection } + | { readonly type: "duplicate" } + | { readonly type: "refused"; readonly refusal: OrchestrationV2ProviderFailoverRefused }; + +/** + * Admits a failed run's continuation on another provider only when replaying its prompt there + * repeats nothing: a payment, rate-limit, auth or quota failure on the thread's latest run, no + * open request, and no item that may have acted. The target is the first candidate that is + * included, enabled here and not yet tried in the run's lineage. + */ +export function admitProviderFailover( + request: FailoverRequest, + projection: Pick, + /** Every turn item of the failed run, of all types. */ + sourceTurnItems: ReadonlyArray, + settings: Pick< + ServerSettings, + "providerFailover" | "providerInstances" | "projectSettingsOverrides" + >, +): ProviderFailoverAdmission { + // A run continues once; a repeated request accepts without starting another. + if (projection.runs.some((run) => run.providerFailoverOfRunId === request.ofRunId)) { + return { type: "duplicate" }; + } + const source = projection.runs.find((run) => run.id === request.ofRunId); + const providerFailure = + source === undefined ? null : latestRootProviderFailure(source, sourceTurnItems); + const failure = + source === undefined || providerFailure === null + ? null + : orchestrationV2RunFailure(source, providerFailure); + const refuse = ( + reason: Refusal["reason"], + candidates: Refusal["candidates"] = [], + ): ProviderFailoverAdmission => ({ + type: "refused", + refusal: new OrchestrationV2ProviderFailoverRefused({ + runId: request.ofRunId, + reason, + failure, + candidates, + }), + }); + if (!settings.providerFailover.enabled) return refuse("disabled"); + if ( + source === undefined || + source.status !== "failed" || + latestExecutedRun(projection.runs)?.id !== source.id || + projection.thread.archivedAt !== null || + projection.thread.deletedAt !== null + ) { + return refuse("not_latest_failed_run"); + } + if (failure === null || failure.class === "other") return refuse("not_failover_class"); + if (projection.runtimeRequests.some((runtimeRequest) => runtimeRequest.status === "pending")) { + return refuse("pending_request"); + } + if (sourceTurnItems.some((item) => item.runId === source.id && mayHaveActed(item))) { + return refuse("side_effects"); + } + + const runs = new Map(projection.runs.map((run) => [run.id, run])); + const tried = new Set(); + let hops = 0; + for ( + let current: OrchestrationV2Run | undefined = source; + current !== undefined && !tried.has(selectionKey(current.modelSelection)); + current = + current.providerFailoverOfRunId === undefined + ? undefined + : runs.get(current.providerFailoverOfRunId) + ) { + tried.add(selectionKey(current.modelSelection)); + if (current.providerFailoverOfRunId !== undefined) hops += 1; + } + if (hops >= settings.providerFailover.maxAttempts) return refuse("exhausted"); + + const included = new Set(settings.providerFailover.includedProviderInstanceIds); + const skipped: Array = []; + for (const candidate of request.candidates) { + const skip = tried.has(selectionKey(candidate)) + ? "already_tried" + : !included.has(candidate.instanceId) + ? "not_included" + : !Object.hasOwn(settings.providerInstances, candidate.instanceId) || + !resolveProjectProviderInstanceEnabled( + settings, + projection.thread.projectId, + candidate.instanceId, + ) + ? "unavailable" + : null; + if (skip === null) return { type: "admitted", target: candidate }; + skipped.push({ + providerInstanceId: candidate.instanceId, + model: candidate.model, + skipped: skip, + }); + } + return refuse("exhausted", skipped); +} diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 94a2bf650fb23..dbcc7dc2e2136 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -22,7 +22,10 @@ import { TurnItemId, type ModelSelection, type OrchestrationV2DomainEvent, + type OrchestrationV2ProviderFailure, + OrchestrationV2ProviderFailoverRefused, type OrchestrationV2Run, + orchestrationV2RunFailure, type OrchestrationV2ShellSnapshot, type OrchestrationV2RuntimeRequest, ProjectId, @@ -13016,3 +13019,477 @@ it.layer(layerQueueResumeDisabledInstanceTest)( ); }, ); + +const failoverProjectId = ProjectId.make("project:provider-failover"); +const meteredInstanceId = ProviderInstanceId.make("metered_api"); + +const layerProviderFailoverTest = Layer.mergeAll( + RuntimeLayer.layer, + RuntimeLayer.layerEventSink, + ProjectStore.layer, + ProjectionStore.layer, + EffectOutbox.layer, + ThreadCommandExecutor.layer, +).pipe( + Layer.provide(McpSessionRegistryTestkit.layer), + Layer.provide(McpProviderSessions.layer), + Layer.provide(SqlitePersistence.layerMemory), + Layer.provide(layerCheckpointStoreTest), + Layer.provide(layerServerConfig), + Layer.provide( + ServerSettings.layerTest({ + providerInstances: testProviderInstances, + projectSettingsOverrides: { + [failoverProjectId]: { providerInstances: { [antigravityInstanceId]: { enabled: false } } }, + }, + providerFailover: { + enabled: true, + includedProviderInstanceIds: [alternateInstanceId, claudeInstanceId, antigravityInstanceId], + maxAttempts: 3, + }, + }), + ), + Layer.provide(layerTestProviderInstanceRegistry), + Layer.provide(layerGitWorkflowTest), + Layer.provide(layerProjectServiceTest), + Layer.provide(layerPlatformTest), + Layer.provide(ProviderRegistryMock.layer()), +); + +const claudeTarget = { instanceId: claudeInstanceId, model: "claude-haiku-5-5" } as const; +const alternateTarget = { instanceId: alternateInstanceId, model: "gpt-5.5" } as const; +const disabledTarget = { instanceId: antigravityInstanceId, model: "gemini" } as const; +const meteredTarget = { instanceId: meteredInstanceId, model: "metered" } as const; + +const failoverFailures: Record< + "payment" | "rate_limit" | "auth" | "quota" | "policy", + OrchestrationV2ProviderFailure +> = { + payment: { + class: "provider_error", + message: "Payment required.", + code: "api_error_402", + retryable: null, + httpStatus: 402, + }, + rate_limit: { + class: "usage_limit", + message: "Too many requests.", + code: "responseTooManyFailedAttempts", + retryable: false, + httpStatus: 429, + }, + auth: { + class: "provider_error", + message: "Unauthorized.", + code: "unauthorized", + retryable: null, + httpStatus: 401, + }, + quota: { + class: "usage_limit", + message: "Plan limit reached.", + code: "usageLimitExceeded", + retryable: null, + }, + policy: { + class: "provider_error", + message: "Refused.", + code: "content_policy_violation", + retryable: null, + httpStatus: 403, + }, +}; + +type FailoverScenario = { + readonly failure: keyof typeof failoverFailures; + readonly candidates: ReadonlyArray; + readonly sideEffect?: true; + readonly pendingApproval?: true; + readonly repeat?: true; + readonly expected: + | { readonly admitted: ModelSelection } + | { + readonly refused: OrchestrationV2ProviderFailoverRefused["reason"]; + readonly skipped?: OrchestrationV2ProviderFailoverRefused["candidates"]; + }; +}; + +it.layer(layerProviderFailoverTest)("provider failover", (it) => { + it.effect.each<[string, FailoverScenario]>([ + [ + "402", + { failure: "payment", candidates: [claudeTarget], expected: { admitted: claudeTarget } }, + ], + [ + "429", + { failure: "rate_limit", candidates: [claudeTarget], expected: { admitted: claudeTarget } }, + ], + ["auth", { failure: "auth", candidates: [claudeTarget], expected: { admitted: claudeTarget } }], + [ + "quota", + { failure: "quota", candidates: [claudeTarget], expected: { admitted: claudeTarget } }, + ], + [ + "an unavailable or metered provider, skipped", + { + failure: "payment", + candidates: [disabledTarget, meteredTarget, alternateTarget], + expected: { admitted: alternateTarget }, + }, + ], + [ + "a duplicate request, accepted once", + { + failure: "payment", + candidates: [claudeTarget], + repeat: true, + expected: { admitted: claudeTarget }, + }, + ], + [ + "a policy denial, refused", + { + failure: "policy", + candidates: [claudeTarget], + expected: { refused: "not_failover_class" }, + }, + ], + [ + "a pending approval, refused", + { + failure: "payment", + candidates: [claudeTarget], + pendingApproval: true, + expected: { refused: "pending_request" }, + }, + ], + [ + "a partial run with effects, refused", + { + failure: "payment", + candidates: [claudeTarget], + sideEffect: true, + expected: { refused: "side_effects" }, + }, + ], + [ + "an exhausted list, refused with each skip", + { + failure: "quota", + candidates: [modelSelection, disabledTarget, meteredTarget], + expected: { + refused: "exhausted", + skipped: [ + { + providerInstanceId: modelSelection.instanceId, + model: modelSelection.model, + skipped: "already_tried", + }, + { + providerInstanceId: disabledTarget.instanceId, + model: disabledTarget.model, + skipped: "unavailable", + }, + { + providerInstanceId: meteredTarget.instanceId, + model: meteredTarget.model, + skipped: "not_included", + }, + ], + }, + }, + ], + ])("continues a failed run on another provider: %s", ([name, scenario]) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const events = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make(`failover:${name}`); + const now = yield* DateTime.now; + yield* seedProject({ + projectId: failoverProjectId, + title: "Failover project", + workspaceRoot: process.cwd(), + defaultModelSelection: modelSelection, + createdAt: DateTime.formatIso(now), + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: failoverProjectId, + title: "Failing thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "agent", + creationSource: "mcp", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:start`), + threadId, + messageId: MessageId.make(`${threadId}:start`), + text: "Do the task.", + attachments: [], + dispatchMode: { type: "defer_start" }, + createdBy: "agent", + creationSource: "mcp", + }); + const [source] = (yield* orchestrator.getThreadProjection(threadId)).runs as [ + OrchestrationV2Run, + ]; + const item = (id: string, ordinal: number) => ({ + id: TurnItemId.make(`${threadId}:${id}`), + threadId, + runId: source.id, + nodeId: source.rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + startedAt: now, + completedAt: now, + updatedAt: now, + }); + yield* events.write({ + events: [ + { + id: EventId.make(`${threadId}:failed`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...source, status: "failed", completedAt: now }, + }, + { + id: EventId.make(`${threadId}:error`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + ...item("error", 3), + type: "error", + status: "failed", + title: "Provider error", + failure: failoverFailures[scenario.failure], + }, + }, + ...(scenario.pendingApproval + ? [ + { + id: EventId.make(`${threadId}:approval`), + type: "runtime-request.updated" as const, + threadId, + runId: source.id, + occurredAt: now, + payload: { + id: RuntimeRequestId.make(`${threadId}:approval`), + nodeId: source.rootNodeId!, + providerTurnId: null, + nativeRequestRef: null, + kind: "command" as const, + status: "pending" as const, + responseCapability: { type: "message" as const }, + createdAt: now, + resolvedAt: null, + }, + }, + ] + : []), + ...(scenario.sideEffect + ? [ + { + id: EventId.make(`${threadId}:command`), + type: "turn-item.updated" as const, + threadId, + occurredAt: now, + payload: { + ...item("command", 2), + type: "command_execution" as const, + status: "completed" as const, + title: "git push", + input: "git push", + }, + }, + ] + : []), + ], + }); + const failed = yield* orchestrator.getThreadProjection(threadId); + const errorItem = failed.turnItems.find((turnItem) => turnItem.type === "error"); + // The typed error survives the event store and projection read. + assert.deepEqual( + errorItem?.type === "error" ? orchestrationV2RunFailure(source, errorItem.failure) : null, + { + providerInstanceId: modelSelection.instanceId, + model: modelSelection.model, + httpStatus: failoverFailures[scenario.failure].httpStatus ?? null, + class: scenario.failure === "policy" ? "other" : scenario.failure, + code: failoverFailures[scenario.failure].code, + retryable: failoverFailures[scenario.failure].retryable, + }, + ); + const failover = (suffix: string) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:failover:${suffix}`), + threadId, + messageId: MessageId.make(`${threadId}:failover:${suffix}`), + providerFailover: { ofRunId: source.id, candidates: scenario.candidates }, + text: "Continue the task.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "mcp", + }); + + if ("refused" in scenario.expected) { + const error = yield* failover("first").pipe(Effect.flip); + assert.instanceOf(error.cause, OrchestrationV2ProviderFailoverRefused); + const refusal = error.cause as OrchestrationV2ProviderFailoverRefused; + assert.equal(refusal.reason, scenario.expected.refused); + assert.equal(refusal.runId, source.id); + assert.equal( + refusal.failure?.httpStatus, + failoverFailures[scenario.failure].httpStatus ?? null, + ); + assert.deepEqual(refusal.candidates, scenario.expected.skipped ?? []); + assert.lengthOf((yield* orchestrator.getThreadProjection(threadId)).runs, 1); + return; + } + yield* failover("first"); + if (scenario.repeat) yield* failover("second"); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.lengthOf(after.runs, 2); + const continued = after.runs.find((run) => run.id !== source.id); + assert.equal(continued?.providerFailoverOfRunId, source.id); + assert.deepEqual(continued?.modelSelection, scenario.expected.admitted); + assert.equal(continued?.providerInstanceId, scenario.expected.admitted.instanceId); + }), + ); + it.effect("bounds a run lineage and never retries a provider it already tried", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const events = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("failover:lineage"); + const now = yield* DateTime.now; + yield* seedProject({ + projectId: failoverProjectId, + title: "Failover project", + workspaceRoot: process.cwd(), + defaultModelSelection: modelSelection, + createdAt: DateTime.formatIso(now), + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: failoverProjectId, + title: "Failing thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "agent", + creationSource: "mcp", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:start`), + threadId, + messageId: MessageId.make(`${threadId}:start`), + text: "Do the task.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "mcp", + }); + const failLatest = (hop: number) => + Effect.gen(function* () { + const runs = (yield* orchestrator.getThreadProjection(threadId)).runs; + const run = runs.toSorted((a, b) => b.ordinal - a.ordinal)[0]!; + yield* events.write({ + events: [ + { + id: EventId.make(`${threadId}:failed:${hop}`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + ...run, + status: "failed", + completedAt: DateTime.add(now, { seconds: hop }), + }, + }, + { + id: EventId.make(`${threadId}:error:${hop}`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:error:${hop}`), + threadId, + runId: run.id, + nodeId: run.rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 3, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "error", + status: "failed", + title: "Provider error", + failure: failoverFailures.payment, + }, + }, + ], + }); + return run; + }); + const failover = (hop: number, ofRunId: RunId) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:failover:${hop}`), + threadId, + messageId: MessageId.make(`${threadId}:failover:${hop}`), + providerFailover: { + ofRunId, + candidates: [modelSelection, claudeTarget, alternateTarget], + }, + text: "Continue the task.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "mcp", + }); + + yield* failover(1, (yield* failLatest(1)).id); + yield* failover(2, (yield* failLatest(2)).id); + const runs = (yield* orchestrator.getThreadProjection(threadId)).runs.toSorted( + (a, b) => a.ordinal - b.ordinal, + ); + assert.deepEqual( + runs.map((run) => [run.modelSelection.instanceId, run.providerFailoverOfRunId]), + [ + [modelSelection.instanceId, undefined], + [claudeTarget.instanceId, runs[0]!.id], + [alternateTarget.instanceId, runs[1]!.id], + ], + ); + const error = yield* failover(3, (yield* failLatest(3)).id).pipe(Effect.flip); + const refusal = error.cause as OrchestrationV2ProviderFailoverRefused; + assert.equal(refusal.reason, "exhausted"); + assert.deepEqual( + refusal.candidates.map((candidate) => candidate.skipped), + ["already_tried", "already_tried", "already_tried"], + ); + }), + ); +}); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 13659ac2700fb..3a9d4ff2667e7 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -619,11 +619,9 @@ export function applyOrchestrationV2ThreadVisit, @@ -669,7 +667,7 @@ export function nextFounderSeenMessage( ): FounderSeenMessages { const current = thread.seenMessageByFounder; if (current?.[founder] === messageId) return current ?? { [founder]: messageId }; - return { ...(current ?? {}), [founder]: messageId }; + return { ...current, [founder]: messageId }; } /** A thread another agent drives: a local subagent or a task delegated from a linked environment. */ @@ -895,6 +893,8 @@ export const OrchestrationV2Run = Schema.Struct({ restartContinuationOfRunId: Schema.optional(RunId), manualContinuationOfRunId: Schema.optional(RunId), usageLimitContinuationOfRunId: Schema.optional(RunId), + /** The failed run this one continues on another provider; it and its ancestors form one lineage. */ + providerFailoverOfRunId: Schema.optional(RunId), delegatedTaskId: Schema.optional(NodeId), workStartedAt: Schema.optional(Schema.DateTimeUtc), restartCancelledBackgroundWork: Schema.optional( @@ -1764,9 +1764,103 @@ export const OrchestrationV2ProviderFailure = Schema.Struct({ code: Schema.NullOr(OrchestrationV2ProviderFailureCode), retryable: Schema.NullOr(Schema.Boolean), resetAt: Schema.optional(Schema.NullOr(IsoDateTime)), + /** The provider's HTTP status, when it reported one. */ + httpStatus: Schema.optional( + Schema.NullOr(Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 599 }))), + ), }); export type OrchestrationV2ProviderFailure = typeof OrchestrationV2ProviderFailure.Type; +/** Why a failed run may move to another provider; `other` never does. */ +export const OrchestrationV2ProviderFailoverClass = Schema.Literals([ + "payment", + "rate_limit", + "auth", + "quota", + "other", +]); +export type OrchestrationV2ProviderFailoverClass = typeof OrchestrationV2ProviderFailoverClass.Type; + +// A refusal on policy or safety grounds fails the same way on any provider. +const POLICY_DENIAL_CODE = /polic|safety|moderat|content.?filter|refus|guardrail|violat|cyber/iu; +const AUTH_CODE = /^(?:unauthori[sz]ed|unauthenticated|authentication.*|invalid.?api.?key)$/iu; +const RATE_LIMIT_CODE = /rate.?limit/iu; + +/** Unknown or ambiguous failures stay `other`, so they never fail over. */ +export function providerFailoverClass( + failure: Pick, +): OrchestrationV2ProviderFailoverClass { + const code = failure.code ?? ""; + if ( + failure.class === "validation_error" || + failure.class === "permission_error" || + POLICY_DENIAL_CODE.test(code) + ) + return "other"; + if (failure.httpStatus === 402) return "payment"; + if (failure.httpStatus === 401 || AUTH_CODE.test(code)) return "auth"; + if (failure.httpStatus === 429 || RATE_LIMIT_CODE.test(code)) return "rate_limit"; + if (failure.class === "usage_limit") return "quota"; + return "other"; +} + +/** A failed run's provider error for readback. It carries no message text, which may quote the prompt. */ +export const OrchestrationV2RunFailure = Schema.Struct({ + providerInstanceId: ProviderInstanceId, + model: Schema.String, + httpStatus: Schema.NullOr(Schema.Int), + class: OrchestrationV2ProviderFailoverClass, + code: Schema.NullOr(Schema.String), + retryable: Schema.NullOr(Schema.Boolean), +}); +export type OrchestrationV2RunFailure = typeof OrchestrationV2RunFailure.Type; + +export function orchestrationV2RunFailure( + run: Pick, + failure: OrchestrationV2ProviderFailure, +): OrchestrationV2RunFailure { + return { + providerInstanceId: run.modelSelection.instanceId, + model: run.modelSelection.model, + httpStatus: failure.httpStatus ?? null, + class: providerFailoverClass(failure), + code: failure.code, + retryable: failure.retryable, + }; +} + +export const OrchestrationV2ProviderFailoverRefusalReason = Schema.Literals([ + "disabled", + "not_failover_class", + "not_latest_failed_run", + "pending_request", + "side_effects", + "exhausted", +]); +export type OrchestrationV2ProviderFailoverRefusalReason = + typeof OrchestrationV2ProviderFailoverRefusalReason.Type; + +/** Why a provider failover was not admitted. Candidates lists each one passed over and why. */ +export class OrchestrationV2ProviderFailoverRefused extends Schema.TaggedError()( + "OrchestrationV2ProviderFailoverRefused", + { + runId: RunId, + reason: OrchestrationV2ProviderFailoverRefusalReason, + failure: Schema.NullOr(OrchestrationV2RunFailure), + candidates: Schema.Array( + Schema.Struct({ + providerInstanceId: ProviderInstanceId, + model: Schema.String, + skipped: Schema.Literals(["not_included", "unavailable", "already_tried"]), + }), + ), + }, +) { + override get message(): string { + return `Provider failover refused (${this.reason}) for run ${this.runId}.`; + } +} + export const OrchestrationV2ProviderRetry = Schema.Struct({ attempt: PositiveInt, maxAttempts: Schema.NullOr(PositiveInt), @@ -3657,6 +3751,16 @@ export const OrchestrationV2Command = Schema.Union([ restartContinuationOfRunId: Schema.optional(RunId), usageLimitContinuationOfRunId: Schema.optional(RunId), manualContinuationOfRunId: Schema.optional(RunId), + /** Continue a failed run on the first eligible candidate, in order. Replaces `modelSelection`. */ + providerFailover: Schema.optional( + Schema.Struct({ + ofRunId: RunId, + candidates: Schema.Array(ModelSelection).check( + Schema.isMinLength(1), + Schema.isMaxLength(8), + ), + }), + ), steerFollowUpOfRunId: Schema.optional(RunId), steerFollowUpAfterRunOrdinal: Schema.optional(NonNegativeInt), usageLimitRecoveryRequestId: Schema.optional(CommandId), diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index b7278fc9c9984..019f77ddb06c6 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -43,6 +43,7 @@ import { OrchestrationV2DelegatedFrom, OrchestrationV2DeliveryClass, OrchestrationV2DigestCategory, + OrchestrationV2RunFailure, OrchestrationV2RunStatus, OrchestrationV2TurnItemStatus, OrchestrationV2WorkerAlert, @@ -249,6 +250,7 @@ export const OrchestratorMcpDelegateTaskResult = Schema.Struct({ latestTerminalRunId: Schema.NullOr(RunId), latestTerminalStatus: Schema.NullOr(OrchestratorMcpTerminalDelegatedTaskStatus), latestTerminalSummary: Schema.NullOr(Schema.String), + latestTerminalFailure: Schema.optional(OrchestrationV2RunFailure), latestTerminalResultContextTransferId: Schema.NullOr(ContextTransferId), providerInstanceId: ProviderInstanceId, model: Schema.NullOr(Schema.String), @@ -539,6 +541,9 @@ export const OrchestratorMcpThreadRun = Schema.Struct({ model: Schema.String, executedModel: Schema.optional(OrchestratorMcpExecutedModel), workerAlert: Schema.optional(OrchestratorMcpWorkerAlert), + /** Present on a failed latest run with a provider error. */ + failure: Schema.optional(OrchestrationV2RunFailure), + providerFailoverOfRunId: Schema.optional(RunId), requestedAt: IsoDateTime, startedAt: Schema.NullOr(IsoDateTime), completedAt: Schema.NullOr(IsoDateTime), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index f95c6cced897e..7a0783e93e52e 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -750,6 +750,23 @@ export const SessionSpendGuardSettings = Schema.Struct({ }); export type SessionSpendGuardSettings = typeof SessionSpendGuardSettings.Type; +/** + * Closura: a failed run may continue on the next provider in a caller's ordered list only on a + * payment, rate-limit, auth or quota failure with no side effects. Off until Home's routing + * table supplies the list; `includedProviderInstanceIds` names the only targets that bill no + * extra spend, and `maxAttempts` bounds one run lineage. + */ +export const ProviderFailoverSettings = Schema.Struct({ + enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + includedProviderInstanceIds: Schema.Array(ProviderInstanceId).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), + maxAttempts: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 8 })).pipe( + Schema.withDecodingDefault(Effect.succeed(3)), + ), +}); +export type ProviderFailoverSettings = typeof ProviderFailoverSettings.Type; + export const CodexSettings = makeProviderSettingsSchema( { setupMode: Schema.optionalKey(Schema.Literals(["managed", "existing"])).pipe( @@ -1747,6 +1764,7 @@ export const ServerSettings = Schema.Struct({ * warning without stopping, and `off` disables the guard. */ sessionSpendGuard: SessionSpendGuardSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))), + providerFailover: ProviderFailoverSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))), // Schema.Unknown preserves unknown-driver configs across versions; see providerInstance.ts. providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe( @@ -2165,6 +2183,15 @@ export const ServerSettingsPatch = Schema.Struct({ fallbackRate: Schema.optionalKey(UsageModelPriceOverride), }), ), + providerFailover: Schema.optionalKey( + Schema.Struct({ + enabled: Schema.optionalKey(Schema.Boolean), + includedProviderInstanceIds: Schema.optionalKey(Schema.Array(ProviderInstanceId)), + maxAttempts: Schema.optionalKey( + Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 8 })), + ), + }), + ), observability: Schema.optionalKey( Schema.Struct({ otlpTracesUrl: Schema.optionalKey(TrimmedString), diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index c222ef9b27462..bdce14eb37005 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -7,6 +7,7 @@ import { ProviderSetupError, ProviderThreadId, ProviderTurnId, + providerFailoverClass, RunId, ThreadId, } from "@t3tools/contracts"; @@ -59,6 +60,33 @@ it("redacts credentials whose key names end in a credential word", () => { ); }); +it("keeps a provider failure's HTTP status and classes it for failover, failing closed", () => { + for (const [input, httpStatus, failoverClass] of [ + [{ class: "provider_error", code: "api_error_402" }, 402, "payment"], + [{ class: "usage_limit", code: "api_error_429" }, 429, "rate_limit"], + [ + { class: "usage_limit", code: "responseTooManyFailedAttempts", httpStatus: 429 }, + 429, + "rate_limit", + ], + [{ class: "usage_limit", code: "rateLimitExceeded" }, undefined, "rate_limit"], + [{ class: "provider_error", code: "api_error_401" }, 401, "auth"], + [{ class: "provider_error", code: "unauthorized" }, undefined, "auth"], + [{ class: "usage_limit", code: "usageLimitExceeded" }, undefined, "quota"], + // Policy and safety denials, sign-out prompts and other errors never fail over. + [{ class: "provider_error", code: "content_policy_violation", httpStatus: 403 }, 403, "other"], + [{ class: "usage_limit", code: "safety_refusal", httpStatus: 429 }, 429, "other"], + [{ class: "permission_error", code: null }, undefined, "other"], + [{ class: "provider_error", code: "api_error_403" }, 403, "other"], + [{ class: "provider_error", code: "api_error_500" }, 500, "other"], + [{ class: "transport_error", code: null, httpStatus: 0 }, undefined, "other"], + ] as const) { + const failure = makeProviderFailure({ message: "Provider failed.", ...input }); + assert.equal(failure.httpStatus, httpStatus, input.code ?? input.class); + assert.equal(providerFailoverClass(failure), failoverClass, input.code ?? input.class); + } +}); + it("reports an oversized provider request as not retryable instead of the gateway's error page", () => { for (const message of [ "413 \n413 Request Entity Too Large\n\n

413 Request Entity Too Large

\n
nginx
\n\n", diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 136d867e521c2..c41e76e6eaec2 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -281,6 +281,7 @@ export function makeProviderFailure(input: { readonly class?: OrchestrationV2ProviderFailureClass; readonly retryable?: boolean | null; readonly resetAt?: string | null; + readonly httpStatus?: number | null; }): OrchestrationV2ProviderFailure { const curated = curatedCauseMessages(input.cause); const requestTooLarge = @@ -294,11 +295,14 @@ export function makeProviderFailure(input: { const code = rawCode === null ? null : boundedText(rawCode, MAX_PROVIDER_FAILURE_CODE_LENGTH) || null; + // Claude reports its status only as an `api_error_` code. + const status = input.httpStatus ?? Number(/^api_error_(\d{3})$/u.exec(code ?? "")?.[1]); return { class: input.class ?? "unknown", message: message || DEFAULT_PROVIDER_FAILURE_MESSAGE, code, retryable: requestTooLarge ? false : (input.retryable ?? null), + ...(Number.isInteger(status) && status >= 100 && status <= 599 ? { httpStatus: status } : {}), ...(input.class === "usage_limit" && input.resetAt != null && Number.isFinite(Date.parse(input.resetAt))