-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent-handler.ts
More file actions
840 lines (762 loc) · 27 KB
/
event-handler.ts
File metadata and controls
840 lines (762 loc) · 27 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
import type { HookDeps } from "./types"
import type { AutoRetryHelpers } from "./auto-retry"
import { logInfo, logError } from "./logger"
import {
extractStatusCode,
extractErrorName,
classifyErrorType,
isRetryableError,
} from "./error-classifier"
import {
createFallbackState,
prepareFallback,
planFallback,
snapshotFallbackState,
restoreFallbackState,
} from "./fallback-state"
import { getFallbackModelsForSession, resolveAgentForSession } from "./config-reader"
export function createEventHandler(deps: HookDeps, helpers: AutoRetryHelpers) {
const {
config,
sessionStates,
sessionLastAccess,
sessionRetryInFlight,
sessionAwaitingFallbackResult,
sessionFallbackTimeouts,
} = deps
const handleActivity = async (sessionID: string, activityModel?: string) => {
// If a fallback is awaiting results and we know the model that produced
// this activity, verify it matches the current fallback model. Stale
// activity from the failed model (e.g. k2p5 emitting a final
// message.part.delta while gemini-flash is being dispatched) must NOT
// mark firstTokenReceived or reset the timeout — that would cause
// session.idle to declare "fallback model completed" before the actual
// fallback model has produced anything.
if (activityModel && sessionAwaitingFallbackResult.has(sessionID)) {
const state = sessionStates.get(sessionID)
if (state && state.failedModels.has(activityModel)) {
logInfo("Ignoring activity from already-failed model", {
sessionID,
activityModel,
currentModel: state.currentModel,
})
return
}
}
// Any model activity (text deltas, tool calls, diffs) proves the model
// is alive and producing output. Mark first token received so the TTFT
// timeout handler skips the abort when it eventually fires.
if (!deps.sessionFirstTokenReceived.get(sessionID)) {
deps.sessionFirstTokenReceived.set(sessionID, true)
}
if (sessionAwaitingFallbackResult.has(sessionID)) {
const resolvedAgent = resolveAgentForSession(sessionID, undefined)
helpers.scheduleSessionFallbackTimeout(sessionID, resolvedAgent)
logInfo("Resetting fallback timeout due to activity", { sessionID, activityModel })
return
}
if (sessionAwaitingFallbackResult.size === 0) {
return
}
const cachedParentID = deps.sessionParentID.get(sessionID)
const parentID =
cachedParentID !== undefined
? cachedParentID
: await helpers.getParentSessionID(sessionID)
if (parentID && sessionAwaitingFallbackResult.has(parentID)) {
const resolvedAgent = resolveAgentForSession(parentID, undefined)
helpers.scheduleSessionFallbackTimeout(parentID, resolvedAgent)
logInfo("Resetting parent fallback timeout due to child activity", {
sessionID,
parentID,
})
}
}
const handleSessionCreated = (props: Record<string, unknown> | undefined) => {
const sessionInfo = props?.info as { id?: string } | undefined
const sessionID = sessionInfo?.id
if (!sessionID) return
const parentID = (sessionInfo as Record<string, unknown> | undefined)?.parentID
if (typeof parentID === "string" && parentID.length > 0) {
deps.sessionParentID.set(sessionID, parentID)
}
logInfo("Session created, state will be created on-demand", { sessionID })
}
const handleSessionDeleted = (props: Record<string, unknown> | undefined) => {
const sessionInfo = props?.info as { id?: string } | undefined
const sessionID = sessionInfo?.id
if (sessionID) {
logInfo("Cleaning up session state", { sessionID })
sessionStates.delete(sessionID)
sessionLastAccess.delete(sessionID)
sessionRetryInFlight.delete(sessionID)
sessionAwaitingFallbackResult.delete(sessionID)
deps.sessionFirstTokenReceived.delete(sessionID)
deps.sessionSelfAbortTimestamp.delete(sessionID)
deps.sessionParentID.delete(sessionID)
deps.sessionCompactionInFlight.delete(sessionID)
deps.sessionIdleResolvers.delete(sessionID)
deps.sessionLastMessageTime.delete(sessionID)
helpers.clearSessionFallbackTimeout(sessionID)
}
}
const handleSessionStop = async (props: Record<string, unknown> | undefined) => {
const sessionID = props?.sessionID as string | undefined
if (!sessionID) return
helpers.clearSessionFallbackTimeout(sessionID)
if (
sessionRetryInFlight.has(sessionID) ||
sessionAwaitingFallbackResult.has(sessionID)
) {
await helpers.abortSessionRequest(sessionID, "session.stop")
}
sessionRetryInFlight.delete(sessionID)
sessionAwaitingFallbackResult.delete(sessionID)
deps.sessionCompactionInFlight.delete(sessionID)
deps.sessionSelfAbortTimestamp.delete(sessionID)
const state = sessionStates.get(sessionID)
if (state?.pendingFallbackModel) {
state.pendingFallbackModel = undefined
}
logInfo("Cleared fallback retry state on session.stop", { sessionID })
}
const handleSessionIdle = async (props: Record<string, unknown> | undefined) => {
const sessionID = props?.sessionID as string | undefined
if (!sessionID) return
// Resolve any idle waiters FIRST (e.g. subagent-sync waiting for
// a child session's fallback to complete). This must happen before
// the sessionAwaitingFallbackResult early-return below, because
// the waiter needs to know the child went idle regardless.
const idleResolvers = deps.sessionIdleResolvers.get(sessionID)
if (idleResolvers && idleResolvers.length > 0) {
logInfo("session.idle resolving waiters", {
sessionID,
waiterCount: idleResolvers.length,
})
for (const resolve of idleResolvers) resolve()
deps.sessionIdleResolvers.delete(sessionID)
}
if (sessionAwaitingFallbackResult.has(sessionID)) {
// ── COMPACTION IN-FLIGHT: SKIP SILENT-FAILURE DETECTION ──
// Compaction via session.command produces no message.updated events.
// session.idle firing during compaction does NOT mean the model
// failed — it means the session went idle between the original
// error and the compaction starting on the new model. Wait for
// session.compacted (success) or TTFT timeout (failure).
if (deps.sessionCompactionInFlight.has(sessionID)) {
logInfo("session.idle during compaction in-flight — not a silent failure, waiting for session.compacted", {
sessionID,
})
return
}
// ── SILENT MODEL FAILURE DETECTION ──
// If we dispatched a fallback model (sessionAwaitingFallbackResult is
// set) but no first token was ever received, the model silently failed
// (e.g. model_not_found, quota exceeded, empty response). Treat this
// idle as a real failure and advance the fallback chain immediately
// rather than waiting for the full TTFT timeout.
const firstTokenReceived = deps.sessionFirstTokenReceived.get(sessionID)
if (!firstTokenReceived) {
const state = sessionStates.get(sessionID)
if (state) {
logInfo("session.idle detected silent model failure (no first token received)", {
sessionID,
currentModel: state.currentModel,
attemptCount: state.attemptCount,
})
// Acquire retry lock BEFORE clearing the timeout. The TTFT
// timeout callback may already be queued in the event loop
// (clearTimeout only prevents future scheduling, not already-
// queued macrotasks). By holding the lock first, any racing
// timeout callback will see sessionRetryInFlight and bail out
// at its own lock check, preventing dual planFallback calls.
if (sessionRetryInFlight.has(sessionID)) {
logInfo("session.idle silent failure — retry already in flight, skipping", {
sessionID,
})
return
}
sessionRetryInFlight.add(sessionID)
// Now safe to clear awaiting state and timeout
sessionAwaitingFallbackResult.delete(sessionID)
helpers.clearSessionFallbackTimeout(sessionID)
try {
const resolvedAgent = await helpers.resolveAgentForSessionFromContext(
sessionID,
undefined
)
const fallbackModels = getFallbackModelsForSession(
sessionID,
resolvedAgent,
deps.agentConfigs,
deps.globalFallbackModels
)
if (fallbackModels.length === 0) {
logInfo("session.idle silent failure — no fallback models configured", {
sessionID,
})
return
}
const plan = planFallback(sessionID, state, fallbackModels, config)
if (plan.success) {
await helpers.autoRetryWithFallback(
sessionID,
plan.newModel,
resolvedAgent,
"session.idle.silent-failure",
plan
)
} else {
logInfo("session.idle silent failure — no more fallback models available", {
sessionID,
error: plan.error,
})
}
} finally {
sessionRetryInFlight.delete(sessionID)
}
return
}
}
// First token was received and session went idle — the fallback
// model completed its work (possibly with only tool calls, no text).
// Clear the awaiting state so the session isn't stuck.
logInfo("session.idle with first token received — fallback model completed", {
sessionID,
})
sessionAwaitingFallbackResult.delete(sessionID)
helpers.clearSessionFallbackTimeout(sessionID)
sessionRetryInFlight.delete(sessionID)
return
}
const hadTimeout = sessionFallbackTimeouts.has(sessionID)
helpers.clearSessionFallbackTimeout(sessionID)
sessionRetryInFlight.delete(sessionID)
const state = sessionStates.get(sessionID)
if (state?.pendingFallbackModel) {
state.pendingFallbackModel = undefined
}
if (hadTimeout) {
logInfo("Cleared fallback timeout after session completion", { sessionID })
}
}
const handleSessionStatus = async (props: Record<string, unknown> | undefined) => {
const sessionID = props?.sessionID as string | undefined
const status = props?.status as
| { type?: string; attempt?: number; message?: string; next?: number }
| undefined
if (!sessionID || !status || status.type !== "retry") return
// ── EARLY LOCK ACQUISITION ──
if (sessionRetryInFlight.has(sessionID)) {
logInfo("session.status skipped -- retry lock already held", { sessionID })
return
}
sessionRetryInFlight.add(sessionID)
try {
const resolvedAgent = await helpers.resolveAgentForSessionFromContext(
sessionID,
undefined
)
const fallbackModels = getFallbackModelsForSession(
sessionID,
resolvedAgent,
deps.agentConfigs,
deps.globalFallbackModels
)
logInfo("Provider retry detected", {
sessionID,
attempt: status.attempt,
message: status.message,
nextRetryMs: status.next,
resolvedAgent,
totalFallbackModels: fallbackModels.length,
})
if (fallbackModels.length === 0) {
if (config.notify_on_fallback) {
await deps.ctx.client.tui
.showToast({
body: {
title: "Provider Retrying",
variant: "info",
duration: 3000,
message: `${status.message || "retrying..."} (no fallback models configured)`,
},
})
.catch(() => {})
}
return
}
// Check if provider retry is too far in the future - trigger immediate fallback
const nextRetryMs = status.next
if (typeof nextRetryMs === "number" && nextRetryMs > 0) {
const now = Date.now()
const timeoutMs = config.timeout_seconds * 1000
if (nextRetryMs > now + timeoutMs) {
logInfo("Provider retry is beyond timeout, triggering immediate fallback", {
sessionID,
nextRetryMs,
now,
timeoutMs,
diffSeconds: Math.round((nextRetryMs - now) / 1000),
})
await triggerImmediateFallback(sessionID, resolvedAgent, fallbackModels, status)
return
}
}
let state = sessionStates.get(sessionID)
if (!state) {
const agentConfig =
resolvedAgent && deps.agentConfigs
? (deps.agentConfigs[resolvedAgent] as Record<string, unknown> | undefined)
: undefined
const initialModel = (agentConfig?.model as string | undefined) ?? findFirstAgentModel()
if (!initialModel) {
logInfo("No model info for session.status fallback", { sessionID })
return
}
logInfo("Creating on-demand state for session.status", {
sessionID,
model: initialModel,
agent: resolvedAgent,
})
state = createFallbackState(initialModel)
sessionStates.set(sessionID, state)
sessionLastAccess.set(sessionID, Date.now())
} else {
sessionLastAccess.set(sessionID, Date.now())
}
sessionAwaitingFallbackResult.delete(sessionID)
helpers.clearSessionFallbackTimeout(sessionID)
const plan = planFallback(sessionID, state, fallbackModels, config)
if (plan.success) {
if (config.notify_on_fallback) {
const modelName = plan.newModel?.split("/").pop() || plan.newModel
deps.ctx.client.tui
.showToast({
body: {
title: "Retry Detected -- Switching Model",
variant: "warning",
duration: 5000,
message: `${status.message || "Provider retrying"} -> ${modelName} (attempt ${state.attemptCount + 1} of ${fallbackModels.length})`,
},
})
.catch(() => {})
}
await helpers.autoRetryWithFallback(
sessionID,
plan.newModel,
resolvedAgent,
"session.status",
plan
)
} else if (!plan.success) {
logError("session.status fallback failed", {
sessionID,
error: plan.error,
})
if (plan.maxAttemptsReached && config.notify_on_fallback) {
await deps.ctx.client.tui
.showToast({
body: {
title: "All Fallbacks Exhausted",
variant: "error",
duration: 8000,
message: `All ${fallbackModels.length} fallback models exhausted after ${state.attemptCount} attempts`,
},
})
.catch(() => {})
}
}
} finally {
sessionRetryInFlight.delete(sessionID)
}
}
const handleSessionError = async (props: Record<string, unknown> | undefined) => {
const sessionID = props?.sessionID as string | undefined
const error = props?.error
const agent = props?.agent as string | undefined
const errorModel = props?.model as string | undefined
if (!sessionID) {
logInfo("session.error without sessionID, skipping")
return
}
// ── COMPACTION IN-FLIGHT GUARD ──
// Compaction via session.command produces no standard events. Any
// session.error arriving while compaction is running is from the
// pre-compaction model — suppress entirely.
if (deps.sessionCompactionInFlight.has(sessionID)) {
logInfo("Ignoring session.error during compaction in-flight", {
sessionID,
errorName: extractErrorName(error),
})
return
}
// ── SELF-ABORT GUARD ──
// If this is a MessageAbortedError from a plugin-initiated abort
// (TTFT timeout, pre-fallback abort, etc.), suppress it. The handler
// that initiated the abort is already dispatching the fallback.
// We check this FIRST, before any stale-model or pending guards,
// because those guards may not yet reflect the in-progress transition.
const SELF_ABORT_WINDOW_MS = 2000
const selfAbortTs = deps.sessionSelfAbortTimestamp.get(sessionID)
const errorName = extractErrorName(error)
if (
errorName === "MessageAbortedError" &&
selfAbortTs &&
Date.now() - selfAbortTs < SELF_ABORT_WINDOW_MS
) {
logInfo("Ignoring self-inflicted MessageAbortedError in session.error", {
sessionID,
msSinceAbort: Date.now() - selfAbortTs,
awaitingFallback: sessionAwaitingFallbackResult.has(sessionID),
retryInFlight: sessionRetryInFlight.has(sessionID),
})
return
}
// Ignore stale errors from models we already moved past
const currentState = sessionStates.get(sessionID)
if (currentState?.pendingFallbackModel) {
logInfo("Ignoring session.error while fallback replay is pending", {
sessionID,
pendingFallbackModel: currentState.pendingFallbackModel,
currentModel: currentState.currentModel,
errorName: extractErrorName(error),
})
return
}
if (currentState && errorModel && errorModel !== currentState.currentModel) {
logInfo("Ignoring stale session.error from previous model", {
sessionID,
staleModel: errorModel,
currentModel: currentState.currentModel,
errorName: extractErrorName(error),
})
return
}
// If the error model has already been recorded as failed, this is a
// stale echo from a model that already triggered a fallback. Suppress
// it to prevent duplicate fallback planning.
if (currentState && errorModel && currentState.failedModels.has(errorModel)) {
logInfo("Ignoring session.error from already-failed model", {
sessionID,
errorModel,
currentModel: currentState.currentModel,
errorName: extractErrorName(error),
})
return
}
// If we're awaiting a fallback result, this session.error is likely
// a stale abort from the previous model (session.error doesn't carry
// a model field, so we can't reliably tell which model caused it).
//
// If the fallback model itself fails silently (no message.updated error,
// no first token), the session.idle handler will detect it via the
// "silent model failure" path and advance the chain.
if (sessionAwaitingFallbackResult.has(sessionID)) {
logInfo("Ignoring session.error while awaiting fallback result (likely stale abort)", {
sessionID,
currentModel: currentState?.currentModel,
errorName: extractErrorName(error),
})
return
}
// ── EARLY LOCK ACQUISITION ──
// Acquire the lock BEFORE any async work (resolveAgentForSessionFromContext).
// Both message.updated and session.error fire simultaneously for the same
// error. The first handler to reach this point wins; the other bails out.
if (sessionRetryInFlight.has(sessionID)) {
logInfo("session.error skipped -- retry in flight (early lock)", {
sessionID,
retryInFlight: true,
})
return
}
sessionRetryInFlight.add(sessionID)
try {
const resolvedAgent = await helpers.resolveAgentForSessionFromContext(
sessionID,
agent
)
// ── POST-AWAIT COMPACTION GUARD ──
// The pre-await guard at line 431 may miss the flag if
// message.updated's handler set it during our await. Re-check
// here. Only bail if message.updated is already handling the
// compaction fallback (compactionInFlight flag is set).
if (deps.sessionCompactionInFlight.has(sessionID)) {
logInfo("session.error skipping — compaction already being handled by message.updated", {
sessionID,
resolvedAgent,
errorName: extractErrorName(error),
})
return
}
helpers.clearSessionFallbackTimeout(sessionID)
// Re-check pendingFallbackModel after the await — message.updated may
// have created state and called prepareFallback while we were resolving
// the agent. This is the primary guard against the dual-handler race.
const stateAfterAwait = sessionStates.get(sessionID)
if (stateAfterAwait?.pendingFallbackModel) {
logInfo("Ignoring session.error — fallback replay became pending during agent resolution", {
sessionID,
pendingFallbackModel: stateAfterAwait.pendingFallbackModel,
currentModel: stateAfterAwait.currentModel,
errorName: extractErrorName(error),
})
return
}
logInfo("session.error received", {
sessionID,
agent,
resolvedAgent,
statusCode: extractStatusCode(error, config.retry_on_errors),
errorName: extractErrorName(error),
errorType: classifyErrorType(error),
})
const isRetryable = isRetryableError(error, config.retry_on_errors, config.retryable_error_patterns)
let state = sessionStates.get(sessionID)
const fallbackModels = getFallbackModelsForSession(
sessionID,
resolvedAgent,
deps.agentConfigs,
deps.globalFallbackModels
)
if (fallbackModels.length === 0) {
logInfo("No fallback models configured", { sessionID, agent })
return
}
// Check if we're already in a fallback chain
const inFallbackChain = state && state.currentModel !== state.originalModel
if (!isRetryable && !inFallbackChain) {
logInfo("Error not retryable and not in fallback chain, skipping", {
sessionID,
retryable: false,
inFallbackChain: false,
statusCode: extractStatusCode(error, config.retry_on_errors),
errorName: extractErrorName(error),
errorType: classifyErrorType(error),
})
return
}
if (!isRetryable && inFallbackChain) {
logInfo("Non-retryable error but in fallback chain, continuing to next fallback", {
sessionID,
retryable: false,
inFallbackChain: true,
currentModel: state?.currentModel,
originalModel: state?.originalModel,
errorName: extractErrorName(error),
})
}
if (!state) {
const currentModel = props?.model as string | undefined
if (currentModel) {
state = createFallbackState(currentModel)
sessionStates.set(sessionID, state)
sessionLastAccess.set(sessionID, Date.now())
} else if (!errorModel && sessionRetryInFlight.has(sessionID)) {
// No state, no model on the error, and message.updated holds the
// retry lock — this is a stale session.error for the same failure
// that message.updated is already handling. Defer entirely.
logInfo("Deferring to message.updated handler (no state, no errorModel, retry in flight)", {
sessionID,
errorName: extractErrorName(error),
})
return
} else {
const agentConfig =
resolvedAgent && deps.agentConfigs
? (deps.agentConfigs[resolvedAgent] as Record<string, unknown> | undefined)
: undefined
const agentModel = agentConfig?.model as string | undefined
if (agentModel) {
logInfo("Derived model from agent config", {
sessionID,
agent: resolvedAgent,
model: agentModel,
})
state = createFallbackState(agentModel)
sessionStates.set(sessionID, state)
sessionLastAccess.set(sessionID, Date.now())
} else {
const firstModel = findFirstAgentModel()
if (firstModel) {
logInfo("Using first available agent model for state creation", {
sessionID,
model: firstModel,
})
state = createFallbackState(firstModel)
sessionStates.set(sessionID, state)
sessionLastAccess.set(sessionID, Date.now())
} else {
logInfo("No model info available, cannot fallback", { sessionID })
return
}
}
}
} else {
sessionLastAccess.set(sessionID, Date.now())
}
const plan = planFallback(sessionID, state, fallbackModels, config)
if (plan.success) {
if (config.notify_on_fallback) {
const modelName = plan.newModel?.split("/").pop() || plan.newModel
const attemptInfo = `attempt ${state.attemptCount + 1} of ${fallbackModels.length}`
deps.ctx.client.tui
.showToast({
body: {
title: "Model Fallback",
message: `Switching to ${modelName} (${attemptInfo})`,
variant: "warning",
duration: 5000,
},
})
.catch(() => {})
}
await helpers.autoRetryWithFallback(
sessionID,
plan.newModel,
resolvedAgent,
"session.error",
plan
)
} else {
logError("Fallback preparation failed", {
sessionID,
error: plan.error,
})
}
} finally {
sessionRetryInFlight.delete(sessionID)
}
}
const handleSessionCompacted = (props: Record<string, unknown> | undefined) => {
const sessionID = props?.sessionID as string | undefined
if (!sessionID) return
const hadAwaiting = sessionAwaitingFallbackResult.has(sessionID)
const hadCompaction = deps.sessionCompactionInFlight.has(sessionID)
// Clear all fallback tracking state — compaction completed successfully
sessionAwaitingFallbackResult.delete(sessionID)
sessionRetryInFlight.delete(sessionID)
deps.sessionFirstTokenReceived.delete(sessionID)
deps.sessionCompactionInFlight.delete(sessionID)
helpers.clearSessionFallbackTimeout(sessionID)
if (hadAwaiting || hadCompaction) {
logInfo("Compaction completed, clearing fallback state", { sessionID })
}
}
function findFirstAgentModel(): string | undefined {
if (!deps.agentConfigs) return undefined
for (const agentName of Object.keys(deps.agentConfigs)) {
const agentConfig = deps.agentConfigs[agentName] as
| Record<string, unknown>
| undefined
const model = agentConfig?.model as string | undefined
if (model) return model
}
return undefined
}
// Called from handleSessionStatus which already holds the sessionRetryInFlight lock.
// Does NOT acquire/release the lock itself.
async function triggerImmediateFallback(
sessionID: string,
resolvedAgent: string | undefined,
fallbackModels: string[],
status: { type?: string; attempt?: number; message?: string; next?: number }
): Promise<void> {
// Create state if needed
let state = sessionStates.get(sessionID)
if (!state) {
const agentConfig =
resolvedAgent && deps.agentConfigs
? (deps.agentConfigs[resolvedAgent] as Record<string, unknown> | undefined)
: undefined
const initialModel = (agentConfig?.model as string | undefined) ?? findFirstAgentModel()
if (!initialModel) {
logError("Cannot trigger immediate fallback - no model info", { sessionID })
return
}
state = createFallbackState(initialModel)
sessionStates.set(sessionID, state)
sessionLastAccess.set(sessionID, Date.now())
} else {
sessionLastAccess.set(sessionID, Date.now())
}
sessionAwaitingFallbackResult.delete(sessionID)
helpers.clearSessionFallbackTimeout(sessionID)
const plan = planFallback(sessionID, state, fallbackModels, config)
if (plan.success) {
if (config.notify_on_fallback) {
const modelName = plan.newModel?.split("/").pop() || plan.newModel
deps.ctx.client.tui
.showToast({
body: {
title: "Provider Retry Too Slow - Switching Model",
variant: "warning",
duration: 5000,
message: `${status.message || "Provider retrying"} -> ${modelName} (immediate fallback)`,
},
})
.catch(() => {})
}
await helpers.autoRetryWithFallback(
sessionID,
plan.newModel,
resolvedAgent,
"session.status.immediate",
plan
)
} else if (!plan.success) {
logError("Immediate fallback preparation failed", {
sessionID,
error: plan.error,
})
if (plan.maxAttemptsReached && config.notify_on_fallback) {
await deps.ctx.client.tui
.showToast({
body: {
title: "All Fallbacks Exhausted",
variant: "error",
duration: 8000,
message: `All ${fallbackModels.length} fallback models exhausted`,
},
})
.catch(() => {})
}
}
}
return {
handleEvent: async ({ event }: { event: { type: string; properties?: unknown } }) => {
if (!config.enabled) return
const props = event.properties as Record<string, unknown> | undefined
if (event.type === "session.created") {
handleSessionCreated(props)
return
}
if (event.type === "session.deleted") {
handleSessionDeleted(props)
return
}
if (event.type === "session.stop") {
await handleSessionStop(props)
return
}
if (event.type === "session.idle") {
await handleSessionIdle(props)
return
}
if (event.type === "session.error") {
await handleSessionError(props)
return
}
if (event.type === "session.status") {
await handleSessionStatus(props)
return
}
if (event.type === "session.compacted") {
handleSessionCompacted(props)
return
}
},
handleActivity,
}
}