Spaces:
Paused
Paused
Merge branch #anurag008w/HuggingClaw' into 'sunboy0628/HuggingClaw'
Browse files- .env.example +8 -0
- CHANGELOG.md +14 -0
- Dockerfile +1 -1
- README.md +1 -0
- health-server.js +7 -1
- jupyter-devdata-sync.py +32 -0
- key-rotator-manager.html +16 -13
- multi-provider-key-rotator.cjs +300 -93
- openclaw-sync.py +36 -0
.env.example
CHANGED
|
@@ -235,6 +235,14 @@ LLM_API_KEY_FALLBACK_ENABLED=true
|
|
| 235 |
# Set false if you prefer strict withholding until cooldown expiry.
|
| 236 |
# KEY_USE_SUSPENDED_AS_LAST_RESORT=true
|
| 237 |
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
#
|
| 239 |
# Optional diagnostics log snapshot for key pools (default: off).
|
| 240 |
# KEY_ROTATOR_DIAGNOSTICS=true
|
|
|
|
| 235 |
# Set false if you prefer strict withholding until cooldown expiry.
|
| 236 |
# KEY_USE_SUSPENDED_AS_LAST_RESORT=true
|
| 237 |
#
|
| 238 |
+
# Max ms to sleep waiting for the soonest suspended key to recover before
|
| 239 |
+
# forwarding the request anyway (default: 0 = disabled / fire-and-miss).
|
| 240 |
+
# When all keys are in cooldown and KEY_USE_SUSPENDED_AS_LAST_RESORT is true,
|
| 241 |
+
# setting this to a positive value (e.g. 20000) lets the rotator sleep up to
|
| 242 |
+
# that long so the request has a real chance of succeeding instead of hitting
|
| 243 |
+
# a guaranteed 429. Leave at 0 if you prefer the old immediate-forward behaviour.
|
| 244 |
+
# KEY_MAX_WAIT_MS=0
|
| 245 |
+
#
|
| 246 |
#
|
| 247 |
# Optional diagnostics log snapshot for key pools (default: off).
|
| 248 |
# KEY_ROTATOR_DIAGNOSTICS=true
|
CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
| 2 |
|
| 3 |
All notable changes to this project will be documented in this file.
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
## [1.6.0] - 2026-05-14
|
| 6 |
|
| 7 |
### Added
|
|
|
|
| 2 |
|
| 3 |
All notable changes to this project will be documented in this file.
|
| 4 |
|
| 5 |
+
## [Unreleased]
|
| 6 |
+
|
| 7 |
+
### Fixed
|
| 8 |
+
|
| 9 |
+
- **Gemini Bearer auth 401 on newer endpoints** — The key rotator only set `Authorization: Bearer` for OpenAI-compatible paths (`/v1beta/openai/...`), using `?key=` for other endpoints. Newer Google endpoints like `/v1beta/embeddings` (used for memory/embeddings) require Bearer auth. Fixed by always setting Bearer auth for ALL Gemini requests with a key, regardless of endpoint path. Google APIs accept both formats, so no regression.
|
| 10 |
+
- **Anthropic key rotation never applied** — `api.anthropic.com` authenticates via the `x-api-key` header, not `Authorization: Bearer`. The rotator only injected a Bearer header, leaving the caller's original `x-api-key` untouched, so the rotated Anthropic pool was never used. Added a provider-aware auth-header injector (`x-api-key` for Anthropic, `Bearer` for everyone else) wired into all three dispatch layers (`fetch`, `undici`, `node:http`).
|
| 11 |
+
- **Gemini stickiness lost when the model is detected after key selection** — OpenAI-compatible Gemini (and `node:http`) requests reach key selection before the request body reveals the model, so the key is pinned under a temporary unknown-model bucket. Promotion then deleted that bucket, sending the next (also model-unknown) request back to round-robin — keys rotated on every call. The unknown-model bucket now stays pinned to the same key after promotion, and is still cleared on a real provider failure, restoring sticky-until-failure behavior.
|
| 12 |
+
- **Dashboard pick undercount** — `task_affinity_pick` events were emitted but missing from the manager's pick-type set, so affinity reuses were not counted as picks.
|
| 13 |
+
- **Rotator blind to responses on undici 8 (no success/failure accounting, lease leak)** — OpenClaw bundles undici 8, whose dispatch handler interface renamed `onHeaders`/`onData`/`onComplete`/`onError` to `onResponseStart`/`onResponseData`/`onResponseEnd`/`onResponseError`. The rotator's handler wrapper only instrumented the classic names, so on undici 8 none fired: successes were never recorded (`success 0`), 429/auth failures were never classified (keys never penalized or rotated), and the in-flight lease was only released by its 30s TTL (`inflight_lease_expired` "lease cleanup"). The wrapper now instruments both interfaces; classic-undici behavior (e.g. the repo's undici 7) is unchanged.
|
| 14 |
+
|
| 15 |
+
### Added
|
| 16 |
+
|
| 17 |
+
- **Sticky / affinity event-log filters** — the key-rotator manager event log can now be filtered by `sticky_pick` and `task_affinity_pick`, so operators can directly confirm Gemini stickiness and task-affinity reuse in the live log.
|
| 18 |
+
|
| 19 |
## [1.6.0] - 2026-05-14
|
| 20 |
|
| 21 |
### Added
|
Dockerfile
CHANGED
|
@@ -124,7 +124,7 @@ ENV HOME=/home/node \
|
|
| 124 |
OPENCLAW_VERSION=${OPENCLAW_VERSION} \
|
| 125 |
PATH=/home/node/.local/bin:/usr/local/bin:$PATH \
|
| 126 |
NODE_PATH=/home/node/browser-deps/node_modules \
|
| 127 |
-
NODE_OPTIONS="--require /opt/cloudflare-proxy.js"
|
| 128 |
|
| 129 |
WORKDIR /home/node/app
|
| 130 |
|
|
|
|
| 124 |
OPENCLAW_VERSION=${OPENCLAW_VERSION} \
|
| 125 |
PATH=/home/node/.local/bin:/usr/local/bin:$PATH \
|
| 126 |
NODE_PATH=/home/node/browser-deps/node_modules \
|
| 127 |
+
NODE_OPTIONS="--require /opt/cloudflare-proxy.js --require /home/node/app/multi-provider-key-rotator.cjs"
|
| 128 |
|
| 129 |
WORKDIR /home/node/app
|
| 130 |
|
README.md
CHANGED
|
@@ -312,6 +312,7 @@ Optional tuning:
|
|
| 312 |
- `KEY_STICKY_PROVIDERS` (default `gemini`) — comma-separated provider names that should use sticky key selection instead of per-request round-robin.
|
| 313 |
- `KEY_STICKY_SCOPE` (default `auto`) — `auto` uses per-model sticky buckets for Gemini/per-model providers and provider-level buckets for others; set `provider` or `model` to override.
|
| 314 |
- `KEY_FETCH_MAX_RETRIES` (default `0`) — optional auto-retry count for retryable failures on **GET/HEAD/OPTIONS/POST** with a different key. Default `0` means the rotator does **not** spend extra upstream attempts for a single caller request.
|
|
|
|
| 315 |
- `KEY_FETCH_RETRY_BASE_DELAY_MS` (default `250`) — base delay for retry backoff (respects `Retry-After`, capped to 10s).
|
| 316 |
- `KEY_ROTATOR_ASSERT_NO_EXTRA_CALLS=true` — optional diagnostic warning if a single caller fetch creates more than one upstream provider attempt.
|
| 317 |
- `KEY_ROTATOR_EMIT_SYNTHETIC_EVENTS=true` — optional local-only dashboard probe; with `SYNTHETIC_API_KEYS` configured, emits synthetic rotator events without sending an upstream provider request.
|
|
|
|
| 312 |
- `KEY_STICKY_PROVIDERS` (default `gemini`) — comma-separated provider names that should use sticky key selection instead of per-request round-robin.
|
| 313 |
- `KEY_STICKY_SCOPE` (default `auto`) — `auto` uses per-model sticky buckets for Gemini/per-model providers and provider-level buckets for others; set `provider` or `model` to override.
|
| 314 |
- `KEY_FETCH_MAX_RETRIES` (default `0`) — optional auto-retry count for retryable failures on **GET/HEAD/OPTIONS/POST** with a different key. Default `0` means the rotator does **not** spend extra upstream attempts for a single caller request.
|
| 315 |
+
- `KEY_MAX_WAIT_MS` (default `0` / disabled) — when all keys are suspended and best-effort mode is active, sleep up to this many ms for the soonest-recovering key before forwarding the request. `0` (default) preserves the old fire-and-miss behaviour; set e.g. `20000` to give suspended keys a real recovery window instead of forwarding into a guaranteed 429.
|
| 316 |
- `KEY_FETCH_RETRY_BASE_DELAY_MS` (default `250`) — base delay for retry backoff (respects `Retry-After`, capped to 10s).
|
| 317 |
- `KEY_ROTATOR_ASSERT_NO_EXTRA_CALLS=true` — optional diagnostic warning if a single caller fetch creates more than one upstream provider attempt.
|
| 318 |
- `KEY_ROTATOR_EMIT_SYNTHETIC_EVENTS=true` — optional local-only dashboard probe; with `SYNTHETIC_API_KEYS` configured, emits synthetic rotator events without sending an upstream provider request.
|
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 |
}
|
jupyter-devdata-sync.py
CHANGED
|
@@ -18,6 +18,34 @@ MAX_FILE_SIZE_BYTES = int(
|
|
| 18 |
# Max stale files to delete per commit. Mirrors openclaw-sync.py behaviour.
|
| 19 |
# Override via DEVDATA_PRUNE_BATCH_SIZE.
|
| 20 |
PRUNE_BATCH_SIZE = int((os.environ.get("DEVDATA_PRUNE_BATCH_SIZE", "").strip() or "50"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# Reserved filenames previously generated by DevData. Never copy or restore
|
| 22 |
# them as user content, and let prune delete any old remote marker files.
|
| 23 |
RESERVED_SYNC_FILENAMES = {".huggingclaw-empty-dir"}
|
|
@@ -287,6 +315,8 @@ def restore_once(api, rid: str):
|
|
| 287 |
tmp = Path(tempfile.mkdtemp(prefix="devdata-restore-"))
|
| 288 |
try:
|
| 289 |
snapshot_download(repo_id=rid, repo_type="dataset", local_dir=str(tmp), local_dir_use_symlinks=False, token=HF_TOKEN)
|
|
|
|
|
|
|
| 290 |
for p in tmp.rglob("*"):
|
| 291 |
rel = p.relative_to(tmp)
|
| 292 |
if str(rel) == ".gitattributes":
|
|
@@ -372,6 +402,8 @@ def sync_loop(api, rid: str):
|
|
| 372 |
tmp = Path(tempfile.mkdtemp(prefix="devdata-snap-"))
|
| 373 |
try:
|
| 374 |
had_copy_failures, protected_large_files = snapshot(JUPYTER_ROOT, tmp)
|
|
|
|
|
|
|
| 375 |
upload_folder(
|
| 376 |
folder_path=str(tmp),
|
| 377 |
repo_id=rid,
|
|
|
|
| 18 |
# Max stale files to delete per commit. Mirrors openclaw-sync.py behaviour.
|
| 19 |
# Override via DEVDATA_PRUNE_BATCH_SIZE.
|
| 20 |
PRUNE_BATCH_SIZE = int((os.environ.get("DEVDATA_PRUNE_BATCH_SIZE", "").strip() or "50"))
|
| 21 |
+
|
| 22 |
+
# huggingface_hub.upload_folder hard-blocks .git/ via DEFAULT_IGNORE_PATTERNS
|
| 23 |
+
# regardless of the ignore_patterns= argument. Escape before upload and
|
| 24 |
+
# unescape after restore so git repos inside the Jupyter workspace survive
|
| 25 |
+
# Space restarts.
|
| 26 |
+
_GIT_ESCAPE = "__dot_git__"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _escape_git_dirs(root: Path) -> None:
|
| 30 |
+
"""Rename every .git dir inside *root* to __dot_git__ before upload_folder."""
|
| 31 |
+
for dirpath, dirnames, _ in os.walk(root, topdown=False):
|
| 32 |
+
for dirname in list(dirnames):
|
| 33 |
+
if dirname == ".git":
|
| 34 |
+
src = Path(dirpath) / ".git"
|
| 35 |
+
dst = Path(dirpath) / _GIT_ESCAPE
|
| 36 |
+
if src.exists() and not dst.exists():
|
| 37 |
+
src.rename(dst)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _unescape_git_dirs(root: Path) -> None:
|
| 41 |
+
"""Rename every __dot_git__ dir inside *root* back to .git after restore."""
|
| 42 |
+
for dirpath, dirnames, _ in os.walk(root, topdown=False):
|
| 43 |
+
for dirname in list(dirnames):
|
| 44 |
+
if dirname == _GIT_ESCAPE:
|
| 45 |
+
src = Path(dirpath) / _GIT_ESCAPE
|
| 46 |
+
dst = Path(dirpath) / ".git"
|
| 47 |
+
if src.exists() and not dst.exists():
|
| 48 |
+
src.rename(dst)
|
| 49 |
# Reserved filenames previously generated by DevData. Never copy or restore
|
| 50 |
# them as user content, and let prune delete any old remote marker files.
|
| 51 |
RESERVED_SYNC_FILENAMES = {".huggingclaw-empty-dir"}
|
|
|
|
| 315 |
tmp = Path(tempfile.mkdtemp(prefix="devdata-restore-"))
|
| 316 |
try:
|
| 317 |
snapshot_download(repo_id=rid, repo_type="dataset", local_dir=str(tmp), local_dir_use_symlinks=False, token=HF_TOKEN)
|
| 318 |
+
# Undo the .git → __dot_git__ escaping applied before upload.
|
| 319 |
+
_unescape_git_dirs(tmp)
|
| 320 |
for p in tmp.rglob("*"):
|
| 321 |
rel = p.relative_to(tmp)
|
| 322 |
if str(rel) == ".gitattributes":
|
|
|
|
| 402 |
tmp = Path(tempfile.mkdtemp(prefix="devdata-snap-"))
|
| 403 |
try:
|
| 404 |
had_copy_failures, protected_large_files = snapshot(JUPYTER_ROOT, tmp)
|
| 405 |
+
# Escape .git → __dot_git__ so upload_folder doesn't hard-block them.
|
| 406 |
+
_escape_git_dirs(tmp)
|
| 407 |
upload_folder(
|
| 408 |
folder_path=str(tmp),
|
| 409 |
repo_id=rid,
|
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>
|
|
@@ -44,7 +44,7 @@
|
|
| 44 |
<div class="panel-title"><h2>Rotation event log</h2><span id="eventCount" class="pill">0</span></div>
|
| 45 |
<div class="toolbar">
|
| 46 |
<input id="q" class="input" placeholder="Filter provider, key, model, event…" aria-label="Filter events">
|
| 47 |
-
<select id="type" class="select" aria-label="Event type"><option value="">All events</option><option value="pick">Picks</option><option value="success">Success</option><option value="rate_limited">Rate limits</option><option value="network_retryable">Network retries</option><option value="pick_retry_fresh">Retry picks</option><option value="auth_failed">Auth failures</option></select>
|
| 48 |
<label class="toggle"><input id="scope" type="checkbox" checked> selected provider only</label>
|
| 49 |
</div>
|
| 50 |
<div id="events" class="events"><div class="empty">Loading rotator events…</div></div>
|
|
@@ -55,30 +55,33 @@
|
|
| 55 |
<script>
|
| 56 |
let state={events:[],providers:[],runtime:{routes:[]},paused:false,selected:localStorage.getItem('hc.keyRotator.provider')||''};
|
| 57 |
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>
|
|
|
|
| 44 |
<div class="panel-title"><h2>Rotation event log</h2><span id="eventCount" class="pill">0</span></div>
|
| 45 |
<div class="toolbar">
|
| 46 |
<input id="q" class="input" placeholder="Filter provider, key, model, event…" aria-label="Filter events">
|
| 47 |
+
<select id="type" class="select" aria-label="Event type"><option value="">All events</option><option value="pick">Picks</option><option value="sticky_pick">Sticky picks</option><option value="task_affinity_pick">Affinity picks</option><option value="success">Success</option><option value="rate_limited">Rate limits</option><option value="network_retryable">Network retries</option><option value="pick_retry_fresh">Retry picks</option><option value="auth_failed">Auth failures</option></select>
|
| 48 |
<label class="toggle"><input id="scope" type="checkbox" checked> selected provider only</label>
|
| 49 |
</div>
|
| 50 |
<div id="events" class="events"><div class="empty">Loading rotator events…</div></div>
|
|
|
|
| 55 |
<script>
|
| 56 |
let state={events:[],providers:[],runtime:{routes:[]},paused:false,selected:localStorage.getItem('hc.keyRotator.provider')||''};
|
| 57 |
const $=id=>document.getElementById(id), HTML_ESCAPE={'&':'&','<':'<','>':'>','"':'"',"'":'''};
|
| 58 |
+
const PICK_TYPES=['pick','sticky_pick','task_affinity_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,26 @@ 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),
|
|
@@ -149,21 +170,30 @@ const STICKY_PROVIDER_SET = new Set(
|
|
| 149 |
);
|
| 150 |
const UNKNOWN_MODEL_SCOPE = '__unknown_model__';
|
| 151 |
|
| 152 |
-
// Task affinity keeps
|
| 153 |
-
//
|
| 154 |
-
//
|
| 155 |
-
// per-request round-robin would spend a different key
|
| 156 |
-
//
|
| 157 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
const RAW_TASK_AFFINITY_MS = parseInt(process.env.KEY_TASK_AFFINITY_MS || '', 10);
|
| 159 |
const TASK_AFFINITY_MS = Math.max(
|
| 160 |
0,
|
| 161 |
-
Number.isFinite(RAW_TASK_AFFINITY_MS) ? RAW_TASK_AFFINITY_MS :
|
| 162 |
);
|
| 163 |
const RAW_TASK_AFFINITY_MAX_REUSES = parseInt(process.env.KEY_TASK_AFFINITY_MAX_REUSES || '', 10);
|
| 164 |
const TASK_AFFINITY_MAX_REUSES = Math.max(
|
| 165 |
0,
|
| 166 |
-
Number.isFinite(RAW_TASK_AFFINITY_MAX_REUSES) ? RAW_TASK_AFFINITY_MAX_REUSES :
|
| 167 |
);
|
| 168 |
|
| 169 |
// Maximum ms to respect from a Retry-After header.
|
|
@@ -179,10 +209,12 @@ const MAX_RETRY_AFTER_MS = Math.max(
|
|
| 179 |
// sleep never causes a proxy timeout. With large key pools (50+) this
|
| 180 |
// path rarely triggers anyway; with 2-3 keys it prevents the rotator from
|
| 181 |
// sleeping longer than the upstream proxy allows.
|
| 182 |
-
//
|
|
|
|
|
|
|
| 183 |
const MAX_KEY_WAIT_MS = Math.max(
|
| 184 |
0,
|
| 185 |
-
parseInt(process.env.KEY_MAX_WAIT_MS || '', 10) ||
|
| 186 |
);
|
| 187 |
|
| 188 |
// Long suspend window for exhausted/invalid keys.
|
|
@@ -195,11 +227,19 @@ 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 |
|
| 201 |
const PROVIDERS = [
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
{ name:'openai', hostname:/(?:^|\.)api\.openai\.com$/i, envPlural:'OPENAI_API_KEYS', envSingular:'OPENAI_API_KEY' },
|
| 204 |
{ name:'gemini', hostname:/(?:^|\.)(?:generativelanguage\.googleapis\.com|aiplatform\.googleapis\.com)$/i,
|
| 205 |
envPlural:'GEMINI_API_KEYS', envSingular:'GEMINI_API_KEY', queryParam:true,
|
|
@@ -277,7 +317,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 +434,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 +457,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 +473,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 +537,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 +566,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';
|
|
@@ -590,7 +657,17 @@ function rememberTaskAffinityKey(p, model, key) {
|
|
| 590 |
// second affinity system on top, otherwise diagnostics and expiry semantics
|
| 591 |
// become harder to reason about.
|
| 592 |
if (isStickyProvider(p)) return;
|
| 593 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 594 |
key,
|
| 595 |
expiresAt: Date.now() + TASK_AFFINITY_MS,
|
| 596 |
remainingReuses: TASK_AFFINITY_MAX_REUSES,
|
|
@@ -630,23 +707,47 @@ function pickAffinitizedKey(p, model) {
|
|
| 630 |
return null;
|
| 631 |
}
|
| 632 |
const inflight = p.inFlight.get(key) || 0;
|
| 633 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
entry.remainingReuses -= 1;
|
| 635 |
entry.expiresAt = Date.now() + TASK_AFFINITY_MS;
|
| 636 |
if (entry.remainingReuses <= 0) p.taskAffinity.delete(bucket);
|
| 637 |
-
|
| 638 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 639 |
return { key, waitMs: 0 };
|
| 640 |
}
|
| 641 |
|
| 642 |
function promoteStickyKeyModel(p, key, fromModel, toModel) {
|
| 643 |
if (!key || !toModel) return;
|
| 644 |
const fromBucket = stickyBucketForProvider(p, fromModel);
|
|
|
|
| 645 |
if (isStickyProvider(p)) {
|
| 646 |
-
|
| 647 |
rememberStickyKey(p, toModel, key);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
}
|
| 649 |
-
if (p.taskAffinity?.get(fromBucket)?.key === key) p.taskAffinity.delete(fromBucket);
|
| 650 |
rememberTaskAffinityKey(p, toModel, key);
|
| 651 |
}
|
| 652 |
|
|
@@ -1068,22 +1169,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);
|
|
@@ -1223,12 +1330,36 @@ function setAuthHeader(headers, key) {
|
|
| 1223 |
return { authorization: val };
|
| 1224 |
}
|
| 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 +1400,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 +1464,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 |
/**
|
|
@@ -1606,19 +1739,12 @@ function buildAttemptFetchArgs(input, init, provider, usedKey) {
|
|
| 1606 |
const openAICompatGemini = isGeminiOpenAICompatPath(rawUrl);
|
| 1607 |
if (!openAICompatGemini) url.searchParams.set('key', usedKey);
|
| 1608 |
|
| 1609 |
-
//
|
| 1610 |
-
//
|
| 1611 |
-
//
|
| 1612 |
-
//
|
| 1613 |
-
//
|
| 1614 |
-
|
| 1615 |
-
? baseHeaders.get('authorization')
|
| 1616 |
-
: (baseHeaders['authorization'] || baseHeaders['Authorization'] || '');
|
| 1617 |
-
const needsBearerAuth = openAICompatGemini ||
|
| 1618 |
-
(existingAuth && String(existingAuth).toLowerCase().startsWith('bearer '));
|
| 1619 |
-
if (needsBearerAuth) {
|
| 1620 |
-
setAuthHeader(baseHeaders, usedKey);
|
| 1621 |
-
}
|
| 1622 |
|
| 1623 |
// With Request input and no explicit init overrides, keep request semantics by cloning shape.
|
| 1624 |
if (inputIsRequest && (!init || Object.keys(initObj).length === 0)) {
|
|
@@ -1642,7 +1768,7 @@ function buildAttemptFetchArgs(input, init, provider, usedKey) {
|
|
| 1642 |
}
|
| 1643 |
|
| 1644 |
if (usedKey) {
|
| 1645 |
-
return [input, { ...initObj, headers:
|
| 1646 |
}
|
| 1647 |
|
| 1648 |
return [input, initObj];
|
|
@@ -1898,6 +2024,55 @@ function wrapUndiciHandler(handler, provider, key, inFlightToken, getModel) {
|
|
| 1898 |
}
|
| 1899 |
};
|
| 1900 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1901 |
const v = target[prop];
|
| 1902 |
return typeof v === 'function' ? v.bind(target) : v;
|
| 1903 |
},
|
|
@@ -1973,15 +2148,16 @@ function patchUndiciDispatch(proto, tag) {
|
|
| 1973 |
if (!isGeminiOpenAICompatPath(pathStr)) pu.searchParams.set('key', key);
|
| 1974 |
newOptions.path = pu.pathname + pu.search;
|
| 1975 |
} catch (_) { /* leave path unchanged on URL parse failure */ }
|
| 1976 |
-
//
|
| 1977 |
-
//
|
| 1978 |
-
|
| 1979 |
-
|
| 1980 |
-
|
| 1981 |
-
}
|
| 1982 |
-
} else {
|
| 1983 |
-
// All other providers: inject / replace Authorization: Bearer
|
| 1984 |
newOptions.headers = uSetHeader(options.headers || {}, 'authorization', `Bearer ${key}`);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1985 |
}
|
| 1986 |
|
| 1987 |
newOptions.body = wrapBodyForModelSniffing(
|
|
@@ -2164,7 +2340,7 @@ function patchFetch() {
|
|
| 2164 |
// Old behaviour fired immediately into a guaranteed 429 (fake cycle).
|
| 2165 |
// Now we sleep until the key's cooldown expires so the request has a
|
| 2166 |
// real chance of succeeding. Capped by MAX_KEY_WAIT_MS (env-tunable,
|
| 2167 |
-
// default
|
| 2168 |
if (key && waitMs > 0 && MAX_KEY_WAIT_MS > 0) {
|
| 2169 |
const actualWait = Math.min(waitMs, MAX_KEY_WAIT_MS);
|
| 2170 |
await sleep(actualWait);
|
|
@@ -2249,14 +2425,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,43 +2457,56 @@ 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 |
-
//
|
| 2283 |
-
//
|
| 2284 |
-
//
|
| 2285 |
-
//
|
|
|
|
| 2286 |
const existingHeaders = (typeof options === 'object' && !(options instanceof URL) && options.headers)
|
| 2287 |
? options.headers
|
| 2288 |
: (hasOptionsArg ? args[1].headers : undefined);
|
| 2289 |
-
const
|
| 2290 |
-
const needsBearer = isGeminiOpenAICompatPath(u.pathname) || String(authVal).toLowerCase().startsWith('bearer ');
|
| 2291 |
-
const patchedHeaders = needsBearer
|
| 2292 |
-
? setAuthHeader(existingHeaders, key)
|
| 2293 |
-
: existingHeaders;
|
| 2294 |
if (typeof options === 'object' && !(options instanceof URL)) {
|
| 2295 |
args[0] = { ...options, path:`${u.pathname}${u.search}`, headers: patchedHeaders };
|
| 2296 |
} else {
|
| 2297 |
args[0] = u.toString();
|
| 2298 |
-
if (
|
| 2299 |
-
|
| 2300 |
-
|
| 2301 |
-
|
| 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:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2310 |
} else if (options && typeof options === 'object') {
|
| 2311 |
-
args[0] = { ...options, headers:
|
| 2312 |
}
|
| 2313 |
}
|
| 2314 |
}
|
|
@@ -2392,9 +2590,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 +2623,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 +2668,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,
|
|
@@ -2473,7 +2678,9 @@ if (hasProviderKeys) {
|
|
| 2473 |
errorBodySniffMaxBytes: ERROR_BODY_SNIFF_MAX_BYTES,
|
| 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 |
+
// Task-affinity keys: same reasoning as sticky — in-flight leases are local
|
| 87 |
+
// bookkeeping only. When the affinity key reaches MAX_INFLIGHT_PER_KEY,
|
| 88 |
+
// re-using it (with a warning) keeps the whole task on one key. The
|
| 89 |
+
// alternative — dropping affinity and letting round-robin pick a new key —
|
| 90 |
+
// causes exactly the mid-task API-key switch the user observes.
|
| 91 |
+
// FIX: default changed to true so non-sticky providers (Anthropic, OpenAI, etc.)
|
| 92 |
+
// are protected from mid-task rotation just like Gemini sticky keys.
|
| 93 |
+
const TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION = !/^(0|false|no|off)$/i.test(
|
| 94 |
+
String(process.env.KEY_AFFINITY_IGNORE_INFLIGHT_SATURATION || 'true').trim(),
|
| 95 |
+
);
|
| 96 |
const COOLDOWN_JITTER_PCT = Math.min(
|
| 97 |
50,
|
| 98 |
Math.max(0, parseInt(process.env.KEY_BLACKLIST_JITTER_PCT || '', 10) || 15),
|
|
|
|
| 170 |
);
|
| 171 |
const UNKNOWN_MODEL_SCOPE = '__unknown_model__';
|
| 172 |
|
| 173 |
+
// Task affinity keeps sequential non-sticky provider calls on the same key for
|
| 174 |
+
// an entire task window. OpenClaw/HuggingClaw splits one user task into many
|
| 175 |
+
// upstream requests (planning → tool calls → result synthesis → follow-ups);
|
| 176 |
+
// pure per-request round-robin would spend a different key on every chunk and
|
| 177 |
+
// cause visible mid-task provider switches.
|
| 178 |
+
//
|
| 179 |
+
// FIX: defaults raised from 30 s / 3 reuses to 300 s / 50 reuses.
|
| 180 |
+
// - 30 s was too short: complex tasks (deep research, multi-tool chains) easily
|
| 181 |
+
// exceed it, causing a key switch at the 31st second.
|
| 182 |
+
// - 3 reuses was too low: a single OpenClaw task can involve 5-20+ upstream
|
| 183 |
+
// calls (think → tool → observe → think → tool → synthesize …). After the
|
| 184 |
+
// 3rd call the rotator picked a fresh key mid-task.
|
| 185 |
+
// Round-robin load-balancing still resumes when a *new* task starts (affinity
|
| 186 |
+
// expires or key fails), so fairness across keys is preserved over time.
|
| 187 |
+
// Sticky providers (Gemini) use their stronger until-failure pin and are unaffected.
|
| 188 |
const RAW_TASK_AFFINITY_MS = parseInt(process.env.KEY_TASK_AFFINITY_MS || '', 10);
|
| 189 |
const TASK_AFFINITY_MS = Math.max(
|
| 190 |
0,
|
| 191 |
+
Number.isFinite(RAW_TASK_AFFINITY_MS) ? RAW_TASK_AFFINITY_MS : 300_000, // 5 min — covers full task burst
|
| 192 |
);
|
| 193 |
const RAW_TASK_AFFINITY_MAX_REUSES = parseInt(process.env.KEY_TASK_AFFINITY_MAX_REUSES || '', 10);
|
| 194 |
const TASK_AFFINITY_MAX_REUSES = Math.max(
|
| 195 |
0,
|
| 196 |
+
Number.isFinite(RAW_TASK_AFFINITY_MAX_REUSES) ? RAW_TASK_AFFINITY_MAX_REUSES : 50, // 50 calls — covers any task
|
| 197 |
);
|
| 198 |
|
| 199 |
// Maximum ms to respect from a Retry-After header.
|
|
|
|
| 209 |
// sleep never causes a proxy timeout. With large key pools (50+) this
|
| 210 |
// path rarely triggers anyway; with 2-3 keys it prevents the rotator from
|
| 211 |
// sleeping longer than the upstream proxy allows.
|
| 212 |
+
// Default is 0 (disabled) — fire-and-miss on all-suspended pools.
|
| 213 |
+
// Set to a positive value (e.g. 20000) to sleep up to that many ms for the
|
| 214 |
+
// soonest-recovering key instead of immediately forwarding into a guaranteed 429.
|
| 215 |
const MAX_KEY_WAIT_MS = Math.max(
|
| 216 |
0,
|
| 217 |
+
parseInt(process.env.KEY_MAX_WAIT_MS || '', 10) || 0,
|
| 218 |
);
|
| 219 |
|
| 220 |
// Long suspend window for exhausted/invalid keys.
|
|
|
|
| 227 |
* Short keys (≤12 chars) are fully masked as "***".
|
| 228 |
*/
|
| 229 |
const keyMask = (k) => (k && k.length > 12 ? `${k.slice(0, 4)}...${k.slice(-6)}` : '***');
|
| 230 |
+
const keyFingerprint = (k) => {
|
| 231 |
+
try { return k ? crypto.createHash('sha256').update(String(k)).digest('hex').slice(0, 12) : null; }
|
| 232 |
+
catch (_) { return null; }
|
| 233 |
+
};
|
| 234 |
|
| 235 |
// ─── Provider definitions ────────────────────────────────────────────────────
|
| 236 |
|
| 237 |
const PROVIDERS = [
|
| 238 |
+
// Anthropic's native REST API (api.anthropic.com) authenticates via the
|
| 239 |
+
// `x-api-key` header, NOT `Authorization: Bearer`. Injecting only a Bearer
|
| 240 |
+
// header leaves the caller's original x-api-key in place, so the rotated pool
|
| 241 |
+
// is never used. authHeader pins the correct header for key injection.
|
| 242 |
+
{ name:'anthropic', hostname:/(?:^|\.)api\.anthropic\.com$/i, envPlural:'ANTHROPIC_API_KEYS', envSingular:'ANTHROPIC_API_KEY', authHeader:'x-api-key' },
|
| 243 |
{ name:'openai', hostname:/(?:^|\.)api\.openai\.com$/i, envPlural:'OPENAI_API_KEYS', envSingular:'OPENAI_API_KEY' },
|
| 244 |
{ name:'gemini', hostname:/(?:^|\.)(?:generativelanguage\.googleapis\.com|aiplatform\.googleapis\.com)$/i,
|
| 245 |
envPlural:'GEMINI_API_KEYS', envSingular:'GEMINI_API_KEY', queryParam:true,
|
|
|
|
| 317 |
ts: new Date().toISOString(),
|
| 318 |
type,
|
| 319 |
provider: p?.name || extra.provider || 'system',
|
| 320 |
+
...(idx >= 0 ? { slot: idx + 1, total: p.keys.length, key: keyMask(key), kid: keyFingerprint(key) } : {}),
|
| 321 |
...extra,
|
| 322 |
};
|
| 323 |
const dir = path.dirname(EVENT_LOG_FILE);
|
|
|
|
| 434 |
|
| 435 |
async function parseResponseErrorInfo(response) {
|
| 436 |
if (!response || response.status < 400 || typeof response.clone !== 'function') return null;
|
| 437 |
+
const deadline = Date.now() + ERROR_BODY_WAIT_MS;
|
| 438 |
+
const remainingWait = () => Math.max(0, deadline - Date.now());
|
| 439 |
+
const withDeadline = async (promise) => {
|
| 440 |
+
const waitMs = remainingWait();
|
| 441 |
+
if (waitMs <= 0) return { timedOut: true };
|
| 442 |
+
let timer = null;
|
| 443 |
+
try {
|
| 444 |
+
return await Promise.race([
|
| 445 |
+
promise.then(value => ({ value }), error => ({ error })),
|
| 446 |
+
new Promise(resolve => { timer = setTimeout(() => resolve({ timedOut: true }), waitMs); }),
|
| 447 |
+
]);
|
| 448 |
+
} finally {
|
| 449 |
+
if (timer) clearTimeout(timer);
|
| 450 |
+
}
|
| 451 |
+
};
|
| 452 |
try {
|
| 453 |
const clone = response.clone();
|
| 454 |
if (clone.body && typeof clone.body.getReader === 'function') {
|
|
|
|
| 457 |
let total = 0;
|
| 458 |
try {
|
| 459 |
while (total < ERROR_BODY_SNIFF_MAX_BYTES) {
|
| 460 |
+
const result = await withDeadline(reader.read());
|
| 461 |
+
if (result.timedOut || result.error) break;
|
| 462 |
+
const { done, value } = result.value || {};
|
| 463 |
if (done) break;
|
| 464 |
const buf = Buffer.isBuffer(value)
|
| 465 |
? value
|
|
|
|
| 473 |
total += slice.length;
|
| 474 |
}
|
| 475 |
} finally {
|
| 476 |
+
try { reader.cancel().catch?.(() => {}); } catch (_) {}
|
| 477 |
}
|
| 478 |
+
return chunks.length ? parseProviderErrorInfo(Buffer.concat(chunks).toString('utf8')) : null;
|
| 479 |
}
|
| 480 |
+
const result = await withDeadline(clone.text());
|
| 481 |
+
if (result.timedOut || result.error || typeof result.value !== 'string') return null;
|
| 482 |
+
return parseProviderErrorInfo(result.value.slice(0, ERROR_BODY_SNIFF_MAX_BYTES));
|
| 483 |
} catch (_) {
|
| 484 |
return null;
|
| 485 |
}
|
|
|
|
| 537 |
return info;
|
| 538 |
}
|
| 539 |
|
| 540 |
+
function normalizeHttpStatusCode(status) {
|
| 541 |
+
const n = Number(status);
|
| 542 |
+
return Number.isFinite(n) ? Math.trunc(n) : 0;
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
function statusNeedsErrorBodyForScope(status) {
|
| 546 |
+
status = normalizeHttpStatusCode(status);
|
| 547 |
+
// Production classification needs provider error bodies for more than Gemini
|
| 548 |
+
// 403s: many gateways encode quota/auth/transient reasons in JSON even when
|
| 549 |
+
// the HTTP code is generic (400/404/422/5xx). We still cap the wait with
|
| 550 |
+
// ERROR_BODY_WAIT_MS, so missing bodies close quickly instead of aging into
|
| 551 |
+
// lease-only/pending dashboard noise.
|
| 552 |
+
return status >= 400 && status < 600;
|
| 553 |
}
|
| 554 |
|
| 555 |
function classifyProviderFailure(p, status, errorInfo) {
|
| 556 |
+
status = normalizeHttpStatusCode(status);
|
| 557 |
const haystack = [
|
| 558 |
errorInfo?.code,
|
| 559 |
errorInfo?.type,
|
|
|
|
| 566 |
const looksAuth = /auth|unauthori[sz]ed|invalid.?api.?key|invalid.?key|permission|forbidden|billing|credit|payment|required/.test(haystack);
|
| 567 |
const looksTransient = /overload|temporar|unavailable|timeout|backend|internal|server.?error|try.?again|capacity/.test(haystack);
|
| 568 |
|
| 569 |
+
if (status >= 100 && status < 400) return 'success';
|
| 570 |
if (status === 401) return 'auth';
|
| 571 |
if (status === 402) return 'rate';
|
| 572 |
if (status === 429) return 'rate';
|
| 573 |
+
if (status === 529) return looksRateOrQuota ? 'rate' : 'transient';
|
| 574 |
// Google/Vertex and some Google APIs can return 403 for quota/rate conditions
|
| 575 |
// (rateLimitExceeded / QUOTA_EXCEEDED), while plain 403 remains auth/permission.
|
| 576 |
if (status === 403) return looksRateOrQuota ? 'rate' : 'auth';
|
|
|
|
| 657 |
// second affinity system on top, otherwise diagnostics and expiry semantics
|
| 658 |
// become harder to reason about.
|
| 659 |
if (isStickyProvider(p)) return;
|
| 660 |
+
const bucket = stickyBucketForProvider(p, model);
|
| 661 |
+
// FIX: do NOT reset a still-valid affinity slot for the same key.
|
| 662 |
+
// rememberTaskAffinityKey is called from nextKey's round-robin path every time
|
| 663 |
+
// ANY key is picked (including the saturated-reuse fallback). Overwriting a
|
| 664 |
+
// live entry here would silently refill remainingReuses and extend expiresAt,
|
| 665 |
+
// hiding the mid-task switch that TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION is
|
| 666 |
+
// meant to guard against. Only create/replace when the bucket is empty,
|
| 667 |
+
// pointing at a different key, or the existing entry has expired/exhausted.
|
| 668 |
+
const existing = p.taskAffinity.get(bucket);
|
| 669 |
+
if (existing && existing.key === key && Date.now() < existing.expiresAt && (existing.remainingReuses || 0) > 0) return;
|
| 670 |
+
p.taskAffinity.set(bucket, {
|
| 671 |
key,
|
| 672 |
expiresAt: Date.now() + TASK_AFFINITY_MS,
|
| 673 |
remainingReuses: TASK_AFFINITY_MAX_REUSES,
|
|
|
|
| 707 |
return null;
|
| 708 |
}
|
| 709 |
const inflight = p.inFlight.get(key) || 0;
|
| 710 |
+
const saturated = inflight >= MAX_INFLIGHT_PER_KEY;
|
| 711 |
+
// FIX: when the affinity key is saturated, do NOT return null.
|
| 712 |
+
// Returning null here drops affinity and sends the caller back to round-robin,
|
| 713 |
+
// which picks a DIFFERENT key mid-task — the exact bug reported.
|
| 714 |
+
// In-flight counts are local safety leases (they expire via INFLIGHT_TTL_MS),
|
| 715 |
+
// not real provider verdicts; a saturated key is almost certainly still healthy.
|
| 716 |
+
// Mirror sticky-provider behaviour: stay pinned and warn, rotate only on a
|
| 717 |
+
// real provider failure (auth / rate / transient from handleStatus).
|
| 718 |
+
if (saturated && !TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION) return null;
|
| 719 |
entry.remainingReuses -= 1;
|
| 720 |
entry.expiresAt = Date.now() + TASK_AFFINITY_MS;
|
| 721 |
if (entry.remainingReuses <= 0) p.taskAffinity.delete(bucket);
|
| 722 |
+
if (saturated) {
|
| 723 |
+
warn(`[key-rotator] ${p.name}: task-affinity key saturated but staying pinned on ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''} inflight=${inflight + 1}/${MAX_INFLIGHT_PER_KEY} remaining-reuses=${Math.max(0, entry.remainingReuses || 0)} (affinity protects mid-task key switch)`);
|
| 724 |
+
emitEvent('task_affinity_saturated_reuse', p, key, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY, ttlMs: TASK_AFFINITY_MS, remainingReuses: Math.max(0, entry.remainingReuses || 0), sticky: false, reason: 'affinity_until_real_failure' });
|
| 725 |
+
} else {
|
| 726 |
+
verbosePickLog(`[key-rotator] ${p.name}: task-affinity picked ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''} inflight=${inflight + 1}/${MAX_INFLIGHT_PER_KEY} remaining-reuses=${Math.max(0, entry.remainingReuses)}`);
|
| 727 |
+
emitEvent('task_affinity_pick', p, key, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY, ttlMs: TASK_AFFINITY_MS, remainingReuses: Math.max(0, entry.remainingReuses), sticky: false });
|
| 728 |
+
}
|
| 729 |
return { key, waitMs: 0 };
|
| 730 |
}
|
| 731 |
|
| 732 |
function promoteStickyKeyModel(p, key, fromModel, toModel) {
|
| 733 |
if (!key || !toModel) return;
|
| 734 |
const fromBucket = stickyBucketForProvider(p, fromModel);
|
| 735 |
+
const toBucket = stickyBucketForProvider(p, toModel);
|
| 736 |
if (isStickyProvider(p)) {
|
| 737 |
+
// Pin the now-known model bucket so future picks that DO know the model reuse it.
|
| 738 |
rememberStickyKey(p, toModel, key);
|
| 739 |
+
// Keep the unknown-model fallback bucket pinned to this key instead of
|
| 740 |
+
// vacating it. OpenAI-compatible Gemini (and node:http) requests routinely
|
| 741 |
+
// reach nextKey() before the body reveals the model, so the *next* request
|
| 742 |
+
// also picks under the unknown bucket. Deleting it here sent every such
|
| 743 |
+
// request back to round-robin, defeating stickiness entirely (keys rotated
|
| 744 |
+
// on every call). The fallback pin is still cleared on a real provider
|
| 745 |
+
// failure via clearStickyKey()'s fallback-bucket path.
|
| 746 |
+
if (fromBucket !== toBucket && !p.stickyKeys.has(fromBucket)) {
|
| 747 |
+
rememberStickyKey(p, fromModel, key);
|
| 748 |
+
}
|
| 749 |
}
|
| 750 |
+
if (fromBucket !== toBucket && p.taskAffinity?.get(fromBucket)?.key === key) p.taskAffinity.delete(fromBucket);
|
| 751 |
rememberTaskAffinityKey(p, toModel, key);
|
| 752 |
}
|
| 753 |
|
|
|
|
| 1169 |
const stickyKey = p.stickyKeys.get(stickyBucketForProvider(p, model));
|
| 1170 |
if (stickyKey && p.keys.includes(stickyKey) && isActive(p, stickyKey, model)) {
|
| 1171 |
const inflight = p.inFlight.get(stickyKey) || 0;
|
| 1172 |
+
if (inflight < MAX_INFLIGHT_PER_KEY || STICKY_IGNORE_INFLIGHT_SATURATION) {
|
| 1173 |
rememberTaskAffinityKey(p, model, stickyKey);
|
| 1174 |
+
const saturated = inflight >= MAX_INFLIGHT_PER_KEY;
|
| 1175 |
+
if (saturated) {
|
| 1176 |
+
// In-flight count is a local safety lease, not a provider verdict.
|
| 1177 |
+
// For sticky providers, only a real provider failure should move the
|
| 1178 |
+
// bucket to a different key; otherwise long streams/abandoned callers
|
| 1179 |
+
// make Gemini appear to "fail" every key by lease expiry alone.
|
| 1180 |
+
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}`);
|
| 1181 |
+
emitEvent('sticky_saturated_reuse', p, stickyKey, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY, sticky: true, reason: 'sticky_until_real_failure' });
|
| 1182 |
+
} else {
|
| 1183 |
+
verbosePickLog(`[key-rotator] ${p.name}: sticky picked ${keySlot(p, stickyKey)}${keyMask(stickyKey)}${model ? ` model=${model}` : ''} inflight=${inflight + 1}/${MAX_INFLIGHT_PER_KEY}`);
|
| 1184 |
+
emitEvent('sticky_pick', p, stickyKey, { model, inflight: inflight + 1, maxInflight: MAX_INFLIGHT_PER_KEY });
|
| 1185 |
+
}
|
| 1186 |
return { key: stickyKey, waitMs: 0 };
|
| 1187 |
}
|
| 1188 |
|
| 1189 |
+
// Operator opted out of strict sticky pinning. In that mode, saturation can
|
| 1190 |
+
// rotate away from the sticky key, but this is no longer the default for
|
| 1191 |
+
// Gemini because lease-only saturation is not a real key failure.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1192 |
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}`);
|
| 1193 |
+
emitEvent('sticky_saturated_rotate', p, stickyKey, { model, inflight, maxInflight: MAX_INFLIGHT_PER_KEY, sticky: true, reason: 'operator_opt_out' });
|
| 1194 |
clearStickyKey(p, stickyKey, model);
|
| 1195 |
} else if (stickyKey) {
|
| 1196 |
clearStickyKey(p, stickyKey, model);
|
|
|
|
| 1330 |
return { authorization: val };
|
| 1331 |
}
|
| 1332 |
|
| 1333 |
+
// Provider-aware auth injection. Most providers use `Authorization: Bearer <key>`,
|
| 1334 |
+
// but some native APIs read the key from a different header (e.g. Anthropic uses
|
| 1335 |
+
// `x-api-key`). For those, set the raw key on the provider's header instead of a
|
| 1336 |
+
// Bearer token so the rotated key is actually the one the upstream API reads.
|
| 1337 |
+
function applyProviderAuthHeaders(headers, provider, key) {
|
| 1338 |
+
if (!key) return headers;
|
| 1339 |
+
const headerName = provider && provider.authHeader ? String(provider.authHeader) : 'authorization';
|
| 1340 |
+
const value = headerName.toLowerCase() === 'authorization' ? `Bearer ${key}` : key;
|
| 1341 |
+
// uSetHeader handles every header shape used at the call sites — undici flat
|
| 1342 |
+
// arrays, fetch Headers/Map, and plain objects — and replaces case-insensitively.
|
| 1343 |
+
return uSetHeader(headers || {}, headerName, value);
|
| 1344 |
+
}
|
| 1345 |
+
|
| 1346 |
function handleStatus(p, key, status, model, retryAfterMs, errorInfo, extra = {}) {
|
| 1347 |
if (!p || !key) return;
|
| 1348 |
+
status = normalizeHttpStatusCode(status);
|
| 1349 |
retryAfterMs = retryAfterMs || errorInfo?.retryAfterMs || 0;
|
| 1350 |
const failureKind = classifyProviderFailure(p, status, errorInfo);
|
| 1351 |
const errorFields = { ...providerErrorFields(errorInfo), ...extra };
|
| 1352 |
|
| 1353 |
+
// Count every final HTTP success code as success before any key-failure logic.
|
| 1354 |
+
// Some transports/providers can surface 1xx/204/206/304-style successful
|
| 1355 |
+
// completions; these must reset the selected key and show as success in the
|
| 1356 |
+
// manager instead of falling through as an unclassified/no-op outcome.
|
| 1357 |
+
if (failureKind === 'success') {
|
| 1358 |
+
recordSuccess(p, key, model);
|
| 1359 |
+
emitEvent('success', p, key, { status, model, ...errorFields });
|
| 1360 |
+
return;
|
| 1361 |
+
}
|
| 1362 |
+
|
| 1363 |
if (failureKind === 'auth') {
|
| 1364 |
// Invalid/expired/unauthorized key — always a global (not model-scoped) blacklist.
|
| 1365 |
let ks = p.keyState.get(key);
|
|
|
|
| 1400 |
return;
|
| 1401 |
}
|
| 1402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1403 |
if (status >= 400) {
|
| 1404 |
// Non-key failures (malformed request, missing model, unsupported feature,
|
| 1405 |
// content/safety/request-size errors, etc.) still need an explicit outcome
|
|
|
|
| 1464 |
clearTaskAffinityKey(p, key, model);
|
| 1465 |
warn(`[key-rotator] ${p.name}: retryable network ${name || 'Error'}${code ? ` code=${code}` : ''} on ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''}`);
|
| 1466 |
emitEvent('network_retryable', p, key, { model, ...extra, name: name || 'Error', code });
|
| 1467 |
+
return;
|
| 1468 |
}
|
| 1469 |
+
|
| 1470 |
+
// Always close the dashboard/request lifecycle with a real observed outcome.
|
| 1471 |
+
// Unknown transport errors are not enough evidence to punish or rotate a key,
|
| 1472 |
+
// but emitting nothing leaves the manager showing phantom pending/lease-only
|
| 1473 |
+
// activity and makes sticky providers look broken.
|
| 1474 |
+
warn(`[key-rotator] ${p.name}: transport unknown ${name || 'Error'}${code ? ` code=${code}` : ''} on ${keySlot(p, key)}${keyMask(key)}${model ? ` model=${model}` : ''} (key not penalized)`);
|
| 1475 |
+
emitEvent('transport_unknown', p, key, { model, ...extra, name: name || 'Error', code, message: message.slice(0, 240), classifiedAs: 'non_key_transport_error' });
|
| 1476 |
}
|
| 1477 |
|
| 1478 |
/**
|
|
|
|
| 1739 |
const openAICompatGemini = isGeminiOpenAICompatPath(rawUrl);
|
| 1740 |
if (!openAICompatGemini) url.searchParams.set('key', usedKey);
|
| 1741 |
|
| 1742 |
+
// ★ FIX: Always set Bearer auth for Gemini requests with a key.
|
| 1743 |
+
// The ?key= approach only works for older Google APIs. Newer endpoints
|
| 1744 |
+
// like /v1beta/embeddings require Bearer auth. Setting both is safe —
|
| 1745 |
+
// Google APIs accept either format, and this fixes the 401 auth error
|
| 1746 |
+
// on memory/embedding calls that were failing before the key rotator.
|
| 1747 |
+
setAuthHeader(baseHeaders, usedKey);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1748 |
|
| 1749 |
// With Request input and no explicit init overrides, keep request semantics by cloning shape.
|
| 1750 |
if (inputIsRequest && (!init || Object.keys(initObj).length === 0)) {
|
|
|
|
| 1768 |
}
|
| 1769 |
|
| 1770 |
if (usedKey) {
|
| 1771 |
+
return [input, { ...initObj, headers: applyProviderAuthHeaders(baseHeaders, provider, usedKey) }];
|
| 1772 |
}
|
| 1773 |
|
| 1774 |
return [input, initObj];
|
|
|
|
| 2024 |
}
|
| 2025 |
};
|
| 2026 |
}
|
| 2027 |
+
// ── undici v6+/v7/v8 dispatch handler interface ──
|
| 2028 |
+
// Newer undici (OpenClaw bundles undici 8) no longer calls the classic
|
| 2029 |
+
// onHeaders/onData/onComplete/onError methods; it calls onResponseStart/
|
| 2030 |
+
// onResponseData/onResponseEnd/onResponseError instead (note the leading
|
| 2031 |
+
// `controller` argument and statusCode at index 1). Without instrumenting
|
| 2032 |
+
// these, status accounting (success + rate/auth classification) and the
|
| 2033 |
+
// in-flight lease release never run, so successful calls show success=0
|
| 2034 |
+
// and leak the lease until it TTL-expires (inflight_lease_expired).
|
| 2035 |
+
// The shared `settled`/`statusHandled` guards make this safe even if a
|
| 2036 |
+
// future undici were to emit both interfaces for one request.
|
| 2037 |
+
if (prop === 'onResponseStart') {
|
| 2038 |
+
return function (controller, sc, headers, statusMessage) {
|
| 2039 |
+
statusCode = sc;
|
| 2040 |
+
retryAfterMs = parseRetryAfterMs(uGetHeader(headers, 'retry-after'));
|
| 2041 |
+
if (handleHeadersStatus()) {
|
| 2042 |
+
settle(() => {});
|
| 2043 |
+
} else if (statusNeedsErrorBodyForScope(statusCode) && !bodyWaitTimer) {
|
| 2044 |
+
bodyWaitTimer = setTimeout(() => {
|
| 2045 |
+
settle(() => { handleHeadersStatus(true); });
|
| 2046 |
+
}, ERROR_BODY_WAIT_MS);
|
| 2047 |
+
bodyWaitTimer.unref?.();
|
| 2048 |
+
}
|
| 2049 |
+
return target.onResponseStart ? target.onResponseStart.call(target, controller, sc, headers, statusMessage) : undefined;
|
| 2050 |
+
};
|
| 2051 |
+
}
|
| 2052 |
+
if (prop === 'onResponseData') {
|
| 2053 |
+
return function (controller, chunk) {
|
| 2054 |
+
collectErrorBody(chunk);
|
| 2055 |
+
return target.onResponseData ? target.onResponseData.call(target, controller, chunk) : undefined;
|
| 2056 |
+
};
|
| 2057 |
+
}
|
| 2058 |
+
if (prop === 'onResponseEnd') {
|
| 2059 |
+
return function (controller, trailers) {
|
| 2060 |
+
try {
|
| 2061 |
+
return target.onResponseEnd ? target.onResponseEnd.call(target, controller, trailers) : undefined;
|
| 2062 |
+
} finally {
|
| 2063 |
+
settle(() => { handleHeadersStatus(true); });
|
| 2064 |
+
}
|
| 2065 |
+
};
|
| 2066 |
+
}
|
| 2067 |
+
if (prop === 'onResponseError') {
|
| 2068 |
+
return function (controller, err) {
|
| 2069 |
+
try {
|
| 2070 |
+
return target.onResponseError ? target.onResponseError.call(target, controller, err) : undefined;
|
| 2071 |
+
} finally {
|
| 2072 |
+
settle(() => { if (!statusHandled) { try { handleTransportError(provider, key, err, currentModel(), { requestId: inFlightToken?.requestId }); } catch (_) {} } });
|
| 2073 |
+
}
|
| 2074 |
+
};
|
| 2075 |
+
}
|
| 2076 |
const v = target[prop];
|
| 2077 |
return typeof v === 'function' ? v.bind(target) : v;
|
| 2078 |
},
|
|
|
|
| 2148 |
if (!isGeminiOpenAICompatPath(pathStr)) pu.searchParams.set('key', key);
|
| 2149 |
newOptions.path = pu.pathname + pu.search;
|
| 2150 |
} catch (_) { /* leave path unchanged on URL parse failure */ }
|
| 2151 |
+
// ★ FIX: Always set Bearer auth for Gemini requests with a key.
|
| 2152 |
+
// The ?key= approach only works for older Google APIs. Newer endpoints
|
| 2153 |
+
// like /v1beta/embeddings require Bearer auth. Setting both is safe —
|
| 2154 |
+
// Google APIs accept either format, and this fixes the 401 auth error
|
| 2155 |
+
// on memory/embedding calls that were failing before the key rotator.
|
|
|
|
|
|
|
|
|
|
| 2156 |
newOptions.headers = uSetHeader(options.headers || {}, 'authorization', `Bearer ${key}`);
|
| 2157 |
+
} else {
|
| 2158 |
+
// All other providers: inject / replace the provider's auth header
|
| 2159 |
+
// (Authorization: Bearer for most; x-api-key for Anthropic, etc.)
|
| 2160 |
+
newOptions.headers = applyProviderAuthHeaders(options.headers || {}, provider, key);
|
| 2161 |
}
|
| 2162 |
|
| 2163 |
newOptions.body = wrapBodyForModelSniffing(
|
|
|
|
| 2340 |
// Old behaviour fired immediately into a guaranteed 429 (fake cycle).
|
| 2341 |
// Now we sleep until the key's cooldown expires so the request has a
|
| 2342 |
// real chance of succeeding. Capped by MAX_KEY_WAIT_MS (env-tunable,
|
| 2343 |
+
// default 0 / disabled) so we never stall indefinitely.
|
| 2344 |
if (key && waitMs > 0 && MAX_KEY_WAIT_MS > 0) {
|
| 2345 |
const actualWait = Math.min(waitMs, MAX_KEY_WAIT_MS);
|
| 2346 |
await sleep(actualWait);
|
|
|
|
| 2425 |
|
| 2426 |
try {
|
| 2427 |
const options = args[0];
|
| 2428 |
+
const hasOptionsArg = args[1] && typeof args[1] === 'object' && typeof args[1].on !== 'function';
|
| 2429 |
+
const optionHeaders = (() => {
|
| 2430 |
+
const first = options && typeof options === 'object' ? options.headers : undefined;
|
| 2431 |
+
const second = hasOptionsArg ? args[1].headers : undefined;
|
| 2432 |
+
if (!first) return second;
|
| 2433 |
+
if (!second) return first;
|
| 2434 |
+
return { ...first, ...second };
|
| 2435 |
+
})();
|
| 2436 |
const provider = resolveProviderForUrl(options, optionHeaders);
|
| 2437 |
|
| 2438 |
if (provider) {
|
| 2439 |
+
// Extract model for per-model-limit providers from the effective request path.
|
| 2440 |
+
const pathStr = hasOptionsArg && args[1].path
|
| 2441 |
+
? args[1].path
|
| 2442 |
+
: typeof options === 'object' && options.path
|
| 2443 |
+
? options.path
|
| 2444 |
+
: (typeof options === 'string' || options instanceof URL) ? String(options) : '';
|
| 2445 |
const model = provider.perModelLimits
|
| 2446 |
? (pathStr.match(/\/models\/([^/:?]+)/)?.[1]?.toLowerCase() || null)
|
| 2447 |
: null;
|
|
|
|
| 2457 |
usedKey = key; usedProvider = provider; usedModel = model;
|
| 2458 |
usedInFlight = beginInFlight(usedProvider, usedKey, usedModel);
|
| 2459 |
if (provider.queryParam) {
|
|
|
|
| 2460 |
const u = new URL(String(
|
| 2461 |
typeof options === 'string' || options instanceof URL
|
| 2462 |
? options
|
| 2463 |
+
: `${options.protocol || 'https:'}//${options.hostname || options.host || 'localhost'}${options.path || '/'}`
|
| 2464 |
));
|
| 2465 |
+
// node:http merges request(url, options) with options taking
|
| 2466 |
+
// precedence, including `path`. If callers pass an override path in
|
| 2467 |
+
// the second arg, inject into that effective path too; otherwise the
|
| 2468 |
+
// key added to the URL arg can be silently discarded by Node.
|
| 2469 |
+
if (hasOptionsArg && args[1].path) {
|
| 2470 |
+
const override = new URL(String(args[1].path), u);
|
| 2471 |
+
u.pathname = override.pathname;
|
| 2472 |
+
u.search = override.search;
|
| 2473 |
+
}
|
| 2474 |
if (!isGeminiOpenAICompatPath(u.pathname)) u.searchParams.set('key', key);
|
| 2475 |
+
// ★ FIX: Always set Bearer auth for Gemini requests with a key.
|
| 2476 |
+
// The ?key= approach only works for older Google APIs. Newer endpoints
|
| 2477 |
+
// like /v1beta/embeddings require Bearer auth. Setting both is safe —
|
| 2478 |
+
// Google APIs accept either format, and this fixes the 401 auth error
|
| 2479 |
+
// on memory/embedding calls that were failing before the key rotator.
|
| 2480 |
const existingHeaders = (typeof options === 'object' && !(options instanceof URL) && options.headers)
|
| 2481 |
? options.headers
|
| 2482 |
: (hasOptionsArg ? args[1].headers : undefined);
|
| 2483 |
+
const patchedHeaders = setAuthHeader(existingHeaders, key);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2484 |
if (typeof options === 'object' && !(options instanceof URL)) {
|
| 2485 |
args[0] = { ...options, path:`${u.pathname}${u.search}`, headers: patchedHeaders };
|
| 2486 |
} else {
|
| 2487 |
args[0] = u.toString();
|
| 2488 |
+
if (hasOptionsArg) {
|
| 2489 |
+
args[1] = { ...args[1], path:`${u.pathname}${u.search}`, headers: patchedHeaders };
|
| 2490 |
+
} else {
|
| 2491 |
+
args[1] = { headers: patchedHeaders };
|
| 2492 |
}
|
| 2493 |
}
|
| 2494 |
} else if (typeof options === 'string' || options instanceof URL) {
|
| 2495 |
const u = new URL(String(options));
|
| 2496 |
+
const extra = hasOptionsArg ? args[1] : {};
|
| 2497 |
args[0] = { protocol:u.protocol, hostname:u.hostname, port:u.port,
|
| 2498 |
path:`${u.pathname}${u.search}`, ...extra,
|
| 2499 |
+
headers:applyProviderAuthHeaders(extra.headers, provider, key) };
|
| 2500 |
+
// We have folded the second options argument into args[0]. Leaving it
|
| 2501 |
+
// in place would call http.request(options, options, cb), where Node
|
| 2502 |
+
// expects the second argument to be the callback and can throw or drop
|
| 2503 |
+
// the real callback for non-query providers such as OpenAI/Anthropic.
|
| 2504 |
+
if (hasOptionsArg) {
|
| 2505 |
+
if (typeof args[2] === 'function') { args[1] = args[2]; args.length = 2; }
|
| 2506 |
+
else { args.length = 1; }
|
| 2507 |
+
}
|
| 2508 |
} else if (options && typeof options === 'object') {
|
| 2509 |
+
args[0] = { ...options, headers:applyProviderAuthHeaders(options.headers, provider, key) };
|
| 2510 |
}
|
| 2511 |
}
|
| 2512 |
}
|
|
|
|
| 2590 |
if (usedProvider && usedKey) {
|
| 2591 |
const _emit = req.emit.bind(req);
|
| 2592 |
let statusHandled = false;
|
| 2593 |
+
let bodyWaitTimer = null;
|
| 2594 |
+
const clearBodyWaitTimer = () => {
|
| 2595 |
+
if (bodyWaitTimer) { clearTimeout(bodyWaitTimer); bodyWaitTimer = null; }
|
| 2596 |
+
};
|
| 2597 |
const finishStatus = (res, errorInfo) => {
|
| 2598 |
if (statusHandled) return;
|
| 2599 |
statusHandled = true;
|
| 2600 |
+
clearBodyWaitTimer();
|
| 2601 |
const retryAfterMs = parseRetryAfterMs(res?.headers?.['retry-after']);
|
| 2602 |
try { endInFlight(usedProvider, usedKey, usedInFlight); } catch (_) {}
|
| 2603 |
try { handleStatus(usedProvider, usedKey, res?.statusCode, usedModel, retryAfterMs, errorInfo, { requestId: usedInFlight?.requestId }); } catch (_) {}
|
|
|
|
| 2623 |
: null;
|
| 2624 |
finishStatus(res, errorInfo);
|
| 2625 |
};
|
| 2626 |
+
bodyWaitTimer = setTimeout(finishWithSniffedBody, ERROR_BODY_WAIT_MS);
|
| 2627 |
+
bodyWaitTimer.unref?.();
|
| 2628 |
res.on('end', finishWithSniffedBody);
|
| 2629 |
res.on('close', finishWithSniffedBody);
|
| 2630 |
} else {
|
|
|
|
| 2668 |
patchUndici(); // covers OpenClaw gateway's bundled undici AI calls
|
| 2669 |
startDiagnostics();
|
| 2670 |
|
| 2671 |
+
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 task-affinity-ignore-inflight:${TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION ? 'on' : 'off'} 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'}`);
|
| 2672 |
emitEvent('rotator_loaded', null, null, {
|
| 2673 |
providers: providerState.filter(p => p.keys.length).map(p => ({ name: p.name, total: p.keys.length })),
|
| 2674 |
logLevel: LOG_LEVEL,
|
|
|
|
| 2678 |
errorBodySniffMaxBytes: ERROR_BODY_SNIFF_MAX_BYTES,
|
| 2679 |
taskAffinityMs: TASK_AFFINITY_MS,
|
| 2680 |
taskAffinityMaxReuses: TASK_AFFINITY_MAX_REUSES,
|
| 2681 |
+
taskAffinityIgnoreInflightSaturation: TASK_AFFINITY_IGNORE_INFLIGHT_SATURATION,
|
| 2682 |
stickyUntilFailure: STICKY_UNTIL_FAILURE,
|
| 2683 |
+
stickyIgnoreInflightSaturation: STICKY_IGNORE_INFLIGHT_SATURATION,
|
| 2684 |
stickyScope: String(process.env.KEY_STICKY_SCOPE || 'auto').trim().toLowerCase() || 'auto',
|
| 2685 |
stickyProviders: [...STICKY_PROVIDER_SET],
|
| 2686 |
llmFallbackProviders: LLM_FALLBACK_PROVIDER_SET ? [...LLM_FALLBACK_PROVIDER_SET] : ['*'],
|
openclaw-sync.py
CHANGED
|
@@ -31,6 +31,34 @@ os.environ.setdefault("HF_HUB_VERBOSITY", "error")
|
|
| 31 |
from huggingface_hub import CommitOperationDelete, HfApi, snapshot_download, upload_folder
|
| 32 |
from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
# Belt-and-suspenders: also raise the level after import in case the env var
|
| 35 |
# wasn't honored (older hub versions, or message logged via a sub-logger).
|
| 36 |
logging.getLogger("huggingface_hub").setLevel(logging.ERROR)
|
|
@@ -768,6 +796,10 @@ def create_snapshot_dir(source_root: Path) -> Path:
|
|
| 768 |
raise RuntimeError(
|
| 769 |
f"Snapshot changed while copying {rel_posix}; retrying next sync pass."
|
| 770 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 771 |
return staging_root
|
| 772 |
|
| 773 |
|
|
@@ -930,6 +962,10 @@ def restore_workspace() -> bool:
|
|
| 930 |
write_status("fresh", "Backup dataset is empty. Starting fresh.")
|
| 931 |
return True
|
| 932 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 933 |
# Build the restored workspace in a staging dir without touching the
|
| 934 |
# live workspace. Only swap once staging is fully written so a copy
|
| 935 |
# failure mid-way can never leave the workspace in a partial state.
|
|
|
|
| 31 |
from huggingface_hub import CommitOperationDelete, HfApi, snapshot_download, upload_folder
|
| 32 |
from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
|
| 33 |
|
| 34 |
+
# huggingface_hub.upload_folder always appends DEFAULT_IGNORE_PATTERNS which
|
| 35 |
+
# hard-blocks every .git/ subtree regardless of ignore_patterns= argument.
|
| 36 |
+
# Work around this by escaping .git → __dot_git__ in the local snapshot before
|
| 37 |
+
# upload, then unescaping after snapshot_download on restore.
|
| 38 |
+
_GIT_ESCAPE = "__dot_git__"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _escape_git_dirs(root: Path) -> None:
|
| 42 |
+
"""Rename every .git dir inside *root* to __dot_git__ so upload_folder uploads them."""
|
| 43 |
+
for dirpath, dirnames, _ in os.walk(root, topdown=False):
|
| 44 |
+
for dirname in list(dirnames):
|
| 45 |
+
if dirname == ".git":
|
| 46 |
+
src = Path(dirpath) / ".git"
|
| 47 |
+
dst = Path(dirpath) / _GIT_ESCAPE
|
| 48 |
+
if src.exists() and not dst.exists():
|
| 49 |
+
src.rename(dst)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _unescape_git_dirs(root: Path) -> None:
|
| 53 |
+
"""Rename every __dot_git__ dir inside *root* back to .git after snapshot_download."""
|
| 54 |
+
for dirpath, dirnames, _ in os.walk(root, topdown=False):
|
| 55 |
+
for dirname in list(dirnames):
|
| 56 |
+
if dirname == _GIT_ESCAPE:
|
| 57 |
+
src = Path(dirpath) / _GIT_ESCAPE
|
| 58 |
+
dst = Path(dirpath) / ".git"
|
| 59 |
+
if src.exists() and not dst.exists():
|
| 60 |
+
src.rename(dst)
|
| 61 |
+
|
| 62 |
# Belt-and-suspenders: also raise the level after import in case the env var
|
| 63 |
# wasn't honored (older hub versions, or message logged via a sub-logger).
|
| 64 |
logging.getLogger("huggingface_hub").setLevel(logging.ERROR)
|
|
|
|
| 796 |
raise RuntimeError(
|
| 797 |
f"Snapshot changed while copying {rel_posix}; retrying next sync pass."
|
| 798 |
)
|
| 799 |
+
# Escape .git dirs so upload_folder (which hard-blocks .git via
|
| 800 |
+
# DEFAULT_IGNORE_PATTERNS) can upload them. _unescape_git_dirs is called
|
| 801 |
+
# in restore_workspace after snapshot_download.
|
| 802 |
+
_escape_git_dirs(staging_root)
|
| 803 |
return staging_root
|
| 804 |
|
| 805 |
|
|
|
|
| 962 |
write_status("fresh", "Backup dataset is empty. Starting fresh.")
|
| 963 |
return True
|
| 964 |
|
| 965 |
+
# Undo the .git → __dot_git__ escaping applied before upload
|
| 966 |
+
# (upload_folder hard-blocks .git via DEFAULT_IGNORE_PATTERNS).
|
| 967 |
+
_unescape_git_dirs(tmp_path)
|
| 968 |
+
|
| 969 |
# Build the restored workspace in a staging dir without touching the
|
| 970 |
# live workspace. Only swap once staging is fully written so a copy
|
| 971 |
# failure mid-way can never leave the workspace in a partial state.
|