@goodandready/dsh-key-rotation 0.7.26 → 0.7.28

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/lib/index.js CHANGED
@@ -1,1402 +1,1658 @@
1
- // ─────────────────────────────────────────────────────────────────────────────
2
- // dsh-key-rotation — per-provider API key rotation for DeepSeek Harness.
3
- //
4
- // Transparent key rotation, Hermes-style: every configured provider has a KEY
5
- // POOL (env refs). The plugin patches `ctx.credentials.resolve` so a pool ref
6
- // resolves to the next available key (round-robin, skipping keys in cooldown),
7
- // and intercepts `llm/stream` to retry a request on the next key when the
8
- // current one fails with a switchable error (QUOTA, RATE_LIMIT, ...) before
9
- // any content chunk.
10
- //
11
- // The PROVIDER IDENTITY NEVER CHANGES: requests always go out with the
12
- // provider the user selected, only the resolved API key differs. This keeps
13
- // pi-ai's replay state consistent across multi-call turns and multi-turn
14
- // sessions (the earlier clone-provider approach broke it with
15
- // INVALID_REPLAY_STATE).
16
- //
17
- // Config is a KEY POOL PER PROVIDER: you list a real provider id and the env
18
- // names of its API keys (e.g. <PROVIDER>_API_KEY, <PROVIDER>_API_KEY_2, ...).
19
- // When a key's limit is exhausted, the request retries on the next key in the
20
- // list; exhausted keys stay in cooldown for cooldownMs. Clone provider routes
21
- // (named `<base>-2`, `<base>-3`, ...) are no longer used for rotation but
22
- // remain registered, so selecting them also rotates (their apiKeyEnv ref
23
- // belongs to the same pool).
24
- //
25
- // The Settings section ("Key Rotation") edits the provider key pools as a
26
- // simple list: pick a provider from the dropdown of every provider registered
27
- // with ctx.llm (clone routes are hidden from the dropdown), then add/remove key
28
- // env names. Plus cooldown and switch codes.
29
- //
30
- // Config (all optional, sane defaults):
31
- // switchCodes: string[] failure codes eligible to switch
32
- // cooldownMs: number key cooldown after a switchable failure
33
- // providers: array [{ provider, keys: [envName, ...] }]
34
- // ─────────────────────────────────────────────────────────────────────────────
35
- import Schema from '@deepseek-ai/schemastery';
36
- import { keyTail, isLoopbackAddress, isTrustedBridgeRequest, SWITCHABLE_MESSAGE_PATTERN, DEFAULT_SWITCH_CODES, isValidRef, pickNext, applyCooldown, recordFailure, recordSuccess, computeBackoff, envValue, sweepExpired, parseRetryAfter, computeHealthScore, extractRateLimit, isRateLimited } from './pool.js';
37
-
38
- export const name = 'dsh-key-rotation';
39
- export const inject = ['llm', 'webServer', 'settings', 'credentials'];
40
- export { keyTail, isLoopbackAddress, isTrustedBridgeRequest, DEFAULT_SWITCH_CODES };
41
-
42
- /** Settings namespace owning the GUI-editable section (settingsNamespace-valid). */
43
- const NS = 'dsh-key-rotation';
44
- /** Config bridge route (GET / PUT / DELETE), loopback-fenced like llm-fallback. */
45
- const CONFIG_PATH = '/dsh-key-rotation/config';
46
- const STATUS_PATH = '/dsh-key-rotation/status';
47
- const KEY_PATH = '/dsh-key-rotation/key';
48
- const RESET_PATH = '/dsh-key-rotation/reset';
49
- const IMPORT_PATH = '/dsh-key-rotation/import';
50
- const HEALTH_PATH = '/dsh-key-rotation/health';
51
- const TEST_PATH = '/dsh-key-rotation/test';
52
- const SANDBOX_CACHE_PATH = '/dsh-key-rotation/sandbox-cache';
53
- const AGENT_BUDGET_PATH = '/dsh-key-rotation/agent-budget';
54
- const REGIONS_PATH = '/dsh-key-rotation/regions';
55
- const INCIDENT_RESET_PATH = '/dsh-key-rotation/incident-reset';
56
- const SHADOW_PATH = '/dsh-key-rotation/shadow';
57
- const WEBHOOK_TEST_PATH = '/dsh-key-rotation/webhook-test';
58
- const TEST_MATRIX_PATH = '/dsh-key-rotation/test-matrix';
59
- import { LastTestCache, SandboxRunner } from './sandbox.js';
60
- import { healIdleCooldowns } from './heal.js';
61
- import { LatencyHistogram } from './histogram.js';
62
- import { pickCascadeFallback } from './cascade.js';
63
- import { ConcurrencyTracker } from './concurrency.js';
64
- import { nextQuotaReset } from './quota-window.js';
65
- import { CanaryProber } from './canary.js';
66
- import { QuotaStore } from './quota.js';
67
- import { AgentBudget } from './agent-budget.js';
68
- import { RegionMap } from './region.js';
69
- import { IncidentReporter } from './incident.js';
70
- import { ShadowRouter } from './shadow.js';
71
- import { WebhookSender } from './webhook.js';
72
-
73
- /** The llm-pi-ai namespace whose provider profiles map providers to pools. */
74
- const PIAI_NS = 'llm-pi-ai';
75
- /** Marker on internally re-dispatched requests so the interceptor does not loop. */
76
- const MARKER = '__dshKeyRotation';
77
- const MAX_EVENTS = 50;
78
- function pushEvent(pool, ref, reason, cooldownMs, type) {
79
- const ev = { at: Date.now(), ref, reason: String(reason ?? 'UNKNOWN'), cooldownMs, type: type ?? 'fail' };
80
- pool.state.events.push(ev);
81
- if (pool.state.events.length > MAX_EVENTS) pool.state.events.shift();
82
- }
83
-
84
-
85
- // Fallback classification by failure message. pi-ai surfaces many real quota /
86
- // rate-limit / transport failures as thrown exceptions (e.g. the OpenAI SDK
87
- // throws on HTTP 429 before the stream starts), and dsh-llm then normalizes
88
- // them to finish chunks with code "UNKNOWN". The message still carries the
89
- // provider's own text ("429: ...", "Weekly usage limit reached", ...), so we
90
- // treat pre-content failures whose message matches these patterns as
91
- // switchable even when the code is not in `switchCodes`.
92
-
93
- // Sandbox-test infrastructure (sandbox.js): in-memory cache + runner.
94
- let lastTestCacheRunnerCtx = null;
95
- const lastTestCache = new LastTestCache();
96
- const latencyHistogram = new LatencyHistogram();
97
- const quotaStore = new QuotaStore();
98
- const agentBudget = new AgentBudget();
99
- const regionMap = new RegionMap();
100
- // IncidentReporter: lazily built when Config provides incidentGitHubToken + incidentGitHubBaseUrl.
101
- // ponytail: never bake the token into source; repo is hardcoded (this plugin's home repo) but token is per-deploy.
102
- let incidentReporter = null;
103
- function ensureIncidentReporter() {
104
- if (incidentReporter) return incidentReporter;
105
- const cfg = getConfig();
106
- const token = cfg ? cfg.incidentGitHubToken : '';
107
- const baseUrl = cfg ? cfg.incidentGitHubBaseUrl : '';
108
- if (!token || !baseUrl) return null;
109
- incidentReporter = new IncidentReporter({ token, baseUrl, repo: 'goodandready/dsh-key-rotation', fetchImpl: globalThis.fetch });
110
- return incidentReporter;
111
- }
112
- const shadowRouter = new ShadowRouter({ primary: '', secondary: '', percent: 0 });let sandboxRunner = null;
113
- const webhookSender = new WebhookSender({ fetchImpl: globalThis.fetch });
114
- const concurrencyTracker = new ConcurrencyTracker();
115
- let canaryProber = null;
116
- function ensureSandboxRunner(ctx) {
117
- if (sandboxRunner) return sandboxRunner;
118
- // provider id -> baseUrl (stripped of trailing /) for fetch /models probe
119
- function resolveBaseUrl(provider) {
120
- try {
121
- const ns = ctx.get(PIAI_NS);
122
- const list = ns && (ns.providers || (ns.config && ns.config.providers) || []);
123
- if (!Array.isArray(list)) return null;
124
- // ponytail: match by id OR name OR alias; pick first hit
125
- const hit = list.find((p) => p && (p.id === provider || p.name === provider || (Array.isArray(p.aliases) && p.aliases.includes(provider))));
126
- const base = hit && (hit.baseUrl || hit.endpoint || hit.url);
127
- return base ? String(base) : null;
128
- } catch (e) {
129
- return null;
130
- }
131
- }
132
- sandboxRunner = new SandboxRunner({ fetchImpl: globalThis.fetch, resolveBaseUrl });
133
- return sandboxRunner;
134
- }
135
- async function probeRef(ref, key) {
136
- // ref may be like "PROVIDER/KEY_NAME" for sandbox we only care about the credential ref
137
- // (the resolveBaseUrl uses the full provider id; ref can carry any string)
138
- const runner = ensureSandboxRunner(lastTestCacheRunnerCtx);
139
- const result = await runner.probeModels(ref, key);
140
- lastTestCache.set(ref, { ...result, at: Date.now() });
141
- return result;
142
- }
143
-
144
- // // Bootstrap key pools. The user configures them in the Settings GUI or via
145
- // the dsh profile bundle config; the plugin itself ships no provider defaults
146
- // so it does not bind to any specific installation. Empty array means: until
147
- // the user adds a pool, no rotation happens, and every provider falls back to
148
- // its single configured credential exactly as before this plugin was installed.
149
- const DEFAULT_PROVIDERS = [];
150
-
151
- export const Config = Schema.object({
152
- switchCodes: Schema.array(Schema.string()).default([...DEFAULT_SWITCH_CODES]),
153
- cooldownMs: Schema.number().default(60000),
154
- maxCooldownMs: Schema.number(),
155
- notifyWebhook: Schema.string().default(''),
156
- notifyThreshold: Schema.number().default(3),
157
- backupDir: Schema.string().default(''),
158
- backupIntervalMs: Schema.number().default(86400000),
159
- backupKeep: Schema.number().default(7),
160
- rotationScheduleDays: Schema.number().default(0),
161
- selfHealCooldown: Schema.boolean().default(true),
162
- selfHealIdleMs: Schema.number().default(3600000),
163
- latencyEnabled: Schema.boolean().default(true),
164
- latencyWindow: Schema.number().default(200),
165
- incidentGitHubToken: Schema.string().default(''),
166
- incidentGitHubBaseUrl: Schema.string().default(''),
167
- incidentThreshold: Schema.number().default(5),
168
- concurrencyLimit: Schema.number().default(0),
169
- canaryProbingEnabled: Schema.boolean().default(false),
170
- canaryIntervalMs: Schema.number().default(30000),
171
- cascade: Schema.array(Schema.object({
172
- provider: Schema.string().required(),
173
- model: Schema.string(),
174
- })).default([]),
175
- quotaResetWindow: Schema.object({
176
- type: Schema.string().default('midnight_utc'),
177
- hour: Schema.number().default(0),
178
- }),
179
- rateLimitThreshold: Schema.number().default(0.1),
180
- providers: Schema.array(Schema.object({
181
- provider: Schema.string().required(),
182
- keys: Schema.array(Schema.string()).default([]),
183
- weights: Schema.array(Schema.number()).default([]),
184
- expiresAt: Schema.array(Schema.union([Schema.number(), Schema.string()])).default([]),
185
- models: Schema.dict(Schema.object({
186
- keys: Schema.array(Schema.string()).default([]),
187
- weights: Schema.array(Schema.number()).default([]),
188
- })).default({}),
189
- cooldownMs: Schema.number(),
190
- maxCooldownMs: Schema.number(),
191
- })).default([...DEFAULT_PROVIDERS]),
192
- });
193
-
194
- // ── config bridge (GET/PUT/DELETE on CONFIG_PATH), mirroring llm-fallback ──
195
-
196
-
197
- function json(res, status, obj) {
198
- res.writeHead(status, { 'content-type': 'application/json' });
199
- res.end(JSON.stringify(obj));
200
- }
201
-
202
- function readJson(request) {
203
- return new Promise((resolve, reject) => {
204
- let raw = '';
205
- request.on('data', (c) => { raw += c; });
206
- request.on('end', () => {
207
- try {
208
- resolve(JSON.parse(raw || '{}'));
209
- } catch (e) {
210
- reject(e);
211
- }
212
- });
213
- request.on('error', reject);
214
- });
215
- }
216
-
217
- function descriptorOf(ctx, ns) {
218
- const settings = ctx.get('settings');
219
- if (settings === void 0) return void 0;
220
- return settings.describe({ redactSecrets: true }).find((candidate) => candidate.ns === ns);
221
- }
222
-
223
- function viewOf(descriptor, settings) {
224
- return {
225
- available: true,
226
- writable: settings.writable,
227
- hasDocument: settings.hasDocument,
228
- value: descriptor.value,
229
- ...descriptor.base === void 0 ? {} : { base: descriptor.base },
230
- ...descriptor.user === void 0 || Object.keys(descriptor.user).length === 0 ? {} : { user: descriptor.user },
231
- revision: descriptor.revision,
232
- };
233
- }
234
-
235
- async function writeSection(ctx, ns, section, expectedRevision, res) {
236
- const settings = ctx.get('settings');
237
- if (settings === void 0) {
238
- json(res, 503, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: no settings provider is mounted' } });
239
- return;
240
- }
241
- try {
242
- await settings.replace(ns, section, expectedRevision);
243
- } catch (error) {
244
- if (error?.code === 'SETTINGS_CONFLICT') {
245
- json(res, 409, { error: { code: 'settings-conflict', message: `dsh-key-rotation: changed elsewhere (expected revision ${String(error.expected)}, current ${String(error.actual)}); reload and retry` } });
246
- return;
247
- }
248
- json(res, 400, { error: { code: 'settings-rejected', message: error instanceof Error ? error.message : String(error) } });
249
- return;
250
- }
251
- const descriptor = descriptorOf(ctx, ns);
252
- if (descriptor === void 0) {
253
- json(res, 500, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: namespace vanished after write' } });
254
- return;
255
- }
256
- json(res, 200, viewOf(descriptor, { writable: settings.writable, hasDocument: settings.documentPath !== void 0 }));
257
- }
258
-
259
- /** Provider catalog for the GUI dropdown, minus clone routes of configured chains. */
260
- function providerCatalog(ctx, cloneIds) {
261
- const seen = new Set();
262
- const out = [];
263
- for (const info of ctx.llm.listProviders()) {
264
- if (seen.has(info.id) || cloneIds.has(info.id)) continue;
265
- seen.add(info.id);
266
- out.push({ id: info.id, name: info.name ?? info.id });
267
- }
268
- return out;
269
- }
270
-
271
- async function handleConfigBridge(ctx, request, res, getCloneIds) {
272
- if (!isTrustedBridgeRequest(request)) {
273
- res.writeHead(403);
274
- res.end();
275
- return;
276
- }
277
- const method = request.method ?? 'GET';
278
- if (method === 'GET') {
279
- const settings = ctx.get('settings');
280
- const descriptor = descriptorOf(ctx, NS);
281
- const body = {
282
- providers: providerCatalog(ctx, getCloneIds()),
283
- };
284
- if (descriptor === void 0) {
285
- json(res, 200, {
286
- ...body,
287
- available: false,
288
- writable: settings?.writable ?? false,
289
- hasDocument: settings?.documentPath !== void 0,
290
- value: void 0,
291
- revision: 0,
292
- });
293
- return;
294
- }
295
- json(res, 200, {
296
- ...body,
297
- ...viewOf(descriptor, {
298
- writable: settings?.writable ?? false,
299
- hasDocument: settings?.documentPath !== void 0,
300
- }),
301
- });
302
- return;
303
- }
304
- if (method === 'PUT' || method === 'DELETE') {
305
- let section;
306
- let expectedRevision;
307
- if (method === 'PUT') {
308
- let body;
309
- try {
310
- body = await readJson(request);
311
- } catch (error) {
312
- json(res, 400, { error: { code: 'settings-rejected', message: `dsh-key-rotation: invalid request body: ${error instanceof Error ? error.message : String(error)}` } });
313
- return;
314
- }
315
- if (typeof body !== 'object' || body === null || typeof body.section !== 'object' || body.section === null || Array.isArray(body.section)) {
316
- json(res, 400, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: PUT requires {"section": {...}}' } });
317
- return;
318
- }
319
- section = body.section;
320
- expectedRevision = typeof body.expectedRevision === 'number' ? body.expectedRevision : void 0;
321
- } else {
322
- section = {};
323
- }
324
- await writeSection(ctx, NS, section, expectedRevision, res);
325
- return;
326
- }
327
- res.writeHead(405);
328
- res.end();
329
- }
330
-
331
- function registerConfigBridge(ctx, getCloneIds) {
332
- return ctx.webServer.register({
333
- kind: 'exact',
334
- path: CONFIG_PATH,
335
- handler: (req, res) => void handleConfigBridge(ctx, req, res, getCloneIds),
336
- });
337
- }
338
-
339
- // ── plugin ──
340
-
341
- export function apply(ctx, config = {}) {
342
- // GUI section: defaults -> cordis row config -> saved user section.
343
- // (installSettingsSection inlined: no @deepseek-ai/dsh-settings import, so the
344
- // profile does not need a second copy of that package.)
345
- let getConfig = () => config;
346
- registerConfigBridge(ctx, () => buildRuntime().cloneIds);
347
- lastTestCacheRunnerCtx = ctx;
348
- // Cache should not survive profile restarts (apply is called per reload).
349
- // We deliberately do NOT clear on every apply — that would wipe badges when
350
- // the user is just typing in the settings card. Re-init only on true reload.
351
- ensureSandboxRunner(ctx);
352
-
353
- // Self-healing idle cooldowns: every 60s, lift expired cooldowns for keys
354
- // that have been idle for selfHealIdleMs (default 1h). ponytail: small
355
- // interval, low cost; skipped when selfHealCooldown is disabled in config.
356
- // ponytail: keep handle on the same ctx via closure so buildRuntime() reads
357
- // fresh config on every tick. Naive but correct: 60s cadence is cheap.
358
- // #196: canary probing before key release from cooldown.
359
- // Every canaryIntervalMs, probe refs that are in cooldown and close to expiry.
360
- let canaryTimer = null;
361
- const startCanary = () => {
362
- const cfg = getConfig();
363
- if (!cfg || !cfg.canaryProbingEnabled) return;
364
- if (canaryTimer) return;
365
- canaryTimer = setInterval(() => {
366
- try {
367
- const c = getConfig();
368
- if (!c || !c.canaryProbingEnabled) return;
369
- const runner = ensureSandboxRunner();
370
- if (!runner) return;
371
- if (!canaryProber) {
372
- canaryProber = new CanaryProber({ sandboxRunner: runner, intervalMs: c.canaryIntervalMs });
373
- }
374
- const providers = Array.isArray(c.providers) ? c.providers : [];
375
- for (const p of providers) {
376
- const pool = buildRuntime().providerToPool.get(p.provider);
377
- if (!pool) continue;
378
- for (const ref of pool.refs) {
379
- const until = pool.state.failedUntil.get(ref) ?? 0;
380
- const now = Date.now();
381
- // Probe refs in cooldown whose expiry is within canaryIntervalMs of now
382
- if (until > now && until - now < (c.canaryIntervalMs ?? 30000)) {
383
- canaryProber.probe(ref, ref);
384
- }
385
- }
386
- }
387
- } catch (_) { /* ponytail: never crash the timer */ }
388
- }, cfg.canaryIntervalMs ?? 30000);
389
- if (typeof canaryTimer.unref === 'function') canaryTimer.unref();
390
- };
391
- startCanary();
392
-
393
- const selfHealTimer = setInterval(() => {
394
- const cfg = getConfig();
395
- if (!cfg || cfg.selfHealCooldown === false) return;
396
- try {
397
- const idle = Number.isFinite(cfg.selfHealIdleMs) && cfg.selfHealIdleMs > 0 ? cfg.selfHealIdleMs : 3600000;
398
- const providers = Array.isArray(cfg.providers) ? cfg.providers : [];
399
- const pools = providers
400
- .map((p) => buildRuntime().providerToPool.get(p.provider))
401
- .filter(Boolean);
402
- healIdleCooldowns(pools, idle);
403
- } catch (_) { /* ponytail: never crash the timer */ }
404
- }, 60000);
405
- if (typeof selfHealTimer.unref === 'function') selfHealTimer.unref();
406
-
407
- // Dashboard widget now lives in client.js (mountDashboard, see issue #152).
408
- const DASH_HTML = '';
409
- // ── key-pool state, persisted across config reloads ──
410
- // base provider -> { failedUntil: Map<ref, epochMs>, pointer: number, lastUsed: ref }
411
- const poolState = new Map();
412
- // Periodic backup of pools config
413
- ctx.effect(() => {
414
- const { backupDir, backupIntervalMs, backupKeep } = buildRuntime();
415
- if (!backupDir) return;
416
- const id = setInterval(() => {
417
- try {
418
- const fs = require('node:fs');
419
- const path = require('node:path');
420
- const dir = backupDir;
421
- fs.mkdirSync(dir, { recursive: true });
422
- const now = new Date();
423
- const dateStr = now.toISOString().slice(0,10).replace(/-/g,'');
424
- const file = path.join(dir, 'pools-' + dateStr + '.json');
425
- const data = JSON.stringify({ backup: now.toISOString(), providers: getConfig()?.providers ?? [] }, null, 2);
426
- fs.writeFileSync(file, data, 'utf8');
427
- // prune old backups
428
- const keep = backupKeep || 7;
429
- const files = fs.readdirSync(dir).filter((f) => f.startsWith('pools-') && f.endsWith('.json')).sort();
430
- while (files.length > keep) {
431
- const old = files.shift();
432
- fs.unlinkSync(path.join(dir, old));
433
- }
434
- } catch (e) {
435
- console.warn('[dsh-key-rotation] backup failed:', String(e?.message ?? e));
436
- }
437
- }, backupIntervalMs || 86400000);
438
- return () => clearInterval(id);
439
- }, 'dsh-key-rotation: backup pools');
440
- // Periodic save of usage/cost stats to file
441
- ctx.effect(() => {
442
- const { backupDir } = buildRuntime();
443
- if (!backupDir) return;
444
- try {
445
- const fs = require('node:fs');
446
- const path = require('node:path');
447
- const statsFile = path.join(backupDir, 'stats.json');
448
- // Load existing stats at startup
449
- try {
450
- if (fs.existsSync(statsFile)) {
451
- const saved = JSON.parse(fs.readFileSync(statsFile, 'utf8'));
452
- for (const st of poolState.values()) {
453
- if (saved.usageCounts && st.usageCounts) { for (const [k, v] of Object.entries(saved.usageCounts)) st.usageCounts.set(k, (st.usageCounts.get(k) ?? 0) + v); }
454
- if (saved.costPerKey && st.costPerKey) { for (const [k, v] of Object.entries(saved.costPerKey)) st.costPerKey.set(k, (st.costPerKey.get(k) ?? 0) + v); }
455
- if (saved.lastUsedAt && st.lastUsedAt) { for (const [k, v] of Object.entries(saved.lastUsedAt)) { if (!st.lastUsedAt.has(k) || v > st.lastUsedAt.get(k)) st.lastUsedAt.set(k, v); } }
456
- }
457
- }
458
- } catch {}
459
- // Periodic save
460
- const id = setInterval(() => {
461
- try {
462
- const usageCounts = {}; const costPerKey = {}; const lastUsedAt = {};
463
- for (const [base, st] of poolState) {
464
- if (st.usageCounts) for (const [k, v] of st.usageCounts) usageCounts[k] = v;
465
- if (st.costPerKey) for (const [k, v] of st.costPerKey) costPerKey[k] = v;
466
- if (st.lastUsedAt) for (const [k, v] of st.lastUsedAt) lastUsedAt[k] = v;
467
- }
468
- fs.writeFileSync(statsFile, JSON.stringify({ t: Date.now(), usageCounts, costPerKey, lastUsedAt }), 'utf8');
469
- } catch {}
470
- }, 60000);
471
- return () => clearInterval(id);
472
- } catch { return () => {}; }
473
- }, 'dsh-key-rotation: persist stats');
474
- // Rotation schedule: shift pointer every N days
475
- ctx.effect(() => {
476
- const { rotationScheduleDays } = buildRuntime();
477
- if (!rotationScheduleDays || rotationScheduleDays <= 0) return;
478
- const intervalMs = Math.min(rotationScheduleDays * 86400000, 2147483647);
479
- const id = setInterval(() => {
480
- try {
481
- const rt = buildRuntime();
482
- let shifted = 0;
483
- for (const pool of rt.poolByRef.values()) {
484
- if (pool.refs.length < 2) continue;
485
- const oldPtr = pool.state.pointer ?? 0;
486
- pool.state.pointer = (oldPtr + 1) % pool.refs.length;
487
- shifted++;
488
- console.warn(`[dsh-key-rotation] ${pool.base}: scheduled rotation -> ${pool.refs[pool.state.pointer]} (day ${rotationScheduleDays})`);
489
- }
490
- if (shifted) console.warn(`[dsh-key-rotation] schedule: rotated ${shifted} pools`);
491
- } catch (e) {
492
- console.warn('[dsh-key-rotation] schedule error:', String(e?.message ?? e));
493
- }
494
- }, intervalMs);
495
- return () => clearInterval(id);
496
- }, 'dsh-key-rotation: rotation schedule');
497
- // Periodic sweep of expired cooldowns keeps health probe cheap and avoids waiting for next user request
498
- ctx.effect(() => {
499
- const id = setInterval(() => {
500
- const now = Date.now();
501
- // probe events for keys whose cooldown just expired
502
- for (const st of poolState.values()) {
503
- for (const [ref, until] of [...(st.failedUntil?.entries() ?? [])]) {
504
- if (until <= now && !st.probedAt?.has(ref)) {
505
- st.events.push({ at: until, ref, reason: 'probe', cooldownMs: 0, type: 'probe' });
506
- if (st.events.length > 50) st.events.shift();
507
- if (!st.probedAt) st.probedAt = new Map();
508
- st.probedAt.set(ref, until);
509
- }
510
- }
511
- }
512
- const n = sweepExpired(poolState, now);
513
- if (n > 0) console.warn(`[dsh-key-rotation] sweep: cleared ${n} expired cooldown(s)`);
514
- }, 30000);
515
- return () => clearInterval(id);
516
- }, 'dsh-key-rotation: sweep expired cooldowns');
517
-
518
- // ── runtime snapshot: config + llm-pi-ai profile mapping ──
519
- function buildRuntime() {
520
- // Deep-clone before resolving: the frozen snapshot from settings.register
521
- // must never be written to by schemastery's dict resolver.
522
- const cfg = Config(structuredClone(getConfig() ?? {})) ?? {};
523
- const switchCodes = new Set(cfg.switchCodes ?? DEFAULT_SWITCH_CODES);
524
- const cooldownMs = cfg.cooldownMs ?? 60000;
525
- const maxCooldownMs = cfg.maxCooldownMs ?? undefined;
526
- const notifyWebhook = cfg.notifyWebhook ?? '';
527
- const notifyThreshold = cfg.notifyThreshold ?? 3;
528
- const backupDir = cfg.backupDir ?? '';
529
- const backupIntervalMs = cfg.backupIntervalMs ?? 86400000;
530
- const backupKeep = cfg.backupKeep ?? 7;
531
- const rotationScheduleDays = cfg.rotationScheduleDays ?? 0;
532
- const rateLimitThreshold = cfg.rateLimitThreshold ?? 0.1;
533
- const incidentThreshold = cfg.incidentThreshold ?? 5;
534
- const concurrencyLimit = cfg.concurrencyLimit ?? 0;
535
- const canaryProbingEnabled = cfg.canaryProbingEnabled ?? false;
536
- const canaryIntervalMs = cfg.canaryIntervalMs ?? 30000;
537
- const cascade = Array.isArray(cfg.cascade) ? cfg.cascade : [];
538
- const quotaResetWindow = cfg.quotaResetWindow || null;
539
-
540
- // ref -> pool (every key env of every configured provider)
541
- const poolByRef = new Map();
542
- // provider route (from llm-pi-ai profiles) -> its key pool
543
- const providerToPool = new Map();
544
- // per-model key pools: provider -> Map<model, pool>
545
- const modelPoolByProvider = new Map();
546
- // clone route ids (for the settings dropdown filter)
547
- const cloneIds = new Set();
548
-
549
- const makeState = (base) => {
550
- let st = poolState.get(base);
551
- if (!st) {
552
- st = {
553
- failedUntil: new Map(),
554
- failCounts: new Map(),
555
- authFailCounts: new Map(),
556
- brokenUntil: new Map(),
557
- costPerKey: new Map(),
558
- lastUsedAt: new Map(),
559
- usageCounts: new Map(),
560
- byModel: new Map(),
561
- usageDays: new Map(),
562
- quotaWindows: new Map(),
563
- pointer: 0,
564
- lastUsed: undefined,
565
- switches: 0,
566
- lastReason: undefined,
567
- lastSwitchAt: undefined,
568
- lastExhaustionAt: undefined,
569
- exhaustionCount: 0,
570
- events: [],
571
- };
572
- poolState.set(base, st);
573
- }
574
- return st;
575
- };
576
- const parseExpiry = (v) => {
577
- if (typeof v === 'number' && v > 0) return v;
578
- if (typeof v === 'string' && v.length > 0) { const ts = Date.parse(v); return Number.isNaN(ts) ? undefined : ts; }
579
- return undefined;
580
- };
581
- const buildPool = (base, keys, weights, poolCooldown, poolMax, expiresAt) => {
582
- const refs = (keys ?? []).filter((ref) => typeof ref === 'string' && ref.length > 0);
583
- if (refs.length === 0) return null;
584
- const w = Array.isArray(weights) ? weights : [];
585
- const weightedRefs = [];
586
- for (let i = 0; i < refs.length; i++) {
587
- const ww = typeof w[i] === 'number' && w[i] > 0 ? Math.floor(w[i]) : 1;
588
- for (let k = 0; k < ww; k++) weightedRefs.push(refs[i]);
589
- }
590
- const parsedExpiry = {};
591
- if (Array.isArray(expiresAt)) {
592
- for (let i = 0; i < refs.length; i++) {
593
- const exp = parseExpiry(expiresAt[i]);
594
- if (exp !== undefined) parsedExpiry[refs[i]] = exp;
595
- }
596
- }
597
- return { base, refs, weightedRefs: weightedRefs.length > 0 ? weightedRefs : refs,
598
- state: makeState(base), cooldownMs: poolCooldown, maxCooldownMs: poolMax, expiresAt: parsedExpiry };
599
- };
600
- for (const p of cfg.providers ?? []) {
601
- const poolCooldown = typeof p.cooldownMs === 'number' ? p.cooldownMs : (cfg.cooldownMs ?? 60000);
602
- const poolMax = typeof p.maxCooldownMs === 'number' ? p.maxCooldownMs : (cfg.maxCooldownMs ?? undefined);
603
- // base provider pool (fallback)
604
- const pool = buildPool(p.provider, p.keys, p.weights, poolCooldown, poolMax);
605
- if (pool) {
606
- for (const ref of pool.refs) poolByRef.set(ref, pool);
607
- for (let i = 1; i < pool.refs.length; i++) cloneIds.add(`${p.provider}-${i + 1}`);
608
- }
609
- // per-model pools
610
- const models = p.models ?? {};
611
- const byModel = new Map();
612
- for (const [model, mp] of Object.entries(models)) {
613
- const mpool = buildPool(`${p.provider}::${model}`, mp.keys, mp.weights, poolCooldown, poolMax);
614
- if (mpool) {
615
- byModel.set(model, mpool);
616
- for (const ref of mpool.refs) poolByRef.set(ref, mpool);
617
- }
618
- }
619
- if (byModel.size > 0) modelPoolByProvider.set(p.provider, byModel);
620
- }
621
-
622
- let profiles = {};
623
- try {
624
- profiles = ctx.get('settings')?.get(PIAI_NS)?.providers ?? {};
625
- } catch {
626
- /* settings not mounted yet — empty mapping */
627
- }
628
- for (const [provider, profile] of Object.entries(profiles)) {
629
- if (profile?.apiKeyEnv && poolByRef.has(profile.apiKeyEnv)) {
630
- providerToPool.set(provider, poolByRef.get(profile.apiKeyEnv));
631
- }
632
- }
633
-
634
- // auto-cleanup: remove poolState for providers that are now empty or removed
635
- for (const key of [...poolState.keys()]) {
636
- if (![...poolByRef.values()].some((p) => p.base === key)) poolState.delete(key);
637
- }
638
- return { switchCodes, cooldownMs, maxCooldownMs, notifyWebhook, notifyThreshold, incidentThreshold, concurrencyLimit, canaryProbingEnabled, canaryIntervalMs, cascade, quotaResetWindow, backupDir, backupIntervalMs, backupKeep, rotationScheduleDays, rateLimitThreshold, poolByRef, providerToPool, modelPoolByProvider, cloneIds };
639
- }
640
-
641
- // ── patch credentials.resolve: pool refs resolve to the next healthy key ──
642
- // Round-robin over the pool, skipping keys in cooldown; the request's
643
- // provider identity never changes, so pi-ai replay state stays consistent.
644
- const credentials = ctx.get('credentials');
645
- if (credentials && typeof credentials.resolve === 'function' && !credentials.__dshKeyRotationPatched) {
646
- const original = credentials.resolve.bind(credentials);
647
- // Kept for the status route: it must ask about one exact ref instead of
648
- // being rotated to a different key by the patch below.
649
- credentials.__dshKeyRotationOriginalResolve = original;
650
- credentials.resolve = async (ref) => {
651
- const { poolByRef } = buildRuntime();
652
- const pool = poolByRef.get(ref);
653
- if (!pool) return original(ref);
654
- const now = Date.now();
655
- const list = pool.weightedRefs ?? pool.refs;
656
- const start = pool.state.pointer ?? 0;
657
- for (let i = 0; i < list.length; i++) {
658
- const index = (start + i) % list.length;
659
- const candidate = list[index];
660
- const until = pool.state.failedUntil.get(candidate);
661
- if (until !== undefined && until > now) continue;
662
- if (pool.expiresAt?.[candidate] !== undefined && now >= pool.expiresAt[candidate]) continue;
663
- // perHour quota check
664
- if (pool.perHour) {
665
- if (!pool.state.quotaWindows) pool.state.quotaWindows = new Map();
666
- let win = pool.state.quotaWindows.get(candidate);
667
- if (!win || now - win.start >= 3600000) win = { count: 0, start: now };
668
- if (win.count >= pool.perHour) {
669
- const until = win.start + 3600000;
670
- if ((pool.state.failedUntil.get(candidate) ?? 0) < until) pool.state.failedUntil.set(candidate, until);
671
- continue;
672
- }
673
- }
674
- let hit = await original(candidate);
675
- if (hit && typeof hit.value === 'string' && hit.value.length > 0) {
676
- pool.state.pointer = (index + 1) % list.length;
677
- pool.state.lastUsed = candidate;
678
- if (pool.state.failCounts) pool.state.failCounts.delete(candidate);
679
- pool.state.failedUntil.delete(candidate);
680
- if (pool.state.authFailCounts) pool.state.authFailCounts.delete(candidate);
681
- if (pool.state.brokenUntil) pool.state.brokenUntil.delete(candidate);
682
- if (!pool.state.usageCounts) pool.state.usageCounts = new Map();
683
- pool.state.usageCounts.set(candidate, (pool.state.usageCounts.get(candidate) ?? 0) + 1);
684
- if (pool.perHour) {
685
- if (!pool.state.quotaWindows) pool.state.quotaWindows = new Map();
686
- let win2 = pool.state.quotaWindows.get(candidate);
687
- if (!win2 || now - win2.start >= 3600000) win2 = { count: 0, start: now };
688
- win2.count++;
689
- pool.state.quotaWindows.set(candidate, win2);
690
- }
691
- return hit;
692
- }
693
- // fallback: env var (transient, not persisted)
694
- const envVal = envValue(candidate);
695
- if (envVal !== undefined) {
696
- pool.state.pointer = (index + 1) % list.length;
697
- pool.state.lastUsed = candidate;
698
- if (pool.state.failCounts) pool.state.failCounts.delete(candidate);
699
- pool.state.failedUntil.delete(candidate);
700
- if (pool.state.authFailCounts) pool.state.authFailCounts.delete(candidate);
701
- if (pool.state.brokenUntil) pool.state.brokenUntil.delete(candidate);
702
- if (!pool.state.usageCounts) pool.state.usageCounts = new Map();
703
- pool.state.usageCounts.set(candidate, (pool.state.usageCounts.get(candidate) ?? 0) + 1);
704
- if (pool.perHour) {
705
- if (!pool.state.quotaWindows) pool.state.quotaWindows = new Map();
706
- let win2 = pool.state.quotaWindows.get(candidate);
707
- if (!win2 || now - win2.start >= 3600000) win2 = { count: 0, start: now };
708
- win2.count++;
709
- pool.state.quotaWindows.set(candidate, win2);
710
- }
711
- return { value: envVal, source: 'env' };
712
- }
713
- }
714
- return original(ref); // everything cooled/missing — surface the base value
715
- };
716
- credentials.__dshKeyRotationPatched = true;
717
- }
718
-
719
- const finishError = (code, message) => ({
720
- type: 'finish',
721
- reason: { kind: 'error', failure: Object.freeze({ code, message }) },
722
- });
723
-
724
- // Latency recording (#6): record successful llm/stream latency per ref.
725
- // ponytail: only the true success path (finish-chunk). Failures are not recorded.
726
- let _rotateStartMs = Date.now();
727
- function recordLatency(pool) {
728
- try {
729
- const cfg = getConfig();
730
- if (!cfg || cfg.latencyEnabled === false) return;
731
- const ref = pool && pool.state && pool.state.lastUsed;
732
- if (!ref) return;
733
- const elapsed = Date.now() - _rotateStartMs;
734
- if (!Number.isFinite(elapsed) || elapsed < 0) return;
735
- latencyHistogram.record(ref, elapsed);
736
- } catch (_) { /* ponytail: never crash */ }
737
- }
738
-
739
- // Retry one request on the next pool key when the current key fails with a
740
- // switchable error before any content chunk. The provider never changes —
741
- // the resolve patch hands out the next key on each dispatch.
742
- function rotate(options, pool) {
743
- return (async function* () {
744
- const { switchCodes, cooldownMs, maxCooldownMs } = buildRuntime();
745
- let lastFailure = null;
746
- _rotateStartMs = Date.now();
747
-
748
- const runtime0 = buildRuntime();
749
- if (runtime0.concurrencyLimit > 0 && concurrencyTracker.isEnabled()) {
750
- // #193: prefer least-loaded key within limit
751
- const available = (pool.weightedRefs ?? pool.refs).filter((r) => {
752
- const fu = pool.state.failedUntil.get(r) ?? 0;
753
- if (fu > Date.now()) return false;
754
- const exp = pool.expiresAt ? pool.expiresAt[r] : undefined;
755
- if (exp !== undefined && Date.now() >= exp) return false;
756
- return true;
757
- });
758
- const preferred = concurrencyTracker.pickLeastLoaded(available);
759
- if (preferred && (pool.weightedRefs ?? pool.refs)[0] !== preferred) {
760
- // Move preferred to front of the attempt list
761
- const list = (pool.weightedRefs ?? pool.refs).slice();
762
- const i = list.indexOf(preferred);
763
- if (i > 0) { list.splice(i, 1); list.unshift(preferred); }
764
- pool.weightedRefs = list;
765
- }
766
- }
767
- for (let attempt = 0; attempt < (pool.weightedRefs ?? pool.refs).length; attempt++) {
768
- let yielded = false;
769
- let switching = false;
770
- let inner;
771
- try {
772
- // mark the internal dispatch so the interceptor does not re-rotate
773
- inner = ctx.llm.stream({ ...options, [MARKER]: true });
774
- } catch (e) {
775
- if (pool.state.lastUsed) { const _retry = parseRetryAfter(String(e?.message ?? '')); const _base = pool.cooldownMs ?? cooldownMs; const _max = pool.maxCooldownMs ?? maxCooldownMs; const _effBase = _retry !== undefined ? Math.max(_base, Math.min(_retry, _max ?? _base * 8)) : _base; const _b = recordFailure(pool, pool.state.lastUsed, Date.now(), _effBase, _max); pushEvent(pool, pool.state.lastUsed, e?.code ?? 'TRANSPORT', _b); const _code = String(e?.code ?? ''); if (_code === 'AUTH' || /auth/i.test(String(e?.message ?? ''))) { const _c = (pool.state.authFailCounts.get(pool.state.lastUsed) ?? 0) + 1; pool.state.authFailCounts.set(pool.state.lastUsed, _c); if (_c >= 3) { pool.state.brokenUntil.set(pool.state.lastUsed, Date.now() + 86400000*30); pool.state.failedUntil.set(pool.state.lastUsed, Date.now() + 86400000*30); } } else { pool.state.authFailCounts.delete(pool.state.lastUsed); } }
776
- lastFailure = finishError(e?.code ?? 'TRANSPORT',
777
- `dsh-key-rotation: dispatch failed: ${String(e?.message ?? e)}`);
778
- console.warn(`[dsh-key-rotation] ${options.provider}: key ${String(pool.state.lastUsed ?? '?')} threw ${String(e?.code ?? e?.message ?? e)}`);
779
- continue;
780
- }
781
-
782
- const _pickedRef = pool.state.lastUsed;
783
- if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.acquire(_pickedRef);
784
- try {
785
- for await (const chunk of inner) {
786
- // Only actual content deltas lock the stream (no more rotation).
787
- // Structural/metadata chunks (block-start/end, usage) do not.
788
- if (chunk && (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta' || chunk.type === 'tool-call-delta')) {
789
- yielded = true;
790
- yield chunk;
791
- continue;
792
- }
793
- if (chunk && chunk.type === 'finish') {
794
- const kind = chunk.reason?.kind;
795
- const failure = chunk.reason?.failure;
796
- const code = failure?.code;
797
- const message = failure?.message ?? '';
798
- const effectiveSwitchCodes = pool.switchCodes ?? switchCodes;
799
- const switchable = !yielded && kind === 'error' &&
800
- (effectiveSwitchCodes.has(code) || SWITCHABLE_MESSAGE_PATTERN.test(message));
801
- if (switchable) {
802
- if (pool.state.lastUsed) {
803
- const _retry = parseRetryAfter(message);
804
- const _base = pool.cooldownMs ?? cooldownMs;
805
- const _max = pool.maxCooldownMs ?? maxCooldownMs;
806
- const _effBase = _retry !== undefined ? Math.max(_base, Math.min(_retry, _max ?? _base * 8)) : _base;
807
- const _b = recordFailure(pool, pool.state.lastUsed, Date.now(), _effBase, _max);
808
- pushEvent(pool, pool.state.lastUsed, code ?? 'UNKNOWN', _b);
809
- // authFailCounts/brokenUntil: lazy-init if state was created by an older plugin version
810
- if (!pool.state.authFailCounts) pool.state.authFailCounts = new Map();
811
- if (!pool.state.brokenUntil) pool.state.brokenUntil = new Map();
812
- const _code2 = String(code ?? '');
813
- if (_code2 === 'AUTH' || /auth/i.test(message)) {
814
- const _c2 = (pool.state.authFailCounts.get(pool.state.lastUsed) ?? 0) + 1;
815
- pool.state.authFailCounts.set(pool.state.lastUsed, _c2);
816
- if (_c2 >= 3) {
817
- pool.state.brokenUntil.set(pool.state.lastUsed, Date.now() + 86400000*30);
818
- pool.state.failedUntil.set(pool.state.lastUsed, Date.now() + 86400000*30);
819
- }
820
- } else {
821
- pool.state.authFailCounts.delete(pool.state.lastUsed);
822
- }
823
- }
824
- pool.state.switches = (pool.state.switches ?? 0) + 1;
825
- pool.state.lastReason = String(code ?? 'UNKNOWN');
826
- pool.state.lastSwitchAt = Date.now();
827
- lastFailure = chunk;
828
- console.warn(`[dsh-key-rotation] ${options.provider}: key ${String(pool.state.lastUsed ?? '?')} failed (${String(code)} ${String(message).slice(0, 100)}) — next key`);
829
- switching = true;
830
- break;
831
- }
832
- // cost tracking if provider returns usage.cost
833
- if (chunk.usage?.cost != null && pool.state.lastUsed) {
834
- const c = Number(chunk.usage.cost);
835
- if (!isNaN(c)) {
836
- if (!pool.state.costPerKey) pool.state.costPerKey = new Map();
837
- pool.state.costPerKey.set(pool.state.lastUsed, (pool.state.costPerKey.get(pool.state.lastUsed) ?? 0) + c);
838
- }
839
- }
840
- // Usage by day (#119)
841
- if (pool.state.lastUsed) {
842
- if (!pool.state.usageDays) pool.state.usageDays = new Map();
843
- const day = new Date().toISOString().slice(0, 10);
844
- const dayMap = pool.state.usageDays.get(pool.state.lastUsed) || new Map();
845
- dayMap.set(day, (dayMap.get(day) ?? 0) + 1);
846
- pool.state.usageDays.set(pool.state.lastUsed, dayMap);
847
- }
848
- // Per-model request detail (#121)
849
- if (pool.state.lastUsed && options.model) {
850
- if (!pool.state.byModel) pool.state.byModel = new Map();
851
- let byRef = pool.state.byModel.get(pool.state.lastUsed);
852
- if (!byRef) { byRef = new Map(); pool.state.byModel.set(pool.state.lastUsed, byRef); }
853
- byRef.set(options.model, (byRef.get(options.model) ?? 0) + 1);
854
- }
855
- // Proactive rate-limit (#115): if response headers say this key is near
856
- // its quota, cool it down so the NEXT request starts on a different key.
857
- // We do NOT re-run this (already successful) request — that would double-send.
858
- const rate = extractRateLimit(chunk?.metadata?.headers ?? chunk?.headers);
859
- if (rate && pool.state.lastUsed) {
860
- const { rateLimitThreshold } = buildRuntime();
861
- if (isRateLimited(rate, rateLimitThreshold ?? 0.1)) {
862
- const cool = rate.reset && rate.reset > Date.now() ? (rate.reset - Date.now()) : pool.cooldownMs;
863
- recordFailure(pool, pool.state.lastUsed, Date.now(), cool, pool.maxCooldownMs);
864
- pushEvent(pool, pool.state.lastUsed, 'RATE_LIMIT', cool);
865
- console.warn(`[dsh-key-rotation] ${options.provider}: key ${pool.state.lastUsed} near quota (remaining ${String(rate.remaining)}/${String(rate.limit)}) — next request will rotate`);
866
- }
867
- }
868
- // #7: persist quota snapshot regardless of threshold (so dashboard widget can show it).
869
- if (rate && pool.state.lastUsed && Number.isFinite(rate.remaining)) {
870
- quotaStore.set(pool.state.lastUsed, { remaining: rate.remaining, limit: rate.limit, reset: rate.reset, at: Date.now() });
871
- }
872
- yield chunk;
873
- recordLatency(pool);
874
- return;
875
- }
876
- yield chunk;
877
- }
878
- } catch (e) {
879
- if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.release(_pickedRef);
880
- yield finishError(e?.code ?? 'TRANSPORT', String(e?.message ?? e));
881
- return;
882
- }
883
-
884
- if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.release(_pickedRef);
885
- if (switching) continue; // try the next key
886
- return; // clean end served
887
- }
888
-
889
- // pool exhausted — all keys cooling or missing
890
- pool.state.lastExhaustionAt = Date.now();
891
- pool.state.exhaustionCount = (pool.state.exhaustionCount ?? 0) + 1;
892
- console.warn(`[dsh-key-rotation] ${options.provider}: pool exhausted — all ${pool.refs.length} keys cooling`);
893
- // notify via extracted helper (see notifyExhaustion above)
894
- notifyExhaustion(buildRuntime(), pool, { provider: options.provider });
895
-
896
- // #194: cross-provider cascade failover
897
- const runtime = buildRuntime();
898
- if (Array.isArray(runtime.cascade) && runtime.cascade.length > 0) {
899
- const pools = runtime.providerToPool;
900
- const fb = pickCascadeFallback(options.provider, runtime, pools);
901
- if (fb && fb.pool && fb.pool !== pool) {
902
- console.warn(`[dsh-key-rotation] ${options.provider}: pool exhausted — cascading to ${fb.provider}`);
903
- pool.state.lastReason = 'CASCADE';
904
- pool.state.lastSwitchAt = Date.now();
905
- // Re-dispatch on the fallback pool (depth-1 via marker check)
906
- const innerCascade = rotate({ ...options, provider: fb.provider }, fb.pool);
907
- for await (const chunk of innerCascade) {
908
- yield chunk;
909
- }
910
- return;
911
- }
912
- }
913
-
914
- yield lastFailure ?? finishError('TRANSPORT', 'dsh-key-rotation: all keys failed');
915
- })();
916
- }
917
-
918
- // ── status route: what the settings card cannot know on its own ──
919
- //
920
- // Reports, per configured provider, which key is in use, which are cooling
921
- // down and until when, whether an env name resolves to a credential at all
922
- // (a typo is otherwise silent), and how often rotation has fired.
923
- //
924
- // Key VALUES never leave the host — only the boolean fact that one exists.
925
- ctx.effect(() => ctx.webServer.register({
926
- kind: 'exact',
927
- path: STATUS_PATH,
928
- handler: async (req, res) => {
929
- if (req.method !== 'GET') {
930
- json(res, 405, { error: { code: 'method', message: 'GET only' } });
931
- return;
932
- }
933
- if (!isTrustedBridgeRequest(req)) {
934
- json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: status is local-only' } });
935
- return;
936
- }
937
- const { poolByRef } = buildRuntime();
938
- const base = ctx.get('credentials');
939
- const now = Date.now();
940
- const seen = new Set();
941
- const providers = [];
942
- for (const pool of poolByRef.values()) {
943
- if (seen.has(pool.base)) continue;
944
- seen.add(pool.base);
945
- const keys = [];
946
- for (const ref of pool.refs) {
947
- let present = false;
948
- let tail = '';
949
- let source = null;
950
- let writable = true;
951
- try {
952
- // The resolve patch is installed on this same service, so ask for
953
- // the exact ref: a pool ref would otherwise round-robin to another
954
- // key and report a missing name as present.
955
- let hit = await (base?.__dshKeyRotationOriginalResolve ?? base?.resolve)?.call(base, ref);
956
- present = Boolean(hit && typeof hit.value === 'string' && hit.value.length > 0);
957
- if (present) tail = keyTail(hit.value);
958
- // fallback: env var bootstrapping (issue #7)
959
- if (!present) {
960
- const ev = envValue(ref);
961
- if (ev !== undefined) { present = true; tail = keyTail(ev); source = 'env'; writable = false; }
962
- }
963
- } catch {
964
- present = false;
965
- }
966
- try {
967
- const described = await base?.describe?.(ref);
968
- source = described?.source ?? null;
969
- writable = described?.writable !== false;
970
- } catch {
971
- /* describe is optional — the card falls back to editable */
972
- }
973
- const until = pool.state.failedUntil.get(ref);
974
- keys.push({
975
- ref,
976
- present,
977
- tail,
978
- source,
979
- writable,
980
- active: pool.state.lastUsed === ref,
981
- cooldownMsLeft: until !== undefined && until > now ? until - now : 0,
982
- usage: pool.state.usageCounts?.get(ref) ?? 0,
983
- byModel: pool.state.byModel?.get(ref) ? Object.fromEntries(pool.state.byModel.get(ref)) : {},
984
- usageDays: pool.state.usageDays?.get(ref) ? Object.fromEntries(pool.state.usageDays.get(ref)) : {},
985
- cost: pool.state.costPerKey?.get(ref) ?? 0,
986
- lastUsedAt: pool.state.lastUsedAt?.get(ref) ?? null,
987
- expiresAt: pool.expiresAt?.[ref] ?? null,
988
- expired: pool.expiresAt?.[ref] !== undefined && now >= pool.expiresAt[ref],
989
- broken: pool.state.brokenUntil?.has(ref) ?? false,
990
- });
991
- }
992
- providers.push({
993
- provider: pool.base,
994
- keys,
995
- switches: pool.state.switches ?? 0,
996
- lastReason: pool.state.lastReason ?? null,
997
- lastSwitchAt: pool.state.lastSwitchAt ?? null,
998
- lastExhaustionAt: pool.state.lastExhaustionAt ?? null,
999
- exhaustionCount: pool.state.exhaustionCount ?? 0,
1000
- totalUsage: [...(pool.state.usageCounts?.values() ?? [])].reduce((a, b) => a + b, 0),
1001
- events: (pool.state.events ?? []).slice(-50),
1002
- healthScore: computeHealthScore(pool.state),
1003
- });
1004
- }
1005
- json(res, 200, { providers });
1006
- },
1007
- }), 'dsh-key-rotation: status route');
1008
-
1009
- // ── key route: store a key value without leaving the rotation card ──
1010
- //
1011
- // Adding a key used to mean two screens: create the credential elsewhere,
1012
- // then type its env name here. The value is write-only from the browser —
1013
- // it is never sent back, only its last few characters are (see the status
1014
- // route)and the route is loopback- and same-origin-gated like the config
1015
- // bridge next to it.
1016
- ctx.effect(() => ctx.webServer.register({
1017
- kind: 'exact',
1018
- path: KEY_PATH,
1019
- handler: async (req, res) => {
1020
- if (req.method !== 'PUT' && req.method !== 'DELETE') {
1021
- json(res, 405, { error: { code: 'method', message: 'PUT or DELETE only' } });
1022
- return;
1023
- }
1024
- if (!isTrustedBridgeRequest(req)) {
1025
- json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: keys are local-only' } });
1026
- return;
1027
- }
1028
- const credentialsService = ctx.get('credentials');
1029
- if (!credentialsService || typeof credentialsService.set !== 'function') {
1030
- json(res, 503, { error: { code: 'no-credentials', message: 'dsh-key-rotation: no credentials service is mounted' } });
1031
- return;
1032
- }
1033
- let body;
1034
- try {
1035
- body = await readJson(req);
1036
- } catch (error) {
1037
- json(res, 400, { error: { code: 'bad-request', message: String(error?.message ?? error) } });
1038
- return;
1039
- }
1040
- const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1041
- if (!isValidRef(ref)) {
1042
- json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } });
1043
- return;
1044
- }
1045
- try {
1046
- if (req.method === 'DELETE') {
1047
- await credentialsService.unset(ref);
1048
- json(res, 200, { ok: true, ref });
1049
- return;
1050
- }
1051
- const value = typeof body?.value === 'string' ? body.value.trim() : '';
1052
- if (value.length === 0) {
1053
- json(res, 400, { error: { code: 'empty-value', message: 'dsh-key-rotation: an empty key cannot be stored' } });
1054
- return;
1055
- }
1056
- await credentialsService.set(ref, value);
1057
- json(res, 200, { ok: true, ref, tail: keyTail(value) });
1058
- } catch (error) {
1059
- // A ref supplied by the launching environment is read-only, and the
1060
- // service says so in plain words — pass that through to the card.
1061
- json(res, 409, { error: { code: 'write-rejected', message: String(error?.message ?? error) } });
1062
- }
1063
- },
1064
- }), 'dsh-key-rotation: key route');
1065
-
1066
- // ── reset route: clear cooldown for a provider (or a single ref) ──
1067
- ctx.effect(() => ctx.webServer.register({
1068
- kind: 'exact',
1069
- path: RESET_PATH,
1070
- handler: async (req, res) => {
1071
- if (req.method !== 'POST') {
1072
- json(res, 405, { error: { code: 'method', message: 'POST only' } });
1073
- return;
1074
- }
1075
- if (!isTrustedBridgeRequest(req)) {
1076
- json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: reset is local-only' } });
1077
- return;
1078
- }
1079
- let body;
1080
- try { body = await readJson(req); } catch (e) {
1081
- json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } });
1082
- return;
1083
- }
1084
- const provider = typeof body?.provider === 'string' ? body.provider.trim() : '';
1085
- const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1086
- if (provider) {
1087
- const st = poolState.get(provider);
1088
- if (!st) { json(res, 404, { error: { code: 'not-found', message: `dsh-key-rotation: no pool for '${provider}'` } }); return; }
1089
- const cleared = st.failedUntil.size;
1090
- st.failedUntil.clear();
1091
- st.failCounts?.clear();
1092
- st.authFailCounts?.clear();
1093
- st.brokenUntil?.clear();
1094
- st.switches = 0; st.lastReason = undefined; st.lastSwitchAt = undefined;
1095
- json(res, 200, { ok: true, provider, cleared });
1096
- return;
1097
- }
1098
- if (ref) {
1099
- let found = false;
1100
- for (const st of poolState.values()) {
1101
- if (st.failedUntil.has(ref) || st.failCounts?.has(ref)) {
1102
- st.failedUntil.delete(ref);
1103
- st.failCounts?.delete(ref);
1104
- st.authFailCounts?.delete(ref);
1105
- st.brokenUntil?.delete(ref);
1106
- if (st.lastUsed === ref) st.lastUsed = undefined;
1107
- found = true; break;
1108
- }
1109
- }
1110
- // idempotent: even if ref was not cooling, report ok if it looks like a valid ref name
1111
- if (!found && !isValidRef(ref)) { json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } }); return; }
1112
- json(res, 200, { ok: true, ref });
1113
- return;
1114
- }
1115
- json(res, 400, { error: { code: 'bad-request', message: 'dsh-key-rotation: POST requires {"provider": "..."} or {"ref": "..."}' } });
1116
- },
1117
- }), 'dsh-key-rotation: reset route');
1118
-
1119
- ctx.effect(() => ctx.webServer.register({
1120
- kind: 'exact',
1121
- path: IMPORT_PATH,
1122
- handler: async (req, res) => {
1123
- if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1124
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: import is local-only' } }); return; }
1125
- let body; try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1126
- const url = typeof body?.url === 'string' ? body.url.trim() : '';
1127
- if (!url || !url.startsWith('https://')) { json(res, 400, { error: { code: 'bad-url', message: 'dsh-key-rotation: only HTTPS URLs are allowed' } }); return; }
1128
- try {
1129
- const resp = await fetch(url);
1130
- if (!resp.ok) { json(res, 400, { error: { code: 'fetch-failed', message: 'dsh-key-rotation: fetch returned ' + resp.status } }); return; }
1131
- const data = await resp.json();
1132
- if (!Array.isArray(data)) { json(res, 400, { error: { code: 'bad-format', message: 'dsh-key-rotation: expected JSON array of providers' } }); return; }
1133
- const settings = ctx.get('settings');
1134
- if (!settings) { json(res, 503, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: no settings provider' } }); return; }
1135
- const desc = settings.describe({ redactSecrets: true }).find((c) => c.ns === NS);
1136
- const cur = desc?.value?.providers ?? [];
1137
- const merged = new Map();
1138
- for (const p of cur) if (p && p.provider) merged.set(p.provider, p);
1139
- for (const p of data) if (p && p.provider && typeof p.provider === 'string') merged.set(p.provider, p);
1140
- const mergedArr = [...merged.values()];
1141
- await settings.replace(NS, { ...(desc?.value ?? {}), providers: mergedArr }, desc?.revision);
1142
- json(res, 200, { ok: true, providersImported: data.length, total: mergedArr.length });
1143
- } catch (e) { json(res, 400, { error: { code: 'import-failed', message: String(e?.message ?? e) } }); }
1144
- },
1145
- }), 'dsh-key-rotation: import route');
1146
-
1147
- // Health for external panels (Beszel/Uptime)
1148
- ctx.effect(() => ctx.webServer.register({
1149
- kind: 'exact',
1150
- path: HEALTH_PATH,
1151
- handler: async (req, res) => {
1152
- if (!isTrustedBridgeRequest(req) && req.socket?.remoteAddress !== '127.0.0.1' && req.socket?.remoteAddress !== '::1') { } // allow same-origin already checked
1153
- if (!isTrustedBridgeRequest(req)) {
1154
- // also allow plain loopback without Origin
1155
- if (!isLoopbackAddress(req.socket?.remoteAddress)) { res.writeHead(403); res.end(); return; }
1156
- if (req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); res.end(); return; }
1157
- }
1158
- if (req.method !== 'GET') { json(res, 405, { error: { code: 'method', message: 'GET only' } }); return; }
1159
- const now = Date.now();
1160
- const pools = {};
1161
- let exhaustedAny = false;
1162
- const { poolByRef: pr } = buildRuntime();
1163
- const seenH = new Set();
1164
- for (const pool of pr.values()) {
1165
- if (seenH.has(pool.base)) continue;
1166
- seenH.add(pool.base);
1167
- let healthy = 0;
1168
- for (const ref of pool.refs) {
1169
- const until = pool.state.failedUntil.get(ref);
1170
- if (until !== undefined && until > now) continue;
1171
- const exp = pool.expiresAt?.[ref];
1172
- if (exp !== undefined && now >= exp) continue;
1173
- healthy++;
1174
- }
1175
- const total = pool.refs.length;
1176
- const exhausted = healthy === 0 && total > 0;
1177
- if (exhausted) exhaustedAny = true;
1178
- pools[pool.base] = { healthy, total, exhausted, healthScore: computeHealthScore(pool.state) };
1179
- }
1180
- json(res, 200, { status: exhaustedAny ? 'degraded' : 'ok', pools, exhaustedAny, latency: latencyHistogram.snapshotAll(), quota: quotaStore.snapshot() });
1181
- },
1182
- }), 'dsh-key-rotation: health');
1183
-
1184
- // ── test route: dry-run a single key without rotation ──
1185
- ctx.effect(() => ctx.webServer.register({
1186
- kind: 'exact',
1187
- path: TEST_PATH,
1188
- handler: async (req, res) => {
1189
- if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1190
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: test is local-only' } }); return; }
1191
- let body; try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1192
- const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1193
- if (!isValidRef(ref)) { json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } }); return; }
1194
- // Optional value for pre-save validation (issue #118)
1195
- const testValue = typeof body?.value === 'string' && body.value.length > 0 ? body.value : undefined;
1196
- const probe = body?.probe === 'models' || body?.probe === 'chat' ? body.probe : undefined;
1197
- const base = ctx.get('credentials');
1198
- try {
1199
- let hit = await (base?.__dshKeyRotationOriginalResolve ?? base?.resolve)?.call(base, ref);
1200
- let present = Boolean(hit && typeof hit.value === 'string' && hit.value.length > 0);
1201
- const effectiveValue = testValue || hit?.value;
1202
- const valid = present ? Boolean(effectiveValue && typeof effectiveValue === 'string' && effectiveValue.length > 0) : Boolean(testValue);
1203
- const tail = valid ? keyTail(effectiveValue) : '';
1204
- let source = null;
1205
- try { const d = await base?.describe?.(ref); source = d?.source ?? null; } catch {}
1206
- if (!present && !testValue) { json(res, 200, { ok: false, ref, code: 'no-credential', message: 'no such credential' }); return; }
1207
- if (!present && testValue) { source = 'pre-save'; }
1208
- else if (!present) {
1209
- const ev = envValue(ref);
1210
- if (ev !== undefined) { present = true; json(res, 200, { ok: true, ref, tail: keyTail(ev), source: 'env' }); return; }
1211
- }
1212
- // sandbox probe (models is free; chat is hook-only, see sandbox.js)
1213
- if (probe) {
1214
- const keyForProbe = effectiveValue;
1215
- const runner = ensureSandboxRunner(ctx);
1216
- const result = probe === 'chat' ? await runner.probeChat(ref, keyForProbe) : await runner.probeModels(ref, keyForProbe);
1217
- const cached = { ...result, at: Date.now() };
1218
- lastTestCache.set(ref, cached);
1219
- json(res, 200, { ok: cached.ok, ref, tail, source, probe, code: cached.code, latencyMs: cached.latencyMs, modelsCount: cached.modelsCount });
1220
- return;
1221
- }
1222
- json(res, 200, { ok: true, ref, tail, source });
1223
- } catch (e) {
1224
- json(res, 200, { ok: false, ref, code: 'error', message: String(e?.message ?? e) });
1225
- }
1226
- },
1227
- }), 'dsh-key-rotation: test route');
1228
-
1229
- // Intercept the llm/stream waterfall: rotate any request whose provider maps
1230
- // to a configured key pool; pass everything else (and internal dispatches)
1231
- // straight through.
1232
- // Read-only cache snapshot for clients (badge polling).
1233
- ctx.effect(() => ctx.webServer.register({
1234
- kind: 'exact',
1235
- path: SANDBOX_CACHE_PATH,
1236
- handler: (req, res) => {
1237
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: cache is local-only' } }); return; }
1238
- json(res, 200, lastTestCache.snapshot());
1239
- },
1240
- }), 'dsh-key-rotation: sandbox cache');
1241
-
1242
- // Auto-incident reset (#8).
1243
- ctx.effect(() => ctx.webServer.register({
1244
- kind: 'exact',
1245
- path: INCIDENT_RESET_PATH,
1246
- handler: (req, res) => {
1247
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: incident-reset is local-only' } }); return; }
1248
- if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1249
- readJson(req).then((body) => {
1250
- const provider = typeof body?.provider === 'string' ? body.provider : '';
1251
- if (provider) incidentReporter.resetCooldown(provider);
1252
- else incidentReporter.resetCooldown();
1253
- json(res, 200, { ok: true, reset: provider || 'all' });
1254
- }).catch((e) => json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }));
1255
- },
1256
- }), 'dsh-key-rotation: incident-reset');
1257
-
1258
- // #198: 1-click Health Matrix parallel probe of all configured keys.
1259
- ctx.effect(() => ctx.webServer.register({
1260
- kind: 'exact',
1261
- path: TEST_MATRIX_PATH,
1262
- handler: async (req, res) => {
1263
- if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1264
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: matrix is local-only' } }); return; }
1265
- const cfg = getConfig();
1266
- const runner = ensureSandboxRunner();
1267
- if (!runner) { json(res, 500, { error: { code: 'no-runner', message: 'sandbox runner unavailable' } }); return; }
1268
- const providers = Array.isArray(cfg?.providers) ? cfg.providers : [];
1269
- const jobs = [];
1270
- for (const p of providers) {
1271
- for (const ref of (p.keys ?? [])) {
1272
- if (typeof ref !== 'string' || !ref) continue;
1273
- jobs.push((async () => {
1274
- try {
1275
- const probeResult = await runner.probeModels(ref, ref);
1276
- return { provider: p.provider, ref, ok: probeResult.ok, code: probeResult.code, latencyMs: probeResult.latencyMs, modelsCount: probeResult.modelsCount ?? 0 };
1277
- } catch (e) {
1278
- return { provider: p.provider, ref, ok: false, code: 'error', latencyMs: 0, modelsCount: 0 };
1279
- }
1280
- })());
1281
- }
1282
- }
1283
- const results = await Promise.all(jobs);
1284
- json(res, 200, { at: Date.now(), total: results.length, ok: results.filter(r => r.ok).length, results });
1285
- },
1286
- }), 'dsh-key-rotation: test-matrix');
1287
-
1288
- // Webhook test endpoint (#10): dry-run that validates webhookSender setup.
1289
- ctx.effect(() => ctx.webServer.register({
1290
- kind: 'exact',
1291
- path: WEBHOOK_TEST_PATH,
1292
- handler: (req, res) => {
1293
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: webhook-test is local-only' } }); return; }
1294
- json(res, 200, { ok: true, snapshot: webhookSender.snapshot() });
1295
- },
1296
- }), 'dsh-key-rotation: webhook-test');
1297
-
1298
- // Shadow A/B sampling snapshot (#9).
1299
- ctx.effect(() => ctx.webServer.register({
1300
- kind: 'exact',
1301
- path: SHADOW_PATH,
1302
- handler: (req, res) => {
1303
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: shadow is local-only' } }); return; }
1304
- json(res, 200, shadowRouter.snapshot());
1305
- },
1306
- }), 'dsh-key-rotation: shadow');
1307
-
1308
- // Region tags + failover chain (#4).
1309
- ctx.effect(() => ctx.webServer.register({
1310
- kind: 'exact',
1311
- path: REGIONS_PATH,
1312
- handler: (req, res) => {
1313
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: regions is local-only' } }); return; }
1314
- const body = regionMap.snapshot();
1315
- // Add pickFallback hints per provider for inspection.
1316
- const out = {};
1317
- for (const p of Object.keys(body)) out[p] = { region: body[p], fallback: regionMap.pickFallback(p) };
1318
- json(res, 200, out);
1319
- },
1320
- }), 'dsh-key-rotation: regions');
1321
-
1322
- // Per-agent rate budget snapshot (#3).
1323
- ctx.effect(() => ctx.webServer.register({
1324
- kind: 'exact',
1325
- path: AGENT_BUDGET_PATH,
1326
- handler: (req, res) => {
1327
- if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: agent-budget is local-only' } }); return; }
1328
- json(res, 200, { enabled: agentBudget.isEnabled(), agents: agentBudget.snapshot() });
1329
- },
1330
- }), 'dsh-key-rotation: agent-budget');
1331
-
1332
- ctx.on('llm/stream', (options, next) => {
1333
- if (options[MARKER]) return next();
1334
- const { providerToPool, modelPoolByProvider } = buildRuntime();
1335
- const byModel = modelPoolByProvider.get(options.provider);
1336
- const pool = (byModel && byModel.get(options.model)) || providerToPool.get(options.provider);
1337
- if (!pool) return next();
1338
- console.warn(`[dsh-key-rotation] rotating ${options.provider}/${options.model} across ${(pool.weightedRefs ?? pool.refs).length} slots (${pool.refs.length} keys)`);
1339
- return rotate(options, pool);
1340
- });
1341
-
1342
- // Safety net for non-stream requests (agent/request-error waterfall).
1343
- // llm/stream covers streaming calls; sync calls (embeddings, batch) go
1344
- // through agent/request and surface errors here. If the error is
1345
- // switchable, mark the key and ask the agent loop to retry.
1346
- ctx.on('agent/request-error', async (payload, next) => {
1347
- const provider = payload?.provider ?? payload?.failure?.provider ?? '';
1348
- if (!provider) return next();
1349
- const { providerToPool, modelPoolByProvider, switchCodes } = buildRuntime();
1350
- const model = payload?.model || payload?.failure?.model || '';
1351
- const byModel = modelPoolByProvider.get(provider);
1352
- const pool = (byModel && byModel.get(model)) || providerToPool.get(provider);
1353
- if (!pool) return next();
1354
- const code = String(payload?.failure?.code ?? payload?.code ?? '');
1355
- const message = String(payload?.failure?.message ?? payload?.message ?? '');
1356
- const effectiveSwitchCodes = pool.switchCodes ?? switchCodes;
1357
- const switchable = effectiveSwitchCodes.has(code) || SWITCHABLE_MESSAGE_PATTERN.test(message);
1358
- if (!switchable) return next();
1359
- const ref = pool.state.lastUsed;
1360
- if (ref) {
1361
- const backoff = recordFailure(pool, ref, Date.now(), pool.cooldownMs ?? 60000);
1362
- pushEvent(pool, ref, code || 'UNKNOWN', backoff);
1363
- pool.state.switches = (pool.state.switches ?? 0) + 1;
1364
- pool.state.lastReason = code || 'UNKNOWN';
1365
- pool.state.lastSwitchAt = Date.now();
1366
- console.warn(`[dsh-key-rotation] ${provider}: key ${String(ref)} failed via agent/request-error (${String(code)} ${String(message).slice(0, 80)}) retry`);
1367
- }
1368
- return { kind: 'retry' };
1369
- });
1370
-
1371
- ctx.inject(['settings'], (sctx) => {
1372
- const scope = sctx.settings.register(NS, Config, { base: config });
1373
- getConfig = () => scope.get() ?? config;
1374
- sctx.effect(() => () => {
1375
- getConfig = () => config;
1376
- });
1377
- });
1378
- }
1379
-
1380
- // Notify on exhaustion: webhook + (optional) GitHub incident.
1381
- // Extracted at module scope for testability. No I/O outside the injected hooks.
1382
- // ponytail: thresholds and URLs are runtime-resolved per call, so changing Config is reflected immediately.
1383
- export function notifyExhaustion(runtime, pool, options, hooks = { webhookSender, ensureIncidentReporter }) {
1384
- if (!runtime || !pool) return;
1385
- const count = pool.state ? (pool.state.exhaustionCount ?? 0) : 0;
1386
- if (count <= 0) return;
1387
- try {
1388
- if (runtime.notifyWebhook && count >= (runtime.notifyThreshold ?? 0)) {
1389
- hooks.webhookSender.send(runtime.notifyWebhook, {
1390
- provider: options.provider,
1391
- exhaustionCount: count,
1392
- at: pool.state.lastExhaustionAt,
1393
- keys: pool.refs,
1394
- });
1395
- }
1396
- if (runtime.incidentThreshold && count >= runtime.incidentThreshold) {
1397
- const reporter = hooks.ensureIncidentReporter();
1398
- if (reporter) reporter.open(options.provider, pool.state.lastExhaustionAt);
1399
- }
1400
- } catch (_) { /* ponytail: never crash rotate() */ }
1401
- }
1402
-
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // dsh-key-rotation — per-provider API key rotation for DeepSeek Harness.
3
+ //
4
+ // Transparent key rotation, Hermes-style: every configured provider has a KEY
5
+ // POOL (env refs). The plugin patches `ctx.credentials.resolve` so a pool ref
6
+ // resolves to the next available key (round-robin, skipping keys in cooldown),
7
+ // and intercepts `llm/stream` to retry a request on the next key when the
8
+ // current one fails with a switchable error (QUOTA, RATE_LIMIT, ...) before
9
+ // any content chunk.
10
+ //
11
+ // The PROVIDER IDENTITY NEVER CHANGES: requests always go out with the
12
+ // provider the user selected, only the resolved API key differs. This keeps
13
+ // pi-ai's replay state consistent across multi-call turns and multi-turn
14
+ // sessions (the earlier clone-provider approach broke it with
15
+ // INVALID_REPLAY_STATE).
16
+ //
17
+ // Config is a KEY POOL PER PROVIDER: you list a real provider id and the env
18
+ // names of its API keys (e.g. <PROVIDER>_API_KEY, <PROVIDER>_API_KEY_2, ...).
19
+ // When a key's limit is exhausted, the request retries on the next key in the
20
+ // list; exhausted keys stay in cooldown for cooldownMs. Clone provider routes
21
+ // (named `<base>-2`, `<base>-3`, ...) are no longer used for rotation but
22
+ // remain registered, so selecting them also rotates (their apiKeyEnv ref
23
+ // belongs to the same pool).
24
+ //
25
+ // The Settings section ("Key Rotation") edits the provider key pools as a
26
+ // simple list: pick a provider from the dropdown of every provider registered
27
+ // with ctx.llm (clone routes are hidden from the dropdown), then add/remove key
28
+ // env names. Plus cooldown and switch codes.
29
+ //
30
+ // Config (all optional, sane defaults):
31
+ // switchCodes: string[] failure codes eligible to switch
32
+ // cooldownMs: number key cooldown after a switchable failure
33
+ // providers: array [{ provider, keys: [envName, ...] }]
34
+ // ─────────────────────────────────────────────────────────────────────────────
35
+ import Schema from '@deepseek-ai/schemastery';
36
+ import { keyTail, isLoopbackAddress, isTrustedBridgeRequest, SWITCHABLE_MESSAGE_PATTERN, DEFAULT_SWITCH_CODES, isValidRef, pickNext, applyCooldown, recordFailure, recordSuccess, computeBackoff, envValue, sweepExpired, parseRetryAfter, computeHealthScore, extractRateLimit, isRateLimited, selectPool } from './pool.js';
37
+
38
+ export const name = 'dsh-key-rotation';
39
+ export const inject = ['llm', 'webServer', 'settings', 'credentials'];
40
+ export { keyTail, isLoopbackAddress, isTrustedBridgeRequest, DEFAULT_SWITCH_CODES };
41
+
42
+ /** Settings namespace owning the GUI-editable section (settingsNamespace-valid). */
43
+ const NS = 'dsh-key-rotation';
44
+ /** Config bridge route (GET / PUT / DELETE), loopback-fenced like llm-fallback. */
45
+ const CONFIG_PATH = '/dsh-key-rotation/config';
46
+ const STATUS_PATH = '/dsh-key-rotation/status';
47
+ const KEY_PATH = '/dsh-key-rotation/key';
48
+ const RESET_PATH = '/dsh-key-rotation/reset';
49
+ const IMPORT_PATH = '/dsh-key-rotation/import';
50
+ const HEALTH_PATH = '/dsh-key-rotation/health';
51
+ const USAGE_PATH = '/dsh-key-rotation/usage';
52
+ const TEST_PATH = '/dsh-key-rotation/test';
53
+ const SANDBOX_CACHE_PATH = '/dsh-key-rotation/sandbox-cache';
54
+ const AGENT_BUDGET_PATH = '/dsh-key-rotation/agent-budget';
55
+ const REGIONS_PATH = '/dsh-key-rotation/regions';
56
+ const INCIDENT_RESET_PATH = '/dsh-key-rotation/incident-reset';
57
+ const SHADOW_PATH = '/dsh-key-rotation/shadow';
58
+ const WEBHOOK_TEST_PATH = '/dsh-key-rotation/webhook-test';
59
+ const TEST_MATRIX_PATH = '/dsh-key-rotation/test-matrix';
60
+ import { LastTestCache, SandboxRunner } from './sandbox.js';
61
+ import { healIdleCooldowns } from './heal.js';
62
+ import { LatencyHistogram } from './histogram.js';
63
+ import { pickCascadeFallback } from './cascade.js';
64
+ import { ConcurrencyTracker } from './concurrency.js';
65
+ import { nextQuotaReset } from './quota-window.js';
66
+ import { CanaryProber } from './canary.js';
67
+ import { QuotaStore } from './quota.js';
68
+ import { AgentBudget } from './agent-budget.js';
69
+ import { RegionMap } from './region.js';
70
+ import { IncidentReporter } from './incident.js';
71
+ import { ShadowRouter } from './shadow.js';
72
+ import { WebhookSender } from './webhook.js';
73
+ import { bucketAllow, bucketRetryMs, bucketSweep, bucketInfo } from './bucket.js';
74
+ import { expiringSoon, shouldNotifyDaily, costForDay, budgetVerdict, costForWeek } from './maintenance.js';
75
+ import { usageRows, usageCsv } from './usage-report.js';
76
+ import { findSecrets, looksLikeApiSecret } from './keycheck.js';
77
+
78
+ /** The llm-pi-ai namespace whose provider profiles map providers to pools. */
79
+ const PIAI_NS = 'llm-pi-ai';
80
+ /** Marker on internally re-dispatched requests so the interceptor does not loop. */
81
+ const MARKER = '__dshKeyRotation';
82
+ /** #199: set true via webhook action; checked in the llm/stream interceptor. */
83
+ let rotationDisabled = false;
84
+ // #207/#208 dedupe maps: one notification per key/window per day.
85
+ const expiryNotifiedAt = new Map();
86
+ const budgetNotifiedAt = new Map();
87
+ const DAY_MS = 86400000;
88
+ const MAX_EVENTS = 50;
89
+ function pushEvent(pool, ref, reason, cooldownMs, type) {
90
+ const ev = { at: Date.now(), ref, reason: String(reason ?? 'UNKNOWN'), cooldownMs, type: type ?? 'fail' };
91
+ pool.state.events.push(ev);
92
+ if (pool.state.events.length > MAX_EVENTS) pool.state.events.shift();
93
+ }
94
+
95
+
96
+ // Fallback classification by failure message. pi-ai surfaces many real quota /
97
+ // rate-limit / transport failures as thrown exceptions (e.g. the OpenAI SDK
98
+ // throws on HTTP 429 before the stream starts), and dsh-llm then normalizes
99
+ // them to finish chunks with code "UNKNOWN". The message still carries the
100
+ // provider's own text ("429: ...", "Weekly usage limit reached", ...), so we
101
+ // treat pre-content failures whose message matches these patterns as
102
+ // switchable even when the code is not in `switchCodes`.
103
+
104
+ // Sandbox-test infrastructure (sandbox.js): in-memory cache + runner.
105
+ let lastTestCacheRunnerCtx = null;
106
+ const lastTestCache = new LastTestCache();
107
+ const latencyHistogram = new LatencyHistogram();
108
+ const quotaStore = new QuotaStore();
109
+ const agentBudget = new AgentBudget();
110
+ const regionMap = new RegionMap();
111
+ // IncidentReporter: lazily built when Config provides incidentGitHubToken + incidentGitHubBaseUrl.
112
+ // ponytail: never bake the token into source; repo is hardcoded (this plugin's home repo) but token is per-deploy.
113
+ let incidentReporter = null;
114
+ function ensureIncidentReporter() {
115
+ if (incidentReporter) return incidentReporter;
116
+ const cfg = getConfig();
117
+ const token = cfg ? cfg.incidentGitHubToken : '';
118
+ const baseUrl = cfg ? cfg.incidentGitHubBaseUrl : '';
119
+ if (!token || !baseUrl) return null;
120
+ incidentReporter = new IncidentReporter({ token, baseUrl, repo: 'goodandready/dsh-key-rotation', fetchImpl: globalThis.fetch });
121
+ return incidentReporter;
122
+ }
123
+ const shadowRouter = new ShadowRouter({ primary: '', secondary: '', percent: 0 });let sandboxRunner = null;
124
+ const webhookSender = new WebhookSender({ fetchImpl: globalThis.fetch });
125
+ const concurrencyTracker = new ConcurrencyTracker();
126
+ let canaryProber = null;
127
+ function ensureSandboxRunner(ctx) {
128
+ if (sandboxRunner) return sandboxRunner;
129
+ // provider id -> baseUrl (stripped of trailing /) for fetch /models probe
130
+ function resolveBaseUrl(provider) {
131
+ try {
132
+ const ns = ctx.get(PIAI_NS);
133
+ const list = ns && (ns.providers || (ns.config && ns.config.providers) || []);
134
+ if (!Array.isArray(list)) return null;
135
+ // ponytail: match by id OR name OR alias; pick first hit
136
+ const hit = list.find((p) => p && (p.id === provider || p.name === provider || (Array.isArray(p.aliases) && p.aliases.includes(provider))));
137
+ const base = hit && (hit.baseUrl || hit.endpoint || hit.url);
138
+ return base ? String(base) : null;
139
+ } catch (e) {
140
+ return null;
141
+ }
142
+ }
143
+ sandboxRunner = new SandboxRunner({ fetchImpl: globalThis.fetch, resolveBaseUrl });
144
+ return sandboxRunner;
145
+ }
146
+ async function probeRef(ref, key) {
147
+ // ref may be like "PROVIDER/KEY_NAME" for sandbox we only care about the credential ref
148
+ // (the resolveBaseUrl uses the full provider id; ref can carry any string)
149
+ const runner = ensureSandboxRunner(lastTestCacheRunnerCtx);
150
+ const result = await runner.probeModels(ref, key);
151
+ lastTestCache.set(ref, { ...result, at: Date.now() });
152
+ return result;
153
+ }
154
+
155
+ // // Bootstrap key pools. The user configures them in the Settings GUI or via
156
+ // the dsh profile bundle config; the plugin itself ships no provider defaults
157
+ // so it does not bind to any specific installation. Empty array means: until
158
+ // the user adds a pool, no rotation happens, and every provider falls back to
159
+ // its single configured credential exactly as before this plugin was installed.
160
+ const DEFAULT_PROVIDERS = [];
161
+
162
+ export const Config = Schema.object({
163
+ switchCodes: Schema.array(Schema.string()).default([...DEFAULT_SWITCH_CODES]),
164
+ cooldownMs: Schema.number().default(60000),
165
+ maxCooldownMs: Schema.number(),
166
+ notifyWebhook: Schema.string().default(''),
167
+ notifyThreshold: Schema.number().default(3),
168
+ backupDir: Schema.string().default(''),
169
+ backupIntervalMs: Schema.number().default(86400000),
170
+ backupKeep: Schema.number().default(7),
171
+ rotationScheduleDays: Schema.number().default(0),
172
+ selfHealCooldown: Schema.boolean().default(true),
173
+ selfHealIdleMs: Schema.number().default(3600000),
174
+ latencyEnabled: Schema.boolean().default(true),
175
+ latencyWindow: Schema.number().default(200),
176
+ incidentGitHubToken: Schema.string().default(''),
177
+ incidentGitHubBaseUrl: Schema.string().default(''),
178
+ incidentThreshold: Schema.number().default(5),
179
+ concurrencyLimit: Schema.number().default(0),
180
+ canaryProbingEnabled: Schema.boolean().default(false),
181
+ canaryIntervalMs: Schema.number().default(30000),
182
+ cascade: Schema.array(Schema.object({
183
+ provider: Schema.string().required(),
184
+ model: Schema.string(),
185
+ })).default([]),
186
+ quotaResetWindow: Schema.object({
187
+ type: Schema.string().default('midnight_utc'),
188
+ hour: Schema.number().default(0),
189
+ }),
190
+ rateLimitThreshold: Schema.number().default(0.1),
191
+ rpmLimit: Schema.number().default(0),
192
+ webhookActionToken: Schema.string().default(''),
193
+ expiryWarnDays: Schema.number().default(7),
194
+ providers: Schema.array(Schema.object({
195
+ provider: Schema.string().required(),
196
+ keys: Schema.array(Schema.string()).default([]),
197
+ weights: Schema.array(Schema.number()).default([]),
198
+ expiresAt: Schema.array(Schema.union([Schema.number(), Schema.string()])).default([]),
199
+ tags: Schema.array(Schema.string()).default([]),
200
+ costBudgetDaily: Schema.number(),
201
+ costBudgetWeekly: Schema.number(),
202
+ pauseOnBudget: Schema.boolean().default(false),
203
+ models: Schema.dict(Schema.object({
204
+ keys: Schema.array(Schema.string()).default([]),
205
+ weights: Schema.array(Schema.number()).default([]),
206
+ })).default({}),
207
+ cooldownMs: Schema.number(),
208
+ maxCooldownMs: Schema.number(),
209
+ })).default([...DEFAULT_PROVIDERS]),
210
+ });
211
+
212
+ // ── config bridge (GET/PUT/DELETE on CONFIG_PATH), mirroring llm-fallback ──
213
+
214
+
215
+ function json(res, status, obj) {
216
+ res.writeHead(status, { 'content-type': 'application/json' });
217
+ res.end(JSON.stringify(obj));
218
+ }
219
+
220
+ function readJson(request) {
221
+ return new Promise((resolve, reject) => {
222
+ let raw = '';
223
+ request.on('data', (c) => { raw += c; });
224
+ request.on('end', () => {
225
+ try {
226
+ resolve(JSON.parse(raw || '{}'));
227
+ } catch (e) {
228
+ reject(e);
229
+ }
230
+ });
231
+ request.on('error', reject);
232
+ });
233
+ }
234
+
235
+ function descriptorOf(ctx, ns) {
236
+ const settings = ctx.get('settings');
237
+ if (settings === void 0) return void 0;
238
+ return settings.describe({ redactSecrets: true }).find((candidate) => candidate.ns === ns);
239
+ }
240
+
241
+ function viewOf(descriptor, settings) {
242
+ return {
243
+ available: true,
244
+ writable: settings.writable,
245
+ hasDocument: settings.hasDocument,
246
+ value: descriptor.value,
247
+ ...descriptor.base === void 0 ? {} : { base: descriptor.base },
248
+ ...descriptor.user === void 0 || Object.keys(descriptor.user).length === 0 ? {} : { user: descriptor.user },
249
+ revision: descriptor.revision,
250
+ };
251
+ }
252
+
253
+ async function writeSection(ctx, ns, section, expectedRevision, res) {
254
+ const settings = ctx.get('settings');
255
+ if (settings === void 0) {
256
+ json(res, 503, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: no settings provider is mounted' } });
257
+ return;
258
+ }
259
+ try {
260
+ await settings.replace(ns, section, expectedRevision);
261
+ } catch (error) {
262
+ if (error?.code === 'SETTINGS_CONFLICT') {
263
+ json(res, 409, { error: { code: 'settings-conflict', message: `dsh-key-rotation: changed elsewhere (expected revision ${String(error.expected)}, current ${String(error.actual)}); reload and retry` } });
264
+ return;
265
+ }
266
+ json(res, 400, { error: { code: 'settings-rejected', message: error instanceof Error ? error.message : String(error) } });
267
+ return;
268
+ }
269
+ const descriptor = descriptorOf(ctx, ns);
270
+ if (descriptor === void 0) {
271
+ json(res, 500, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: namespace vanished after write' } });
272
+ return;
273
+ }
274
+ json(res, 200, viewOf(descriptor, { writable: settings.writable, hasDocument: settings.documentPath !== void 0 }));
275
+ }
276
+
277
+ /** Provider catalog for the GUI dropdown, minus clone routes of configured chains. */
278
+ function providerCatalog(ctx, cloneIds) {
279
+ const seen = new Set();
280
+ const out = [];
281
+ for (const info of ctx.llm.listProviders()) {
282
+ if (seen.has(info.id) || cloneIds.has(info.id)) continue;
283
+ seen.add(info.id);
284
+ out.push({ id: info.id, name: info.name ?? info.id });
285
+ }
286
+ return out;
287
+ }
288
+
289
+ async function handleConfigBridge(ctx, request, res, getCloneIds) {
290
+ if (!isTrustedBridgeRequest(request)) {
291
+ res.writeHead(403);
292
+ res.end();
293
+ return;
294
+ }
295
+ const method = request.method ?? 'GET';
296
+ if (method === 'GET') {
297
+ const settings = ctx.get('settings');
298
+ const descriptor = descriptorOf(ctx, NS);
299
+ const body = {
300
+ providers: providerCatalog(ctx, getCloneIds()),
301
+ };
302
+ if (descriptor === void 0) {
303
+ json(res, 200, {
304
+ ...body,
305
+ available: false,
306
+ writable: settings?.writable ?? false,
307
+ hasDocument: settings?.documentPath !== void 0,
308
+ value: void 0,
309
+ revision: 0,
310
+ });
311
+ return;
312
+ }
313
+ json(res, 200, {
314
+ ...body,
315
+ ...viewOf(descriptor, {
316
+ writable: settings?.writable ?? false,
317
+ hasDocument: settings?.documentPath !== void 0,
318
+ }),
319
+ });
320
+ return;
321
+ }
322
+ if (method === 'PUT' || method === 'DELETE') {
323
+ let section;
324
+ let expectedRevision;
325
+ if (method === 'PUT') {
326
+ let body;
327
+ try {
328
+ body = await readJson(request);
329
+ } catch (error) {
330
+ json(res, 400, { error: { code: 'settings-rejected', message: `dsh-key-rotation: invalid request body: ${error instanceof Error ? error.message : String(error)}` } });
331
+ return;
332
+ }
333
+ if (typeof body !== 'object' || body === null || typeof body.section !== 'object' || body.section === null || Array.isArray(body.section)) {
334
+ json(res, 400, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: PUT requires {"section": {...}}' } });
335
+ return;
336
+ }
337
+ section = body.section;
338
+ expectedRevision = typeof body.expectedRevision === 'number' ? body.expectedRevision : void 0;
339
+ // #200 leak detector: a live secret pasted into the config section is
340
+ // almost always a mistake (real key values belong in PUT /key). The two
341
+ // fields that legitimately hold tokens are masked before scanning.
342
+ try {
343
+ const masked = structuredClone(section);
344
+ if (masked.incidentGitHubToken) masked.incidentGitHubToken = '***';
345
+ if (masked.webhookActionToken) masked.webhookActionToken = '***';
346
+ // notifyWebhook legitimately carries bot tokens inside URLs
347
+ // (api.telegram.org/bot<token>/...) - scan it for nothing.
348
+ if (masked.notifyWebhook) masked.notifyWebhook = '***';
349
+ const findings = findSecrets(JSON.stringify(masked));
350
+ if (findings.length > 0) {
351
+ json(res, 400, {
352
+ error: {
353
+ code: 'secret-in-config',
354
+ message: `dsh-key-rotation: value looks like a live credential (${findings[0].type}); store key values via the key field, not the config section`,
355
+ findings,
356
+ },
357
+ });
358
+ return;
359
+ }
360
+ } catch {
361
+ /* scanning must never block a valid save */
362
+ }
363
+ } else {
364
+ section = {};
365
+ }
366
+ await writeSection(ctx, NS, section, expectedRevision, res);
367
+ return;
368
+ }
369
+ res.writeHead(405);
370
+ res.end();
371
+ }
372
+
373
+ function registerConfigBridge(ctx, getCloneIds) {
374
+ return ctx.webServer.register({
375
+ kind: 'exact',
376
+ path: CONFIG_PATH,
377
+ handler: (req, res) => void handleConfigBridge(ctx, req, res, getCloneIds),
378
+ });
379
+ }
380
+
381
+ // ── plugin ──
382
+
383
+ export function apply(ctx, config = {}) {
384
+ // GUI section: defaults -> cordis row config -> saved user section.
385
+ // (installSettingsSection inlined: no @deepseek-ai/dsh-settings import, so the
386
+ // profile does not need a second copy of that package.)
387
+ let getConfig = () => config;
388
+ registerConfigBridge(ctx, () => buildRuntime().cloneIds);
389
+ lastTestCacheRunnerCtx = ctx;
390
+ // Cache should not survive profile restarts (apply is called per reload).
391
+ // We deliberately do NOT clear on every apply — that would wipe badges when
392
+ // the user is just typing in the settings card. Re-init only on true reload.
393
+ ensureSandboxRunner(ctx);
394
+
395
+ // Self-healing idle cooldowns: every 60s, lift expired cooldowns for keys
396
+ // that have been idle for selfHealIdleMs (default 1h). ponytail: small
397
+ // interval, low cost; skipped when selfHealCooldown is disabled in config.
398
+ // ponytail: keep handle on the same ctx via closure so buildRuntime() reads
399
+ // fresh config on every tick. Naive but correct: 60s cadence is cheap.
400
+ // #196: canary probing before key release from cooldown.
401
+ // Every canaryIntervalMs, probe refs that are in cooldown and close to expiry.
402
+ let canaryTimer = null;
403
+ const startCanary = () => {
404
+ const cfg = getConfig();
405
+ if (!cfg || !cfg.canaryProbingEnabled) return;
406
+ if (canaryTimer) return;
407
+ canaryTimer = setInterval(() => {
408
+ try {
409
+ const c = getConfig();
410
+ if (!c || !c.canaryProbingEnabled) return;
411
+ const runner = ensureSandboxRunner();
412
+ if (!runner) return;
413
+ if (!canaryProber) {
414
+ canaryProber = new CanaryProber({ sandboxRunner: runner, intervalMs: c.canaryIntervalMs });
415
+ }
416
+ const providers = Array.isArray(c.providers) ? c.providers : [];
417
+ for (const p of providers) {
418
+ const pool = buildRuntime().providerToPool.get(p.provider);
419
+ if (!pool) continue;
420
+ for (const ref of pool.refs) {
421
+ const until = pool.state.failedUntil.get(ref) ?? 0;
422
+ const now = Date.now();
423
+ // Probe refs in cooldown whose expiry is within canaryIntervalMs of now
424
+ if (until > now && until - now < (c.canaryIntervalMs ?? 30000)) {
425
+ canaryProber.probe(ref, ref);
426
+ }
427
+ }
428
+ }
429
+ } catch (_) { /* ponytail: never crash the timer */ }
430
+ }, cfg.canaryIntervalMs ?? 30000);
431
+ if (typeof canaryTimer.unref === 'function') canaryTimer.unref();
432
+ };
433
+ startCanary();
434
+
435
+ const selfHealTimer = setInterval(() => {
436
+ const cfg = getConfig();
437
+ if (!cfg || cfg.selfHealCooldown === false) return;
438
+ try {
439
+ const idle = Number.isFinite(cfg.selfHealIdleMs) && cfg.selfHealIdleMs > 0 ? cfg.selfHealIdleMs : 3600000;
440
+ const providers = Array.isArray(cfg.providers) ? cfg.providers : [];
441
+ const pools = providers
442
+ .map((p) => buildRuntime().providerToPool.get(p.provider))
443
+ .filter(Boolean);
444
+ healIdleCooldowns(pools, idle);
445
+ } catch (_) { /* ponytail: never crash the timer */ }
446
+ }, 60000);
447
+ if (typeof selfHealTimer.unref === 'function') selfHealTimer.unref();
448
+
449
+ // Dashboard widget now lives in client.js (mountDashboard, see issue #152).
450
+ const DASH_HTML = '';
451
+ // ── key-pool state, persisted across config reloads ──
452
+ // base provider -> { failedUntil: Map<ref, epochMs>, pointer: number, lastUsed: ref }
453
+ const poolState = new Map();
454
+ // Periodic backup of pools config
455
+ ctx.effect(() => {
456
+ const { backupDir, backupIntervalMs, backupKeep } = buildRuntime();
457
+ if (!backupDir) return;
458
+ const id = setInterval(() => {
459
+ try {
460
+ const fs = require('node:fs');
461
+ const path = require('node:path');
462
+ const dir = backupDir;
463
+ fs.mkdirSync(dir, { recursive: true });
464
+ const now = new Date();
465
+ const dateStr = now.toISOString().slice(0,10).replace(/-/g,'');
466
+ const file = path.join(dir, 'pools-' + dateStr + '.json');
467
+ const data = JSON.stringify({ backup: now.toISOString(), providers: getConfig()?.providers ?? [] }, null, 2);
468
+ fs.writeFileSync(file, data, 'utf8');
469
+ // prune old backups
470
+ const keep = backupKeep || 7;
471
+ const files = fs.readdirSync(dir).filter((f) => f.startsWith('pools-') && f.endsWith('.json')).sort();
472
+ while (files.length > keep) {
473
+ const old = files.shift();
474
+ fs.unlinkSync(path.join(dir, old));
475
+ }
476
+ } catch (e) {
477
+ console.warn('[dsh-key-rotation] backup failed:', String(e?.message ?? e));
478
+ }
479
+ }, backupIntervalMs || 86400000);
480
+ return () => clearInterval(id);
481
+ }, 'dsh-key-rotation: backup pools');
482
+ // Periodic save of usage/cost stats to file
483
+ ctx.effect(() => {
484
+ const { backupDir } = buildRuntime();
485
+ if (!backupDir) return;
486
+ try {
487
+ const fs = require('node:fs');
488
+ const path = require('node:path');
489
+ const statsFile = path.join(backupDir, 'stats.json');
490
+ // Load existing stats at startup
491
+ try {
492
+ if (fs.existsSync(statsFile)) {
493
+ const saved = JSON.parse(fs.readFileSync(statsFile, 'utf8'));
494
+ for (const st of poolState.values()) {
495
+ if (saved.usageCounts && st.usageCounts) { for (const [k, v] of Object.entries(saved.usageCounts)) st.usageCounts.set(k, (st.usageCounts.get(k) ?? 0) + v); }
496
+ if (saved.costPerKey && st.costPerKey) { for (const [k, v] of Object.entries(saved.costPerKey)) st.costPerKey.set(k, (st.costPerKey.get(k) ?? 0) + v); }
497
+ if (saved.lastUsedAt && st.lastUsedAt) { for (const [k, v] of Object.entries(saved.lastUsedAt)) { if (!st.lastUsedAt.has(k) || v > st.lastUsedAt.get(k)) st.lastUsedAt.set(k, v); } }
498
+ }
499
+ }
500
+ } catch {}
501
+ // Periodic save
502
+ const id = setInterval(() => {
503
+ try {
504
+ const usageCounts = {}; const costPerKey = {}; const lastUsedAt = {};
505
+ for (const [base, st] of poolState) {
506
+ if (st.usageCounts) for (const [k, v] of st.usageCounts) usageCounts[k] = v;
507
+ if (st.costPerKey) for (const [k, v] of st.costPerKey) costPerKey[k] = v;
508
+ if (st.lastUsedAt) for (const [k, v] of st.lastUsedAt) lastUsedAt[k] = v;
509
+ }
510
+ fs.writeFileSync(statsFile, JSON.stringify({ t: Date.now(), usageCounts, costPerKey, lastUsedAt }), 'utf8');
511
+ } catch {}
512
+ }, 60000);
513
+ return () => clearInterval(id);
514
+ } catch { return () => {}; }
515
+ }, 'dsh-key-rotation: persist stats');
516
+ // Rotation schedule: shift pointer every N days
517
+ ctx.effect(() => {
518
+ const { rotationScheduleDays } = buildRuntime();
519
+ if (!rotationScheduleDays || rotationScheduleDays <= 0) return;
520
+ const intervalMs = Math.min(rotationScheduleDays * 86400000, 2147483647);
521
+ const id = setInterval(() => {
522
+ try {
523
+ const rt = buildRuntime();
524
+ let shifted = 0;
525
+ for (const pool of rt.poolByRef.values()) {
526
+ if (pool.refs.length < 2) continue;
527
+ const oldPtr = pool.state.pointer ?? 0;
528
+ pool.state.pointer = (oldPtr + 1) % pool.refs.length;
529
+ shifted++;
530
+ console.warn(`[dsh-key-rotation] ${pool.base}: scheduled rotation -> ${pool.refs[pool.state.pointer]} (day ${rotationScheduleDays})`);
531
+ }
532
+ if (shifted) console.warn(`[dsh-key-rotation] schedule: rotated ${shifted} pools`);
533
+ } catch (e) {
534
+ console.warn('[dsh-key-rotation] schedule error:', String(e?.message ?? e));
535
+ }
536
+ }, intervalMs);
537
+ return () => clearInterval(id);
538
+ }, 'dsh-key-rotation: rotation schedule');
539
+ // Periodic sweep of expired cooldowns — keeps health probe cheap and avoids waiting for next user request
540
+ ctx.effect(() => {
541
+ const id = setInterval(() => {
542
+ const now = Date.now();
543
+ // probe events for keys whose cooldown just expired
544
+ for (const st of poolState.values()) {
545
+ for (const [ref, until] of [...(st.failedUntil?.entries() ?? [])]) {
546
+ if (until <= now && !st.probedAt?.has(ref)) {
547
+ st.events.push({ at: until, ref, reason: 'probe', cooldownMs: 0, type: 'probe' });
548
+ if (st.events.length > 50) st.events.shift();
549
+ if (!st.probedAt) st.probedAt = new Map();
550
+ st.probedAt.set(ref, until);
551
+ }
552
+ }
553
+ }
554
+ const n = sweepExpired(poolState, now);
555
+ if (n > 0) console.warn(`[dsh-key-rotation] sweep: cleared ${n} expired cooldown(s)`);
556
+ // #207 expiry pre-warning + #208 cost budget - piggybacked on this timer,
557
+ // deduped to one notification per key/window per day (shouldNotifyDaily).
558
+ try {
559
+ const runtime = buildRuntime();
560
+ const seen = new Set();
561
+ for (const pool of runtime.poolByRef.values()) {
562
+ if (seen.has(pool.base)) continue;
563
+ seen.add(pool.base);
564
+ // #207: keys expiring within expiryWarnDays -> one webhook per key/day
565
+ for (const { ref, expiresInDays } of expiringSoon(pool, runtime.expiryWarnDays, now)) {
566
+ if (!shouldNotifyDaily(expiryNotifiedAt, pool.base + ':' + ref, now)) continue;
567
+ console.warn(`[dsh-key-rotation] ${pool.base}: key ${ref} expires in ~${expiresInDays}d`);
568
+ if (runtime.notifyWebhook) {
569
+ webhookSender.send(runtime.notifyWebhook, {
570
+ title: `Key expiring soon: ${pool.base}`,
571
+ text: `${ref} expires in ~${expiresInDays} day(s)`,
572
+ provider: pool.base,
573
+ kind: 'expiry',
574
+ keys: [ref],
575
+ });
576
+ }
577
+ }
578
+ // #208: daily/weekly budget -> warn webhook, optional 1-day pause at 100%
579
+ const budget = runtime.providerBudgets.get(pool.base);
580
+ if (!budget) continue;
581
+ const daily = costForDay(pool.state.costDays);
582
+ const weekly = costForWeek(pool.state.costDays, now);
583
+ const verdict = budgetVerdict(daily, budget.costBudgetDaily);
584
+ const wVerdict = budgetVerdict(weekly, budget.costBudgetWeekly);
585
+ const hit = verdict.warn || wVerdict.warn;
586
+ if (hit && shouldNotifyDaily(budgetNotifiedAt, pool.base + ':budget', now)) {
587
+ console.warn(`[dsh-key-rotation] ${pool.base}: cost budget - day $${daily.toFixed(2)}/$${budget.costBudgetDaily} week $${weekly.toFixed(2)}/$${budget.costBudgetWeekly}`);
588
+ if (runtime.notifyWebhook) {
589
+ webhookSender.send(runtime.notifyWebhook, {
590
+ title: `Cost budget: ${pool.base}`,
591
+ text: `day $${daily.toFixed(2)} of $${budget.costBudgetDaily} · week $${weekly.toFixed(2)} of $${budget.costBudgetWeekly}` + (verdict.exceeded || wVerdict.exceeded ? ' · EXCEEDED' : ''),
592
+ provider: pool.base,
593
+ kind: 'budget',
594
+ spend: { daily, weekly },
595
+ });
596
+ }
597
+ }
598
+ if ((verdict.exceeded || wVerdict.exceeded) && budget.pauseOnBudget) {
599
+ const until = now + DAY_MS;
600
+ for (const ref of pool.refs) {
601
+ if ((pool.state.failedUntil.get(ref) ?? 0) < until) pool.state.failedUntil.set(ref, until);
602
+ }
603
+ }
604
+ }
605
+ } catch (_) { /* maintenance must never crash the sweep */ }
606
+ }, 30000);
607
+ return () => clearInterval(id);
608
+ }, 'dsh-key-rotation: sweep expired cooldowns');
609
+
610
+ // ── runtime snapshot: config + llm-pi-ai profile mapping ──
611
+ function buildRuntime() {
612
+ // Deep-clone before resolving: the frozen snapshot from settings.register
613
+ // must never be written to by schemastery's dict resolver.
614
+ const cfg = Config(structuredClone(getConfig() ?? {})) ?? {};
615
+ const switchCodes = new Set(cfg.switchCodes ?? DEFAULT_SWITCH_CODES);
616
+ const cooldownMs = cfg.cooldownMs ?? 60000;
617
+ const maxCooldownMs = cfg.maxCooldownMs ?? undefined;
618
+ const notifyWebhook = cfg.notifyWebhook ?? '';
619
+ const notifyThreshold = cfg.notifyThreshold ?? 3;
620
+ const backupDir = cfg.backupDir ?? '';
621
+ const backupIntervalMs = cfg.backupIntervalMs ?? 86400000;
622
+ const backupKeep = cfg.backupKeep ?? 7;
623
+ const rotationScheduleDays = cfg.rotationScheduleDays ?? 0;
624
+ const rateLimitThreshold = cfg.rateLimitThreshold ?? 0.1;
625
+ const rpmLimit = cfg.rpmLimit ?? 0;
626
+ const webhookActionToken = cfg.webhookActionToken ?? '';
627
+ const incidentThreshold = cfg.incidentThreshold ?? 5;
628
+ const concurrencyLimit = cfg.concurrencyLimit ?? 0;
629
+ const canaryProbingEnabled = cfg.canaryProbingEnabled ?? false;
630
+ const canaryIntervalMs = cfg.canaryIntervalMs ?? 30000;
631
+ const cascade = Array.isArray(cfg.cascade) ? cfg.cascade : [];
632
+ const quotaResetWindow = cfg.quotaResetWindow || null;
633
+
634
+ // ref -> pool (every key env of every configured provider)
635
+ const poolByRef = new Map();
636
+ // provider route (from llm-pi-ai profiles) -> its key pool
637
+ const providerToPool = new Map();
638
+ // per-model key pools: provider -> Map<model, pool>
639
+ const modelPoolByProvider = new Map();
640
+ // clone route ids (for the settings dropdown filter)
641
+ const cloneIds = new Set();
642
+
643
+ const makeState = (base) => {
644
+ let st = poolState.get(base);
645
+ if (!st) {
646
+ st = {
647
+ failedUntil: new Map(),
648
+ failCounts: new Map(),
649
+ authFailCounts: new Map(),
650
+ brokenUntil: new Map(),
651
+ costPerKey: new Map(),
652
+ lastUsedAt: new Map(),
653
+ usageCounts: new Map(),
654
+ byModel: new Map(),
655
+ usageDays: new Map(),
656
+ quotaWindows: new Map(),
657
+ pointer: 0,
658
+ lastUsed: undefined,
659
+ switches: 0,
660
+ lastReason: undefined,
661
+ lastSwitchAt: undefined,
662
+ lastExhaustionAt: undefined,
663
+ exhaustionCount: 0,
664
+ events: [],
665
+ };
666
+ poolState.set(base, st);
667
+ }
668
+ return st;
669
+ };
670
+ const parseExpiry = (v) => {
671
+ if (typeof v === 'number' && v > 0) return v;
672
+ if (typeof v === 'string' && v.length > 0) { const ts = Date.parse(v); return Number.isNaN(ts) ? undefined : ts; }
673
+ return undefined;
674
+ };
675
+ const buildPool = (base, keys, weights, poolCooldown, poolMax, expiresAt) => {
676
+ const refs = (keys ?? []).filter((ref) => typeof ref === 'string' && ref.length > 0);
677
+ if (refs.length === 0) return null;
678
+ const w = Array.isArray(weights) ? weights : [];
679
+ const weightedRefs = [];
680
+ for (let i = 0; i < refs.length; i++) {
681
+ const ww = typeof w[i] === 'number' && w[i] > 0 ? Math.floor(w[i]) : 1;
682
+ for (let k = 0; k < ww; k++) weightedRefs.push(refs[i]);
683
+ }
684
+ const parsedExpiry = {};
685
+ if (Array.isArray(expiresAt)) {
686
+ for (let i = 0; i < refs.length; i++) {
687
+ const exp = parseExpiry(expiresAt[i]);
688
+ if (exp !== undefined) parsedExpiry[refs[i]] = exp;
689
+ }
690
+ }
691
+ return { base, refs, weightedRefs: weightedRefs.length > 0 ? weightedRefs : refs,
692
+ state: makeState(base), cooldownMs: poolCooldown, maxCooldownMs: poolMax, expiresAt: parsedExpiry, rpmLimit };
693
+ };
694
+ for (const p of cfg.providers ?? []) {
695
+ const poolCooldown = typeof p.cooldownMs === 'number' ? p.cooldownMs : (cfg.cooldownMs ?? 60000);
696
+ const poolMax = typeof p.maxCooldownMs === 'number' ? p.maxCooldownMs : (cfg.maxCooldownMs ?? undefined);
697
+ // base provider pool (fallback)
698
+ const pool = buildPool(p.provider, p.keys, p.weights, poolCooldown, poolMax);
699
+ if (pool) {
700
+ for (const ref of pool.refs) poolByRef.set(ref, pool);
701
+ for (let i = 1; i < pool.refs.length; i++) cloneIds.add(`${p.provider}-${i + 1}`);
702
+ }
703
+ // per-model pools
704
+ const models = p.models ?? {};
705
+ const byModel = new Map();
706
+ for (const [model, mp] of Object.entries(models)) {
707
+ const mpool = buildPool(`${p.provider}::${model}`, mp.keys, mp.weights, poolCooldown, poolMax);
708
+ if (mpool) {
709
+ byModel.set(model, mpool);
710
+ for (const ref of mpool.refs) poolByRef.set(ref, mpool);
711
+ }
712
+ }
713
+ if (byModel.size > 0) modelPoolByProvider.set(p.provider, byModel);
714
+ }
715
+
716
+ let profiles = {};
717
+ try {
718
+ profiles = ctx.get('settings')?.get(PIAI_NS)?.providers ?? {};
719
+ } catch {
720
+ /* settings not mounted yet — empty mapping */
721
+ }
722
+ for (const [provider, profile] of Object.entries(profiles)) {
723
+ if (profile?.apiKeyEnv && poolByRef.has(profile.apiKeyEnv)) {
724
+ providerToPool.set(provider, poolByRef.get(profile.apiKeyEnv));
725
+ }
726
+ }
727
+
728
+ // auto-cleanup: remove poolState for providers that are now empty or removed
729
+ for (const key of [...poolState.keys()]) {
730
+ if (![...poolByRef.values()].some((p) => p.base === key)) poolState.delete(key);
731
+ }
732
+ // #192: drop RPM windows for refs that no longer belong to any pool
733
+ for (const st of poolState.values()) {
734
+ if (st.rpmWindows) bucketSweep(st.rpmWindows, new Set(poolByRef.keys()));
735
+ }
736
+ // #195: provider -> tags (metadata, surfaced in status)
737
+ const providerTags = new Map();
738
+ // #208: provider -> { costBudgetDaily, costBudgetWeekly, pauseOnBudget }
739
+ const providerBudgets = new Map();
740
+ for (const p of cfg.providers ?? []) {
741
+ if (Array.isArray(p.tags) && p.tags.length > 0) providerTags.set(p.provider, p.tags);
742
+ const daily = typeof p.costBudgetDaily === 'number' ? p.costBudgetDaily : 0;
743
+ const weekly = typeof p.costBudgetWeekly === 'number' ? p.costBudgetWeekly : 0;
744
+ if (daily > 0 || weekly > 0) providerBudgets.set(p.provider, { costBudgetDaily: daily, costBudgetWeekly: weekly, pauseOnBudget: p.pauseOnBudget ?? false });
745
+ }
746
+ return { switchCodes, cooldownMs, maxCooldownMs, notifyWebhook, notifyThreshold, incidentThreshold, concurrencyLimit, canaryProbingEnabled, canaryIntervalMs, cascade, quotaResetWindow, backupDir, backupIntervalMs, backupKeep, rotationScheduleDays, rateLimitThreshold, rpmLimit, webhookActionToken, expiryWarnDays: cfg.expiryWarnDays ?? 7, providerTags, providerBudgets, poolByRef, providerToPool, modelPoolByProvider, cloneIds };
747
+ }
748
+
749
+ // ── patch credentials.resolve: pool refs resolve to the next healthy key ──
750
+ // Round-robin over the pool, skipping keys in cooldown; the request's
751
+ // provider identity never changes, so pi-ai replay state stays consistent.
752
+ const credentials = ctx.get('credentials');
753
+ if (credentials && typeof credentials.resolve === 'function' && !credentials.__dshKeyRotationPatched) {
754
+ const original = credentials.resolve.bind(credentials);
755
+ // Kept for the status route: it must ask about one exact ref instead of
756
+ // being rotated to a different key by the patch below.
757
+ credentials.__dshKeyRotationOriginalResolve = original;
758
+ credentials.resolve = async (ref) => {
759
+ const { poolByRef } = buildRuntime();
760
+ const pool = poolByRef.get(ref);
761
+ if (!pool) return original(ref);
762
+ const now = Date.now();
763
+ const list = pool.weightedRefs ?? pool.refs;
764
+ const start = pool.state.pointer ?? 0;
765
+ for (let i = 0; i < list.length; i++) {
766
+ const index = (start + i) % list.length;
767
+ const candidate = list[index];
768
+ const until = pool.state.failedUntil.get(candidate);
769
+ if (until !== undefined && until > now) continue;
770
+ if (pool.expiresAt?.[candidate] !== undefined && now >= pool.expiresAt[candidate]) continue;
771
+ // #192 RPM token bucket: skip a key that already hit its requests/min cap
772
+ const rpmLimit = pool.rpmLimit ?? 0;
773
+ if (rpmLimit > 0) {
774
+ if (!pool.state.rpmWindows) pool.state.rpmWindows = new Map();
775
+ if (!bucketAllow(pool.state.rpmWindows, candidate, rpmLimit, now)) {
776
+ const waitMs = bucketRetryMs(pool.state.rpmWindows, candidate, rpmLimit, now);
777
+ if ((pool.state.failedUntil.get(candidate) ?? 0) < now + waitMs) {
778
+ pool.state.failedUntil.set(candidate, now + waitMs);
779
+ }
780
+ continue;
781
+ }
782
+ }
783
+ if (pool.perHour) {
784
+ if (!pool.state.quotaWindows) pool.state.quotaWindows = new Map();
785
+ let win = pool.state.quotaWindows.get(candidate);
786
+ if (!win || now - win.start >= 3600000) win = { count: 0, start: now };
787
+ if (win.count >= pool.perHour) {
788
+ const until = win.start + 3600000;
789
+ if ((pool.state.failedUntil.get(candidate) ?? 0) < until) pool.state.failedUntil.set(candidate, until);
790
+ continue;
791
+ }
792
+ }
793
+ let hit = await original(candidate);
794
+ if (hit && typeof hit.value === 'string' && hit.value.length > 0) {
795
+ pool.state.pointer = (index + 1) % list.length;
796
+ pool.state.lastUsed = candidate;
797
+ if (pool.state.failCounts) pool.state.failCounts.delete(candidate);
798
+ pool.state.failedUntil.delete(candidate);
799
+ if (pool.state.authFailCounts) pool.state.authFailCounts.delete(candidate);
800
+ if (pool.state.brokenUntil) pool.state.brokenUntil.delete(candidate);
801
+ if (!pool.state.usageCounts) pool.state.usageCounts = new Map();
802
+ pool.state.usageCounts.set(candidate, (pool.state.usageCounts.get(candidate) ?? 0) + 1);
803
+ if (pool.perHour) {
804
+ if (!pool.state.quotaWindows) pool.state.quotaWindows = new Map();
805
+ let win2 = pool.state.quotaWindows.get(candidate);
806
+ if (!win2 || now - win2.start >= 3600000) win2 = { count: 0, start: now };
807
+ win2.count++;
808
+ pool.state.quotaWindows.set(candidate, win2);
809
+ }
810
+ return hit;
811
+ }
812
+ // fallback: env var (transient, not persisted)
813
+ const envVal = envValue(candidate);
814
+ if (envVal !== undefined) {
815
+ pool.state.pointer = (index + 1) % list.length;
816
+ pool.state.lastUsed = candidate;
817
+ if (pool.state.failCounts) pool.state.failCounts.delete(candidate);
818
+ pool.state.failedUntil.delete(candidate);
819
+ if (pool.state.authFailCounts) pool.state.authFailCounts.delete(candidate);
820
+ if (pool.state.brokenUntil) pool.state.brokenUntil.delete(candidate);
821
+ if (!pool.state.usageCounts) pool.state.usageCounts = new Map();
822
+ pool.state.usageCounts.set(candidate, (pool.state.usageCounts.get(candidate) ?? 0) + 1);
823
+ if (pool.perHour) {
824
+ if (!pool.state.quotaWindows) pool.state.quotaWindows = new Map();
825
+ let win2 = pool.state.quotaWindows.get(candidate);
826
+ if (!win2 || now - win2.start >= 3600000) win2 = { count: 0, start: now };
827
+ win2.count++;
828
+ pool.state.quotaWindows.set(candidate, win2);
829
+ }
830
+ return { value: envVal, source: 'env' };
831
+ }
832
+ }
833
+ return original(ref); // everything cooled/missing surface the base value
834
+ };
835
+ credentials.__dshKeyRotationPatched = true;
836
+ }
837
+
838
+ const finishError = (code, message) => ({
839
+ type: 'finish',
840
+ reason: { kind: 'error', failure: Object.freeze({ code, message }) },
841
+ });
842
+
843
+ // Latency recording (#6): record successful llm/stream latency per ref.
844
+ // ponytail: only the true success path (finish-chunk). Failures are not recorded.
845
+ let _rotateStartMs = Date.now();
846
+ function recordLatency(pool) {
847
+ try {
848
+ const cfg = getConfig();
849
+ if (!cfg || cfg.latencyEnabled === false) return;
850
+ const ref = pool && pool.state && pool.state.lastUsed;
851
+ if (!ref) return;
852
+ const elapsed = Date.now() - _rotateStartMs;
853
+ if (!Number.isFinite(elapsed) || elapsed < 0) return;
854
+ latencyHistogram.record(ref, elapsed);
855
+ } catch (_) { /* ponytail: never crash */ }
856
+ }
857
+
858
+ // Retry one request on the next pool key when the current key fails with a
859
+ // switchable error before any content chunk. The provider never changes —
860
+ // the resolve patch hands out the next key on each dispatch.
861
+ function rotate(options, pool) {
862
+ return (async function* () {
863
+ const { switchCodes, cooldownMs, maxCooldownMs } = buildRuntime();
864
+ let lastFailure = null;
865
+ _rotateStartMs = Date.now();
866
+
867
+ const runtime0 = buildRuntime();
868
+ if (runtime0.concurrencyLimit > 0 && concurrencyTracker.isEnabled()) {
869
+ // #193: prefer least-loaded key within limit
870
+ const available = (pool.weightedRefs ?? pool.refs).filter((r) => {
871
+ const fu = pool.state.failedUntil.get(r) ?? 0;
872
+ if (fu > Date.now()) return false;
873
+ const exp = pool.expiresAt ? pool.expiresAt[r] : undefined;
874
+ if (exp !== undefined && Date.now() >= exp) return false;
875
+ return true;
876
+ });
877
+ const preferred = concurrencyTracker.pickLeastLoaded(available);
878
+ if (preferred && (pool.weightedRefs ?? pool.refs)[0] !== preferred) {
879
+ // Move preferred to front of the attempt list
880
+ const list = (pool.weightedRefs ?? pool.refs).slice();
881
+ const i = list.indexOf(preferred);
882
+ if (i > 0) { list.splice(i, 1); list.unshift(preferred); }
883
+ pool.weightedRefs = list;
884
+ }
885
+ }
886
+ for (let attempt = 0; attempt < (pool.weightedRefs ?? pool.refs).length; attempt++) {
887
+ let yielded = false;
888
+ let switching = false;
889
+ let inner;
890
+ try {
891
+ // mark the internal dispatch so the interceptor does not re-rotate
892
+ inner = ctx.llm.stream({ ...options, [MARKER]: true });
893
+ } catch (e) {
894
+ if (pool.state.lastUsed) { const _retry = parseRetryAfter(String(e?.message ?? '')); const _base = pool.cooldownMs ?? cooldownMs; const _max = pool.maxCooldownMs ?? maxCooldownMs; const _effBase = _retry !== undefined ? Math.max(_base, Math.min(_retry, _max ?? _base * 8)) : _base; const _b = recordFailure(pool, pool.state.lastUsed, Date.now(), _effBase, _max); pushEvent(pool, pool.state.lastUsed, e?.code ?? 'TRANSPORT', _b); const _code = String(e?.code ?? ''); if (_code === 'AUTH' || /auth/i.test(String(e?.message ?? ''))) { const _c = (pool.state.authFailCounts.get(pool.state.lastUsed) ?? 0) + 1; pool.state.authFailCounts.set(pool.state.lastUsed, _c); if (_c >= 3) { pool.state.brokenUntil.set(pool.state.lastUsed, Date.now() + 86400000*30); pool.state.failedUntil.set(pool.state.lastUsed, Date.now() + 86400000*30); } } else { pool.state.authFailCounts.delete(pool.state.lastUsed); } }
895
+ lastFailure = finishError(e?.code ?? 'TRANSPORT',
896
+ `dsh-key-rotation: dispatch failed: ${String(e?.message ?? e)}`);
897
+ console.warn(`[dsh-key-rotation] ${options.provider}: key ${String(pool.state.lastUsed ?? '?')} threw ${String(e?.code ?? e?.message ?? e)}`);
898
+ continue;
899
+ }
900
+
901
+ const _pickedRef = pool.state.lastUsed;
902
+ if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.acquire(_pickedRef);
903
+ try {
904
+ for await (const chunk of inner) {
905
+ // Only actual content deltas lock the stream (no more rotation).
906
+ // Structural/metadata chunks (block-start/end, usage) do not.
907
+ if (chunk && (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta' || chunk.type === 'tool-call-delta')) {
908
+ yielded = true;
909
+ yield chunk;
910
+ continue;
911
+ }
912
+ if (chunk && chunk.type === 'finish') {
913
+ const kind = chunk.reason?.kind;
914
+ const failure = chunk.reason?.failure;
915
+ const code = failure?.code;
916
+ const message = failure?.message ?? '';
917
+ const effectiveSwitchCodes = pool.switchCodes ?? switchCodes;
918
+ const switchable = !yielded && kind === 'error' &&
919
+ (effectiveSwitchCodes.has(code) || SWITCHABLE_MESSAGE_PATTERN.test(message));
920
+ if (switchable) {
921
+ if (pool.state.lastUsed) {
922
+ const _retry = parseRetryAfter(message);
923
+ const _base = pool.cooldownMs ?? cooldownMs;
924
+ const _max = pool.maxCooldownMs ?? maxCooldownMs;
925
+ const _effBase = _retry !== undefined ? Math.max(_base, Math.min(_retry, _max ?? _base * 8)) : _base;
926
+ const _b = recordFailure(pool, pool.state.lastUsed, Date.now(), _effBase, _max);
927
+ pushEvent(pool, pool.state.lastUsed, code ?? 'UNKNOWN', _b);
928
+ // authFailCounts/brokenUntil: lazy-init if state was created by an older plugin version
929
+ if (!pool.state.authFailCounts) pool.state.authFailCounts = new Map();
930
+ if (!pool.state.brokenUntil) pool.state.brokenUntil = new Map();
931
+ const _code2 = String(code ?? '');
932
+ if (_code2 === 'AUTH' || /auth/i.test(message)) {
933
+ const _c2 = (pool.state.authFailCounts.get(pool.state.lastUsed) ?? 0) + 1;
934
+ pool.state.authFailCounts.set(pool.state.lastUsed, _c2);
935
+ if (_c2 >= 3) {
936
+ pool.state.brokenUntil.set(pool.state.lastUsed, Date.now() + 86400000*30);
937
+ pool.state.failedUntil.set(pool.state.lastUsed, Date.now() + 86400000*30);
938
+ }
939
+ } else {
940
+ pool.state.authFailCounts.delete(pool.state.lastUsed);
941
+ }
942
+ }
943
+ pool.state.switches = (pool.state.switches ?? 0) + 1;
944
+ pool.state.lastReason = String(code ?? 'UNKNOWN');
945
+ pool.state.lastSwitchAt = Date.now();
946
+ lastFailure = chunk;
947
+ console.warn(`[dsh-key-rotation] ${options.provider}: key ${String(pool.state.lastUsed ?? '?')} failed (${String(code)} ${String(message).slice(0, 100)}) — next key`);
948
+ switching = true;
949
+ break;
950
+ }
951
+ // cost tracking if provider returns usage.cost
952
+ if (chunk.usage?.cost != null && pool.state.lastUsed) {
953
+ const c = Number(chunk.usage.cost);
954
+ if (!isNaN(c)) {
955
+ if (!pool.state.costPerKey) pool.state.costPerKey = new Map();
956
+ pool.state.costPerKey.set(pool.state.lastUsed, (pool.state.costPerKey.get(pool.state.lastUsed) ?? 0) + c);
957
+ // #208: cost per day per key (mirrors usageDays) for budget checks
958
+ if (!pool.state.costDays) pool.state.costDays = new Map();
959
+ const cday = new Date().toISOString().slice(0, 10);
960
+ const cMap = pool.state.costDays.get(pool.state.lastUsed) || new Map();
961
+ cMap.set(cday, (cMap.get(cday) ?? 0) + c);
962
+ pool.state.costDays.set(pool.state.lastUsed, cMap);
963
+ }
964
+ }
965
+ // Usage by day (#119)
966
+ if (pool.state.lastUsed) {
967
+ if (!pool.state.usageDays) pool.state.usageDays = new Map();
968
+ const day = new Date().toISOString().slice(0, 10);
969
+ const dayMap = pool.state.usageDays.get(pool.state.lastUsed) || new Map();
970
+ dayMap.set(day, (dayMap.get(day) ?? 0) + 1);
971
+ pool.state.usageDays.set(pool.state.lastUsed, dayMap);
972
+ }
973
+ // Per-model request detail (#121)
974
+ if (pool.state.lastUsed && options.model) {
975
+ if (!pool.state.byModel) pool.state.byModel = new Map();
976
+ let byRef = pool.state.byModel.get(pool.state.lastUsed);
977
+ if (!byRef) { byRef = new Map(); pool.state.byModel.set(pool.state.lastUsed, byRef); }
978
+ byRef.set(options.model, (byRef.get(options.model) ?? 0) + 1);
979
+ }
980
+ // Proactive rate-limit (#115): if response headers say this key is near
981
+ // its quota, cool it down so the NEXT request starts on a different key.
982
+ // We do NOT re-run this (already successful) request — that would double-send.
983
+ const rate = extractRateLimit(chunk?.metadata?.headers ?? chunk?.headers);
984
+ if (rate && pool.state.lastUsed) {
985
+ const { rateLimitThreshold } = buildRuntime();
986
+ if (isRateLimited(rate, rateLimitThreshold ?? 0.1)) {
987
+ const cool = rate.reset && rate.reset > Date.now() ? (rate.reset - Date.now()) : pool.cooldownMs;
988
+ recordFailure(pool, pool.state.lastUsed, Date.now(), cool, pool.maxCooldownMs);
989
+ pushEvent(pool, pool.state.lastUsed, 'RATE_LIMIT', cool);
990
+ console.warn(`[dsh-key-rotation] ${options.provider}: key ${pool.state.lastUsed} near quota (remaining ${String(rate.remaining)}/${String(rate.limit)}) — next request will rotate`);
991
+ }
992
+ }
993
+ // #7: persist quota snapshot regardless of threshold (so dashboard widget can show it).
994
+ if (rate && pool.state.lastUsed && Number.isFinite(rate.remaining)) {
995
+ quotaStore.set(pool.state.lastUsed, { remaining: rate.remaining, limit: rate.limit, reset: rate.reset, at: Date.now() });
996
+ }
997
+ yield chunk;
998
+ recordLatency(pool);
999
+ return;
1000
+ }
1001
+ yield chunk;
1002
+ }
1003
+ } catch (e) {
1004
+ if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.release(_pickedRef);
1005
+ yield finishError(e?.code ?? 'TRANSPORT', String(e?.message ?? e));
1006
+ return;
1007
+ }
1008
+
1009
+ if (_pickedRef && runtime0.concurrencyLimit > 0) concurrencyTracker.release(_pickedRef);
1010
+ if (switching) continue; // try the next key
1011
+ return; // clean end served
1012
+ }
1013
+
1014
+ // pool exhausted all keys cooling or missing
1015
+ pool.state.lastExhaustionAt = Date.now();
1016
+ pool.state.exhaustionCount = (pool.state.exhaustionCount ?? 0) + 1;
1017
+ console.warn(`[dsh-key-rotation] ${options.provider}: pool exhausted — all ${pool.refs.length} keys cooling`);
1018
+ // notify via extracted helper (see notifyExhaustion above)
1019
+ notifyExhaustion(buildRuntime(), pool, { provider: options.provider });
1020
+
1021
+ // #194: cross-provider cascade failover
1022
+ const runtime = buildRuntime();
1023
+ if (Array.isArray(runtime.cascade) && runtime.cascade.length > 0) {
1024
+ const pools = runtime.providerToPool;
1025
+ const fb = pickCascadeFallback(options.provider, runtime, pools);
1026
+ if (fb && fb.pool && fb.pool !== pool) {
1027
+ console.warn(`[dsh-key-rotation] ${options.provider}: pool exhausted — cascading to ${fb.provider}`);
1028
+ pool.state.lastReason = 'CASCADE';
1029
+ pool.state.lastSwitchAt = Date.now();
1030
+ // Re-dispatch on the fallback pool (depth-1 via marker check)
1031
+ const innerCascade = rotate({ ...options, provider: fb.provider }, fb.pool);
1032
+ for await (const chunk of innerCascade) {
1033
+ yield chunk;
1034
+ }
1035
+ return;
1036
+ }
1037
+ }
1038
+
1039
+ yield lastFailure ?? finishError('TRANSPORT', 'dsh-key-rotation: all keys failed');
1040
+ })();
1041
+ }
1042
+
1043
+ // ── status route: what the settings card cannot know on its own ──
1044
+ //
1045
+ // Reports, per configured provider, which key is in use, which are cooling
1046
+ // down and until when, whether an env name resolves to a credential at all
1047
+ // (a typo is otherwise silent), and how often rotation has fired.
1048
+ //
1049
+ // Key VALUES never leave the host — only the boolean fact that one exists.
1050
+ ctx.effect(() => ctx.webServer.register({
1051
+ kind: 'exact',
1052
+ path: STATUS_PATH,
1053
+ handler: async (req, res) => {
1054
+ if (req.method !== 'GET') {
1055
+ json(res, 405, { error: { code: 'method', message: 'GET only' } });
1056
+ return;
1057
+ }
1058
+ if (!isTrustedBridgeRequest(req)) {
1059
+ json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: status is local-only' } });
1060
+ return;
1061
+ }
1062
+ const { poolByRef, providerTags, providerBudgets } = buildRuntime();
1063
+ const base = ctx.get('credentials');
1064
+ const now = Date.now();
1065
+ const seen = new Set();
1066
+ const providers = [];
1067
+ for (const pool of poolByRef.values()) {
1068
+ if (seen.has(pool.base)) continue;
1069
+ seen.add(pool.base);
1070
+ try {
1071
+ const keys = [];
1072
+ for (const ref of pool.refs) {
1073
+ let present = false;
1074
+ let tail = '';
1075
+ let source = null;
1076
+ let writable = true;
1077
+ try {
1078
+ // The resolve patch is installed on this same service, so ask for
1079
+ // the exact ref: a pool ref would otherwise round-robin to another
1080
+ // key and report a missing name as present.
1081
+ let hit = await (base?.__dshKeyRotationOriginalResolve ?? base?.resolve)?.call(base, ref);
1082
+ present = Boolean(hit && typeof hit.value === 'string' && hit.value.length > 0);
1083
+ if (present) tail = keyTail(hit.value);
1084
+ // fallback: env var bootstrapping (issue #7)
1085
+ if (!present) {
1086
+ const ev = envValue(ref);
1087
+ if (ev !== undefined) { present = true; tail = keyTail(ev); source = 'env'; writable = false; }
1088
+ }
1089
+ } catch {
1090
+ present = false;
1091
+ }
1092
+ try {
1093
+ const described = await base?.describe?.(ref);
1094
+ source = described?.source ?? null;
1095
+ writable = described?.writable !== false;
1096
+ } catch {
1097
+ /* describe is optional — the card falls back to editable */
1098
+ }
1099
+ const until = pool.state.failedUntil.get(ref);
1100
+ keys.push({
1101
+ ref,
1102
+ present,
1103
+ tail,
1104
+ source,
1105
+ writable,
1106
+ active: pool.state.lastUsed === ref,
1107
+ cooldownMsLeft: until !== undefined && until > now ? until - now : 0,
1108
+ // #210: RPM capacity snapshot (null when rpmLimit is off)
1109
+ rpm: bucketInfo(pool.state.rpmWindows, ref, pool.rpmLimit, now),
1110
+ usage: pool.state.usageCounts?.get(ref) ?? 0,
1111
+ byModel: pool.state.byModel?.get(ref) ? Object.fromEntries(pool.state.byModel.get(ref)) : {},
1112
+ usageDays: pool.state.usageDays?.get(ref) ? Object.fromEntries(pool.state.usageDays.get(ref)) : {},
1113
+ cost: pool.state.costPerKey?.get(ref) ?? 0,
1114
+ lastUsedAt: pool.state.lastUsedAt?.get(ref) ?? null,
1115
+ expiresAt: pool.expiresAt?.[ref] ?? null,
1116
+ expired: pool.expiresAt?.[ref] !== undefined && now >= pool.expiresAt[ref],
1117
+ broken: pool.state.brokenUntil?.has(ref) ?? false,
1118
+ });
1119
+ }
1120
+ providers.push({
1121
+ provider: pool.base,
1122
+ keys,
1123
+ tags: providerTags.get(pool.base) ?? [],
1124
+ switches: pool.state.switches ?? 0,
1125
+ lastReason: pool.state.lastReason ?? null,
1126
+ lastSwitchAt: pool.state.lastSwitchAt ?? null,
1127
+ lastExhaustionAt: pool.state.lastExhaustionAt ?? null,
1128
+ exhaustionCount: pool.state.exhaustionCount ?? 0,
1129
+ totalUsage: [...(pool.state.usageCounts?.values() ?? [])].reduce((a, b) => a + b, 0),
1130
+ events: (pool.state.events ?? []).slice(-50),
1131
+ healthScore: computeHealthScore(pool.state),
1132
+ // #208: today/week spend + configured budget for the card
1133
+ todayCost: costForDay(pool.state.costDays),
1134
+ weeklyCost: costForWeek(pool.state.costDays, now),
1135
+ budgetDaily: providerBudgets.get(pool.base)?.costBudgetDaily ?? 0,
1136
+ budgetWeekly: providerBudgets.get(pool.base)?.costBudgetWeekly ?? 0,
1137
+ pauseOnBudget: providerBudgets.get(pool.base)?.pauseOnBudget ?? false,
1138
+ });
1139
+ } catch (e) {
1140
+ console.warn(`[dsh-key-rotation] status: pool ${pool.base} failed: ${String(e?.message ?? e)} ${e?.stack ?? ''}`);
1141
+ providers.push({ provider: pool.base, keys: [], statusError: String(e?.message ?? e) });
1142
+ }
1143
+ }
1144
+ json(res, 200, { providers });
1145
+ },
1146
+ }), 'dsh-key-rotation: status route');
1147
+
1148
+ // #209: usage report - per-key requests/cost over the last N days.
1149
+ // ?format=csv returns text/csv; ?days=N window (1..90, default 7).
1150
+ ctx.effect(() => ctx.webServer.register({
1151
+ kind: 'exact',
1152
+ path: USAGE_PATH,
1153
+ handler: (req, res) => {
1154
+ if (req.method !== 'GET') { json(res, 405, { error: { code: 'method', message: 'GET only' } }); return; }
1155
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: usage is local-only' } }); return; }
1156
+ const url = new URL(req.url ?? USAGE_PATH, 'http://localhost');
1157
+ const days = Math.min(90, Math.max(1, Number(url.searchParams.get('days')) || 7));
1158
+ const csv = url.searchParams.get('format') === 'csv';
1159
+ const provider = url.searchParams.get('provider') ?? '';
1160
+ const runtime = buildRuntime();
1161
+ const now = Date.now();
1162
+ const seen = new Set();
1163
+ const report = [];
1164
+ for (const pool of runtime.poolByRef.values()) {
1165
+ if (seen.has(pool.base)) continue;
1166
+ seen.add(pool.base);
1167
+ if (provider && pool.base !== provider) continue;
1168
+ report.push({ provider: pool.base, rows: usageRows(pool, days, now) });
1169
+ }
1170
+ if (csv) {
1171
+ res.writeHead(200, { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': 'attachment; filename="dsh-key-rotation-usage.csv"' });
1172
+ const parts = [];
1173
+ for (const p of report) {
1174
+ if (parts.length > 0) parts.push('');
1175
+ parts.push('# ' + p.provider);
1176
+ parts.push(usageCsv(p.rows));
1177
+ }
1178
+ res.end(parts.join('\n') + '\n');
1179
+ return;
1180
+ }
1181
+ json(res, 200, { at: now, days, providers: report });
1182
+ },
1183
+ }), 'dsh-key-rotation: usage route');
1184
+
1185
+ // ── key route: store a key value without leaving the rotation card ──
1186
+ //
1187
+ // Adding a key used to mean two screens: create the credential elsewhere,
1188
+ // then type its env name here. The value is write-only from the browser —
1189
+ // it is never sent back, only its last few characters are (see the status
1190
+ // route) and the route is loopback- and same-origin-gated like the config
1191
+ // bridge next to it.
1192
+ ctx.effect(() => ctx.webServer.register({
1193
+ kind: 'exact',
1194
+ path: KEY_PATH,
1195
+ handler: async (req, res) => {
1196
+ if (req.method !== 'PUT' && req.method !== 'DELETE') {
1197
+ json(res, 405, { error: { code: 'method', message: 'PUT or DELETE only' } });
1198
+ return;
1199
+ }
1200
+ if (!isTrustedBridgeRequest(req)) {
1201
+ json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: keys are local-only' } });
1202
+ return;
1203
+ }
1204
+ const credentialsService = ctx.get('credentials');
1205
+ if (!credentialsService || typeof credentialsService.set !== 'function') {
1206
+ json(res, 503, { error: { code: 'no-credentials', message: 'dsh-key-rotation: no credentials service is mounted' } });
1207
+ return;
1208
+ }
1209
+ let body;
1210
+ try {
1211
+ body = await readJson(req);
1212
+ } catch (error) {
1213
+ json(res, 400, { error: { code: 'bad-request', message: String(error?.message ?? error) } });
1214
+ return;
1215
+ }
1216
+ const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1217
+ if (!isValidRef(ref)) {
1218
+ json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } });
1219
+ return;
1220
+ }
1221
+ try {
1222
+ if (req.method === 'DELETE') {
1223
+ await credentialsService.unset(ref);
1224
+ json(res, 200, { ok: true, ref });
1225
+ return;
1226
+ }
1227
+ const value = typeof body?.value === 'string' ? body.value.trim() : '';
1228
+ if (value.length === 0) {
1229
+ json(res, 400, { error: { code: 'empty-value', message: 'dsh-key-rotation: an empty key cannot be stored' } });
1230
+ return;
1231
+ }
1232
+ await credentialsService.set(ref, value);
1233
+ // #200: leak-detector hint - stored value should look like a credential
1234
+ const secretShape = looksLikeApiSecret(value);
1235
+ json(res, 200, { ok: true, ref, tail: keyTail(value), looksLikeSecret: secretShape });
1236
+ } catch (error) {
1237
+ // A ref supplied by the launching environment is read-only, and the
1238
+ // service says so in plain words — pass that through to the card.
1239
+ json(res, 409, { error: { code: 'write-rejected', message: String(error?.message ?? error) } });
1240
+ }
1241
+ },
1242
+ }), 'dsh-key-rotation: key route');
1243
+
1244
+ // ── reset route: clear cooldown for a provider (or a single ref) ──
1245
+ ctx.effect(() => ctx.webServer.register({
1246
+ kind: 'exact',
1247
+ path: RESET_PATH,
1248
+ handler: async (req, res) => {
1249
+ if (req.method !== 'POST') {
1250
+ json(res, 405, { error: { code: 'method', message: 'POST only' } });
1251
+ return;
1252
+ }
1253
+ if (!isTrustedBridgeRequest(req)) {
1254
+ json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: reset is local-only' } });
1255
+ return;
1256
+ }
1257
+ let body;
1258
+ try { body = await readJson(req); } catch (e) {
1259
+ json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } });
1260
+ return;
1261
+ }
1262
+ const provider = typeof body?.provider === 'string' ? body.provider.trim() : '';
1263
+ const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1264
+ if (provider) {
1265
+ const st = poolState.get(provider);
1266
+ if (!st) { json(res, 404, { error: { code: 'not-found', message: `dsh-key-rotation: no pool for '${provider}'` } }); return; }
1267
+ const cleared = st.failedUntil.size;
1268
+ st.failedUntil.clear();
1269
+ st.failCounts?.clear();
1270
+ st.authFailCounts?.clear();
1271
+ st.brokenUntil?.clear();
1272
+ st.switches = 0; st.lastReason = undefined; st.lastSwitchAt = undefined;
1273
+ json(res, 200, { ok: true, provider, cleared });
1274
+ return;
1275
+ }
1276
+ if (ref) {
1277
+ let found = false;
1278
+ for (const st of poolState.values()) {
1279
+ if (st.failedUntil.has(ref) || st.failCounts?.has(ref)) {
1280
+ st.failedUntil.delete(ref);
1281
+ st.failCounts?.delete(ref);
1282
+ st.authFailCounts?.delete(ref);
1283
+ st.brokenUntil?.delete(ref);
1284
+ if (st.lastUsed === ref) st.lastUsed = undefined;
1285
+ found = true; break;
1286
+ }
1287
+ }
1288
+ // idempotent: even if ref was not cooling, report ok if it looks like a valid ref name
1289
+ if (!found && !isValidRef(ref)) { json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } }); return; }
1290
+ json(res, 200, { ok: true, ref });
1291
+ return;
1292
+ }
1293
+ json(res, 400, { error: { code: 'bad-request', message: 'dsh-key-rotation: POST requires {"provider": "..."} or {"ref": "..."}' } });
1294
+ },
1295
+ }), 'dsh-key-rotation: reset route');
1296
+
1297
+ ctx.effect(() => ctx.webServer.register({
1298
+ kind: 'exact',
1299
+ path: IMPORT_PATH,
1300
+ handler: async (req, res) => {
1301
+ if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1302
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: import is local-only' } }); return; }
1303
+ let body; try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1304
+ const url = typeof body?.url === 'string' ? body.url.trim() : '';
1305
+ if (!url || !url.startsWith('https://')) { json(res, 400, { error: { code: 'bad-url', message: 'dsh-key-rotation: only HTTPS URLs are allowed' } }); return; }
1306
+ try {
1307
+ const resp = await fetch(url);
1308
+ if (!resp.ok) { json(res, 400, { error: { code: 'fetch-failed', message: 'dsh-key-rotation: fetch returned ' + resp.status } }); return; }
1309
+ const data = await resp.json();
1310
+ if (!Array.isArray(data)) { json(res, 400, { error: { code: 'bad-format', message: 'dsh-key-rotation: expected JSON array of providers' } }); return; }
1311
+ const settings = ctx.get('settings');
1312
+ if (!settings) { json(res, 503, { error: { code: 'settings-rejected', message: 'dsh-key-rotation: no settings provider' } }); return; }
1313
+ const desc = settings.describe({ redactSecrets: true }).find((c) => c.ns === NS);
1314
+ const cur = desc?.value?.providers ?? [];
1315
+ const merged = new Map();
1316
+ for (const p of cur) if (p && p.provider) merged.set(p.provider, p);
1317
+ for (const p of data) if (p && p.provider && typeof p.provider === 'string') merged.set(p.provider, p);
1318
+ const mergedArr = [...merged.values()];
1319
+ await settings.replace(NS, { ...(desc?.value ?? {}), providers: mergedArr }, desc?.revision);
1320
+ json(res, 200, { ok: true, providersImported: data.length, total: mergedArr.length });
1321
+ } catch (e) { json(res, 400, { error: { code: 'import-failed', message: String(e?.message ?? e) } }); }
1322
+ },
1323
+ }), 'dsh-key-rotation: import route');
1324
+
1325
+ // Health for external panels (Beszel/Uptime)
1326
+ ctx.effect(() => ctx.webServer.register({
1327
+ kind: 'exact',
1328
+ path: HEALTH_PATH,
1329
+ handler: async (req, res) => {
1330
+ if (!isTrustedBridgeRequest(req) && req.socket?.remoteAddress !== '127.0.0.1' && req.socket?.remoteAddress !== '::1') { } // allow same-origin already checked
1331
+ if (!isTrustedBridgeRequest(req)) {
1332
+ // also allow plain loopback without Origin
1333
+ if (!isLoopbackAddress(req.socket?.remoteAddress)) { res.writeHead(403); res.end(); return; }
1334
+ if (req.headers['sec-fetch-site'] === 'cross-site') { res.writeHead(403); res.end(); return; }
1335
+ }
1336
+ if (req.method !== 'GET') { json(res, 405, { error: { code: 'method', message: 'GET only' } }); return; }
1337
+ const now = Date.now();
1338
+ const pools = {};
1339
+ let exhaustedAny = false;
1340
+ const { poolByRef: pr, providerTags } = buildRuntime();
1341
+ const seenH = new Set();
1342
+ for (const pool of pr.values()) {
1343
+ if (seenH.has(pool.base)) continue;
1344
+ seenH.add(pool.base);
1345
+ let healthy = 0;
1346
+ for (const ref of pool.refs) {
1347
+ const until = pool.state.failedUntil.get(ref);
1348
+ if (until !== undefined && until > now) continue;
1349
+ const exp = pool.expiresAt?.[ref];
1350
+ if (exp !== undefined && now >= exp) continue;
1351
+ healthy++;
1352
+ }
1353
+ const total = pool.refs.length;
1354
+ const exhausted = healthy === 0 && total > 0;
1355
+ if (exhausted) exhaustedAny = true;
1356
+ pools[pool.base] = { healthy, total, exhausted, healthScore: computeHealthScore(pool.state) };
1357
+ }
1358
+ json(res, 200, { status: exhaustedAny ? 'degraded' : 'ok', pools, exhaustedAny, latency: latencyHistogram.snapshotAll(), quota: quotaStore.snapshot() });
1359
+ },
1360
+ }), 'dsh-key-rotation: health');
1361
+
1362
+ // ── test route: dry-run a single key without rotation ──
1363
+ ctx.effect(() => ctx.webServer.register({
1364
+ kind: 'exact',
1365
+ path: TEST_PATH,
1366
+ handler: async (req, res) => {
1367
+ if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1368
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: test is local-only' } }); return; }
1369
+ let body; try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1370
+ const ref = typeof body?.ref === 'string' ? body.ref.trim() : '';
1371
+ if (!isValidRef(ref)) { json(res, 400, { error: { code: 'bad-ref', message: 'dsh-key-rotation: ref must be an environment variable name' } }); return; }
1372
+ // Optional value for pre-save validation (issue #118)
1373
+ const testValue = typeof body?.value === 'string' && body.value.length > 0 ? body.value : undefined;
1374
+ const probe = body?.probe === 'models' || body?.probe === 'chat' ? body.probe : undefined;
1375
+ const base = ctx.get('credentials');
1376
+ try {
1377
+ let hit = await (base?.__dshKeyRotationOriginalResolve ?? base?.resolve)?.call(base, ref);
1378
+ let present = Boolean(hit && typeof hit.value === 'string' && hit.value.length > 0);
1379
+ const effectiveValue = testValue || hit?.value;
1380
+ const valid = present ? Boolean(effectiveValue && typeof effectiveValue === 'string' && effectiveValue.length > 0) : Boolean(testValue);
1381
+ const tail = valid ? keyTail(effectiveValue) : '';
1382
+ let source = null;
1383
+ try { const d = await base?.describe?.(ref); source = d?.source ?? null; } catch {}
1384
+ if (!present && !testValue) { json(res, 200, { ok: false, ref, code: 'no-credential', message: 'no such credential' }); return; }
1385
+ if (!present && testValue) { source = 'pre-save'; }
1386
+ else if (!present) {
1387
+ const ev = envValue(ref);
1388
+ if (ev !== undefined) { present = true; json(res, 200, { ok: true, ref, tail: keyTail(ev), source: 'env' }); return; }
1389
+ }
1390
+ // sandbox probe (models is free; chat is hook-only, see sandbox.js)
1391
+ if (probe) {
1392
+ const keyForProbe = effectiveValue;
1393
+ const runner = ensureSandboxRunner(ctx);
1394
+ const result = probe === 'chat' ? await runner.probeChat(ref, keyForProbe) : await runner.probeModels(ref, keyForProbe);
1395
+ const cached = { ...result, at: Date.now() };
1396
+ lastTestCache.set(ref, cached);
1397
+ json(res, 200, { ok: cached.ok, ref, tail, source, probe, code: cached.code, latencyMs: cached.latencyMs, modelsCount: cached.modelsCount });
1398
+ return;
1399
+ }
1400
+ json(res, 200, { ok: true, ref, tail, source });
1401
+ } catch (e) {
1402
+ json(res, 200, { ok: false, ref, code: 'error', message: String(e?.message ?? e) });
1403
+ }
1404
+ },
1405
+ }), 'dsh-key-rotation: test route');
1406
+
1407
+ // Intercept the llm/stream waterfall: rotate any request whose provider maps
1408
+ // to a configured key pool; pass everything else (and internal dispatches)
1409
+ // straight through.
1410
+ // Read-only cache snapshot for clients (badge polling).
1411
+ ctx.effect(() => ctx.webServer.register({
1412
+ kind: 'exact',
1413
+ path: SANDBOX_CACHE_PATH,
1414
+ handler: (req, res) => {
1415
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: cache is local-only' } }); return; }
1416
+ json(res, 200, lastTestCache.snapshot());
1417
+ },
1418
+ }), 'dsh-key-rotation: sandbox cache');
1419
+
1420
+ // Auto-incident reset (#8).
1421
+ ctx.effect(() => ctx.webServer.register({
1422
+ kind: 'exact',
1423
+ path: INCIDENT_RESET_PATH,
1424
+ handler: (req, res) => {
1425
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: incident-reset is local-only' } }); return; }
1426
+ if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1427
+ readJson(req).then((body) => {
1428
+ const provider = typeof body?.provider === 'string' ? body.provider : '';
1429
+ if (provider) incidentReporter.resetCooldown(provider);
1430
+ else incidentReporter.resetCooldown();
1431
+ json(res, 200, { ok: true, reset: provider || 'all' });
1432
+ }).catch((e) => json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }));
1433
+ },
1434
+ }), 'dsh-key-rotation: incident-reset');
1435
+
1436
+ // #198: 1-click Health Matrix — parallel probe of all configured keys.
1437
+ ctx.effect(() => ctx.webServer.register({
1438
+ kind: 'exact',
1439
+ path: TEST_MATRIX_PATH,
1440
+ handler: async (req, res) => {
1441
+ if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1442
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: matrix is local-only' } }); return; }
1443
+ const cfg = getConfig();
1444
+ const runner = ensureSandboxRunner();
1445
+ if (!runner) { json(res, 500, { error: { code: 'no-runner', message: 'sandbox runner unavailable' } }); return; }
1446
+ const providers = Array.isArray(cfg?.providers) ? cfg.providers : [];
1447
+ const jobs = [];
1448
+ for (const p of providers) {
1449
+ for (const ref of (p.keys ?? [])) {
1450
+ if (typeof ref !== 'string' || !ref) continue;
1451
+ jobs.push((async () => {
1452
+ try {
1453
+ const probeResult = await runner.probeModels(ref, ref);
1454
+ return { provider: p.provider, ref, ok: probeResult.ok, code: probeResult.code, latencyMs: probeResult.latencyMs, modelsCount: probeResult.modelsCount ?? 0 };
1455
+ } catch (e) {
1456
+ return { provider: p.provider, ref, ok: false, code: 'error', latencyMs: 0, modelsCount: 0 };
1457
+ }
1458
+ })());
1459
+ }
1460
+ }
1461
+ const results = await Promise.all(jobs);
1462
+ json(res, 200, { at: Date.now(), total: results.length, ok: results.filter(r => r.ok).length, results });
1463
+ },
1464
+ }), 'dsh-key-rotation: test-matrix');
1465
+
1466
+ // Webhook test endpoint (#10): dry-run that validates webhookSender setup.
1467
+ ctx.effect(() => ctx.webServer.register({
1468
+ kind: 'exact',
1469
+ path: WEBHOOK_TEST_PATH,
1470
+ handler: (req, res) => {
1471
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: webhook-test is local-only' } }); return; }
1472
+ json(res, 200, { ok: true, snapshot: webhookSender.snapshot() });
1473
+ },
1474
+ }), 'dsh-key-rotation: webhook-test');
1475
+
1476
+ // #199 webhook-action: interactive webhook buttons call back here.
1477
+ // Auth: bearer token from Config (external services like Telegram/Discord
1478
+ // cannot be same-origin, so a shared secret is the gate).
1479
+ ctx.effect(() => ctx.webServer.register({
1480
+ kind: 'exact',
1481
+ path: '/dsh-key-rotation/webhook-action',
1482
+ handler: async (req, res) => {
1483
+ if (req.method !== 'POST') { json(res, 405, { error: { code: 'method', message: 'POST only' } }); return; }
1484
+ const runtime = buildRuntime();
1485
+ const expected = runtime.webhookActionToken;
1486
+ if (!expected) { json(res, 503, { error: { code: 'no-token', message: 'dsh-key-rotation: webhookActionToken is not configured' } }); return; }
1487
+ const auth = String(req.headers.authorization ?? '');
1488
+ if (auth !== `Bearer ${expected}`) { json(res, 401, { error: { code: 'unauthorized', message: 'dsh-key-rotation: bad webhook action token' } }); return; }
1489
+ let body;
1490
+ try { body = await readJson(req); } catch (e) { json(res, 400, { error: { code: 'bad-request', message: String(e?.message ?? e) } }); return; }
1491
+ // Accept callback payloads from formatInteractive (Telegram/Discord/Slack) or plain {action}
1492
+ let action = typeof body?.action === 'string' ? body.action : '';
1493
+ if (!action && typeof body?.data === 'string') {
1494
+ try { action = String(JSON.parse(body.data)?.id ?? ''); } catch { action = ''; }
1495
+ }
1496
+ if (!action && typeof body?.callback_data === 'string') {
1497
+ try { action = String(JSON.parse(body.callback_data)?.id ?? ''); } catch { action = ''; }
1498
+ }
1499
+ if (!action) { json(res, 400, { error: { code: 'bad-action', message: 'dsh-key-rotation: no action in payload' } }); return; }
1500
+ const provider = action.startsWith('pause-') || action.startsWith('reset-') ? action.replace(/^(pause|reset)-/, '') : '';
1501
+ try {
1502
+ if (action === 'disable-rotation') {
1503
+ rotationDisabled = true;
1504
+ console.warn('[dsh-key-rotation] rotation DISABLED via webhook action');
1505
+ json(res, 200, { ok: true, action });
1506
+ return;
1507
+ }
1508
+ if (action === 'enable-rotation') {
1509
+ rotationDisabled = false;
1510
+ json(res, 200, { ok: true, action });
1511
+ return;
1512
+ }
1513
+ if (action.startsWith('pause-') || action.startsWith('reset-')) {
1514
+ const st = poolState.get(provider);
1515
+ if (!st) { json(res, 404, { error: { code: 'not-found', message: `dsh-key-rotation: no pool for '${provider}'` } }); return; }
1516
+ if (action.startsWith('pause-')) {
1517
+ const until = Date.now() + 3600000; // 1h pause
1518
+ for (const ref of (st.failedUntil ? [...st.failedUntil.keys()] : [])) st.failedUntil.set(ref, Math.max(st.failedUntil.get(ref) ?? 0, until));
1519
+ // also pause every key currently healthy
1520
+ for (const p of buildRuntime().poolByRef.values()) {
1521
+ if (p.base !== provider) continue;
1522
+ for (const ref of p.refs) st.failedUntil.set(ref, Math.max(st.failedUntil.get(ref) ?? 0, until));
1523
+ }
1524
+ console.warn(`[dsh-key-rotation] pool ${provider} PAUSED 1h via webhook action`);
1525
+ json(res, 200, { ok: true, action, provider, until: Date.now() + 3600000 });
1526
+ return;
1527
+ }
1528
+ const cleared = st.failedUntil.size;
1529
+ st.failedUntil.clear(); st.failCounts?.clear(); st.brokenUntil?.clear();
1530
+ console.warn(`[dsh-key-rotation] pool ${provider} RESET via webhook action`);
1531
+ json(res, 200, { ok: true, action, provider, cleared });
1532
+ return;
1533
+ }
1534
+ json(res, 400, { error: { code: 'unknown-action', message: `dsh-key-rotation: unknown action '${action}'` } });
1535
+ } catch (e) {
1536
+ json(res, 500, { error: { code: 'action-failed', message: String(e?.message ?? e) } });
1537
+ }
1538
+ },
1539
+ }), 'dsh-key-rotation: webhook-action');
1540
+
1541
+ // Shadow A/B sampling snapshot (#9).
1542
+ ctx.effect(() => ctx.webServer.register({
1543
+ kind: 'exact',
1544
+ path: SHADOW_PATH,
1545
+ handler: (req, res) => {
1546
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: shadow is local-only' } }); return; }
1547
+ json(res, 200, shadowRouter.snapshot());
1548
+ },
1549
+ }), 'dsh-key-rotation: shadow');
1550
+
1551
+ // Region tags + failover chain (#4).
1552
+ ctx.effect(() => ctx.webServer.register({
1553
+ kind: 'exact',
1554
+ path: REGIONS_PATH,
1555
+ handler: (req, res) => {
1556
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: regions is local-only' } }); return; }
1557
+ const body = regionMap.snapshot();
1558
+ // Add pickFallback hints per provider for inspection.
1559
+ const out = {};
1560
+ for (const p of Object.keys(body)) out[p] = { region: body[p], fallback: regionMap.pickFallback(p) };
1561
+ json(res, 200, out);
1562
+ },
1563
+ }), 'dsh-key-rotation: regions');
1564
+
1565
+ // Per-agent rate budget snapshot (#3).
1566
+ ctx.effect(() => ctx.webServer.register({
1567
+ kind: 'exact',
1568
+ path: AGENT_BUDGET_PATH,
1569
+ handler: (req, res) => {
1570
+ if (!isTrustedBridgeRequest(req)) { json(res, 403, { error: { code: 'forbidden', message: 'dsh-key-rotation: agent-budget is local-only' } }); return; }
1571
+ json(res, 200, { enabled: agentBudget.isEnabled(), agents: agentBudget.snapshot() });
1572
+ },
1573
+ }), 'dsh-key-rotation: agent-budget');
1574
+
1575
+ ctx.on('llm/stream', (options, next) => {
1576
+ if (options[MARKER]) return next();
1577
+ if (rotationDisabled) return next(); // #199: disabled via webhook action
1578
+ const { providerToPool, modelPoolByProvider } = buildRuntime();
1579
+ // #195: exact model pool -> longest model-family prefix -> provider pool
1580
+ const pool = selectPool(modelPoolByProvider, providerToPool, options.provider, options.model);
1581
+ if (!pool) return next();
1582
+ console.warn(`[dsh-key-rotation] rotating ${options.provider}/${options.model} across ${(pool.weightedRefs ?? pool.refs).length} slots (${pool.refs.length} keys)`);
1583
+ return rotate(options, pool);
1584
+ });
1585
+
1586
+ // Safety net for non-stream requests (agent/request-error waterfall).
1587
+ // llm/stream covers streaming calls; sync calls (embeddings, batch) go
1588
+ // through agent/request and surface errors here. If the error is
1589
+ // switchable, mark the key and ask the agent loop to retry.
1590
+ ctx.on('agent/request-error', async (payload, next) => {
1591
+ const provider = payload?.provider ?? payload?.failure?.provider ?? '';
1592
+ if (!provider) return next();
1593
+ const { providerToPool, modelPoolByProvider, switchCodes } = buildRuntime();
1594
+ const model = payload?.model || payload?.failure?.model || '';
1595
+ // #195: same tier-aware selection as llm/stream
1596
+ const pool = selectPool(modelPoolByProvider, providerToPool, provider, model);
1597
+ if (!pool) return next();
1598
+ const code = String(payload?.failure?.code ?? payload?.code ?? '');
1599
+ const message = String(payload?.failure?.message ?? payload?.message ?? '');
1600
+ const effectiveSwitchCodes = pool.switchCodes ?? switchCodes;
1601
+ const switchable = effectiveSwitchCodes.has(code) || SWITCHABLE_MESSAGE_PATTERN.test(message);
1602
+ if (!switchable) return next();
1603
+ const ref = pool.state.lastUsed;
1604
+ if (ref) {
1605
+ const backoff = recordFailure(pool, ref, Date.now(), pool.cooldownMs ?? 60000);
1606
+ pushEvent(pool, ref, code || 'UNKNOWN', backoff);
1607
+ pool.state.switches = (pool.state.switches ?? 0) + 1;
1608
+ pool.state.lastReason = code || 'UNKNOWN';
1609
+ pool.state.lastSwitchAt = Date.now();
1610
+ console.warn(`[dsh-key-rotation] ${provider}: key ${String(ref)} failed via agent/request-error (${String(code)} ${String(message).slice(0, 80)}) — retry`);
1611
+ }
1612
+ return { kind: 'retry' };
1613
+ });
1614
+
1615
+ ctx.inject(['settings'], (sctx) => {
1616
+ const scope = sctx.settings.register(NS, Config, { base: config });
1617
+ getConfig = () => scope.get() ?? config;
1618
+ sctx.effect(() => () => {
1619
+ getConfig = () => config;
1620
+ });
1621
+ });
1622
+ }
1623
+
1624
+ // Notify on exhaustion: webhook + (optional) GitHub incident.
1625
+ // Extracted at module scope for testability. No I/O outside the injected hooks.
1626
+ // ponytail: thresholds and URLs are runtime-resolved per call, so changing Config is reflected immediately.
1627
+ export function notifyExhaustion(runtime, pool, options, hooks = { webhookSender, ensureIncidentReporter }) {
1628
+ if (!runtime || !pool) return;
1629
+ const count = pool.state ? (pool.state.exhaustionCount ?? 0) : 0;
1630
+ if (count <= 0) return;
1631
+ try {
1632
+ if (runtime.notifyWebhook && count >= (runtime.notifyThreshold ?? 0)) {
1633
+ // #199: interactive payload when an action token is configured - the
1634
+ // platform formatter (webhook.js) turns `actions` into buttons whose
1635
+ // callback carries the token back to /dsh-key-rotation/webhook-action.
1636
+ const token = runtime.webhookActionToken ?? '';
1637
+ const payload = {
1638
+ title: `Key pool exhausted: ${options.provider}`,
1639
+ text: `${count} exhaustion(s); keys: ${(pool.refs ?? []).join(', ')}`,
1640
+ provider: options.provider,
1641
+ exhaustionCount: count,
1642
+ at: pool.state.lastExhaustionAt,
1643
+ keys: pool.refs,
1644
+ actionToken: token || undefined,
1645
+ actions: token ? [
1646
+ { id: `reset-${options.provider}`, label: 'Reset cooldown' },
1647
+ { id: `pause-${options.provider}`, label: 'Pause 1h' },
1648
+ ] : undefined,
1649
+ };
1650
+ hooks.webhookSender.send(runtime.notifyWebhook, payload);
1651
+ }
1652
+ if (runtime.incidentThreshold && count >= runtime.incidentThreshold) {
1653
+ const reporter = hooks.ensureIncidentReporter();
1654
+ if (reporter) reporter.open(options.provider, pool.state.lastExhaustionAt);
1655
+ }
1656
+ } catch (_) { /* ponytail: never crash rotate() */ }
1657
+ }
1658
+