Spaces:
Paused
Paused
Merge pull request #208 from anurag008w/codex/fix-key-rotator-for-production-stability
Browse filesKey rotator: add key fingerprints (kid), improve event classification, sticky logic, and HTTP/Fetch patch robustness
- health-server.js +7 -1
- key-rotator-manager.html +14 -11
- multi-provider-key-rotator.cjs +140 -41
health-server.js
CHANGED
|
@@ -595,6 +595,12 @@ function maskApiKey(value) {
|
|
| 595 |
return key.length > 12 ? `${key.slice(0, 4)}...${key.slice(-6)}` : "***";
|
| 596 |
}
|
| 597 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 598 |
function modelProviderToRotatorProvider(model) {
|
| 599 |
const provider = String(model || "").split("/")[0].toLowerCase();
|
| 600 |
const aliases = {
|
|
@@ -716,7 +722,7 @@ function providerKeySummary() {
|
|
| 716 |
total: keys.length,
|
| 717 |
env: used.slice(0, 2).join(", "),
|
| 718 |
aliases: used.length > 2 ? `${used.length - 2} more envs` : "",
|
| 719 |
-
keys: keys.map((key, idx) => ({ slot: idx + 1, total: keys.length, key: maskApiKey(key) })),
|
| 720 |
};
|
| 721 |
}).filter((p) => p.total > 0);
|
| 722 |
}
|
|
|
|
| 595 |
return key.length > 12 ? `${key.slice(0, 4)}...${key.slice(-6)}` : "***";
|
| 596 |
}
|
| 597 |
|
| 598 |
+
function keyFingerprint(value) {
|
| 599 |
+
const key = String(value || "");
|
| 600 |
+
if (!key) return null;
|
| 601 |
+
return crypto.createHash("sha256").update(key).digest("hex").slice(0, 12);
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
function modelProviderToRotatorProvider(model) {
|
| 605 |
const provider = String(model || "").split("/")[0].toLowerCase();
|
| 606 |
const aliases = {
|
|
|
|
| 722 |
total: keys.length,
|
| 723 |
env: used.slice(0, 2).join(", "),
|
| 724 |
aliases: used.length > 2 ? `${used.length - 2} more envs` : "",
|
| 725 |
+
keys: keys.map((key, idx) => ({ slot: idx + 1, total: keys.length, key: maskApiKey(key), kid: keyFingerprint(key) })),
|
| 726 |
};
|
| 727 |
}).filter((p) => p.total > 0);
|
| 728 |
}
|
key-rotator-manager.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
| 6 |
<title>HuggingClaw · API Key Rotator</title>
|
| 7 |
<style>
|
| 8 |
-
:root{color-scheme:dark;--bg:#070711;--panel:#111120;--panel2:#17172a;--line:#292945;--text:#f8f7ff;--muted:#9892b8;--soft:#c7c2e6;--good:#22c55e;--warn:#f5c542;--bad:#fb7185;--blue:#60a5fa;--violet:#a78bfa}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:radial-gradient(circle at top left,#25145a 0,#070711 34%,#070711 100%);font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:var(--text);font-size:13px}main{width:min(1280px,calc(100% - 28px));margin:0 auto;padding:28px 0 44px}.top{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;margin-bottom:18px}.eyebrow{font-size:.7rem;letter-spacing:.18em;text-transform:uppercase;color:var(--muted);font-weight:900}h1{margin:6px 0 8px;font-size:clamp(1.6rem,4vw,2.7rem);line-height:1}.sub{color:var(--soft);max-width:860px;line-height:1.55}.actions{display:flex;gap:10px;flex-wrap:wrap}.btn{border:1px solid var(--line);background:rgba(255,255,255,.06);color:var(--text);border-radius:11px;padding:10px 14px;text-decoration:none;font-weight:850;cursor:pointer}.btn.primary{background:#fff;color:#050510}.btn:hover{filter:brightness(1.08)}.grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;margin:18px 0}.card{background:linear-gradient(180deg,rgba(255,255,255,.055),rgba(255,255,255,.025));border:1px solid var(--line);border-radius:18px;padding:16px;box-shadow:0 18px 45px rgba(0,0,0,.22)}.metric-title{color:var(--muted);text-transform:uppercase;letter-spacing:.16em;font-size:.66rem;font-weight:900}.metric-value{font-size:1.65rem;font-weight:950;margin-top:8px}.metric-detail{color:var(--muted);margin-top:6px;line-height:1.45}.ok{color:var(--good)}.warn{color:var(--warn)}.bad{color:var(--bad)}.blue{color:var(--blue)}.layout{display:grid;grid-template-columns:340px minmax(0,1fr);gap:14px}.panel-title{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:12px}.panel-title h2{font-size:1rem;margin:0}.pill{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:999px;padding:5px 9px;color:var(--soft);background:rgba(255,255,255,.035);font-size:.72rem;font-weight:850}.dot{width:7px;height:7px;border-radius:50%;background:var(--muted)}.dot.live{background:var(--good);box-shadow:0 0 15px var(--good)}.providers{display:flex;flex-direction:column;gap:9px}.provider{border:1px solid var(--line);border-radius:14px;background:rgba(0,0,0,.12);padding:12px;cursor:pointer}.provider.active{border-color:var(--blue);box-shadow:0 0 0 1px rgba(96,165,250,.25)}.provider-top{display:flex;justify-content:space-between;align-items:center;gap:12px}.provider-name{font-weight:950}.provider-meta{color:var(--muted);font-size:.78rem;margin-top:5px}.bar{height:8px;background:#22223a;border-radius:999px;overflow:hidden;margin-top:10px}.bar>span{display:block;height:100%;background:linear-gradient(90deg,var(--violet),var(--blue));border-radius:999px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px}.input{flex:1;min-width:180px;border:1px solid var(--line);background:#0c0c18;color:var(--text);border-radius:11px;padding:10px 12px;outline:none}.select{border:1px solid var(--line);background:#0c0c18;color:var(--text);border-radius:11px;padding:10px 12px}.toggle{display:flex;align-items:center;gap:7px;color:var(--soft);font-weight:800}.events{display:flex;flex-direction:column;gap:9px;max-height:620px;overflow:auto;padding-right:4px}.event{border:1px solid var(--line);border-left-width:4px;border-radius:14px;background:rgba(0,0,0,.16);padding:12px;display:grid;grid-template-columns:155px minmax(0,1fr) auto;gap:12px}.event.pick,.event.sticky_pick,.event.pick_retry_fresh,.event.model_detected,.event.request_started{border-left-color:var(--blue)}.event.success{border-left-color:var(--good)}.event.rate_limited,.event.auth_failed,.event.transport_aborted,.event.all_suspended_pick,.event.all_suspended_withheld,.event.client_error,.event.provider_error{border-left-color:var(--warn)}.event.network_retryable,.event.transient_status,.event.saturated_reuse,.event.sticky_saturated_reuse,.event.sticky_saturated_rotate{border-left-color:var(--bad)}.event.inflight_timeout,.event.inflight_lease_expired{border-left-color:var(--muted)}.time{color:var(--muted);font-variant-numeric:tabular-nums}.etype{font-weight:950}.msg{color:var(--soft);line-height:1.45;word-break:break-word}.key,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:#e9d5ff}.empty{padding:34px;text-align:center;color:var(--muted);border:1px dashed var(--line);border-radius:16px}.foot{color:var(--muted);margin-top:16px;line-height:1.55}.kbd{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;background:#23233a;border:1px solid #363653;border-radius:7px;padding:2px 6px;color:var(--text)}.detail-grid{display:grid;grid-template-columns:repeat(
|
| 9 |
</style>
|
| 10 |
</head>
|
| 11 |
<body>
|
|
@@ -58,27 +58,30 @@ const $=id=>document.getElementById(id), HTML_ESCAPE={'&':'&','<':'<','>'
|
|
| 58 |
const PICK_TYPES=['pick','sticky_pick','pick_retry_fresh','all_suspended_pick','saturated_reuse','sticky_saturated_reuse'];
|
| 59 |
const START_TYPES=['request_started'];
|
| 60 |
const STALE_PENDING_MS=35000;
|
| 61 |
-
const OUTCOME_TYPES=['success','rate_limited','network_retryable','auth_failed','transient_status','transport_aborted','client_error','provider_error'];
|
|
|
|
| 62 |
function esc(v){return String(v??'').replace(/[&<>"']/g,ch=>HTML_ESCAPE[ch]);}
|
| 63 |
function eventClass(v){return String(v||'event').replace(/[^a-z0-9_-]/gi,'_');}
|
| 64 |
function fmtTime(ts){const d=new Date(ts);return isNaN(d)?'—':d.toLocaleString();}
|
| 65 |
function isKeyEvent(e){return e.provider&&e.slot&&(e.key||e.type==='all_suspended_withheld');}
|
| 66 |
-
function
|
|
|
|
| 67 |
function eventText(e){const bits=[];if(e.provider)bits.push(e.provider);if(e.slot)bits.push(`#${e.slot}/${e.total}`);if(e.key)bits.push(e.key);if(e.model)bits.push(`model=${e.model}`);if(e.status)bits.push(`status=${e.status}`);if(e.errorStatus)bits.push(`error=${e.errorStatus}`);if(e.errorReason)bits.push(`reason=${e.errorReason}`);if(e.errorType)bits.push(`type=${e.errorType}`);if(e.source)bits.push(`source=${e.source}`);if(e.name)bits.push(`name=${e.name}`);if(e.waitMs)bits.push(`wait=${Math.round(e.waitMs/1000)}s`);if(e.code)bits.push(`code=${e.code}`);if(e.errorCode)bits.push(`errorCode=${e.errorCode}`);if(e.message)bits.push(`message=${e.message}`);if(e.requestId)bits.push(`req=${e.requestId}`);if(e.inflight)bits.push(`inflight=${e.inflight}/${e.maxInflight||'?'}`);return bits.join(' · ');}
|
| 68 |
-
function emptyStat(provider,slot,total,key){return{provider,slot,total,key,picks:0,pending:0,pendingIds:new Set(),success:0,rate:0,retry:0,auth:0,transient:0,abort:0,other:0,lease:0,last:'',lastPick:'',models:new Map()};}
|
| 69 |
-
function emptyScopedStat(){return{picks:0,pending:0,pendingIds:new Set(),success:0,rate:0,retry:0,auth:0,transient:0,abort:0,other:0,lease:0,last:'',lastPick:'',observed:false};}
|
| 70 |
function bumpPending(v,e){v.pending++;if(e.requestId)v.pendingIds.add(e.requestId);v.lastPick=e.ts||v.lastPick;v.last=e.ts||v.last;}
|
| 71 |
function closePending(v,e){if(e.requestId){if(!v.pendingIds.has(e.requestId))return false;v.pendingIds.delete(e.requestId);v.pending=Math.max(0,(v.pending||0)-1);return true;}if((v.pending||0)>0){v.pending--;return true;}return false;}
|
| 72 |
-
function bumpOutcome(v,type,isLease,ts){if(type==='success')v.success++;if(type==='rate_limited')v.rate++;if(type==='network_retryable')v.retry++;if(type==='auth_failed')v.auth++;if(type==='transport_aborted')v.abort++;if(type==='client_error'||type==='provider_error')v.other++;if(isLease)v.lease++;if(type==='transient_status')v.transient++;v.last=ts||v.last;}
|
| 73 |
function bumpPick(v,ts){v.picks++;v.lastPick=ts||v.lastPick;v.last=ts||v.last;}
|
| 74 |
-
function buildStats(){const stats=new Map(),events=state.events||[],hasRequestStarted=events.some(e=>START_TYPES.includes(e.type));for(const p of state.providers){for(const k of (p.keys||[]))
|
| 75 |
function ageStalePending(v,now){const pending=pendingCount(v);if(!pending)return;const ts=Date.parse(v.lastPick||v.last||'');if(Number.isFinite(ts)&&now-ts>STALE_PENDING_MS){v.stalePending=(v.stalePending||0)+pending;}}
|
| 76 |
-
function providerRows(provider,stats){return (provider?.keys||[]).map(k=>
|
|
|
|
| 77 |
function pendingCount(v){return Math.max(0,v.pending||0);}
|
| 78 |
-
function modelChips(row){const entries=[...row.models.entries()];const un=row.unscoped||{picks:0,success:0,rate:0,retry:0,auth:0,transient:0,abort:0,other:0,lease:0};const unPending=pendingCount(un);if(!entries.length){const total=row.picks+row.success+
|
| 79 |
function routeNote(provider){const routes=(state.runtime&&state.runtime.routes)||[],hits=routes.filter(r=>r.provider===provider.name);if(!routes.length)return '<div class="session-note">Current LLM route is unknown to this view. Usage appears only after OpenClaw sends a request to this provider hostname.</div>';if(hits.length)return `<div class="session-note"><b>Active route:</b> ${hits.map(r=>`${esc(r.role)} ${esc(r.model)}`).join(' · ')}. New messages using this route should create pick/success events below.</div>`;return `<div class="session-note bad"><b>Not on current model route.</b> Current route is ${routes.map(r=>`${esc(r.role)} ${esc(r.model)} → ${esc(r.provider)}`).join(' · ')}. ${esc(provider.name)} keys stay unused until you select a ${esc(provider.name)} model or a fallback reaches it.</div>`;}
|
| 80 |
-
function renderProviderDetails(provider,stats){if(!provider){$('detailTitle').textContent='Provider details';$('details').innerHTML='<div class="empty">Select a provider to see key/session usage.</div>';return;}const rows=providerRows(provider,stats),used=rows.filter(r=>r.picks||r.success).length,rates=rows.reduce((a,r)=>a+r.rate,0),retries=rows.reduce((a,r)=>a+r.retry+r.transient,0),auths=rows.reduce((a,r)=>a+r.auth,0),aborts=rows.reduce((a,r)=>a+(r.abort||0),0),pending=rows.reduce((a,r)=>a+pendingCount(r),0);$('detailTitle').textContent=`${provider.name} · provider session`;const modelSet=new Set();rows.forEach(r=>r.models.forEach((_,m)=>modelSet.add(m)));const table=rows.map(r=>{const usedKey=(r.picks||r.success)>0,pending=pendingCount(r),stale=r.stalePending||0;return `<tr><td><b class="mono">#${r.slot}/${r.total}</b><div class="key">${esc(r.key)}</div></td><td><span class="status ${usedKey?'used':'unused'}">${usedKey?'USED':'UNUSED'}</span><div class="metric-detail">last: ${esc(r.last?fmtTime(r.last):'never')}</div>${pending?`<div class="metric-detail warn">pending/no response observed: ${pending}${stale?` (stale ${stale})`:''}</div>`:''}</td><td>pick ${r.picks}<br>success ${r.success}<br>pending ${pending}<br>rate ${r.rate}</td><td>retry ${r.retry}<br>transient ${r.transient}<br>auth ${r.auth}<br>abort ${r.abort||0}<br>other ${r.other||0}<br>lease cleanup ${r.lease||0}</td><td>${modelChips(r)}</td></tr>`;}).join('');$('details').innerHTML=`${routeNote(provider)}<div class="session-note">Session: <b>${esc(provider.name)}</b>. Raw keys are never returned here; this page only shows masked keys and slot numbers from the configured pool.</div><div class="detail-grid"><div class="mini"><span class="metric-title">Total keys</span><b>${provider.total||0}</b></div><div class="mini"><span class="metric-title">Used / unused</span><b>${used}/${Math.max(0,(provider.total||0)-used)}</b></div><div class="mini"><span class="metric-title">Rate / pending</span><b>${rates}/${pending}</b></div><div class="mini"><span class="metric-title">Retry/auth/abort</span><b>${retries}/${auths}/${aborts}</b></div></div>${provider.name==='gemini'?`<p class="foot">Gemini quota is tracked per key + model. Models seen: ${modelSet.size?[...modelSet].map(m=>`<span class="model-chip">${esc(m)}</span>`).join(''):'<span class="kbd">none yet — new requests will show per-model once the rotator can read the request body</span>'}</p>`:''}<div class="key-table-wrap"><table class="key-table"><thead><tr><th>Hidden key slot</th><th>Status</th><th>Usage</th><th>Failures / aborts</th><th>Per-model / details</th></tr></thead><tbody>${table||'<tr><td colspan="5">No keys configured</td></tr>'}</tbody></table></div>`;}
|
| 81 |
-
function render(){const q=$('q').value.trim().toLowerCase(),type=$('type').value,providers=state.providers||[],events=state.events||[],stats=buildStats();if(!providers.some(p=>p.name===state.selected)&&providers[0])state.selected=providers[0].name;const totalKeys=providers.reduce((a,p)=>a+(Number(p.total)||0),0),usedKeyCount=
|
| 82 |
async function load(){if(state.paused)return;try{const r=await fetch('/api/key-rotator/logs?limit=1000',{cache:'no-store'});if(r.status===401){location.href='/login?next='+encodeURIComponent('/key-rotator');return;}const d=await r.json();state.events=d.events||[];state.providers=d.providers||[];state.runtime=d.runtime||{routes:[]};state.lastPayload=d;const log=d.log||{};$('source').textContent=log.exists?`${d.file||'event log'} · ${Math.round((log.size||0)/1024)} KiB`:`${d.file||'event log'} · waiting`;render();}catch(e){$('events').innerHTML='<div class="empty bad">Could not load rotator logs: '+esc(e.message)+'</div>';}}
|
| 83 |
$('q').addEventListener('input',render);$('type').addEventListener('change',render);$('scope').addEventListener('change',render);$('refresh').onclick=load;$('pause').onclick=()=>{state.paused=!state.paused;$('pause').textContent=state.paused?'Resume':'Pause';$('liveDot').classList.toggle('live',!state.paused);$('liveText').textContent=state.paused?'Paused':'Live';};$('export').onclick=()=>{const data=JSON.stringify(state.lastPayload||{providers:state.providers,events:state.events},null,2),blob=new Blob([data],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='huggingclaw-key-rotator.json';a.click();URL.revokeObjectURL(url);};load();setInterval(load,2500);
|
| 84 |
</script>
|
|
|
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
| 6 |
<title>HuggingClaw · API Key Rotator</title>
|
| 7 |
<style>
|
| 8 |
+
:root{color-scheme:dark;--bg:#070711;--panel:#111120;--panel2:#17172a;--line:#292945;--text:#f8f7ff;--muted:#9892b8;--soft:#c7c2e6;--good:#22c55e;--warn:#f5c542;--bad:#fb7185;--blue:#60a5fa;--violet:#a78bfa}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:radial-gradient(circle at top left,#25145a 0,#070711 34%,#070711 100%);font-family:Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:var(--text);font-size:13px}main{width:min(1280px,calc(100% - 28px));margin:0 auto;padding:28px 0 44px}.top{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;margin-bottom:18px}.eyebrow{font-size:.7rem;letter-spacing:.18em;text-transform:uppercase;color:var(--muted);font-weight:900}h1{margin:6px 0 8px;font-size:clamp(1.6rem,4vw,2.7rem);line-height:1}.sub{color:var(--soft);max-width:860px;line-height:1.55}.actions{display:flex;gap:10px;flex-wrap:wrap}.btn{border:1px solid var(--line);background:rgba(255,255,255,.06);color:var(--text);border-radius:11px;padding:10px 14px;text-decoration:none;font-weight:850;cursor:pointer}.btn.primary{background:#fff;color:#050510}.btn:hover{filter:brightness(1.08)}.grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;margin:18px 0}.card{background:linear-gradient(180deg,rgba(255,255,255,.055),rgba(255,255,255,.025));border:1px solid var(--line);border-radius:18px;padding:16px;box-shadow:0 18px 45px rgba(0,0,0,.22)}.metric-title{color:var(--muted);text-transform:uppercase;letter-spacing:.16em;font-size:.66rem;font-weight:900}.metric-value{font-size:1.65rem;font-weight:950;margin-top:8px}.metric-detail{color:var(--muted);margin-top:6px;line-height:1.45}.ok{color:var(--good)}.warn{color:var(--warn)}.bad{color:var(--bad)}.blue{color:var(--blue)}.layout{display:grid;grid-template-columns:340px minmax(0,1fr);gap:14px}.panel-title{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-bottom:12px}.panel-title h2{font-size:1rem;margin:0}.pill{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:999px;padding:5px 9px;color:var(--soft);background:rgba(255,255,255,.035);font-size:.72rem;font-weight:850}.dot{width:7px;height:7px;border-radius:50%;background:var(--muted)}.dot.live{background:var(--good);box-shadow:0 0 15px var(--good)}.providers{display:flex;flex-direction:column;gap:9px}.provider{border:1px solid var(--line);border-radius:14px;background:rgba(0,0,0,.12);padding:12px;cursor:pointer}.provider.active{border-color:var(--blue);box-shadow:0 0 0 1px rgba(96,165,250,.25)}.provider-top{display:flex;justify-content:space-between;align-items:center;gap:12px}.provider-name{font-weight:950}.provider-meta{color:var(--muted);font-size:.78rem;margin-top:5px}.bar{height:8px;background:#22223a;border-radius:999px;overflow:hidden;margin-top:10px}.bar>span{display:block;height:100%;background:linear-gradient(90deg,var(--violet),var(--blue));border-radius:999px}.toolbar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px}.input{flex:1;min-width:180px;border:1px solid var(--line);background:#0c0c18;color:var(--text);border-radius:11px;padding:10px 12px;outline:none}.select{border:1px solid var(--line);background:#0c0c18;color:var(--text);border-radius:11px;padding:10px 12px}.toggle{display:flex;align-items:center;gap:7px;color:var(--soft);font-weight:800}.events{display:flex;flex-direction:column;gap:9px;max-height:620px;overflow:auto;padding-right:4px}.event{border:1px solid var(--line);border-left-width:4px;border-radius:14px;background:rgba(0,0,0,.16);padding:12px;display:grid;grid-template-columns:155px minmax(0,1fr) auto;gap:12px}.event.pick,.event.sticky_pick,.event.pick_retry_fresh,.event.model_detected,.event.request_started{border-left-color:var(--blue)}.event.success{border-left-color:var(--good)}.event.rate_limited,.event.auth_failed,.event.transport_aborted,.event.transport_unknown,.event.all_suspended_pick,.event.all_suspended_withheld,.event.client_error,.event.provider_error{border-left-color:var(--warn)}.event.network_retryable,.event.transient_status,.event.saturated_reuse,.event.sticky_saturated_reuse,.event.sticky_saturated_rotate{border-left-color:var(--bad)}.event.inflight_timeout,.event.inflight_lease_expired{border-left-color:var(--muted)}.time{color:var(--muted);font-variant-numeric:tabular-nums}.etype{font-weight:950}.msg{color:var(--soft);line-height:1.45;word-break:break-word}.key,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:#e9d5ff}.empty{padding:34px;text-align:center;color:var(--muted);border:1px dashed var(--line);border-radius:16px}.foot{color:var(--muted);margin-top:16px;line-height:1.55}.kbd{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;background:#23233a;border:1px solid #363653;border-radius:7px;padding:2px 6px;color:var(--text)}.detail-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px;margin-bottom:12px}.mini{border:1px solid var(--line);border-radius:13px;padding:11px;background:rgba(0,0,0,.12)}.mini b{display:block;font-size:1.15rem;margin-top:4px}.key-table-wrap{overflow:auto}.key-table{width:100%;border-collapse:separate;border-spacing:0 8px;min-width:780px}.key-table th{color:var(--muted);font-size:.68rem;text-align:left;text-transform:uppercase;letter-spacing:.12em}.key-table td{background:rgba(0,0,0,.15);border-top:1px solid var(--line);border-bottom:1px solid var(--line);padding:10px;vertical-align:top}.key-table td:first-child{border-left:1px solid var(--line);border-radius:12px 0 0 12px}.key-table td:last-child{border-right:1px solid var(--line);border-radius:0 12px 12px 0}.status{font-weight:900}.status.used{color:var(--good)}.status.unused{color:var(--muted)}.model-chip{display:inline-flex;margin:2px 4px 2px 0;padding:4px 7px;border:1px solid var(--line);border-radius:999px;color:var(--soft);background:rgba(255,255,255,.035);font-size:.72rem}.section{margin-top:14px}.session-note{border:1px solid rgba(96,165,250,.28);background:rgba(96,165,250,.08);border-radius:14px;padding:12px;color:var(--soft);margin-bottom:12px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:1050px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.detail-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.layout{grid-template-columns:1fr}.top{flex-direction:column}.event{grid-template-columns:1fr}.events{max-height:none}}@media(max-width:620px){.grid,.detail-grid{grid-template-columns:1fr}}
|
| 9 |
</style>
|
| 10 |
</head>
|
| 11 |
<body>
|
|
|
|
| 58 |
const PICK_TYPES=['pick','sticky_pick','pick_retry_fresh','all_suspended_pick','saturated_reuse','sticky_saturated_reuse'];
|
| 59 |
const START_TYPES=['request_started'];
|
| 60 |
const STALE_PENDING_MS=35000;
|
| 61 |
+
const OUTCOME_TYPES=['success','rate_limited','network_retryable','auth_failed','transient_status','transport_aborted','transport_unknown','client_error','provider_error','inflight_lease_expired','inflight_timeout'];
|
| 62 |
+
const FAIL_TYPES=['rate_limited','network_retryable','auth_failed','transient_status','transport_unknown','client_error','provider_error'];
|
| 63 |
function esc(v){return String(v??'').replace(/[&<>"']/g,ch=>HTML_ESCAPE[ch]);}
|
| 64 |
function eventClass(v){return String(v||'event').replace(/[^a-z0-9_-]/gi,'_');}
|
| 65 |
function fmtTime(ts){const d=new Date(ts);return isNaN(d)?'—':d.toLocaleString();}
|
| 66 |
function isKeyEvent(e){return e.provider&&e.slot&&(e.key||e.type==='all_suspended_withheld');}
|
| 67 |
+
function keyIds(provider,slot,key,kid,includeSlot){const safeKey=key&&key!=='***'?key:'';const vals=[kid,safeKey,(includeSlot||!kid)&&slot?`slot:${slot}`:''].filter(Boolean);return [...new Set(vals.map(v=>`${provider}::${v}`))];}
|
| 68 |
+
function keyId(provider,slot,key,kid){return keyIds(provider,slot,key,kid)[0]||`${provider}::`;}
|
| 69 |
function eventText(e){const bits=[];if(e.provider)bits.push(e.provider);if(e.slot)bits.push(`#${e.slot}/${e.total}`);if(e.key)bits.push(e.key);if(e.model)bits.push(`model=${e.model}`);if(e.status)bits.push(`status=${e.status}`);if(e.errorStatus)bits.push(`error=${e.errorStatus}`);if(e.errorReason)bits.push(`reason=${e.errorReason}`);if(e.errorType)bits.push(`type=${e.errorType}`);if(e.source)bits.push(`source=${e.source}`);if(e.name)bits.push(`name=${e.name}`);if(e.waitMs)bits.push(`wait=${Math.round(e.waitMs/1000)}s`);if(e.code)bits.push(`code=${e.code}`);if(e.errorCode)bits.push(`errorCode=${e.errorCode}`);if(e.message)bits.push(`message=${e.message}`);if(e.requestId)bits.push(`req=${e.requestId}`);if(e.inflight)bits.push(`inflight=${e.inflight}/${e.maxInflight||'?'}`);return bits.join(' · ');}
|
| 70 |
+
function emptyStat(provider,slot,total,key){return{provider,slot,total,key,picks:0,pending:0,pendingIds:new Set(),success:0,fail:0,rate:0,retry:0,auth:0,transient:0,abort:0,other:0,lease:0,last:'',lastPick:'',models:new Map()};}
|
| 71 |
+
function emptyScopedStat(){return{picks:0,pending:0,pendingIds:new Set(),success:0,fail:0,rate:0,retry:0,auth:0,transient:0,abort:0,other:0,lease:0,last:'',lastPick:'',observed:false};}
|
| 72 |
function bumpPending(v,e){v.pending++;if(e.requestId)v.pendingIds.add(e.requestId);v.lastPick=e.ts||v.lastPick;v.last=e.ts||v.last;}
|
| 73 |
function closePending(v,e){if(e.requestId){if(!v.pendingIds.has(e.requestId))return false;v.pendingIds.delete(e.requestId);v.pending=Math.max(0,(v.pending||0)-1);return true;}if((v.pending||0)>0){v.pending--;return true;}return false;}
|
| 74 |
+
function bumpOutcome(v,type,isLease,ts){if(type==='success')v.success++;if(FAIL_TYPES.includes(type))v.fail++;if(type==='rate_limited')v.rate++;if(type==='network_retryable')v.retry++;if(type==='auth_failed')v.auth++;if(type==='transport_aborted')v.abort++;if(type==='transport_unknown'||type==='client_error'||type==='provider_error')v.other++;if(isLease)v.lease++;if(type==='transient_status')v.transient++;v.last=ts||v.last;}
|
| 75 |
function bumpPick(v,ts){v.picks++;v.lastPick=ts||v.lastPick;v.last=ts||v.last;}
|
| 76 |
+
function buildStats(){const stats=new Map(),events=state.events||[],hasRequestStarted=events.some(e=>START_TYPES.includes(e.type));for(const p of state.providers){for(const k of (p.keys||[])){const s=emptyStat(p.name,k.slot,k.total,k.key);for(const id of keyIds(p.name,k.slot,k.key,k.kid,true))if(!stats.has(id))stats.set(id,s);}}for(const e of events){if(!isKeyEvent(e))continue;const ids=keyIds(e.provider,e.slot,e.key,e.kid,false);let s=ids.map(id=>stats.get(id)).find(Boolean);if(!s)s=emptyStat(e.provider,e.slot,e.total,e.key||'***');for(const id of ids)if(!stats.has(id))stats.set(id,s);const isPick=PICK_TYPES.includes(e.type),isStart=START_TYPES.includes(e.type),isLegacyStart=!hasRequestStarted&&isPick;const isLease=e.type==='inflight_timeout'||e.type==='inflight_lease_expired',isOutcome=OUTCOME_TYPES.includes(e.type)||isLease;if(isPick)bumpPick(s,e.ts);if(isStart||isLegacyStart)bumpPending(s,e);if(!isPick&&!isStart)s.last=e.ts||s.last;if(e.model){let m=s.models.get(e.model);if(!m)m=emptyScopedStat();if(e.type==='model_detected')m.observed=true;if(isPick)bumpPick(m,e.ts);if(isStart||isLegacyStart)bumpPending(m,e);else if(isOutcome){closePending(m,e);bumpOutcome(m,e.type,isLease,e.ts);}else m.last=e.ts||m.last;s.models.set(e.model,m);if(isOutcome&&!isPick&&!isStart&&s.unscoped&&s.unscoped.pending>0){if(closePending(s.unscoped,e))bumpOutcome(s.unscoped,e.type,isLease,e.ts);}}else if(isPick||isStart||isLegacyStart||isOutcome){s.unscoped=s.unscoped||emptyScopedStat();if(isPick)bumpPick(s.unscoped,e.ts);if(isStart||isLegacyStart)bumpPending(s.unscoped,e);else if(isOutcome){closePending(s.unscoped,e);bumpOutcome(s.unscoped,e.type,isLease,e.ts);}}if(isOutcome&&!isPick&&!isStart)closePending(s,e);if(isOutcome)bumpOutcome(s,e.type,isLease,e.ts);}const now=Date.now();for(const s of uniqueStats(stats)){ageStalePending(s,now);for(const m of s.models.values())ageStalePending(m,now);if(s.unscoped)ageStalePending(s.unscoped,now);}return stats;}
|
| 77 |
function ageStalePending(v,now){const pending=pendingCount(v);if(!pending)return;const ts=Date.parse(v.lastPick||v.last||'');if(Number.isFinite(ts)&&now-ts>STALE_PENDING_MS){v.stalePending=(v.stalePending||0)+pending;}}
|
| 78 |
+
function providerRows(provider,stats){return (provider?.keys||[]).map(k=>keyIds(provider.name,k.slot,k.key,k.kid,true).map(id=>stats.get(id)).find(Boolean)||emptyStat(provider.name,k.slot,k.total,k.key));}
|
| 79 |
+
function uniqueStats(stats){return [...new Set(stats.values())];}
|
| 80 |
function pendingCount(v){return Math.max(0,v.pending||0);}
|
| 81 |
+
function modelChips(row){const entries=[...row.models.entries()];const un=row.unscoped||{picks:0,success:0,fail:0,rate:0,retry:0,auth:0,transient:0,abort:0,other:0,lease:0};const unPending=pendingCount(un);if(!entries.length){const total=row.picks+row.success+(row.fail||0)+(row.abort||0)+(row.lease||0);return total?`<span class="model-chip">unscoped · p:${row.picks} ok:${row.success} fail:${row.fail||0} pending:${pendingCount(row)} rl:${row.rate} retry:${row.retry+row.transient}${row.abort?` abort:${row.abort}`:''}${row.other?` other:${row.other}`:''}${row.lease?` lease:${row.lease}`:''}</span>`:'<span class="model-chip">no model events yet</span>';}const chips=entries.map(([m,v])=>{const onlyObserved=v.observed&&!v.picks&&!v.success&&!(v.fail||0)&&!v.rate&&!v.retry&&!v.transient&&!v.auth&&!v.abort&&!v.other&&!v.lease;return `<span class="model-chip">${esc(m)} · ${onlyObserved?'observed':`p:${v.picks} ok:${v.success} fail:${v.fail||0} pending:${pendingCount(v)} rl:${v.rate} retry:${v.retry+v.transient}${v.abort?` abort:${v.abort}`:''}${v.other?` other:${v.other}`:''}${v.lease?` lease:${v.lease}`:''}`}</span>`;});if(un.picks||un.success||(un.fail||0)||un.rate||un.retry||un.transient||un.auth||un.abort||un.other||un.lease)chips.push(`<span class="model-chip">unscoped totals · p:${un.picks} ok:${un.success} fail:${un.fail||0} pending:${unPending} rl:${un.rate} retry:${un.retry+un.transient}${un.abort?` abort:${un.abort}`:''}${un.other?` other:${un.other}`:''}${un.lease?` lease:${un.lease}`:''}</span>`);return chips.join('');}
|
| 82 |
function routeNote(provider){const routes=(state.runtime&&state.runtime.routes)||[],hits=routes.filter(r=>r.provider===provider.name);if(!routes.length)return '<div class="session-note">Current LLM route is unknown to this view. Usage appears only after OpenClaw sends a request to this provider hostname.</div>';if(hits.length)return `<div class="session-note"><b>Active route:</b> ${hits.map(r=>`${esc(r.role)} ${esc(r.model)}`).join(' · ')}. New messages using this route should create pick/success events below.</div>`;return `<div class="session-note bad"><b>Not on current model route.</b> Current route is ${routes.map(r=>`${esc(r.role)} ${esc(r.model)} → ${esc(r.provider)}`).join(' · ')}. ${esc(provider.name)} keys stay unused until you select a ${esc(provider.name)} model or a fallback reaches it.</div>`;}
|
| 83 |
+
function renderProviderDetails(provider,stats){if(!provider){$('detailTitle').textContent='Provider details';$('details').innerHTML='<div class="empty">Select a provider to see key/session usage.</div>';return;}const rows=providerRows(provider,stats),used=rows.filter(r=>r.picks||r.success).length,successes=rows.reduce((a,r)=>a+r.success,0),fails=rows.reduce((a,r)=>a+(r.fail||0),0),rates=rows.reduce((a,r)=>a+r.rate,0),retries=rows.reduce((a,r)=>a+r.retry+r.transient,0),auths=rows.reduce((a,r)=>a+r.auth,0),aborts=rows.reduce((a,r)=>a+(r.abort||0),0),pending=rows.reduce((a,r)=>a+pendingCount(r),0);$('detailTitle').textContent=`${provider.name} · provider session`;const modelSet=new Set();rows.forEach(r=>r.models.forEach((_,m)=>modelSet.add(m)));const table=rows.map(r=>{const usedKey=(r.picks||r.success)>0,pending=pendingCount(r),stale=r.stalePending||0;return `<tr><td><b class="mono">#${r.slot}/${r.total}</b><div class="key">${esc(r.key)}</div></td><td><span class="status ${usedKey?'used':'unused'}">${usedKey?'USED':'UNUSED'}</span><div class="metric-detail">last: ${esc(r.last?fmtTime(r.last):'never')}</div>${pending?`<div class="metric-detail warn">pending/no response observed: ${pending}${stale?` (stale ${stale})`:''}</div>`:''}</td><td>pick ${r.picks}<br>success ${r.success}<br>fail ${r.fail||0}<br>pending ${pending}<br>rate ${r.rate}</td><td>retry ${r.retry}<br>transient ${r.transient}<br>auth ${r.auth}<br>abort ${r.abort||0}<br>other ${r.other||0}<br>lease cleanup ${r.lease||0}</td><td>${modelChips(r)}</td></tr>`;}).join('');$('details').innerHTML=`${routeNote(provider)}<div class="session-note">Session: <b>${esc(provider.name)}</b>. Raw keys are never returned here; this page only shows masked keys and slot numbers from the configured pool.</div><div class="detail-grid"><div class="mini"><span class="metric-title">Total keys</span><b>${provider.total||0}</b></div><div class="mini"><span class="metric-title">Used / unused</span><b>${used}/${Math.max(0,(provider.total||0)-used)}</b></div><div class="mini"><span class="metric-title">Success / fail</span><b>${successes}/${fails}</b></div><div class="mini"><span class="metric-title">Rate / pending</span><b>${rates}/${pending}</b></div><div class="mini"><span class="metric-title">Retry/auth/abort</span><b>${retries}/${auths}/${aborts}</b></div></div>${provider.name==='gemini'?`<p class="foot">Gemini quota is tracked per key + model. Models seen: ${modelSet.size?[...modelSet].map(m=>`<span class="model-chip">${esc(m)}</span>`).join(''):'<span class="kbd">none yet — new requests will show per-model once the rotator can read the request body</span>'}</p>`:''}<div class="key-table-wrap"><table class="key-table"><thead><tr><th>Hidden key slot</th><th>Status</th><th>Usage</th><th>Failures / aborts</th><th>Per-model / details</th></tr></thead><tbody>${table||'<tr><td colspan="5">No keys configured</td></tr>'}</tbody></table></div>`;}
|
| 84 |
+
function render(){const q=$('q').value.trim().toLowerCase(),type=$('type').value,providers=state.providers||[],events=state.events||[],stats=buildStats();if(!providers.some(p=>p.name===state.selected)&&providers[0])state.selected=providers[0].name;const totalKeys=providers.reduce((a,p)=>a+(Number(p.total)||0),0),usedKeyCount=providers.reduce((a,p)=>a+providerRows(p,stats).filter(s=>s.picks||s.success).length,0);$('mKeys').textContent=totalKeys;$('mUsed').textContent=usedKeyCount;$('mUnused').textContent=Math.max(0,totalKeys-usedKeyCount);$('mRate').textContent=events.filter(e=>e.type==='rate_limited').length;$('mUpdate').textContent=new Date().toLocaleTimeString();$('providerCount').textContent=`${providers.length} active`;$('eventCount').textContent=`${events.length} events`;$('providers').innerHTML=providers.length?providers.map(p=>{const rows=providerRows(p,stats),used=rows.filter(r=>r.picks||r.success).length,total=Number(p.total)||0,aliases=p.aliases?' · '+esc(p.aliases):'';return `<button class="provider ${p.name===state.selected?'active':''}" data-provider="${esc(p.name)}" type="button"><div class="provider-top"><div class="provider-name">${esc(p.name)}</div><span class="pill">${used}/${total} used</span></div><div class="provider-meta">${esc(p.env||'configured pool')}${aliases}</div><div class="bar"><span style="width:${total?Math.round((used/total)*100):0}%"></span></div></button>`;}).join(''):'<div class="empty">No key pools detected in this process env.</div>';$('providers').querySelectorAll('[data-provider]').forEach(el=>el.onclick=()=>{state.selected=el.dataset.provider;localStorage.setItem('hc.keyRotator.provider',state.selected);render();});renderProviderDetails(providers.find(p=>p.name===state.selected)||providers[0],stats);let filtered=events.slice().reverse().filter(e=>(!type||e.type===type));if($('scope').checked&&state.selected)filtered=filtered.filter(e=>!e.provider||e.provider==='system'||e.provider===state.selected);if(q)filtered=filtered.filter(e=>JSON.stringify(e).toLowerCase().includes(q));$('events').innerHTML=filtered.length?filtered.map(e=>`<article class="event ${eventClass(e.type)}"><div class="time">${esc(fmtTime(e.ts))}</div><div><div class="etype">${esc(e.type||'event')}</div><div class="msg">${esc(eventText(e)||'system event')}</div></div><div class="key">${esc(e.key||'')}</div></article>`).join(''):'<div class="empty">No matching events yet. Send a message or disable provider scope to view other providers.</div>';}
|
| 85 |
async function load(){if(state.paused)return;try{const r=await fetch('/api/key-rotator/logs?limit=1000',{cache:'no-store'});if(r.status===401){location.href='/login?next='+encodeURIComponent('/key-rotator');return;}const d=await r.json();state.events=d.events||[];state.providers=d.providers||[];state.runtime=d.runtime||{routes:[]};state.lastPayload=d;const log=d.log||{};$('source').textContent=log.exists?`${d.file||'event log'} · ${Math.round((log.size||0)/1024)} KiB`:`${d.file||'event log'} · waiting`;render();}catch(e){$('events').innerHTML='<div class="empty bad">Could not load rotator logs: '+esc(e.message)+'</div>';}}
|
| 86 |
$('q').addEventListener('input',render);$('type').addEventListener('change',render);$('scope').addEventListener('change',render);$('refresh').onclick=load;$('pause').onclick=()=>{state.paused=!state.paused;$('pause').textContent=state.paused?'Resume':'Pause';$('liveDot').classList.toggle('live',!state.paused);$('liveText').textContent=state.paused?'Paused':'Live';};$('export').onclick=()=>{const data=JSON.stringify(state.lastPayload||{providers:state.providers,events:state.events},null,2),blob=new Blob([data],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='huggingclaw-key-rotator.json';a.click();URL.revokeObjectURL(url);};load();setInterval(load,2500);
|
| 87 |
</script>
|
multi-provider-key-rotator.cjs
CHANGED
|
@@ -25,6 +25,7 @@ const http = require('node:http');
|
|
| 25 |
const https = require('node:https');
|
| 26 |
const fs = require('node:fs');
|
| 27 |
const path = require('node:path');
|
|
|
|
| 28 |
const { AsyncLocalStorage } = require('node:async_hooks');
|
| 29 |
|
| 30 |
const VERBOSE_PICKS = /^(1|true|yes|on)$/i.test(String(process.env.KEY_ROTATOR_VERBOSE_PICKS || '').trim());
|
|
@@ -72,6 +73,16 @@ const MAX_INFLIGHT_PER_KEY = Math.max(
|
|
| 72 |
1,
|
| 73 |
parseInt(process.env.KEY_MAX_INFLIGHT_PER_KEY || '', 10) || 3,
|
| 74 |
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
const COOLDOWN_JITTER_PCT = Math.min(
|
| 76 |
50,
|
| 77 |
Math.max(0, parseInt(process.env.KEY_BLACKLIST_JITTER_PCT || '', 10) || 15),
|
|
@@ -195,6 +206,10 @@ const formatHours = (ms) => (ms / (60 * 60 * 1000)).toFixed(ms % (60 * 60 * 1000
|
|
| 195 |
* Short keys (≤12 chars) are fully masked as "***".
|
| 196 |
*/
|
| 197 |
const keyMask = (k) => (k && k.length > 12 ? `${k.slice(0, 4)}...${k.slice(-6)}` : '***');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
// ─── Provider definitions ────────────────────────────────────────────────────
|
| 200 |
|
|
@@ -277,7 +292,7 @@ function emitEvent(type, p, key, extra = {}) {
|
|
| 277 |
ts: new Date().toISOString(),
|
| 278 |
type,
|
| 279 |
provider: p?.name || extra.provider || 'system',
|
| 280 |
-
...(idx >= 0 ? { slot: idx + 1, total: p.keys.length, key: keyMask(key) } : {}),
|
| 281 |
...extra,
|
| 282 |
};
|
| 283 |
const dir = path.dirname(EVENT_LOG_FILE);
|
|
@@ -394,6 +409,21 @@ function parseProviderErrorInfo(text) {
|
|
| 394 |
|
| 395 |
async function parseResponseErrorInfo(response) {
|
| 396 |
if (!response || response.status < 400 || typeof response.clone !== 'function') return null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
try {
|
| 398 |
const clone = response.clone();
|
| 399 |
if (clone.body && typeof clone.body.getReader === 'function') {
|
|
@@ -402,7 +432,9 @@ async function parseResponseErrorInfo(response) {
|
|
| 402 |
let total = 0;
|
| 403 |
try {
|
| 404 |
while (total < ERROR_BODY_SNIFF_MAX_BYTES) {
|
| 405 |
-
const
|
|
|
|
|
|
|
| 406 |
if (done) break;
|
| 407 |
const buf = Buffer.isBuffer(value)
|
| 408 |
? value
|
|
@@ -416,12 +448,13 @@ async function parseResponseErrorInfo(response) {
|
|
| 416 |
total += slice.length;
|
| 417 |
}
|
| 418 |
} finally {
|
| 419 |
-
try {
|
| 420 |
}
|
| 421 |
-
return parseProviderErrorInfo(Buffer.concat(chunks).toString('utf8'));
|
| 422 |
}
|
| 423 |
-
const
|
| 424 |
-
|
|
|
|
| 425 |
} catch (_) {
|
| 426 |
return null;
|
| 427 |
}
|
|
@@ -479,16 +512,23 @@ function transportErrorInfo(err, status) {
|
|
| 479 |
return info;
|
| 480 |
}
|
| 481 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
function statusNeedsErrorBodyForScope(status) {
|
| 483 |
-
|
| 484 |
-
//
|
| 485 |
-
//
|
| 486 |
-
//
|
| 487 |
-
//
|
| 488 |
-
|
|
|
|
| 489 |
}
|
| 490 |
|
| 491 |
function classifyProviderFailure(p, status, errorInfo) {
|
|
|
|
| 492 |
const haystack = [
|
| 493 |
errorInfo?.code,
|
| 494 |
errorInfo?.type,
|
|
@@ -501,9 +541,11 @@ function classifyProviderFailure(p, status, errorInfo) {
|
|
| 501 |
const looksAuth = /auth|unauthori[sz]ed|invalid.?api.?key|invalid.?key|permission|forbidden|billing|credit|payment|required/.test(haystack);
|
| 502 |
const looksTransient = /overload|temporar|unavailable|timeout|backend|internal|server.?error|try.?again|capacity/.test(haystack);
|
| 503 |
|
|
|
|
| 504 |
if (status === 401) return 'auth';
|
| 505 |
if (status === 402) return 'rate';
|
| 506 |
if (status === 429) return 'rate';
|
|
|
|
| 507 |
// Google/Vertex and some Google APIs can return 403 for quota/rate conditions
|
| 508 |
// (rateLimitExceeded / QUOTA_EXCEEDED), while plain 403 remains auth/permission.
|
| 509 |
if (status === 403) return looksRateOrQuota ? 'rate' : 'auth';
|
|
@@ -1068,22 +1110,28 @@ function nextKey(p, model) {
|
|
| 1068 |
const stickyKey = p.stickyKeys.get(stickyBucketForProvider(p, model));
|
| 1069 |
if (stickyKey && p.keys.includes(stickyKey) && isActive(p, stickyKey, model)) {
|
| 1070 |
const inflight = p.inFlight.get(stickyKey) || 0;
|
| 1071 |
-
if (inflight < MAX_INFLIGHT_PER_KEY) {
|
| 1072 |
rememberTaskAffinityKey(p, model, stickyKey);
|
| 1073 |
-
|
| 1074 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1075 |
return { key: stickyKey, waitMs: 0 };
|
| 1076 |
}
|
| 1077 |
|
| 1078 |
-
//
|
| 1079 |
-
//
|
| 1080 |
-
//
|
| 1081 |
-
// mode intentionally reused the same key even after it was saturated. Clear
|
| 1082 |
-
// the bucket and let the normal active-key scan below choose another key;
|
| 1083 |
-
// only if every key is saturated will the fallback path reuse the least-bad
|
| 1084 |
-
// candidate.
|
| 1085 |
warn(`[key-rotator] ${p.name}: sticky key saturated, rotating away from ${keySlot(p, stickyKey)}${keyMask(stickyKey)}${model ? ` model=${model}` : ''} inflight=${inflight}/${MAX_INFLIGHT_PER_KEY}`);
|
| 1086 |
-
emitEvent('sticky_saturated_rotate', p, stickyKey, { model, inflight, maxInflight: MAX_INFLIGHT_PER_KEY });
|
| 1087 |
clearStickyKey(p, stickyKey, model);
|
| 1088 |
} else if (stickyKey) {
|
| 1089 |
clearStickyKey(p, stickyKey, model);
|
|
@@ -1225,10 +1273,21 @@ function setAuthHeader(headers, key) {
|
|
| 1225 |
|
| 1226 |
function handleStatus(p, key, status, model, retryAfterMs, errorInfo, extra = {}) {
|
| 1227 |
if (!p || !key) return;
|
|
|
|
| 1228 |
retryAfterMs = retryAfterMs || errorInfo?.retryAfterMs || 0;
|
| 1229 |
const failureKind = classifyProviderFailure(p, status, errorInfo);
|
| 1230 |
const errorFields = { ...providerErrorFields(errorInfo), ...extra };
|
| 1231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1232 |
if (failureKind === 'auth') {
|
| 1233 |
// Invalid/expired/unauthorized key — always a global (not model-scoped) blacklist.
|
| 1234 |
let ks = p.keyState.get(key);
|
|
@@ -1269,12 +1328,6 @@ function handleStatus(p, key, status, model, retryAfterMs, errorInfo, extra = {}
|
|
| 1269 |
return;
|
| 1270 |
}
|
| 1271 |
|
| 1272 |
-
if (status >= 200 && status < 400) {
|
| 1273 |
-
recordSuccess(p, key, model);
|
| 1274 |
-
emitEvent('success', p, key, { status, model });
|
| 1275 |
-
return;
|
| 1276 |
-
}
|
| 1277 |
-
|
| 1278 |
if (status >= 400) {
|
| 1279 |
// Non-key failures (malformed request, missing model, unsupported feature,
|
| 1280 |
// content/safety/request-size errors, etc.) still need an explicit outcome
|
|
@@ -1339,7 +1392,15 @@ function handleTransportError(p, key, err, model = null, extra = {}) {
|
|
| 1339 |
clearTaskAffinityKey(p, key, model);
|
| 1340 |
warn(`[key-rotator] ${p.name}: retryable network ${name || 'Error'}${code ? ` code=${code}` : ''} on ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''}`);
|
| 1341 |
emitEvent('network_retryable', p, key, { model, ...extra, name: name || 'Error', code });
|
|
|
|
| 1342 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1343 |
}
|
| 1344 |
|
| 1345 |
/**
|
|
@@ -2249,14 +2310,23 @@ function patchHttpModule(mod) {
|
|
| 2249 |
|
| 2250 |
try {
|
| 2251 |
const options = args[0];
|
| 2252 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2253 |
const provider = resolveProviderForUrl(options, optionHeaders);
|
| 2254 |
|
| 2255 |
if (provider) {
|
| 2256 |
-
// Extract model for per-model-limit providers from the request path.
|
| 2257 |
-
const pathStr =
|
| 2258 |
-
?
|
| 2259 |
-
:
|
|
|
|
|
|
|
| 2260 |
const model = provider.perModelLimits
|
| 2261 |
? (pathStr.match(/\/models\/([^/:?]+)/)?.[1]?.toLowerCase() || null)
|
| 2262 |
: null;
|
|
@@ -2272,12 +2342,20 @@ function patchHttpModule(mod) {
|
|
| 2272 |
usedKey = key; usedProvider = provider; usedModel = model;
|
| 2273 |
usedInFlight = beginInFlight(usedProvider, usedKey, usedModel);
|
| 2274 |
if (provider.queryParam) {
|
| 2275 |
-
const hasOptionsArg = args[1] && typeof args[1] === 'object' && typeof args[1].on !== 'function';
|
| 2276 |
const u = new URL(String(
|
| 2277 |
typeof options === 'string' || options instanceof URL
|
| 2278 |
? options
|
| 2279 |
-
: `https://${options.hostname}${options.path || '/'}`
|
| 2280 |
));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2281 |
if (!isGeminiOpenAICompatPath(u.pathname)) u.searchParams.set('key', key);
|
| 2282 |
// BUG FIX: Google OpenAI-compatible endpoint uses Bearer, not ?key=.
|
| 2283 |
// Preserve string/URL overload options too; many SDKs call
|
|
@@ -2295,18 +2373,31 @@ function patchHttpModule(mod) {
|
|
| 2295 |
args[0] = { ...options, path:`${u.pathname}${u.search}`, headers: patchedHeaders };
|
| 2296 |
} else {
|
| 2297 |
args[0] = u.toString();
|
| 2298 |
-
if (
|
| 2299 |
-
|
| 2300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2301 |
else args[1] = { headers: patchedHeaders };
|
| 2302 |
}
|
| 2303 |
}
|
| 2304 |
} else if (typeof options === 'string' || options instanceof URL) {
|
| 2305 |
const u = new URL(String(options));
|
| 2306 |
-
const extra =
|
| 2307 |
args[0] = { protocol:u.protocol, hostname:u.hostname, port:u.port,
|
| 2308 |
path:`${u.pathname}${u.search}`, ...extra,
|
| 2309 |
headers:setAuthHeader(extra.headers, key) };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2310 |
} else if (options && typeof options === 'object') {
|
| 2311 |
args[0] = { ...options, headers:setAuthHeader(options.headers, key) };
|
| 2312 |
}
|
|
@@ -2392,9 +2483,14 @@ function patchHttpModule(mod) {
|
|
| 2392 |
if (usedProvider && usedKey) {
|
| 2393 |
const _emit = req.emit.bind(req);
|
| 2394 |
let statusHandled = false;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2395 |
const finishStatus = (res, errorInfo) => {
|
| 2396 |
if (statusHandled) return;
|
| 2397 |
statusHandled = true;
|
|
|
|
| 2398 |
const retryAfterMs = parseRetryAfterMs(res?.headers?.['retry-after']);
|
| 2399 |
try { endInFlight(usedProvider, usedKey, usedInFlight); } catch (_) {}
|
| 2400 |
try { handleStatus(usedProvider, usedKey, res?.statusCode, usedModel, retryAfterMs, errorInfo, { requestId: usedInFlight?.requestId }); } catch (_) {}
|
|
@@ -2420,6 +2516,8 @@ function patchHttpModule(mod) {
|
|
| 2420 |
: null;
|
| 2421 |
finishStatus(res, errorInfo);
|
| 2422 |
};
|
|
|
|
|
|
|
| 2423 |
res.on('end', finishWithSniffedBody);
|
| 2424 |
res.on('close', finishWithSniffedBody);
|
| 2425 |
} else {
|
|
@@ -2463,7 +2561,7 @@ if (hasProviderKeys) {
|
|
| 2463 |
patchUndici(); // covers OpenClaw gateway's bundled undici AI calls
|
| 2464 |
startDiagnostics();
|
| 2465 |
|
| 2466 |
-
debug(`[key-rotator] loaded — cooldown base:${BASE_COOLDOWN_MS/1000}s max-strikes:${MAX_STRIKES} perm-suspend:${formatHours(PERM_SUSPEND_MS)}h (cap 16h) max-inflight-per-key:${MAX_INFLIGHT_PER_KEY} max-retry-after:${MAX_RETRY_AFTER_MS/1000}s max-key-wait:${MAX_KEY_WAIT_MS/1000}s diagnostics:${DIAGNOSTICS_ENABLED ? 'on' : 'off'} log-level:${LOG_LEVEL} verbose-picks:${VERBOSE_PICKS ? 'on' : 'off'} suspended-last-resort:${USE_SUSPENDED_KEY_AS_LAST_RESORT ? 'on' : 'off'} per-model-providers:${providerState.filter(p => p.perModelLimits).map(p => p.name).join(',') || 'none'} model-from-body:on model-sniff-max:${REQUEST_MODEL_SNIFF_MAX_BYTES} error-sniff-max:${ERROR_BODY_SNIFF_MAX_BYTES} error-body-wait:${ERROR_BODY_WAIT_MS}ms inflight-ttl:${INFLIGHT_TTL_MS}ms task-affinity:${TASK_AFFINITY_MS}ms/${TASK_AFFINITY_MAX_REUSES}reuses sticky-until-failure:${STICKY_UNTIL_FAILURE ? 'on' : 'off'} sticky-scope:${String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto'} sticky-providers:${[...STICKY_PROVIDER_SET].join(',') || 'none'} llm-fallback-providers:${LLM_FALLBACK_PROVIDER_SET ? [...LLM_FALLBACK_PROVIDER_SET].join(',') : 'all'}`);
|
| 2467 |
emitEvent('rotator_loaded', null, null, {
|
| 2468 |
providers: providerState.filter(p => p.keys.length).map(p => ({ name: p.name, total: p.keys.length })),
|
| 2469 |
logLevel: LOG_LEVEL,
|
|
@@ -2474,6 +2572,7 @@ if (hasProviderKeys) {
|
|
| 2474 |
taskAffinityMs: TASK_AFFINITY_MS,
|
| 2475 |
taskAffinityMaxReuses: TASK_AFFINITY_MAX_REUSES,
|
| 2476 |
stickyUntilFailure: STICKY_UNTIL_FAILURE,
|
|
|
|
| 2477 |
stickyScope: String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto',
|
| 2478 |
stickyProviders: [...STICKY_PROVIDER_SET],
|
| 2479 |
llmFallbackProviders: LLM_FALLBACK_PROVIDER_SET ? [...LLM_FALLBACK_PROVIDER_SET] : ['*'],
|
|
|
|
| 25 |
const https = require('node:https');
|
| 26 |
const fs = require('node:fs');
|
| 27 |
const path = require('node:path');
|
| 28 |
+
const crypto = require('node:crypto');
|
| 29 |
const { AsyncLocalStorage } = require('node:async_hooks');
|
| 30 |
|
| 31 |
const VERBOSE_PICKS = /^(1|true|yes|on)$/i.test(String(process.env.KEY_ROTATOR_VERBOSE_PICKS || '').trim());
|
|
|
|
| 73 |
1,
|
| 74 |
parseInt(process.env.KEY_MAX_INFLIGHT_PER_KEY || '', 10) || 3,
|
| 75 |
);
|
| 76 |
+
// Sticky providers (Gemini by default) are intentionally pinned until the
|
| 77 |
+
// provider returns a real key outcome (success keeps the pin; quota/auth/
|
| 78 |
+
// retryable provider failures clear it). In-flight leases are only local
|
| 79 |
+
// bookkeeping and can expire when a stream/caller stops being observed, so they
|
| 80 |
+
// must not force Gemini to walk the whole key pool. Keep this production-safe by
|
| 81 |
+
// making the behavior explicit and env-tunable for operators who prefer hard
|
| 82 |
+
// concurrency spreading.
|
| 83 |
+
const STICKY_IGNORE_INFLIGHT_SATURATION = !/^(0|false|no|off)$/i.test(
|
| 84 |
+
String(process.env.KEY_STICKY_IGNORE_INFLIGHT_SATURATION || 'true').trim(),
|
| 85 |
+
);
|
| 86 |
const COOLDOWN_JITTER_PCT = Math.min(
|
| 87 |
50,
|
| 88 |
Math.max(0, parseInt(process.env.KEY_BLACKLIST_JITTER_PCT || '', 10) || 15),
|
|
|
|
| 206 |
* Short keys (≤12 chars) are fully masked as "***".
|
| 207 |
*/
|
| 208 |
const keyMask = (k) => (k && k.length > 12 ? `${k.slice(0, 4)}...${k.slice(-6)}` : '***');
|
| 209 |
+
const keyFingerprint = (k) => {
|
| 210 |
+
try { return k ? crypto.createHash('sha256').update(String(k)).digest('hex').slice(0, 12) : null; }
|
| 211 |
+
catch (_) { return null; }
|
| 212 |
+
};
|
| 213 |
|
| 214 |
// ─── Provider definitions ────────────────────────────────────────────────────
|
| 215 |
|
|
|
|
| 292 |
ts: new Date().toISOString(),
|
| 293 |
type,
|
| 294 |
provider: p?.name || extra.provider || 'system',
|
| 295 |
+
...(idx >= 0 ? { slot: idx + 1, total: p.keys.length, key: keyMask(key), kid: keyFingerprint(key) } : {}),
|
| 296 |
...extra,
|
| 297 |
};
|
| 298 |
const dir = path.dirname(EVENT_LOG_FILE);
|
|
|
|
| 409 |
|
| 410 |
async function parseResponseErrorInfo(response) {
|
| 411 |
if (!response || response.status < 400 || typeof response.clone !== 'function') return null;
|
| 412 |
+
const deadline = Date.now() + ERROR_BODY_WAIT_MS;
|
| 413 |
+
const remainingWait = () => Math.max(0, deadline - Date.now());
|
| 414 |
+
const withDeadline = async (promise) => {
|
| 415 |
+
const waitMs = remainingWait();
|
| 416 |
+
if (waitMs <= 0) return { timedOut: true };
|
| 417 |
+
let timer = null;
|
| 418 |
+
try {
|
| 419 |
+
return await Promise.race([
|
| 420 |
+
promise.then(value => ({ value }), error => ({ error })),
|
| 421 |
+
new Promise(resolve => { timer = setTimeout(() => resolve({ timedOut: true }), waitMs); }),
|
| 422 |
+
]);
|
| 423 |
+
} finally {
|
| 424 |
+
if (timer) clearTimeout(timer);
|
| 425 |
+
}
|
| 426 |
+
};
|
| 427 |
try {
|
| 428 |
const clone = response.clone();
|
| 429 |
if (clone.body && typeof clone.body.getReader === 'function') {
|
|
|
|
| 432 |
let total = 0;
|
| 433 |
try {
|
| 434 |
while (total < ERROR_BODY_SNIFF_MAX_BYTES) {
|
| 435 |
+
const result = await withDeadline(reader.read());
|
| 436 |
+
if (result.timedOut || result.error) break;
|
| 437 |
+
const { done, value } = result.value || {};
|
| 438 |
if (done) break;
|
| 439 |
const buf = Buffer.isBuffer(value)
|
| 440 |
? value
|
|
|
|
| 448 |
total += slice.length;
|
| 449 |
}
|
| 450 |
} finally {
|
| 451 |
+
try { reader.cancel().catch?.(() => {}); } catch (_) {}
|
| 452 |
}
|
| 453 |
+
return chunks.length ? parseProviderErrorInfo(Buffer.concat(chunks).toString('utf8')) : null;
|
| 454 |
}
|
| 455 |
+
const result = await withDeadline(clone.text());
|
| 456 |
+
if (result.timedOut || result.error || typeof result.value !== 'string') return null;
|
| 457 |
+
return parseProviderErrorInfo(result.value.slice(0, ERROR_BODY_SNIFF_MAX_BYTES));
|
| 458 |
} catch (_) {
|
| 459 |
return null;
|
| 460 |
}
|
|
|
|
| 512 |
return info;
|
| 513 |
}
|
| 514 |
|
| 515 |
+
function normalizeHttpStatusCode(status) {
|
| 516 |
+
const n = Number(status);
|
| 517 |
+
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
function statusNeedsErrorBodyForScope(status) {
|
| 521 |
+
status = normalizeHttpStatusCode(status);
|
| 522 |
+
// Production classification needs provider error bodies for more than Gemini
|
| 523 |
+
// 403s: many gateways encode quota/auth/transient reasons in JSON even when
|
| 524 |
+
// the HTTP code is generic (400/404/422/5xx). We still cap the wait with
|
| 525 |
+
// ERROR_BODY_WAIT_MS, so missing bodies close quickly instead of aging into
|
| 526 |
+
// lease-only/pending dashboard noise.
|
| 527 |
+
return status >= 400 && status < 600;
|
| 528 |
}
|
| 529 |
|
| 530 |
function classifyProviderFailure(p, status, errorInfo) {
|
| 531 |
+
status = normalizeHttpStatusCode(status);
|
| 532 |
const haystack = [
|
| 533 |
errorInfo?.code,
|
| 534 |
errorInfo?.type,
|
|
|
|
| 541 |
const looksAuth = /auth|unauthori[sz]ed|invalid.?api.?key|invalid.?key|permission|forbidden|billing|credit|payment|required/.test(haystack);
|
| 542 |
const looksTransient = /overload|temporar|unavailable|timeout|backend|internal|server.?error|try.?again|capacity/.test(haystack);
|
| 543 |
|
| 544 |
+
if (status >= 100 && status < 400) return 'success';
|
| 545 |
if (status === 401) return 'auth';
|
| 546 |
if (status === 402) return 'rate';
|
| 547 |
if (status === 429) return 'rate';
|
| 548 |
+
if (status === 529) return looksRateOrQuota ? 'rate' : 'transient';
|
| 549 |
// Google/Vertex and some Google APIs can return 403 for quota/rate conditions
|
| 550 |
// (rateLimitExceeded / QUOTA_EXCEEDED), while plain 403 remains auth/permission.
|
| 551 |
if (status === 403) return looksRateOrQuota ? 'rate' : 'auth';
|
|
|
|
| 1110 |
const stickyKey = p.stickyKeys.get(stickyBucketForProvider(p, model));
|
| 1111 |
if (stickyKey && p.keys.includes(stickyKey) && isActive(p, stickyKey, model)) {
|
| 1112 |
const inflight = p.inFlight.get(stickyKey) || 0;
|
| 1113 |
+
if (inflight < MAX_INFLIGHT_PER_KEY || STICKY_IGNORE_INFLIGHT_SATURATION) {
|
| 1114 |
rememberTaskAffinityKey(p, model, stickyKey);
|
| 1115 |
+
const saturated = inflight >= MAX_INFLIGHT_PER_KEY;
|
| 1116 |
+
if (saturated) {
|
| 1117 |
+
// In-flight count is a local safety lease, not a provider verdict.
|
| 1118 |
+
// For sticky providers, only a real provider failure should move the
|
| 1119 |
+
// bucket to a different key; otherwise long streams/abandoned callers
|
| 1120 |
+
// make Gemini appear to "fail" every key by lease expiry alone.
|
| 1121 |
+
warn(`[key-rotator] ${p.name}: sticky key saturated but staying pinned until real provider outcome on ${keySlot(p, stickyKey)}${keyMask(stickyKey)}${model ? ` model=${model}` : ''} inflight=${inflight + 1}/${MAX_INFLIGHT_PER_KEY}`);
|
| 1122 |
+
emitEvent('sticky_saturated_reuse', p, stickyKey, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY, sticky: true, reason: 'sticky_until_real_failure' });
|
| 1123 |
+
} else {
|
| 1124 |
+
verbosePickLog(`[key-rotator] ${p.name}: sticky picked ${keySlot(p, stickyKey)}${keyMask(stickyKey)}${model ? ` model=${model}` : ''} inflight=${inflight + 1}/${MAX_INFLIGHT_PER_KEY}`);
|
| 1125 |
+
emitEvent('sticky_pick', p, stickyKey, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY });
|
| 1126 |
+
}
|
| 1127 |
return { key: stickyKey, waitMs: 0 };
|
| 1128 |
}
|
| 1129 |
|
| 1130 |
+
// Operator opted out of strict sticky pinning. In that mode, saturation can
|
| 1131 |
+
// rotate away from the sticky key, but this is no longer the default for
|
| 1132 |
+
// Gemini because lease-only saturation is not a real key failure.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1133 |
warn(`[key-rotator] ${p.name}: sticky key saturated, rotating away from ${keySlot(p, stickyKey)}${keyMask(stickyKey)}${model ? ` model=${model}` : ''} inflight=${inflight}/${MAX_INFLIGHT_PER_KEY}`);
|
| 1134 |
+
emitEvent('sticky_saturated_rotate', p, stickyKey, { model, inflight, maxInflight: MAX_INFLIGHT_PER_KEY, sticky: true, reason: 'operator_opt_out' });
|
| 1135 |
clearStickyKey(p, stickyKey, model);
|
| 1136 |
} else if (stickyKey) {
|
| 1137 |
clearStickyKey(p, stickyKey, model);
|
|
|
|
| 1273 |
|
| 1274 |
function handleStatus(p, key, status, model, retryAfterMs, errorInfo, extra = {}) {
|
| 1275 |
if (!p || !key) return;
|
| 1276 |
+
status = normalizeHttpStatusCode(status);
|
| 1277 |
retryAfterMs = retryAfterMs || errorInfo?.retryAfterMs || 0;
|
| 1278 |
const failureKind = classifyProviderFailure(p, status, errorInfo);
|
| 1279 |
const errorFields = { ...providerErrorFields(errorInfo), ...extra };
|
| 1280 |
|
| 1281 |
+
// Count every final HTTP success code as success before any key-failure logic.
|
| 1282 |
+
// Some transports/providers can surface 1xx/204/206/304-style successful
|
| 1283 |
+
// completions; these must reset the selected key and show as success in the
|
| 1284 |
+
// manager instead of falling through as an unclassified/no-op outcome.
|
| 1285 |
+
if (failureKind === 'success') {
|
| 1286 |
+
recordSuccess(p, key, model);
|
| 1287 |
+
emitEvent('success', p, key, { status, model, ...errorFields });
|
| 1288 |
+
return;
|
| 1289 |
+
}
|
| 1290 |
+
|
| 1291 |
if (failureKind === 'auth') {
|
| 1292 |
// Invalid/expired/unauthorized key — always a global (not model-scoped) blacklist.
|
| 1293 |
let ks = p.keyState.get(key);
|
|
|
|
| 1328 |
return;
|
| 1329 |
}
|
| 1330 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1331 |
if (status >= 400) {
|
| 1332 |
// Non-key failures (malformed request, missing model, unsupported feature,
|
| 1333 |
// content/safety/request-size errors, etc.) still need an explicit outcome
|
|
|
|
| 1392 |
clearTaskAffinityKey(p, key, model);
|
| 1393 |
warn(`[key-rotator] ${p.name}: retryable network ${name || 'Error'}${code ? ` code=${code}` : ''} on ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''}`);
|
| 1394 |
emitEvent('network_retryable', p, key, { model, ...extra, name: name || 'Error', code });
|
| 1395 |
+
return;
|
| 1396 |
}
|
| 1397 |
+
|
| 1398 |
+
// Always close the dashboard/request lifecycle with a real observed outcome.
|
| 1399 |
+
// Unknown transport errors are not enough evidence to punish or rotate a key,
|
| 1400 |
+
// but emitting nothing leaves the manager showing phantom pending/lease-only
|
| 1401 |
+
// activity and makes sticky providers look broken.
|
| 1402 |
+
warn(`[key-rotator] ${p.name}: transport unknown ${name || 'Error'}${code ? ` code=${code}` : ''} on ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''} (key not penalized)`);
|
| 1403 |
+
emitEvent('transport_unknown', p, key, { model, ...extra, name: name || 'Error', code, message: message.slice(0, 240), classifiedAs: 'non_key_transport_error' });
|
| 1404 |
}
|
| 1405 |
|
| 1406 |
/**
|
|
|
|
| 2310 |
|
| 2311 |
try {
|
| 2312 |
const options = args[0];
|
| 2313 |
+
const hasOptionsArg = args[1] && typeof args[1] === 'object' && typeof args[1].on !== 'function';
|
| 2314 |
+
const optionHeaders = (() => {
|
| 2315 |
+
const first = options && typeof options === 'object' ? options.headers : undefined;
|
| 2316 |
+
const second = hasOptionsArg ? args[1].headers : undefined;
|
| 2317 |
+
if (!first) return second;
|
| 2318 |
+
if (!second) return first;
|
| 2319 |
+
return { ...first, ...second };
|
| 2320 |
+
})();
|
| 2321 |
const provider = resolveProviderForUrl(options, optionHeaders);
|
| 2322 |
|
| 2323 |
if (provider) {
|
| 2324 |
+
// Extract model for per-model-limit providers from the effective request path.
|
| 2325 |
+
const pathStr = hasOptionsArg && args[1].path
|
| 2326 |
+
? args[1].path
|
| 2327 |
+
: typeof options === 'object' && options.path
|
| 2328 |
+
? options.path
|
| 2329 |
+
: (typeof options === 'string' || options instanceof URL) ? String(options) : '';
|
| 2330 |
const model = provider.perModelLimits
|
| 2331 |
? (pathStr.match(/\/models\/([^/:?]+)/)?.[1]?.toLowerCase() || null)
|
| 2332 |
: null;
|
|
|
|
| 2342 |
usedKey = key; usedProvider = provider; usedModel = model;
|
| 2343 |
usedInFlight = beginInFlight(usedProvider, usedKey, usedModel);
|
| 2344 |
if (provider.queryParam) {
|
|
|
|
| 2345 |
const u = new URL(String(
|
| 2346 |
typeof options === 'string' || options instanceof URL
|
| 2347 |
? options
|
| 2348 |
+
: `${options.protocol || 'https:'}//${options.hostname || options.host || 'localhost'}${options.path || '/'}`
|
| 2349 |
));
|
| 2350 |
+
// node:http merges request(url, options) with options taking
|
| 2351 |
+
// precedence, including `path`. If callers pass an override path in
|
| 2352 |
+
// the second arg, inject into that effective path too; otherwise the
|
| 2353 |
+
// key added to the URL arg can be silently discarded by Node.
|
| 2354 |
+
if (hasOptionsArg && args[1].path) {
|
| 2355 |
+
const override = new URL(String(args[1].path), u);
|
| 2356 |
+
u.pathname = override.pathname;
|
| 2357 |
+
u.search = override.search;
|
| 2358 |
+
}
|
| 2359 |
if (!isGeminiOpenAICompatPath(u.pathname)) u.searchParams.set('key', key);
|
| 2360 |
// BUG FIX: Google OpenAI-compatible endpoint uses Bearer, not ?key=.
|
| 2361 |
// Preserve string/URL overload options too; many SDKs call
|
|
|
|
| 2373 |
args[0] = { ...options, path:`${u.pathname}${u.search}`, headers: patchedHeaders };
|
| 2374 |
} else {
|
| 2375 |
args[0] = u.toString();
|
| 2376 |
+
if (hasOptionsArg) {
|
| 2377 |
+
args[1] = {
|
| 2378 |
+
...args[1],
|
| 2379 |
+
path: `${u.pathname}${u.search}`,
|
| 2380 |
+
...(needsBearer ? { headers: patchedHeaders } : {}),
|
| 2381 |
+
};
|
| 2382 |
+
} else if (needsBearer) {
|
| 2383 |
+
if (typeof args[1] === 'function') { args[2] = args[1]; args[1] = { headers: patchedHeaders }; }
|
| 2384 |
else args[1] = { headers: patchedHeaders };
|
| 2385 |
}
|
| 2386 |
}
|
| 2387 |
} else if (typeof options === 'string' || options instanceof URL) {
|
| 2388 |
const u = new URL(String(options));
|
| 2389 |
+
const extra = hasOptionsArg ? args[1] : {};
|
| 2390 |
args[0] = { protocol:u.protocol, hostname:u.hostname, port:u.port,
|
| 2391 |
path:`${u.pathname}${u.search}`, ...extra,
|
| 2392 |
headers:setAuthHeader(extra.headers, key) };
|
| 2393 |
+
// We have folded the second options argument into args[0]. Leaving it
|
| 2394 |
+
// in place would call http.request(options, options, cb), where Node
|
| 2395 |
+
// expects the second argument to be the callback and can throw or drop
|
| 2396 |
+
// the real callback for non-query providers such as OpenAI/Anthropic.
|
| 2397 |
+
if (hasOptionsArg) {
|
| 2398 |
+
if (typeof args[2] === 'function') { args[1] = args[2]; args.length = 2; }
|
| 2399 |
+
else { args.length = 1; }
|
| 2400 |
+
}
|
| 2401 |
} else if (options && typeof options === 'object') {
|
| 2402 |
args[0] = { ...options, headers:setAuthHeader(options.headers, key) };
|
| 2403 |
}
|
|
|
|
| 2483 |
if (usedProvider && usedKey) {
|
| 2484 |
const _emit = req.emit.bind(req);
|
| 2485 |
let statusHandled = false;
|
| 2486 |
+
let bodyWaitTimer = null;
|
| 2487 |
+
const clearBodyWaitTimer = () => {
|
| 2488 |
+
if (bodyWaitTimer) { clearTimeout(bodyWaitTimer); bodyWaitTimer = null; }
|
| 2489 |
+
};
|
| 2490 |
const finishStatus = (res, errorInfo) => {
|
| 2491 |
if (statusHandled) return;
|
| 2492 |
statusHandled = true;
|
| 2493 |
+
clearBodyWaitTimer();
|
| 2494 |
const retryAfterMs = parseRetryAfterMs(res?.headers?.['retry-after']);
|
| 2495 |
try { endInFlight(usedProvider, usedKey, usedInFlight); } catch (_) {}
|
| 2496 |
try { handleStatus(usedProvider, usedKey, res?.statusCode, usedModel, retryAfterMs, errorInfo, { requestId: usedInFlight?.requestId }); } catch (_) {}
|
|
|
|
| 2516 |
: null;
|
| 2517 |
finishStatus(res, errorInfo);
|
| 2518 |
};
|
| 2519 |
+
bodyWaitTimer = setTimeout(finishWithSniffedBody, ERROR_BODY_WAIT_MS);
|
| 2520 |
+
bodyWaitTimer.unref?.();
|
| 2521 |
res.on('end', finishWithSniffedBody);
|
| 2522 |
res.on('close', finishWithSniffedBody);
|
| 2523 |
} else {
|
|
|
|
| 2561 |
patchUndici(); // covers OpenClaw gateway's bundled undici AI calls
|
| 2562 |
startDiagnostics();
|
| 2563 |
|
| 2564 |
+
debug(`[key-rotator] loaded — cooldown base:${BASE_COOLDOWN_MS/1000}s max-strikes:${MAX_STRIKES} perm-suspend:${formatHours(PERM_SUSPEND_MS)}h (cap 16h) max-inflight-per-key:${MAX_INFLIGHT_PER_KEY} max-retry-after:${MAX_RETRY_AFTER_MS/1000}s max-key-wait:${MAX_KEY_WAIT_MS/1000}s diagnostics:${DIAGNOSTICS_ENABLED ? 'on' : 'off'} log-level:${LOG_LEVEL} verbose-picks:${VERBOSE_PICKS ? 'on' : 'off'} suspended-last-resort:${USE_SUSPENDED_KEY_AS_LAST_RESORT ? 'on' : 'off'} per-model-providers:${providerState.filter(p => p.perModelLimits).map(p => p.name).join(',') || 'none'} model-from-body:on model-sniff-max:${REQUEST_MODEL_SNIFF_MAX_BYTES} error-sniff-max:${ERROR_BODY_SNIFF_MAX_BYTES} error-body-wait:${ERROR_BODY_WAIT_MS}ms inflight-ttl:${INFLIGHT_TTL_MS}ms task-affinity:${TASK_AFFINITY_MS}ms/${TASK_AFFINITY_MAX_REUSES}reuses sticky-until-failure:${STICKY_UNTIL_FAILURE ? 'on' : 'off'} sticky-ignore-inflight-saturation:${STICKY_IGNORE_INFLIGHT_SATURATION ? 'on' : 'off'} sticky-scope:${String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto'} sticky-providers:${[...STICKY_PROVIDER_SET].join(',') || 'none'} llm-fallback-providers:${LLM_FALLBACK_PROVIDER_SET ? [...LLM_FALLBACK_PROVIDER_SET].join(',') : 'all'}`);
|
| 2565 |
emitEvent('rotator_loaded', null, null, {
|
| 2566 |
providers: providerState.filter(p => p.keys.length).map(p => ({ name: p.name, total: p.keys.length })),
|
| 2567 |
logLevel: LOG_LEVEL,
|
|
|
|
| 2572 |
taskAffinityMs: TASK_AFFINITY_MS,
|
| 2573 |
taskAffinityMaxReuses: TASK_AFFINITY_MAX_REUSES,
|
| 2574 |
stickyUntilFailure: STICKY_UNTIL_FAILURE,
|
| 2575 |
+
stickyIgnoreInflightSaturation: STICKY_IGNORE_INFLIGHT_SATURATION,
|
| 2576 |
stickyScope: String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto',
|
| 2577 |
stickyProviders: [...STICKY_PROVIDER_SET],
|
| 2578 |
llmFallbackProviders: LLM_FALLBACK_PROVIDER_SET ? [...LLM_FALLBACK_PROVIDER_SET] : ['*'],
|