dsh-llm-key-loop 0.0.0-stage → 2.4.1

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.
package/index.js ADDED
@@ -0,0 +1,673 @@
1
+ /**
2
+ * llm-key-loop v2 — walk one provider's own API keys, never another provider.
3
+ *
4
+ * Order per provider: DEFAULT -> CHAIN_1 -> CHAIN_2 -> CHAIN_3 -> … -> stop
5
+ *
6
+ * - The adapter reads the ACTIVE slot `<PROVIDER>_API_KEY`. This plugin only
7
+ * ever writes into that slot; it never writes into the key list itself, so no
8
+ * key can be lost.
9
+ * - The key list is `<PROVIDER>_API_KEY_DEFAULT`, then `<PROVIDER>_API_KEY_CHAIN_1..9`
10
+ * (only refs that hold a value; duplicates are skipped).
11
+ * - On first start, if `_DEFAULT` is empty, the current active key is copied
12
+ * into it, so your default key is preserved.
13
+ * - When a request fails with a key problem (spent allowance / quota, rejected
14
+ * key, rate limit), the key in use is marked failed for this turn and the next
15
+ * key that has not failed in this turn is activated, wrapping around the list.
16
+ * When every key has failed in the same turn the plugin STOPS and lets the
17
+ * error show. It never switches to a different provider.
18
+ * - A new turn (your next message) starts a fresh lap from the key that is
19
+ * active now.
20
+ *
21
+ * No key value is ever logged. Status is printed as `[llm-key-loop]` lines and
22
+ * written (without key values) to ~/.dsh/llm-key-loop-status.json.
23
+ *
24
+ * @module dsh-llm-key-loop
25
+ */
26
+
27
+ import { readFile, readdir, writeFile } from 'node:fs/promises'
28
+ import { createHash } from 'node:crypto'
29
+ import { homedir } from 'node:os'
30
+ import { join } from 'node:path'
31
+
32
+ const name = 'llm-key-loop'
33
+ const inject = ['agents', 'credentials']
34
+
35
+ const MAX_CHAIN = 9
36
+ const DSH_HOME = process.env.DSH_HOME && process.env.DSH_HOME.length > 0 ? process.env.DSH_HOME : join(homedir(), '.dsh')
37
+ const CREDENTIALS_FILE = join(DSH_HOME, '.credentials.yaml')
38
+ const STATUS_FILE = join(DSH_HOME, 'llm-key-loop-status.json')
39
+ const COUNTS_FILE = join(DSH_HOME, 'llm-key-loop-counts.json')
40
+
41
+ /** Codes the host already uses for key problems. */
42
+ const KEY_CODES = new Set(['QUOTA', 'AUTH', 'RATE_LIMIT', 'ACCOUNT_QUOTA', 'ACCOUNT_TOKEN_INVALID'])
43
+ /** Codes that are never a key problem; switching keys cannot help. */
44
+ const NEVER = new Set(['ABORTED', 'CONTEXT_WINDOW_EXCEEDED', 'INVALID_REQUEST', 'EMPTY_RESPONSE', 'TIMEOUT', 'TRANSPORT', 'SERVER'])
45
+
46
+ const QUOTA_TAGS = [
47
+ 'plan_allowance_exhausted', 'allowance_exhausted', 'allowance used up', 'allowance is used up',
48
+ 'allowance for this period', 'pass allowance', 'insufficient_quota', 'insufficient quota',
49
+ 'insufficient balance', 'insufficient_balance', 'insufficient_credits', 'quota_exceeded',
50
+ 'quota exceeded', 'quota exhausted', 'usage_limit_reached', 'usage limit reached',
51
+ 'monthly usage limit', 'out of credits', 'credits exhausted', 'balance exhausted',
52
+ 'payment_required', 'payment required', 'billing',
53
+ ]
54
+ const AUTH_TAGS = ['invalid_api_key', 'incorrect api key', 'invalid api key', 'unauthorized', 'authentication_error', 'api key expired', 'key revoked']
55
+ const RATE_TAGS = ['rate_limit_exceeded', 'rate limit', 'too many requests']
56
+
57
+ /** Default active-slot reference for a provider route id, e.g. token-harbor -> TOKEN_HARBOR_API_KEY. */
58
+ const REF_ALIASES = { 'deepseek-official': 'DEEPSEEK_API_KEY' }
59
+ function envRefOf(provider) {
60
+ if (REF_ALIASES[provider]) return REF_ALIASES[provider]
61
+ return `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
62
+ }
63
+
64
+ /** The ordered list refs for a provider: DEFAULT, CHAIN_1..9. */
65
+ function listRefsOf(activeRef) {
66
+ const refs = [`${activeRef}_DEFAULT`]
67
+ for (let i = 1; i <= MAX_CHAIN; i += 1) refs.push(`${activeRef}_CHAIN_${i}`)
68
+ return refs
69
+ }
70
+
71
+ /**
72
+ * Decide whether a failure is a key problem.
73
+ * @returns 'QUOTA' | 'AUTH' | 'RATE_LIMIT' | undefined
74
+ */
75
+ function classify(failure) {
76
+ if (failure === null || typeof failure !== 'object') return undefined
77
+ const code = typeof failure.code === 'string' ? failure.code : ''
78
+ if (NEVER.has(code)) return undefined
79
+ if (KEY_CODES.has(code)) return code === 'ACCOUNT_QUOTA' ? 'QUOTA' : code === 'ACCOUNT_TOKEN_INVALID' ? 'AUTH' : code
80
+ const status = typeof failure.status === 'number' ? failure.status : undefined
81
+ if (status === 401 || status === 403) return 'AUTH'
82
+ if (status === 402) return 'QUOTA'
83
+ if (status === 429) return 'RATE_LIMIT'
84
+ const text = `${code} ${typeof failure.message === 'string' ? failure.message : ''}`.toLowerCase()
85
+ if (/\b(?:401|403)\b/.test(text)) return 'AUTH'
86
+ for (const tag of AUTH_TAGS) if (text.includes(tag)) return 'AUTH'
87
+ if (/\b402\b/.test(text)) return 'QUOTA'
88
+ for (const tag of QUOTA_TAGS) if (text.includes(tag)) return 'QUOTA'
89
+ if (/\b429\b/.test(text)) return 'RATE_LIMIT'
90
+ for (const tag of RATE_TAGS) if (text.includes(tag)) return 'RATE_LIMIT'
91
+ return undefined
92
+ }
93
+
94
+ /** Merge config over defaults. */
95
+ function resolveConfig(raw) {
96
+ const src = raw !== null && typeof raw === 'object' ? raw : {}
97
+ const providers = {}
98
+ const rawProviders = src.providers !== null && typeof src.providers === 'object' ? src.providers : {}
99
+ for (const [id, p] of Object.entries(rawProviders)) {
100
+ const cfg = p !== null && typeof p === 'object' ? p : {}
101
+ if (cfg.enabled === false) continue
102
+ providers[id] = {
103
+ activeRef: typeof cfg.activeRef === 'string' && cfg.activeRef ? cfg.activeRef : envRefOf(id),
104
+ }
105
+ }
106
+ return { providers }
107
+ }
108
+
109
+ /**
110
+ * Pure loop step, exported for tests.
111
+ * @param keys - ordered `{ ref, value }` list (deduped, non-empty).
112
+ * @param activeValue - value now in the active slot.
113
+ * @param failed - Set of refs that already failed this turn (mutated: current key is added).
114
+ * @returns `{ next, current }` — next `{ref,value,index}` to activate, or `next: undefined` to stop.
115
+ */
116
+ function step(keys, activeValue, failed) {
117
+ let current = keys.findIndex((k) => k.value === activeValue)
118
+ if (current >= 0) failed.add(keys[current].ref)
119
+ const start = current >= 0 ? current + 1 : 0
120
+ for (let s = 0; s < keys.length; s += 1) {
121
+ const index = (start + s) % keys.length
122
+ if (!failed.has(keys[index].ref)) return { current, next: { ...keys[index], index } }
123
+ }
124
+ return { current, next: undefined }
125
+ }
126
+
127
+ function apply(ctx, rawConfig = {}) {
128
+ const config = resolveConfig(rawConfig)
129
+ const log = (msg) => console.log(`[llm-key-loop] ${msg}`)
130
+ /** Providers listed in config are prepared at startup; any other provider is picked up on its first failure. */
131
+ const ids = Object.keys(config.providers)
132
+ const providerConf = (id) => config.providers[id] ?? { activeRef: envRefOf(id) }
133
+ const disabled = new Set(
134
+ Object.entries(rawConfig?.providers ?? {}).filter(([, p]) => p?.enabled === false).map(([id]) => id),
135
+ )
136
+
137
+ /** provider -> { turnKey, failed:Set, lastEvent } */
138
+ const state = new Map()
139
+ /** Agent identity for turn scoping. */
140
+ const agentIds = new WeakMap()
141
+ let agentSeq = 0
142
+ const agentId = (agent) => {
143
+ if (agent === null || typeof agent !== 'object') return 'none'
144
+ let id = agentIds.get(agent)
145
+ if (id === undefined) { agentSeq += 1; id = agentSeq; agentIds.set(agent, id) }
146
+ return id
147
+ }
148
+
149
+ const resolveValue = async (ref) => {
150
+ try {
151
+ const r = await ctx.credentials.resolve(ref)
152
+ return r !== undefined && r !== null && typeof r.value === 'string' && r.value.length > 0 ? r.value : undefined
153
+ } catch {
154
+ return undefined
155
+ }
156
+ }
157
+
158
+ /** Ordered usable key list, duplicates removed. */
159
+ const loadKeys = async (activeRef) => {
160
+ const keys = []
161
+ const seen = new Set()
162
+ for (const ref of listRefsOf(activeRef)) {
163
+ const value = await resolveValue(ref)
164
+ if (value === undefined || seen.has(value)) continue
165
+ seen.add(value)
166
+ keys.push({ ref, value })
167
+ }
168
+ return keys
169
+ }
170
+
171
+ const writeStatus = async () => {
172
+ const out = { updatedAt: new Date().toISOString(), providers: {} }
173
+ for (const id of ids) {
174
+ const { activeRef } = providerConf(id)
175
+ const keys = await loadKeys(activeRef)
176
+ const active = await resolveValue(activeRef)
177
+ const st = state.get(id)
178
+ out.providers[id] = {
179
+ activeSlot: activeRef,
180
+ activeKey: keys.find((k) => k.value === active)?.ref ?? (active ? 'unlisted key' : 'none'),
181
+ order: keys.map((k) => ({ ref: k.ref, tail: k.value.slice(-4), failedThisTurn: st?.failed.has(k.ref) ?? false })),
182
+ lastEvent: st?.lastEvent ?? null,
183
+ }
184
+ }
185
+ await writeFile(STATUS_FILE, `${JSON.stringify(out, null, 2)}\n`, { mode: 0o600 }).catch(() => {})
186
+ }
187
+
188
+ /** Save the provider's current key as its DEFAULT when DEFAULT is empty, so it is never lost. */
189
+ const ensureDefault = async (activeRef) => {
190
+ const defRef = `${activeRef}_DEFAULT`
191
+ if ((await resolveValue(defRef)) !== undefined) return
192
+ const current = await resolveValue(activeRef)
193
+ if (current === undefined) return
194
+ await ctx.credentials.set(defRef, current)
195
+ log(`saved current ${activeRef} as ${defRef}`)
196
+ }
197
+
198
+ const ready = (async () => {
199
+ for (const id of ids) {
200
+ const { activeRef } = providerConf(id)
201
+ await ensureDefault(activeRef)
202
+ const keys = await loadKeys(activeRef)
203
+ log(`${id}: ${keys.length} key(s) in loop: ${keys.map((k) => k.ref.replace(`${activeRef}_`, '')).join(' -> ') || '(none)'}`)
204
+ }
205
+ await writeStatus()
206
+ })().catch((e) => log(`startup failed: ${e instanceof Error ? e.message : String(e)}`))
207
+
208
+ /** Status markers next to a key ref; the panel shows them as red badges. Values hold only a timestamp. */
209
+ const MARKERS = { QUOTA: 'LIMIT', AUTH: 'REJECTED', RATE_LIMIT: 'RATELIMITED' }
210
+ const markFailed = async (ref, reason) => {
211
+ const suffix = MARKERS[reason] ?? 'LIMIT'
212
+ await ctx.credentials.set(`${ref}_${suffix}`, `at-${new Date().toISOString()}`).catch(() => {})
213
+ if ((await resolveValue(`${ref}_OK`)) !== undefined) await ctx.credentials.unset(`${ref}_OK`).catch(() => {})
214
+ }
215
+ const clearMarkers = async (ref) => {
216
+ for (const suffix of [...Object.values(MARKERS), 'ERROR']) {
217
+ if ((await resolveValue(`${ref}_${suffix}`)) !== undefined) await ctx.credentials.unset(`${ref}_${suffix}`).catch(() => {})
218
+ }
219
+ }
220
+
221
+ /** On a successful model call, the key in use is healthy again: clear its red badge. */
222
+ const markOk = async (provider) => {
223
+ const { activeRef } = providerConf(provider)
224
+ const active = await resolveValue(activeRef)
225
+ if (active === undefined) return
226
+ for (const ref of listRefsOf(activeRef)) {
227
+ if ((await resolveValue(ref)) === active) { await clearMarkers(ref); return }
228
+ }
229
+ }
230
+
231
+ ctx.on('llm/stream', (options, next) => {
232
+ const provider = options?.provider
233
+ const source = next()
234
+ if (typeof provider !== 'string' || disabled.has(provider)) return source
235
+ return (async function* () {
236
+ let finish
237
+ let tokens = 0
238
+ for await (const chunk of source) {
239
+ if (chunk !== null && typeof chunk === 'object') {
240
+ if (chunk.type === 'finish') finish = chunk
241
+ else if (chunk.type === 'usage' && chunk.usage) tokens = Number(chunk.usage.totalTokens ?? (Number(chunk.usage.inputTokens) || 0) + (Number(chunk.usage.outputTokens) || 0)) || tokens
242
+ }
243
+ yield chunk
244
+ }
245
+ if (finish !== undefined && finish.reason?.kind !== 'error') {
246
+ markOk(provider).catch(() => {})
247
+ countLocal(provider, tokens).catch(() => {})
248
+ }
249
+ scheduleUsage(provider)
250
+ })()
251
+ })
252
+
253
+ // ── Key test (the panel's plug button) ─────────────────────────────────────
254
+ // The panel cannot read key values, so it asks by writing `<ref>_TESTREQ`.
255
+ // We send a 1-token request with that key and answer with markers:
256
+ // `<ref>_OK` on success, or `<ref>_LIMIT|REJECTED|RATELIMITED|ERROR` on failure.
257
+ /** Every profile's patch file (desktop, web, tui, …); the first that declares the provider wins. */
258
+ const profilePatches = async () => {
259
+ const dir = join(DSH_HOME, 'profiles')
260
+ const names = await readdir(dir).catch(() => [])
261
+ names.sort((a, b) => (a === 'desktop' ? -1 : b === 'desktop' ? 1 : a.localeCompare(b)))
262
+ return names.map((n) => join(dir, n, 'cordis.patch.yml'))
263
+ }
264
+ const RESULT_SUFFIXES = ['OK', 'ERROR', ...Object.values(MARKERS)]
265
+
266
+ /** Find a provider's baseURL, api style, and first model id in the profile patch. */
267
+ const endpointOf = async (provider) => {
268
+ for (const file of await profilePatches()) {
269
+ const found = parseEndpoint(await readFile(file, 'utf8').catch(() => ''), provider)
270
+ if (found !== undefined) return found
271
+ }
272
+ return undefined
273
+ }
274
+ const parseEndpoint = (text, provider) => {
275
+ const lines = text.split('\n')
276
+ const head = lines.findIndex((l) => new RegExp(`^(\\s+)${provider.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:\\s*$`).test(l))
277
+ if (head < 0) return undefined
278
+ const indent = lines[head].match(/^(\s*)/)[1].length
279
+ const out = {}
280
+ for (let i = head + 1; i < lines.length; i += 1) {
281
+ const line = lines[i]
282
+ if (line.trim() === '') continue
283
+ if (line.match(/^(\s*)/)[1].length <= indent) break
284
+ const base = line.match(/^\s+baseURL:\s*['"]?([^'"\s]+)/)
285
+ if (base && out.baseURL === undefined) out.baseURL = base[1].replace(/\/+$/, '')
286
+ const api = line.match(/^\s+api:\s*['"]?([^'"\s]+)/)
287
+ if (api && out.api === undefined) out.api = api[1]
288
+ const model = line.match(/^\s+-\s+id:\s*['"]?([^'"\s]+)/)
289
+ if (model && out.model === undefined) out.model = model[1]
290
+ }
291
+ return out.baseURL === undefined ? undefined : out
292
+ }
293
+
294
+ /** Which provider a key ref belongs to: the active-slot prefix before `_API_KEY`. */
295
+ const providerOfRef = (ref) => {
296
+ const m = ref.match(/^(.*)_API_KEY(?:_DEFAULT|_CHAIN_\d+)?$/)
297
+ if (!m) return undefined
298
+ return m[1].toLowerCase().replace(/_/g, '-')
299
+ }
300
+
301
+ const testing = new Set()
302
+ const runTest = async (ref) => {
303
+ if (testing.has(ref)) return
304
+ testing.add(ref)
305
+ try {
306
+ const provider = providerOfRef(ref)
307
+ const key = await resolveValue(ref)
308
+ const ep = provider === undefined ? undefined : await endpointOf(provider)
309
+ let suffix
310
+ if (key === undefined || ep === undefined) {
311
+ suffix = 'ERROR'
312
+ log(`test ${ref}: ${key === undefined ? 'no key stored' : `no endpoint found for ${provider}`}`)
313
+ } else {
314
+ const chat = ep.api === undefined || /openai|completions/i.test(ep.api)
315
+ const url = chat && ep.model ? `${ep.baseURL}/chat/completions` : `${ep.baseURL}/models`
316
+ const init = chat && ep.model
317
+ ? { method: 'POST', body: JSON.stringify({ model: ep.model, messages: [{ role: 'user', content: 'hi' }], max_tokens: 1 }) }
318
+ : { method: 'GET' }
319
+ try {
320
+ const res = await fetch(url, { ...init, headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' }, signal: AbortSignal.timeout(30_000) })
321
+ const body = res.ok ? '' : (await res.text().catch(() => '')).slice(0, 400)
322
+ if (res.ok) suffix = 'OK'
323
+ else suffix = MARKERS[classify({ code: '', status: res.status, message: body })] ?? 'ERROR'
324
+ // A 1-token chat can fail on the provider's side (e.g. 500 "empty response") although the key is fine: confirm with the model list.
325
+ if (suffix === 'ERROR' && res.status >= 500 && init.method === 'POST') {
326
+ const alt = await fetch(`${ep.baseURL}/models`, { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(20_000) }).catch(() => undefined)
327
+ if (alt?.ok) suffix = 'OK'
328
+ }
329
+ log(`test ${ref}: HTTP ${res.status} -> ${suffix}`)
330
+ } catch (e) {
331
+ suffix = 'ERROR'
332
+ log(`test ${ref}: request failed (${e instanceof Error ? e.message : String(e)})`)
333
+ }
334
+ }
335
+ for (const s of RESULT_SUFFIXES) if (s !== suffix && (await resolveValue(`${ref}_${s}`)) !== undefined) await ctx.credentials.unset(`${ref}_${s}`).catch(() => {})
336
+ await ctx.credentials.set(`${ref}_${suffix}`, `at-${new Date().toISOString()}`).catch(() => {})
337
+ } finally {
338
+ await ctx.credentials.unset(`${ref}_TESTREQ`).catch(() => {})
339
+ testing.delete(ref)
340
+ }
341
+ }
342
+
343
+ // ── Manual key choice (model menu → Key) ─────────────────────────────────────
344
+ // The menu writes `<ACTIVE>_PIN` = `p-D0000…` (main key), `p-C000N…` (Key N chain
345
+ // slot) or `p-A0000…` (keep the key in use). While a pin exists the loop does not
346
+ // switch that provider; removing the pin ("Default") turns automatic switching back on.
347
+ const pinTarget = (activeRef, value) => {
348
+ const m = typeof value === 'string' ? value.match(/^p-([DCA])(\d{4})/) : null
349
+ if (!m) return undefined
350
+ if (m[1] === 'D') return `${activeRef}_DEFAULT`
351
+ if (m[1] === 'C') return `${activeRef}_CHAIN_${Number(m[2])}`
352
+ return activeRef
353
+ }
354
+ const applyPin = async (activeRef) => {
355
+ const ref = pinTarget(activeRef, await resolveValue(`${activeRef}_PIN`))
356
+ if (ref === undefined || ref === activeRef) return
357
+ const key = await resolveValue(ref)
358
+ if (key === undefined) return
359
+ if ((await resolveValue(activeRef)) === key) return
360
+ await ctx.credentials.set(activeRef, key)
361
+ const provider = activeRef.replace(/_API_KEY$/, '').toLowerCase().replace(/_/g, '-')
362
+ log(`${provider}: switched by hand to ${ref} (pinned; automatic switching paused)`)
363
+ scheduleUsage(provider)
364
+ }
365
+
366
+ ctx.on('credentials/reference-updated', (ref) => {
367
+ const name = String(ref)
368
+ if (name.endsWith('_API_KEY_PIN')) applyPin(name.slice(0, -'_PIN'.length)).catch(() => {})
369
+ if (name.endsWith('_TESTREQ')) resolveValue(name).then((v) => { if (v !== undefined) runTest(name.slice(0, -'_TESTREQ'.length)) })
370
+ })
371
+ // Fallback: pick up requests even if the update event is not delivered to this plugin.
372
+ const sweep = setInterval(async () => {
373
+ const text = await readFile(CREDENTIALS_FILE, 'utf8').catch(() => '')
374
+ for (const m of text.matchAll(/^\s+([A-Z0-9_]+)_TESTREQ:/gm)) runTest(m[1])
375
+ for (const m of text.matchAll(/^\s+([A-Z0-9_]+_API_KEY)_PIN:/gm)) applyPin(m[1]).catch(() => {})
376
+ }, 3000)
377
+ ctx.effect(() => () => clearInterval(sweep), 'llm-key-loop: test sweep')
378
+
379
+ // ── Allowance usage ─────────────────────────────────────────────────────────
380
+ // Each source reads a provider's own, key-authenticated usage API and returns
381
+ // limit windows: { kind, pct, spent, resetAt }. Published per key as
382
+ // `<ref>_USAGE`, `<ref>_USAGE2`, `<ref>_USAGE3` = `u-PPPFW` + 8 zeros + `MMDD`
383
+ // so the credential store's masked preview (identifier + first 5 + last 4)
384
+ // carries it to the panel. PPP = percent used, F = n normal | x spent,
385
+ // W = window: w weekly | m monthly | h 5-hour | p plan period, MMDD = local reset date.
386
+ // `_USAGE` is the window closest to its limit. No key value is ever exposed.
387
+ const pctOf = (used, total) => (Number(total) > 0 ? (Number(used) / Number(total)) * 100 : 0)
388
+ const USAGE_SOURCES = [
389
+ {
390
+ // Token Harbor: weekly Pass allowance (docs: /docs/api/allowance)
391
+ match: /(^|\.)tokenharbor\.ai$/i,
392
+ url: () => 'https://tokenharbor.ai/api/cli/free-tier',
393
+ parse: (d) => {
394
+ const onPlan = d.on_plan === true
395
+ return [{ kind: 'w', pct: Number(onPlan ? d.plan_used_pct : d.used_pct) || 0, spent: onPlan ? d.plan_exhausted === true : d.exhausted === true, resetAt: d.reset_at }]
396
+ },
397
+ },
398
+ {
399
+ // Xiaomi MiMo Token Plan: credits for the plan period (docs: api/asset/credits-get)
400
+ match: /(^|\.)xiaomimimo\.com$/i,
401
+ url: (ep) => `${ep.baseURL}/platform/token_plan`,
402
+ parse: (d) => {
403
+ const q = d.quota ?? {}
404
+ const end = typeof d.period?.end_at === 'string' ? `${d.period.end_at.replace(' ', 'T')}Z` : undefined
405
+ return [{ kind: 'p', pct: pctOf(q.used_credits, q.total_credits), spent: Number(q.remaining_credits) <= 0 && Number(q.total_credits) > 0, resetAt: end }]
406
+ },
407
+ },
408
+ {
409
+ // ClinePass: 5-hour, weekly and monthly windows (Cline dashboard endpoint)
410
+ match: /(^|\.)cline\.bot$/i,
411
+ url: () => 'https://api.cline.bot/api/v1/users/me/plan/usage-limits',
412
+ parse: (d) => {
413
+ const kinds = { five_hour: 'h', weekly: 'w', monthly: 'm' }
414
+ return (d.data?.limits ?? []).filter((l) => kinds[l.type]).map((l) => ({ kind: kinds[l.type], pct: Number(l.percentUsed) || 0, spent: Number(l.percentUsed) >= 100, resetAt: l.resetsAt }))
415
+ },
416
+ },
417
+ ]
418
+ const usageCache = new Map() // `${url}|${key}` -> { at, data }
419
+ const USAGE_TTL_MS = 30_000
420
+
421
+ const usageSourceOf = async (provider) => {
422
+ const ep = await endpointOf(provider)
423
+ if (ep === undefined) return undefined
424
+ let host
425
+ try { host = new URL(ep.baseURL).hostname } catch { return undefined }
426
+ const source = USAGE_SOURCES.find((s) => s.match.test(host))
427
+ return source === undefined ? undefined : { ...source, endpoint: ep }
428
+ }
429
+
430
+ const fetchUsage = async (source, key) => {
431
+ const url = source.url(source.endpoint)
432
+ const id = `${url}|${key}`
433
+ const hit = usageCache.get(id)
434
+ if (hit !== undefined && Date.now() - hit.at < USAGE_TTL_MS) return hit.data
435
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${key}`, 'api-key': key }, signal: AbortSignal.timeout(15_000) })
436
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
437
+ const data = source.parse(await res.json())
438
+ usageCache.set(id, { at: Date.now(), data })
439
+ return data
440
+ }
441
+
442
+ const encodeWindow = (w) => {
443
+ const pct = Math.max(0, Math.min(100, Math.round(w.pct)))
444
+ let mmdd = '0000'
445
+ if (typeof w.resetAt === 'string') {
446
+ const t = new Date(w.resetAt)
447
+ if (!Number.isNaN(t.getTime())) mmdd = `${String(t.getMonth() + 1).padStart(2, '0')}${String(t.getDate()).padStart(2, '0')}`
448
+ }
449
+ return `u-${String(pct).padStart(3, '0')}${w.spent ? 'x' : 'n'}${w.kind}${'0'.repeat(8)}${mmdd}`
450
+ }
451
+
452
+ /** Providers that have a usage source and stored keys, from the credential file. */
453
+ const usageProviders = async () => {
454
+ const text = await readFile(CREDENTIALS_FILE, 'utf8').catch(() => '')
455
+ const found = new Set()
456
+ for (const m of text.matchAll(/^\s+([A-Z0-9_]+)_API_KEY:/gm)) found.add(m[1].toLowerCase().replace(/_/g, '-'))
457
+ const out = []
458
+ for (const id of found) {
459
+ if (disabled.has(id)) continue
460
+ const source = await usageSourceOf(id)
461
+ if (source !== undefined) out.push({ id, source })
462
+ }
463
+ return out
464
+ }
465
+
466
+ const refreshUsage = async (only) => {
467
+ await Promise.all((await usageProviders()).map(async ({ id, source }) => {
468
+ if (only !== undefined && only !== id) return
469
+ const { activeRef } = providerConf(id)
470
+ for (const ref of [activeRef, ...listRefsOf(activeRef)]) {
471
+ const key = await resolveValue(ref)
472
+ if (key === undefined) continue
473
+ let windows
474
+ try { windows = await fetchUsage(source, key) } catch { continue }
475
+ if (!Array.isArray(windows) || windows.length === 0) continue
476
+ const ordered = [...windows].sort((a, b) => (b.spent - a.spent) || (b.pct - a.pct))
477
+ const spent = ordered.some((w) => w.spent)
478
+ const names = ['USAGE', 'USAGE2', 'USAGE3']
479
+ for (let i = 0; i < names.length; i += 1) {
480
+ const want = ordered[i] === undefined ? undefined : encodeWindow(ordered[i])
481
+ const have = await resolveValue(`${ref}_${names[i]}`)
482
+ if (want === undefined && have !== undefined) await ctx.credentials.unset(`${ref}_${names[i]}`).catch(() => {})
483
+ else if (want !== undefined && want !== have) await ctx.credentials.set(`${ref}_${names[i]}`, want).catch(() => {})
484
+ }
485
+ const enc = { spent }
486
+ if (ref === activeRef) continue
487
+ // Keep the red badge in step with the provider's own answer.
488
+ const limited = (await resolveValue(`${ref}_LIMIT`)) !== undefined
489
+ if (enc.spent && !limited) await ctx.credentials.set(`${ref}_LIMIT`, `at-${new Date().toISOString()}`).catch(() => {})
490
+ if (!enc.spent && limited) await ctx.credentials.unset(`${ref}_LIMIT`).catch(() => {})
491
+ }
492
+ }))
493
+ }
494
+
495
+ let usageTimer
496
+ /** Debounced refresh after a switch or a finished reply. */
497
+ const scheduleUsage = (provider) => {
498
+ clearTimeout(usageTimer)
499
+ usageTimer = setTimeout(() => { refreshUsage(provider).catch(() => {}) }, 3000)
500
+ }
501
+ setTimeout(() => { refreshUsage().catch(() => {}) }, 2000)
502
+ const usagePoll = setInterval(() => { refreshUsage().catch(() => {}) }, 60_000)
503
+ ctx.effect(() => () => { clearInterval(usagePoll); clearTimeout(usageTimer) }, 'llm-key-loop: usage poll')
504
+
505
+ // ── Local usage count (for providers whose API keys cannot read their own usage) ──
506
+ // Every successful reply is counted per key in COUNTS_FILE (numbers only; keys are
507
+ // identified by a short hash). The day resets at local midnight.
508
+ // Published as `<ref>_LOCAL` = `l-RRRRZ` + 8 zeros + `TTTT`, so the masked preview
509
+ // carries it: RRRR requests today (capped 9999), Z = l (local-midnight reset),
510
+ // TTTT = tokens today (4 digits, or compact like 142K / 1.8M / 12M_).
511
+ // An optional daily request limit `<ACTIVE>_RPD` = `r-NNNNN…` (written by the panel)
512
+ // turns the count into a "Daily" percentage for providers with no usage API.
513
+ const keyId = (key) => createHash('sha256').update(key).digest('hex').slice(0, 12)
514
+ const zoneOf = async () => 'l'
515
+ const dayIn = (_zone, at = new Date()) => new Intl.DateTimeFormat('en-CA', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(at)
516
+ const compact = (n) => {
517
+ if (n < 10000) return String(n).padStart(4, '0')
518
+ const fmt = (v, u) => { const t = v >= 100 ? String(Math.round(v)) : v >= 10 ? String(Math.round(v)) : v.toFixed(1); return `${t}${u}`.slice(0, 4).padEnd(4, '_') }
519
+ if (n < 1e6) return fmt(n / 1e3, 'K')
520
+ if (n < 1e9) return fmt(n / 1e6, 'M')
521
+ return fmt(n / 1e9, 'B')
522
+ }
523
+ let counts
524
+ const loadCounts = async () => {
525
+ if (counts === undefined) counts = JSON.parse(await readFile(COUNTS_FILE, 'utf8').catch(() => '{}') || '{}')
526
+ return counts
527
+ }
528
+ let countsWrite = Promise.resolve()
529
+ const saveCounts = () => { countsWrite = countsWrite.then(() => writeFile(COUNTS_FILE, `${JSON.stringify(counts)}\n`, { mode: 0o600 })).catch(() => {}); return countsWrite }
530
+
531
+ /** Replies finishing together must not overwrite each other's count: one at a time. */
532
+ let countChain = Promise.resolve()
533
+ const countLocal = (provider, tokens) => {
534
+ const run = countChain.then(() => countLocalNow(provider, tokens))
535
+ countChain = run.catch(() => {})
536
+ return run
537
+ }
538
+ const countLocalNow = async (provider, tokens) => {
539
+ const { activeRef } = providerConf(provider)
540
+ const key = await resolveValue(activeRef)
541
+ if (key === undefined) return
542
+ const zone = await zoneOf(provider)
543
+ const day = dayIn(zone)
544
+ const all = await loadCounts()
545
+ const p = (all[provider] ??= {})
546
+ const id = keyId(key)
547
+ const c = p[id]?.day === day ? p[id] : { day, requests: 0, tokens: 0 }
548
+ c.requests += 1
549
+ c.tokens += Math.max(0, Math.round(tokens) || 0)
550
+ p[id] = c
551
+ await saveCounts()
552
+ await publishLocal(provider)
553
+ }
554
+
555
+ const publishLocal = async (provider) => {
556
+ const { activeRef } = providerConf(provider)
557
+ const zone = await zoneOf(provider)
558
+ const day = dayIn(zone)
559
+ const all = await loadCounts()
560
+ const p = all[provider] ?? {}
561
+ const active = await resolveValue(activeRef)
562
+ const rpd = String((await resolveValue(`${activeRef}_RPD`)) ?? '').match(/^r-(\d{5})/)
563
+ const limit = rpd ? Number(rpd[1]) : 0
564
+ const hasSource = (await usageSourceOf(provider)) !== undefined
565
+ for (const ref of [activeRef, ...listRefsOf(activeRef)]) {
566
+ const key = await resolveValue(ref)
567
+ if (key === undefined) continue
568
+ const c = p[keyId(key)]
569
+ const requests = c?.day === day ? c.requests : 0
570
+ const tokens = c?.day === day ? c.tokens : 0
571
+ const want = `l-${String(Math.min(requests, 9999)).padStart(4, '0')}${zone}${'0'.repeat(8)}${compact(tokens)}`
572
+ if ((await resolveValue(`${ref}_LOCAL`)) !== want) await ctx.credentials.set(`${ref}_LOCAL`, want).catch(() => {})
573
+ if (!hasSource && (ref !== activeRef || key === active)) {
574
+ // No provider usage API: turn the local count into a "Daily" window when a limit is set.
575
+ const usage = limit > 0 ? encodeWindow({ kind: 'd', pct: (requests / limit) * 100, spent: requests >= limit, resetAt: undefined }) : undefined
576
+ const have = await resolveValue(`${ref}_USAGE`)
577
+ if (usage === undefined && have !== undefined && /^u-\d{3}[nx]d/.test(have)) await ctx.credentials.unset(`${ref}_USAGE`).catch(() => {})
578
+ else if (usage !== undefined && usage !== have) await ctx.credentials.set(`${ref}_USAGE`, usage).catch(() => {})
579
+ }
580
+ }
581
+ }
582
+
583
+ /** Re-publish every counted provider (new day, limit change, key switch). */
584
+ const publishAllLocal = async () => {
585
+ const all = await loadCounts()
586
+ const text = await readFile(CREDENTIALS_FILE, 'utf8').catch(() => '')
587
+ const ids = new Set(Object.keys(all))
588
+ for (const m of text.matchAll(/^\s+([A-Z0-9_]+)_API_KEY_RPD:/gm)) ids.add(m[1].toLowerCase().replace(/_/g, '-'))
589
+ for (const id of ids) await publishLocal(id).catch(() => {})
590
+ }
591
+ setTimeout(() => { publishAllLocal().catch(() => {}) }, 2500)
592
+ const localPoll = setInterval(() => { publishAllLocal().catch(() => {}) }, 60_000)
593
+ ctx.effect(() => () => clearInterval(localPoll), 'llm-key-loop: local count poll')
594
+ ctx.on('credentials/reference-updated', (ref) => {
595
+ const name = String(ref)
596
+ if (name.endsWith('_API_KEY_RPD')) publishLocal(name.slice(0, -'_API_KEY_RPD'.length).toLowerCase().replace(/_/g, '-')).catch(() => {})
597
+ })
598
+
599
+ /** Serialize rotations per provider so concurrent failures don't skip keys. */
600
+ const queues = new Map()
601
+
602
+ const handle = async (payload, next) => {
603
+ const { provider, failure, agent, turn, signal } = payload
604
+ if (typeof provider !== 'string' || provider === '' || disabled.has(provider)) return next()
605
+ const reason = classify(failure)
606
+ if (reason === undefined) return next()
607
+ await ready
608
+ const pc = providerConf(provider)
609
+ if ((await resolveValue(`${pc.activeRef}_PIN`)) !== undefined) {
610
+ log(`${provider}: ${reason} on a key chosen by hand; not switching (pick Default in the model menu to resume)`)
611
+ if (/^p-/.test(String(await resolveValue(`${pc.activeRef}_PIN`)))) {
612
+ const active = await resolveValue(pc.activeRef)
613
+ for (const ref of listRefsOf(pc.activeRef)) if ((await resolveValue(ref)) === active) { await markFailed(ref, reason); break }
614
+ }
615
+ return next()
616
+ }
617
+ // Only providers with at least one backup key take part; adding keys in the panel opts a provider in.
618
+ const hasBackup = await (async () => {
619
+ for (const ref of listRefsOf(pc.activeRef).slice(1)) if ((await resolveValue(ref)) !== undefined) return true
620
+ return false
621
+ })()
622
+ if (!hasBackup) return next()
623
+ await ensureDefault(pc.activeRef)
624
+ if (!ids.includes(provider)) ids.push(provider)
625
+
626
+ const turnKey = `${agentId(agent)}:${typeof turn === 'number' ? turn : 0}`
627
+ let st = state.get(provider)
628
+ if (st === undefined || st.turnKey !== turnKey) {
629
+ st = { turnKey, failed: new Set(), lastEvent: st?.lastEvent ?? null }
630
+ state.set(provider, st)
631
+ }
632
+
633
+ const keys = await loadKeys(pc.activeRef)
634
+ if (keys.length < 2) {
635
+ log(`${provider}: ${reason} but only ${keys.length} key(s) stored; nothing to switch to`)
636
+ return next()
637
+ }
638
+ const active = await resolveValue(pc.activeRef)
639
+ const { current, next: choice } = step(keys, active, st.failed)
640
+ const from = current >= 0 ? keys[current].ref : 'unlisted key'
641
+ if (current >= 0) await markFailed(from, reason)
642
+
643
+ if (choice === undefined) {
644
+ st.lastEvent = { at: new Date().toISOString(), type: 'stopped', reason, from, message: `all ${keys.length} keys failed this turn` }
645
+ log(`${provider}: all ${keys.length} keys failed this turn (${reason}); stopping, not switching provider`)
646
+ await writeStatus()
647
+ return next()
648
+ }
649
+ if (signal?.aborted === true) return undefined
650
+
651
+ await ctx.credentials.set(pc.activeRef, choice.value)
652
+ st.lastEvent = { at: new Date().toISOString(), type: 'rotated', reason, from, to: choice.ref }
653
+ log(`${provider}: ${from} failed (${reason}) -> switched to ${choice.ref} [${st.failed.size}/${keys.length} failed this turn]`)
654
+ await writeStatus()
655
+ scheduleUsage(provider)
656
+ return { kind: 'retry' }
657
+ }
658
+
659
+ ctx.on('agent/request-error', (payload, next) => {
660
+ const id = payload?.provider
661
+ const prev = queues.get(id) ?? Promise.resolve()
662
+ const result = prev.then(() => handle(payload, next)).catch((e) => {
663
+ log(`handler error, passing failure on: ${e instanceof Error ? e.message : String(e)}`)
664
+ return next()
665
+ })
666
+ queues.set(id, result.then(() => undefined, () => undefined))
667
+ return result
668
+ })
669
+
670
+ ctx.effect(() => () => { state.clear(); queues.clear() }, 'llm-key-loop: clear state')
671
+ }
672
+
673
+ export { apply, classify, envRefOf, inject, listRefsOf, name, resolveConfig, step }