-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfallback-state.ts
More file actions
179 lines (160 loc) · 5.07 KB
/
fallback-state.ts
File metadata and controls
179 lines (160 loc) · 5.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import type { FallbackState, FallbackResult, FallbackPluginConfig, FallbackPlan, FallbackPlanFailure } from "./types"
import { logInfo } from "./logger"
export interface FallbackStateSnapshot {
currentModel: string
fallbackIndex: number
failedModels: Map<string, number>
attemptCount: number
pendingFallbackModel?: string
}
export function snapshotFallbackState(state: FallbackState): FallbackStateSnapshot {
return {
currentModel: state.currentModel,
fallbackIndex: state.fallbackIndex,
failedModels: new Map(state.failedModels),
attemptCount: state.attemptCount,
pendingFallbackModel: state.pendingFallbackModel,
}
}
export function restoreFallbackState(
state: FallbackState,
snapshot: FallbackStateSnapshot
): void {
state.currentModel = snapshot.currentModel
state.fallbackIndex = snapshot.fallbackIndex
state.failedModels = new Map(snapshot.failedModels)
state.attemptCount = snapshot.attemptCount
state.pendingFallbackModel = snapshot.pendingFallbackModel
}
export function createFallbackState(originalModel: string): FallbackState {
return {
originalModel,
currentModel: originalModel,
fallbackIndex: -1,
failedModels: new Map<string, number>(),
attemptCount: 0,
pendingFallbackModel: undefined,
}
}
export function isModelInCooldown(
model: string,
state: FallbackState,
cooldownSeconds: number
): boolean {
const failedAt = state.failedModels.get(model)
if (failedAt === undefined) return false
const cooldownMs = cooldownSeconds * 1000
return Date.now() - failedAt < cooldownMs
}
export function findNextAvailableFallback(
state: FallbackState,
fallbackModels: string[],
cooldownSeconds: number
): string | undefined {
for (let i = state.fallbackIndex + 1; i < fallbackModels.length; i++) {
const candidate = fallbackModels[i]
// Never select the model that is currently failing — that would
// create an infinite retry loop.
if (candidate === state.currentModel) {
logInfo(`Skipping fallback model identical to current: ${candidate} (index ${i})`)
continue
}
if (!isModelInCooldown(candidate, state, cooldownSeconds)) {
return candidate
}
logInfo(`Skipping fallback model in cooldown: ${candidate} (index ${i})`)
}
return undefined
}
function applyFallbackPlan(
state: FallbackState,
plan: FallbackPlan,
pendingFallbackModel?: string
): void {
state.fallbackIndex = plan.newFallbackIndex
state.failedModels.set(plan.failedModel, Date.now())
state.attemptCount++
state.currentModel = plan.newModel
state.pendingFallbackModel = pendingFallbackModel
}
export function prepareFallback(
sessionID: string,
state: FallbackState,
fallbackModels: string[],
config: Required<FallbackPluginConfig>,
): FallbackResult {
const plan = planFallback(sessionID, state, fallbackModels, config)
if (!plan.success) {
return plan
}
applyFallbackPlan(state, plan, plan.newModel)
return { success: true, newModel: plan.newModel }
}
/**
* Phase 1: Determine the next fallback model WITHOUT mutating state.
* Returns a plan that can be committed later via commitFallback().
*/
export function planFallback(
sessionID: string,
state: FallbackState,
fallbackModels: string[],
config: Required<FallbackPluginConfig>,
): FallbackPlan | FallbackPlanFailure {
if (state.attemptCount >= config.max_fallback_attempts) {
logInfo(`Max fallback attempts reached for session ${sessionID} (${state.attemptCount})`)
return {
success: false,
error: "Max fallback attempts reached",
maxAttemptsReached: true,
}
}
const nextModel = findNextAvailableFallback(state, fallbackModels, config.cooldown_seconds)
if (!nextModel) {
logInfo(`No available fallback models for session ${sessionID}`)
return {
success: false,
error: "No available fallback models (all in cooldown or exhausted)",
}
}
logInfo(
`Planned fallback for session ${sessionID}: ${state.currentModel} -> ${nextModel} (will be attempt ${state.attemptCount + 1})`
)
return {
success: true,
newModel: nextModel,
failedModel: state.currentModel,
newFallbackIndex: fallbackModels.indexOf(nextModel),
}
}
/**
* Phase 2: Commit a planned fallback to state. Call this AFTER the replay
* dispatch to promptAsync succeeds, so state only advances when the new
* model is actually being called.
*
* Idempotent: if the state already shows this plan's model (i.e. another
* handler already committed the same plan), this is a no-op and returns false.
*/
export function commitFallback(
state: FallbackState,
plan: FallbackPlan,
): boolean {
// Reject stale or already-committed plans. A plan is only valid if the state
// still reflects the model that originally failed when the plan was created.
if (state.currentModel !== plan.failedModel) {
return false
}
applyFallbackPlan(state, plan)
return true
}
export function recoverToOriginal(
state: FallbackState,
cooldownSeconds: number
): boolean {
if (state.currentModel === state.originalModel) return false
if (isModelInCooldown(state.originalModel, state, cooldownSeconds)) return false
state.currentModel = state.originalModel
state.fallbackIndex = -1
state.attemptCount = 0
state.pendingFallbackModel = undefined
return true
}