dsh-autorouter 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Virtual model metadata: the union/intersection of what the chain can do.
3
+ * A conservative virtual model is what makes host-side compaction and the
4
+ * model picker behave when the actual upstream changes between calls.
5
+ */
6
+
7
+ import { enabledEntries } from '../config.js'
8
+ import { unionEfforts } from './effort.js'
9
+
10
+ export function profileDisplayName(profile) {
11
+ return profile.name === '' ? profile.id : profile.name
12
+ }
13
+
14
+ function intersectModalities(infos) {
15
+ const known = infos
16
+ .map((info) => info?.inputModalities)
17
+ .filter((modalities) => Array.isArray(modalities) && modalities.length > 0)
18
+ if (known.length === 0) return ['text']
19
+ let result = [...new Set(known[0])]
20
+ for (const modalities of known.slice(1)) {
21
+ const set = new Set(modalities)
22
+ result = result.filter((modality) => set.has(modality))
23
+ }
24
+ return result.length === 0 ? ['text'] : result
25
+ }
26
+
27
+ /**
28
+ * @param {object} profile
29
+ * @param {(provider: string, model: string) => Promise<object | undefined>} infoOf
30
+ * @param {{contextPolicy?: 'min' | 'fixed', defaultContextWindow?: number}} policy
31
+ */
32
+ export async function resolveProfileInfo(profile, infoOf, policy = {}) {
33
+ const entries = enabledEntries(profile)
34
+ const infos = await Promise.all(
35
+ entries.map(async (entry) => {
36
+ try {
37
+ return await infoOf(entry.provider, entry.model)
38
+ } catch {
39
+ return undefined
40
+ }
41
+ }),
42
+ )
43
+ const known = infos.filter((info) => info !== undefined && info !== null)
44
+
45
+ const windows = known
46
+ .map((info) => info.context?.contextWindow)
47
+ .filter((value) => typeof value === 'number' && Number.isFinite(value) && value > 0)
48
+ const fallbackWindow = policy.defaultContextWindow ?? 128000
49
+ // The host validates this as a positive integer and throws otherwise, so the
50
+ // last step is a coercion rather than a hope.
51
+ const contextWindow = Math.max(
52
+ 1,
53
+ Math.round(
54
+ policy.contextPolicy === 'fixed' ? fallbackWindow : windows.length > 0 ? Math.min(...windows) : fallbackWindow,
55
+ ),
56
+ )
57
+
58
+ const maxTokens = known
59
+ .map((info) => info.defaultMaxTokens)
60
+ .filter((value) => typeof value === 'number' && Number.isFinite(value) && value > 0)
61
+ .map((value) => Math.max(1, Math.floor(value)))
62
+
63
+ const reasoning = unionEfforts(
64
+ known.map((info) => ({ efforts: info.reasoning?.efforts, defaultEffort: info.reasoning?.defaultEffort })),
65
+ )
66
+
67
+ const toolUpdate = known.some((info) => info.toolUpdate === 'addition-only') ? 'addition-only' : 'in-history'
68
+
69
+ return {
70
+ inputModalities: intersectModalities(known),
71
+ context: { contextWindow },
72
+ ...(maxTokens.length > 0 ? { defaultMaxTokens: Math.min(...maxTokens) } : {}),
73
+ ...(reasoning === undefined ? {} : { reasoning }),
74
+ systemPromptUpdate: 'in-history',
75
+ toolUpdate,
76
+ // Diagnostics, not part of LlmResolvedModelInfo; stripped before returning.
77
+ entryCount: entries.length,
78
+ resolvedCount: known.length,
79
+ }
80
+ }
81
+
82
+ /** Shape a resolved profile for the llm service (no diagnostic fields). */
83
+ export function toModelInfo(provider, profile, resolved) {
84
+ return {
85
+ provider,
86
+ id: profile.id,
87
+ name: profileDisplayName(profile),
88
+ ...(profile.description === '' ? {} : { description: profile.description }),
89
+ inputModalities: resolved.inputModalities,
90
+ context: resolved.context,
91
+ ...(resolved.defaultMaxTokens === undefined ? {} : { defaultMaxTokens: resolved.defaultMaxTokens }),
92
+ ...(resolved.reasoning === undefined
93
+ ? {}
94
+ : {
95
+ reasoning: {
96
+ efforts: resolved.reasoning.efforts,
97
+ ...(resolved.reasoning.defaultEffort === undefined ? {} : { defaultEffort: resolved.reasoning.defaultEffort }),
98
+ },
99
+ }),
100
+ systemPromptUpdate: resolved.systemPromptUpdate,
101
+ toolUpdate: resolved.toolUpdate,
102
+ }
103
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Candidate selection: cooldowns, time windows and sticky sessions. The chain is
3
+ * tried strictly in its configured order; a matching
4
+ * time window may rotate which routes come first, but never filters and never
5
+ * sorts by cost or quality.
6
+ */
7
+
8
+ import {
9
+ activeTimeWindow,
10
+ applyTimeWindow,
11
+ enabledEntries,
12
+ entryKey,
13
+ isEntryEligible,
14
+ } from '../config.js'
15
+
16
+ /** @returns {{usable: boolean, reason?: string, until?: number}} */
17
+ export function usability(entry, state, policy, now) {
18
+ if (!isEntryEligible(entry)) return { usable: false, reason: 'invalid-entry' }
19
+ const key = entryKey(entry)
20
+ const until = state.coolingUntil(key)
21
+ if (until > now) return { usable: false, reason: 'cooldown', until }
22
+ return { usable: true }
23
+ }
24
+
25
+ /**
26
+ * Build the attempt order for one virtual call.
27
+ *
28
+ * @returns {{
29
+ * candidates: object[],
30
+ * blocked: Array<{entry: object, reason: string, until?: number}>,
31
+ * window: object | undefined,
32
+ * sticky: boolean,
33
+ * order: string[],
34
+ * }}
35
+ */
36
+ export function orderCandidates({ profile, state, now = Date.now(), sessionId }) {
37
+ const policy = profile.policy
38
+ const configured = enabledEntries(profile).filter(isEntryEligible)
39
+ const window = activeTimeWindow(policy, now)
40
+
41
+ const candidates = []
42
+ const blocked = []
43
+ for (const entry of configured) {
44
+ const verdict = usability(entry, state, policy, now)
45
+ if (verdict.usable) {
46
+ candidates.push(entry)
47
+ } else {
48
+ blocked.push({ entry, reason: verdict.reason, until: verdict.until })
49
+ }
50
+ }
51
+
52
+ let sticky = false
53
+ let pinnedKey
54
+ if (policy.sticky === true && candidates.length > 1) {
55
+ const pin = state.session(sessionId, now, policy.stickinessTtlMs)
56
+ if (pin !== undefined && pin.profileId === profile.id && candidates.some((entry) => entryKey(entry) === pin.key)) {
57
+ pinnedKey = pin.key
58
+ sticky = true
59
+ }
60
+ }
61
+
62
+ // Chain order is the baseline. A time window is a routing seed, not a
63
+ // filter: it moves the named routes to the front and keeps everything else
64
+ // in its original relative order behind them.
65
+ let ordered = candidates
66
+ if (window !== undefined) ordered = applyTimeWindow(ordered, window)
67
+
68
+ // Stickiness wins over the window: the pinned route goes first so the prompt
69
+ // cache survives, and the rest of the chain stays intact behind it.
70
+ if (pinnedKey !== undefined) {
71
+ const index = ordered.findIndex((entry) => entryKey(entry) === pinnedKey)
72
+ if (index > 0) {
73
+ const next = [...ordered]
74
+ const [pinned] = next.splice(index, 1)
75
+ next.unshift(pinned)
76
+ ordered = next
77
+ }
78
+ }
79
+
80
+ return {
81
+ candidates: ordered,
82
+ blocked,
83
+ window,
84
+ sticky,
85
+ order: ordered.map(entryKey),
86
+ }
87
+ }
88
+
89
+ export function nextCandidate(candidates, fromKey) {
90
+ const index = candidates.findIndex((entry) => entryKey(entry) === fromKey)
91
+ if (index < 0) return undefined
92
+ return candidates[index + 1]
93
+ }
94
+
95
+ export function firstCandidate(candidates) {
96
+ return candidates[0]
97
+ }
98
+
99
+ /** Small human-readable summary for logs and the status route. */
100
+ export function describeOrder(selection) {
101
+ return {
102
+ window: selection.window?.label,
103
+ sticky: selection.sticky,
104
+ candidates: selection.order,
105
+ blocked: selection.blocked.map((item) => `${entryKey(item.entry)} (${item.reason})`),
106
+ }
107
+ }
@@ -0,0 +1,303 @@
1
+ /**
2
+ * The routing walk: one virtual call becomes one or more upstream attempts.
3
+ *
4
+ * Rules (the same contract the incumbent fallback plugin implements, because
5
+ * the harness relies on it):
6
+ * - a failure may advance the chain only before the first output chunk;
7
+ * `block-start` / text / reasoning / tool-call deltas commit the attempt,
8
+ * - `usage` chunks never commit, but are buffered and replayed so a failed
9
+ * attempt still reports what it spent,
10
+ * - after output is committed, a failure is forwarded untouched,
11
+ * - the fuse is `maxSwitches`, so attempts <= maxSwitches + 1.
12
+ */
13
+
14
+ import { entryKey } from '../config.js'
15
+ import { classifyFailure, failureOf } from './classify.js'
16
+ import { mapEffort } from './effort.js'
17
+ import { orderCandidates, usability } from './select.js'
18
+
19
+ const OUTPUT_CHUNKS = new Set(['block-start', 'text-delta', 'reasoning-delta', 'tool-call-delta'])
20
+
21
+ function provenanceOf(replayState) {
22
+ if (typeof replayState !== 'object' || replayState === null) return undefined
23
+ const response = replayState.response
24
+ if (typeof response !== 'object' || response === null) return undefined
25
+ const { provider, model } = response
26
+ if (typeof provider !== 'string' || provider === '') return undefined
27
+ if (typeof model !== 'string' || model === '') return undefined
28
+ return { provider, model }
29
+ }
30
+
31
+ /**
32
+ * Assistant messages produced through AutoRouter carry `source.provider =
33
+ * "autorouter"`. Nested adapters expect their own provenance (and their replay
34
+ * state), so restore it when the envelope still knows where it came from.
35
+ */
36
+ export function restoreProvenance(messages, providerId) {
37
+ if (!Array.isArray(messages)) return messages
38
+ let changed = false
39
+ const restored = messages.map((message) => {
40
+ const source = message?.source
41
+ if (message?.role !== 'assistant' || source?.kind !== 'model' || source.provider !== providerId) return message
42
+ const provenance = provenanceOf(source.replayState)
43
+ if (provenance === undefined || provenance.provider === providerId) return message
44
+ changed = true
45
+ return { ...message, source: { ...source, provider: provenance.provider, model: provenance.model } }
46
+ })
47
+ return changed ? restored : messages
48
+ }
49
+
50
+ function failureChunk(failure) {
51
+ return { type: 'finish', reason: { kind: 'error', failure } }
52
+ }
53
+
54
+ function cooldownFor(policy, entry, streak, verdict, random) {
55
+ const base = Math.max(0, entry.cooldownMs > 0 ? entry.cooldownMs : policy.cooldownMs)
56
+ let duration = base
57
+ if (policy.recovery === 'half-open') {
58
+ const escalations = Math.min(4, Math.max(0, streak - 1))
59
+ duration = base * 2 ** escalations
60
+ }
61
+ if (verdict.retryAfterMs !== undefined && verdict.retryAfterMs > duration) duration = verdict.retryAfterMs
62
+ const jitter = policy.cooldownJitterRatio ?? 0
63
+ if (jitter > 0 && duration > 0) {
64
+ duration = Math.round(duration * (1 + (random() - 0.5) * 2 * jitter))
65
+ }
66
+ return Math.max(0, duration)
67
+ }
68
+
69
+ /**
70
+ * @param {object} input
71
+ * @param {object} input.options GenerateOptions for the virtual model
72
+ * @param {object} input.profile normalized profile (with policy)
73
+ * @param {object} input.config normalized config
74
+ * @param {import('../state.js').RouterState} input.state
75
+ * @param {(options: object) => AsyncIterable<object>} input.streamFn
76
+ * @param {(provider: string, model: string, signal?: AbortSignal) => Promise<object | undefined>} input.infoOf
77
+ * @param {(message: string, code: string) => Error} input.makeError
78
+ * @param {() => number} [input.now]
79
+ * @param {() => number} [input.random]
80
+ * @param {{info?: Function, debug?: Function}} [input.log]
81
+ */
82
+ export async function* walkRoute(input) {
83
+ const {
84
+ options,
85
+ profile,
86
+ config,
87
+ state,
88
+ streamFn,
89
+ infoOf,
90
+ makeError,
91
+ now = Date.now,
92
+ random = Math.random,
93
+ log = {},
94
+ } = input
95
+
96
+ if (config.enabled !== true) {
97
+ throw makeError('AutoRouter is disabled in Settings → AutoRouter.', 'AUTOROUTER_DISABLED')
98
+ }
99
+ if (profile.enabled !== true) {
100
+ throw makeError(`AutoRouter: virtual model "${profile.id}" is disabled.`, 'PROFILE_DISABLED')
101
+ }
102
+
103
+ const policy = profile.policy
104
+ const sessionId = options.sessionId
105
+ const selection = orderCandidates({ profile, state, now: now(), sessionId })
106
+ if (selection.candidates.length === 0) {
107
+ const retryAt = selection.blocked
108
+ .map((item) => item.until)
109
+ .filter((value) => Number.isFinite(value) && value > now())
110
+ .sort((left, right) => left - right)[0]
111
+ const error = makeError(
112
+ `AutoRouter: no healthy route for "${profile.id}" (${selection.blocked
113
+ .map((item) => `${entryKey(item.entry)}: ${item.reason}`)
114
+ .join(', ') || 'empty chain'}).`,
115
+ 'NO_HEALTHY_ROUTE',
116
+ )
117
+ if (retryAt !== undefined) error.providerRetryAfterMs = Math.max(0, retryAt - now())
118
+ throw error
119
+ }
120
+
121
+ const messages = restoreProvenance(options.messages, options.provider)
122
+ const candidates = selection.candidates
123
+ let index = 0
124
+ let switches = 0
125
+ let lastFailure
126
+ let repairedKey
127
+
128
+ for (;;) {
129
+ const entry = candidates[index]
130
+ if (entry === undefined) {
131
+ // The chain ran out before the fuse tripped: forward the last verdict so
132
+ // the caller still gets a terminal finish chunk.
133
+ if (lastFailure !== undefined) yield lastFailure
134
+ return
135
+ }
136
+ const key = entryKey(entry)
137
+
138
+ if (index > 0) {
139
+ const verdict = usability(entry, state, policy, now())
140
+ if (!verdict.usable) {
141
+ index += 1
142
+ continue
143
+ }
144
+ }
145
+
146
+ let targetInfo
147
+ try {
148
+ targetInfo = await infoOf(entry.provider, entry.model, options.signal)
149
+ } catch {
150
+ targetInfo = undefined
151
+ }
152
+ // `null` means "the adapter says this model has no reasoning at all",
153
+ // which is a different fact from "the lookup failed" (`undefined`).
154
+ const targetReasoning = targetInfo === undefined ? undefined : (targetInfo.reasoning ?? null)
155
+ const mapping = mapEffort(options.reasoningEffort, targetReasoning, entry.effortMap, policy)
156
+ if (mapping.coerced) {
157
+ log.info?.(
158
+ `llm-autorouter: effort ${options.reasoningEffort} -> ${mapping.effort ?? '(omit)'} on ${key} (${mapping.reason})`,
159
+ )
160
+ }
161
+
162
+ if (mapping.error !== undefined) {
163
+ const failure = { message: mapping.error.message, code: 'UNSUPPORTED_REASONING_EFFORT' }
164
+ lastFailure = failureChunk(failure)
165
+ if (switches >= policy.maxSwitches) {
166
+ yield lastFailure
167
+ return
168
+ }
169
+ switches += 1
170
+ state.stats.switches += 1
171
+ index += 1
172
+ continue
173
+ }
174
+
175
+ let attemptOptions = { ...options, provider: entry.provider, model: entry.model, messages }
176
+ if (mapping.effort === undefined || repairedKey === key) {
177
+ delete attemptOptions.reasoningEffort
178
+ } else {
179
+ attemptOptions.reasoningEffort = mapping.effort
180
+ }
181
+
182
+ state.noteAttempt(key)
183
+ let committed = false
184
+ let pendingUsage = []
185
+ let swallowed
186
+ let retrySameTarget = false
187
+
188
+ try {
189
+ for await (const chunk of streamFn(attemptOptions)) {
190
+ if (chunk.type === 'usage') {
191
+ if (committed) yield chunk
192
+ else pendingUsage.push(chunk)
193
+ continue
194
+ }
195
+
196
+ if (chunk.type === 'finish') {
197
+ const failure = chunk.reason?.kind === 'error' ? chunk.reason.failure : undefined
198
+ if (failure !== undefined && !committed) {
199
+ // One parameter repair per attempt: the upstream may simply not
200
+ // know this effort, which is not a reason to abandon the route.
201
+ if (
202
+ failure.code === 'UNSUPPORTED_REASONING_EFFORT' &&
203
+ attemptOptions.reasoningEffort !== undefined
204
+ ) {
205
+ attemptOptions = { ...attemptOptions }
206
+ delete attemptOptions.reasoningEffort
207
+ repairedKey = key
208
+ pendingUsage = []
209
+ retrySameTarget = true
210
+ break
211
+ }
212
+ const verdict = classifyFailure(failure, policy, { alreadyCommitted: false })
213
+ if (verdict.retryable || verdict.requestScoped) {
214
+ swallowed = { chunk, verdict }
215
+ break
216
+ }
217
+ }
218
+
219
+ for (const pending of pendingUsage) yield pending
220
+ if (failure === undefined) {
221
+ if (chunk.reason?.kind !== 'aborted') {
222
+ state.recordSuccess(key, now())
223
+ if (policy.sticky === true) state.pin(sessionId, profile.id, key, now())
224
+ }
225
+ } else {
226
+ state.recordFailure(key, now(), policy.failureWindowMs)
227
+ state.setLastError({ key, code: failure.code, status: failure.status, message: failure.message, at: now() })
228
+ }
229
+ yield chunk
230
+ return
231
+ }
232
+
233
+ for (const pending of pendingUsage) yield pending
234
+ pendingUsage = []
235
+ yield chunk
236
+ if (OUTPUT_CHUNKS.has(chunk.type)) committed = true
237
+ }
238
+ } catch (error) {
239
+ // A thrown error is a broken contract or a consumer failure, not a route
240
+ // verdict. Only the walk's own pre-attempt errors are converted.
241
+ if (!committed) {
242
+ const failure = failureOf(error)
243
+ // The host rejects an effort the target does not declare before any
244
+ // I/O, and it throws instead of yielding a finish chunk. That is the
245
+ // same repair as below: drop the parameter, keep the route.
246
+ if (failure.code === 'UNSUPPORTED_REASONING_EFFORT' && attemptOptions.reasoningEffort !== undefined) {
247
+ attemptOptions = { ...attemptOptions }
248
+ delete attemptOptions.reasoningEffort
249
+ repairedKey = key
250
+ pendingUsage = []
251
+ retrySameTarget = true
252
+ } else {
253
+ const verdict = classifyFailure(failure, policy, { alreadyCommitted: false })
254
+ if (verdict.retryable) {
255
+ swallowed = { chunk: failureChunk(failure), verdict }
256
+ } else {
257
+ throw error
258
+ }
259
+ }
260
+ } else {
261
+ throw error
262
+ }
263
+ }
264
+
265
+ if (retrySameTarget) continue
266
+
267
+ if (swallowed === undefined) return
268
+
269
+ lastFailure = swallowed.chunk
270
+ // Usage the failed attempt already reported is real spend: replay it before
271
+ // the next attempt so the host can account for it.
272
+ for (const pending of pendingUsage) yield pending
273
+ pendingUsage = []
274
+
275
+ const streak = state.recordFailure(key, now(), policy.failureWindowMs)
276
+ const cooldown = cooldownFor(policy, entry, streak, swallowed.verdict, random)
277
+ if (!swallowed.verdict.requestScoped || policy.triggerCodes.includes(swallowed.verdict.code)) {
278
+ state.suppress(key, cooldown, now(), {
279
+ code: swallowed.verdict.code,
280
+ status: swallowed.verdict.status,
281
+ message: swallowed.verdict.reason,
282
+ })
283
+ }
284
+ state.setLastError({
285
+ key,
286
+ code: swallowed.verdict.code,
287
+ status: swallowed.verdict.status,
288
+ message: swallowed.verdict.reason,
289
+ at: now(),
290
+ })
291
+ const pin = state.session(sessionId, now(), policy.stickinessTtlMs)
292
+ if (pin?.key === key) state.unpin(sessionId)
293
+
294
+ if (switches >= policy.maxSwitches) {
295
+ yield swallowed.chunk
296
+ return
297
+ }
298
+ switches += 1
299
+ state.stats.switches += 1
300
+ log.debug?.(`llm-autorouter: ${key} failed (${swallowed.verdict.code}); trying the next route`)
301
+ index += 1
302
+ }
303
+ }
package/src/state.js ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * In-memory routing state: per-session stickiness, cooldowns, failure streaks,
3
+ * and counters. Nothing here is persisted: a restart
4
+ * clears every cooldown, which is the behaviour we want after a config change.
5
+ */
6
+
7
+ import { entryKey } from './config.js'
8
+
9
+ const HOUR = 60 * 60 * 1000
10
+
11
+ export class RouterState {
12
+ constructor({ now = Date.now, maxSessions = 1024 } = {}) {
13
+ this.now = now
14
+ this.maxSessions = maxSessions
15
+ this.sessions = new Map()
16
+ this.cooldowns = new Map()
17
+ this.failures = new Map()
18
+ this.stats = {
19
+ startedAt: now(),
20
+ attempts: 0,
21
+ successes: 0,
22
+ failures: 0,
23
+ switches: 0,
24
+ lastRoute: undefined,
25
+ lastError: undefined,
26
+ }
27
+ }
28
+
29
+ // ---- sessions ---------------------------------------------------------
30
+
31
+ session(sessionId, now = this.now(), ttlMs = 30 * 60 * 1000) {
32
+ if (typeof sessionId !== 'string' || sessionId === '') return undefined
33
+ const record = this.sessions.get(sessionId)
34
+ if (record === undefined) return undefined
35
+ if (now - record.at > ttlMs) {
36
+ this.sessions.delete(sessionId)
37
+ return undefined
38
+ }
39
+ return record
40
+ }
41
+
42
+ pin(sessionId, profileId, key, now = this.now()) {
43
+ if (typeof sessionId !== 'string' || sessionId === '') return
44
+ this.sessions.delete(sessionId)
45
+ this.sessions.set(sessionId, { profileId, key, at: now })
46
+ if (this.sessions.size > this.maxSessions) {
47
+ const oldest = this.sessions.keys().next().value
48
+ if (oldest !== undefined) this.sessions.delete(oldest)
49
+ }
50
+ }
51
+
52
+ unpin(sessionId) {
53
+ if (typeof sessionId === 'string') this.sessions.delete(sessionId)
54
+ }
55
+
56
+ touch(sessionId, now = this.now()) {
57
+ const record = typeof sessionId === 'string' ? this.sessions.get(sessionId) : undefined
58
+ if (record !== undefined) record.at = now
59
+ }
60
+
61
+ // ---- cooldowns --------------------------------------------------------
62
+
63
+ coolingUntil(key) {
64
+ return this.cooldowns.get(key)?.until ?? 0
65
+ }
66
+
67
+ isCooling(key, now = this.now()) {
68
+ return this.coolingUntil(key) > now
69
+ }
70
+
71
+ suppress(key, durationMs, now = this.now(), meta = {}) {
72
+ const until = Math.max(this.coolingUntil(key), now + Math.max(0, durationMs))
73
+ this.cooldowns.set(key, { ...this.cooldowns.get(key), ...meta, until, at: now })
74
+ return until
75
+ }
76
+
77
+ clearCooldown(key) {
78
+ this.cooldowns.delete(key)
79
+ }
80
+
81
+ // ---- failure streaks --------------------------------------------------
82
+
83
+ failureStreak(key, now = this.now(), windowMs = 2 * 60 * 1000) {
84
+ const record = this.failures.get(key)
85
+ if (record === undefined) return 0
86
+ if (now - record.lastAt > windowMs) {
87
+ this.failures.delete(key)
88
+ return 0
89
+ }
90
+ return record.count
91
+ }
92
+
93
+ recordFailure(key, now = this.now(), windowMs = 2 * 60 * 1000) {
94
+ const previous = this.failures.get(key)
95
+ const fresh = previous === undefined || now - previous.lastAt > windowMs
96
+ const count = fresh ? 1 : previous.count + 1
97
+ this.failures.set(key, { count, lastAt: now })
98
+ this.stats.failures += 1
99
+ return count
100
+ }
101
+
102
+ recordSuccess(key, now = this.now()) {
103
+ this.failures.delete(key)
104
+ this.clearCooldown(key)
105
+ this.stats.successes += 1
106
+ this.stats.lastRoute = key
107
+ this.stats.lastError = undefined
108
+ return now
109
+ }
110
+
111
+ // ---- counters ---------------------------------------------------------
112
+
113
+ noteAttempt(key) {
114
+ this.stats.attempts += 1
115
+ this.stats.lastRoute = key
116
+ }
117
+
118
+ // ---- bookkeeping ------------------------------------------------------
119
+
120
+ prune(now = this.now(), { sessionTtlMs = 30 * 60 * 1000, cooldownGraceMs = HOUR } = {}) {
121
+ for (const [key, record] of this.sessions) {
122
+ if (now - record.at > sessionTtlMs) this.sessions.delete(key)
123
+ }
124
+ for (const [key, record] of this.cooldowns) {
125
+ if (record.until + cooldownGraceMs < now) this.cooldowns.delete(key)
126
+ }
127
+ for (const [key, record] of this.failures) {
128
+ if (now - record.lastAt > HOUR) this.failures.delete(key)
129
+ }
130
+ }
131
+
132
+ setLastError(error) {
133
+ this.stats.lastError = error
134
+ }
135
+
136
+ /**
137
+ * Serializable view for the settings page. Contains no prompts, no message
138
+ * bodies and no credentials — only route ids and counters.
139
+ */
140
+ snapshot(config, now = this.now()) {
141
+ const routes = []
142
+ for (const profile of config.profiles) {
143
+ for (const entry of profile.chain) {
144
+ const key = entryKey(entry)
145
+ routes.push({
146
+ profileId: profile.id,
147
+ entryId: entry.id,
148
+ key,
149
+ provider: entry.provider,
150
+ model: entry.model,
151
+ label: entry.label,
152
+ enabled: entry.enabled,
153
+ coolingUntil: this.coolingUntil(key) || undefined,
154
+ failures: this.failureStreak(key, now),
155
+ })
156
+ }
157
+ }
158
+ return {
159
+ at: now,
160
+ stats: { ...this.stats },
161
+ routes,
162
+ sessions: [...this.sessions].map(([sessionId, record]) => ({
163
+ sessionId,
164
+ profileId: record.profileId,
165
+ key: record.key,
166
+ ageMs: now - record.at,
167
+ })),
168
+ }
169
+ }
170
+ }