@certalis/agent-smith 0.1.14 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -12
- package/dist/bin.js +1649 -315
- package/dist/client-launcher.js +2473 -0
- package/dist/dashboard/chunk-re8nxxzq.css +1 -0
- package/dist/dashboard/chunk-v15gev12.js +111 -0
- package/dist/dashboard/{chunk-rnbsj0t8.js.map → chunk-v15gev12.js.map} +11 -8
- package/dist/dashboard/index.html +1 -1
- package/dist/dashboard/manifest.json +3 -3
- package/dist/edge.js +12 -1
- package/dist/https.js +16 -3
- package/dist/pool-status.js +170 -0
- package/dist/pool.js +1124 -275
- package/dist/post-processor.worker.js +255 -32
- package/dist/server.js +1123 -274
- package/package.json +1 -1
- package/dist/dashboard/chunk-r6qvhv5e.css +0 -1
- package/dist/dashboard/chunk-rnbsj0t8.js +0 -111
package/dist/server.js
CHANGED
|
@@ -841,7 +841,6 @@ function isRequestStreamEvent(value) {
|
|
|
841
841
|
var init_request_events2 = __esm(() => {
|
|
842
842
|
init_request();
|
|
843
843
|
});
|
|
844
|
-
|
|
845
844
|
// ../../packages/types/src/stats.ts
|
|
846
845
|
function isTimeRange(value) {
|
|
847
846
|
return TIME_RANGES.includes(value);
|
|
@@ -1012,7 +1011,7 @@ var init_src2 = __esm(() => {
|
|
|
1012
1011
|
});
|
|
1013
1012
|
|
|
1014
1013
|
// ../../packages/http/src/errors.ts
|
|
1015
|
-
var ERROR_TYPES, HttpError, BadRequest = (message, details) => new HttpError(400, message, details), NotFound = (message, details) => new HttpError(404, message, details), InternalServerError = (message, details) => new HttpError(500, message, details), DEFAULT_ERROR_MESSAGES;
|
|
1014
|
+
var ERROR_TYPES, HttpError, BadRequest = (message, details) => new HttpError(400, message, details), NotFound = (message, details) => new HttpError(404, message, details), InternalServerError = (message, details) => new HttpError(500, message, details), ServiceUnavailable = (message, details) => new HttpError(503, message, details), DEFAULT_ERROR_MESSAGES;
|
|
1016
1015
|
var init_errors2 = __esm(() => {
|
|
1017
1016
|
ERROR_TYPES = {
|
|
1018
1017
|
NETWORK: "network",
|
|
@@ -1998,7 +1997,7 @@ async function fetchClaudeCodeUsage(accessToken) {
|
|
|
1998
1997
|
var CLAUDE_CODE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
1999
1998
|
|
|
2000
1999
|
// ../../packages/providers/src/providers/claude-code/provider.ts
|
|
2001
|
-
var log2, PROVIDER_NAME2 = "claude-code", DEFAULT_BASE_URL2, CLAUDE_CODE_REFRESH_CONFIG, ClaudeCodeProvider;
|
|
2000
|
+
var log2, PROVIDER_NAME2 = "claude-code", DEFAULT_BASE_URL2, CHEAPEST_MODEL = "claude-haiku-5-5", WINDOW_WARMUP_TIMEOUT_MS = 30000, CLAUDE_CODE_REFRESH_CONFIG, ClaudeCodeProvider;
|
|
2002
2001
|
var init_provider2 = __esm(() => {
|
|
2003
2002
|
init_src4();
|
|
2004
2003
|
init_src();
|
|
@@ -2039,6 +2038,27 @@ var init_provider2 = __esm(() => {
|
|
|
2039
2038
|
async probeQuota(_account, accessToken) {
|
|
2040
2039
|
return await fetchClaudeCodeUsage(accessToken);
|
|
2041
2040
|
}
|
|
2041
|
+
async startQuotaWindow(account2, accessToken, model) {
|
|
2042
|
+
const response = await fetch(this.buildUrl("/v1/messages", "", account2), {
|
|
2043
|
+
method: "POST",
|
|
2044
|
+
headers: {
|
|
2045
|
+
authorization: `Bearer ${accessToken}`,
|
|
2046
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
2047
|
+
"anthropic-version": "2023-06-01",
|
|
2048
|
+
"content-type": "application/json"
|
|
2049
|
+
},
|
|
2050
|
+
body: JSON.stringify({
|
|
2051
|
+
model: model ?? CHEAPEST_MODEL,
|
|
2052
|
+
max_tokens: 1,
|
|
2053
|
+
messages: [{ role: "user", content: "hi" }]
|
|
2054
|
+
}),
|
|
2055
|
+
signal: AbortSignal.timeout(WINDOW_WARMUP_TIMEOUT_MS)
|
|
2056
|
+
});
|
|
2057
|
+
await response.body?.cancel();
|
|
2058
|
+
if (!response.ok)
|
|
2059
|
+
throw new Error(`HTTP ${response.status}`);
|
|
2060
|
+
return this.parseRateLimit(response).quotaState ?? null;
|
|
2061
|
+
}
|
|
2042
2062
|
async refreshToken(account2, clientId) {
|
|
2043
2063
|
return executeTokenRefresh(account2, clientId, CLAUDE_CODE_REFRESH_CONFIG, log2);
|
|
2044
2064
|
}
|
|
@@ -2452,6 +2472,107 @@ var init_oauth3 = __esm(() => {
|
|
|
2452
2472
|
};
|
|
2453
2473
|
});
|
|
2454
2474
|
|
|
2475
|
+
// ../../packages/providers/src/providers/codex/reset-credits.ts
|
|
2476
|
+
function string(value) {
|
|
2477
|
+
return typeof value === "string" && value.length > 0 && value.length <= 2000;
|
|
2478
|
+
}
|
|
2479
|
+
function date(value) {
|
|
2480
|
+
return string(value) && Number.isFinite(Date.parse(value));
|
|
2481
|
+
}
|
|
2482
|
+
function nullableText(value) {
|
|
2483
|
+
if (value === undefined || value === null)
|
|
2484
|
+
return null;
|
|
2485
|
+
if (typeof value !== "string" || value.length > 4000)
|
|
2486
|
+
throw new Error(INVALID);
|
|
2487
|
+
return value;
|
|
2488
|
+
}
|
|
2489
|
+
function nonnegativeInteger(value) {
|
|
2490
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
2491
|
+
}
|
|
2492
|
+
function credit(value) {
|
|
2493
|
+
if (!isRecord(value) || !string(value.id) || !string(value.reset_type) || !string(value.status) || !date(value.granted_at) || value.expires_at !== null && !date(value.expires_at))
|
|
2494
|
+
throw new Error(INVALID);
|
|
2495
|
+
return {
|
|
2496
|
+
id: value.id,
|
|
2497
|
+
resetType: value.reset_type,
|
|
2498
|
+
status: value.status,
|
|
2499
|
+
grantedAt: value.granted_at,
|
|
2500
|
+
expiresAt: value.expires_at,
|
|
2501
|
+
title: nullableText(value.title),
|
|
2502
|
+
description: nullableText(value.description)
|
|
2503
|
+
};
|
|
2504
|
+
}
|
|
2505
|
+
async function request2(account2, token, path, body) {
|
|
2506
|
+
const response = await fetch(`${BACKEND}/${path}`, {
|
|
2507
|
+
method: body === undefined ? "GET" : "POST",
|
|
2508
|
+
headers: {
|
|
2509
|
+
authorization: `Bearer ${token}`,
|
|
2510
|
+
"chatgpt-account-id": account2.account_uuid ?? "",
|
|
2511
|
+
"content-type": "application/json"
|
|
2512
|
+
},
|
|
2513
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
2514
|
+
redirect: "error",
|
|
2515
|
+
signal: AbortSignal.timeout(1e4)
|
|
2516
|
+
});
|
|
2517
|
+
if (!response.ok) {
|
|
2518
|
+
await response.body?.cancel();
|
|
2519
|
+
throw new Error(`Codex reset request failed (${response.status})`);
|
|
2520
|
+
}
|
|
2521
|
+
try {
|
|
2522
|
+
return await response.json();
|
|
2523
|
+
} catch {
|
|
2524
|
+
throw new Error(INVALID);
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
async function listCodexResetCredits(account2, token) {
|
|
2528
|
+
const payload = await request2(account2, token, "rate-limit-reset-credits");
|
|
2529
|
+
if (!isRecord(payload) || !nonnegativeInteger(payload.available_count) || !Array.isArray(payload.credits) || payload.credits.length > 1000)
|
|
2530
|
+
throw new Error(INVALID);
|
|
2531
|
+
return {
|
|
2532
|
+
availableCount: payload.available_count,
|
|
2533
|
+
credits: payload.credits.map(credit)
|
|
2534
|
+
};
|
|
2535
|
+
}
|
|
2536
|
+
async function consumeCodexResetCredit(account2, token, attempt) {
|
|
2537
|
+
const payload = await request2(account2, token, "rate-limit-reset-credits/consume", {
|
|
2538
|
+
credit_id: attempt.creditId,
|
|
2539
|
+
redeem_request_id: attempt.requestId
|
|
2540
|
+
});
|
|
2541
|
+
if (!isRecord(payload) || !["reset", "nothing_to_reset", "no_credit", "already_redeemed"].includes(String(payload.code)) || !nonnegativeInteger(payload.windows_reset ?? 0))
|
|
2542
|
+
throw new Error(INVALID);
|
|
2543
|
+
return {
|
|
2544
|
+
code: payload.code,
|
|
2545
|
+
windowsReset: payload.windows_reset ?? 0
|
|
2546
|
+
};
|
|
2547
|
+
}
|
|
2548
|
+
async function readCodexResetQuota(account2, token) {
|
|
2549
|
+
const payload = await request2(account2, token, "usage");
|
|
2550
|
+
if (!isRecord(payload) || !isRecord(payload.rate_limit))
|
|
2551
|
+
return null;
|
|
2552
|
+
const windows = {};
|
|
2553
|
+
for (const value of [
|
|
2554
|
+
payload.rate_limit.primary_window,
|
|
2555
|
+
payload.rate_limit.secondary_window
|
|
2556
|
+
]) {
|
|
2557
|
+
if (!isRecord(value))
|
|
2558
|
+
continue;
|
|
2559
|
+
const bucket = value.limit_window_seconds === 18000 ? "unified5h" : value.limit_window_seconds === 604800 ? "unified7d" : null;
|
|
2560
|
+
if (!bucket || typeof value.used_percent !== "number" || !Number.isFinite(value.used_percent) || value.used_percent < 0 || value.used_percent > 100 || typeof value.reset_at !== "number" || !Number.isSafeInteger(value.reset_at) || value.reset_at * 1000 <= Date.now())
|
|
2561
|
+
continue;
|
|
2562
|
+
windows[bucket] = {
|
|
2563
|
+
utilization: value.used_percent / 100,
|
|
2564
|
+
resetAt: value.reset_at * 1000,
|
|
2565
|
+
seenAt: Date.now(),
|
|
2566
|
+
status: null
|
|
2567
|
+
};
|
|
2568
|
+
}
|
|
2569
|
+
return Object.keys(windows).length > 0 ? { windows } : null;
|
|
2570
|
+
}
|
|
2571
|
+
var BACKEND = "https://chatgpt.com/backend-api/wham", INVALID = "Invalid Codex reset response";
|
|
2572
|
+
var init_reset_credits = __esm(() => {
|
|
2573
|
+
init_src();
|
|
2574
|
+
});
|
|
2575
|
+
|
|
2455
2576
|
// ../../packages/providers/src/providers/codex/provider.ts
|
|
2456
2577
|
function isEnvironmentContext(value) {
|
|
2457
2578
|
return isRecord(value) && value.type === "input_text" && typeof value.text === "string" && /^<environment_context>\r?\n[\s\S]*<\/environment_context>\s*$/.test(value.text);
|
|
@@ -2517,6 +2638,7 @@ var init_provider4 = __esm(() => {
|
|
|
2517
2638
|
init_base();
|
|
2518
2639
|
init_provider3();
|
|
2519
2640
|
init_oauth3();
|
|
2641
|
+
init_reset_credits();
|
|
2520
2642
|
CODEX_USER_AGENT = `codex_cli_rs/${CODEX_CLIENT_VERSION} (Mac OS; arm64)`;
|
|
2521
2643
|
log3 = new Logger("CodexProvider");
|
|
2522
2644
|
DEFAULT_BASE_URL4 = getProviderDefaultBaseUrl(PROVIDER_NAME4);
|
|
@@ -2548,6 +2670,25 @@ var init_provider4 = __esm(() => {
|
|
|
2548
2670
|
name = PROVIDER_NAME4;
|
|
2549
2671
|
defaultBaseUrl = DEFAULT_BASE_URL4;
|
|
2550
2672
|
wire = "openai-responses";
|
|
2673
|
+
supportsResetCredits(account2) {
|
|
2674
|
+
return account2.auth_method === "oauth" && !!account2.account_uuid && this.defaultBaseUrl.replace(/\/$/, "") === DEFAULT_BASE_URL4.replace(/\/$/, "") && (account2.base_url === null || account2.base_url.replace(/\/$/, "") === DEFAULT_BASE_URL4.replace(/\/$/, ""));
|
|
2675
|
+
}
|
|
2676
|
+
requireResetAccount(account2) {
|
|
2677
|
+
if (!this.supportsResetCredits(account2))
|
|
2678
|
+
throw new Error("Reset credits require a direct Codex subscription");
|
|
2679
|
+
}
|
|
2680
|
+
async listResetCredits(account2, accessToken) {
|
|
2681
|
+
this.requireResetAccount(account2);
|
|
2682
|
+
return listCodexResetCredits(account2, accessToken);
|
|
2683
|
+
}
|
|
2684
|
+
async consumeResetCredit(account2, accessToken, attempt) {
|
|
2685
|
+
this.requireResetAccount(account2);
|
|
2686
|
+
return consumeCodexResetCredit(account2, accessToken, attempt);
|
|
2687
|
+
}
|
|
2688
|
+
async readResetQuota(account2, accessToken) {
|
|
2689
|
+
this.requireResetAccount(account2);
|
|
2690
|
+
return readCodexResetQuota(account2, accessToken);
|
|
2691
|
+
}
|
|
2551
2692
|
getClientSessionId(headers2) {
|
|
2552
2693
|
return headers2.get("session-id");
|
|
2553
2694
|
}
|
|
@@ -3114,9 +3255,9 @@ function startCallbackForwarder(provider, providerRegistry) {
|
|
|
3114
3255
|
try {
|
|
3115
3256
|
const server = Bun.serve({
|
|
3116
3257
|
port,
|
|
3117
|
-
fetch(
|
|
3118
|
-
const url = new URL(
|
|
3119
|
-
if (
|
|
3258
|
+
fetch(request3) {
|
|
3259
|
+
const url = new URL(request3.url);
|
|
3260
|
+
if (request3.method !== "GET" || url.pathname !== "/auth/callback") {
|
|
3120
3261
|
return new Response("Not Found", { status: 404 });
|
|
3121
3262
|
}
|
|
3122
3263
|
const target = new URL(`http://localhost:8080${targetPath}`);
|
|
@@ -3328,6 +3469,7 @@ function serializeAccount(account2, providerRegistry, now = Date.now()) {
|
|
|
3328
3469
|
name: account2.name,
|
|
3329
3470
|
provider: account2.provider,
|
|
3330
3471
|
providerDisabled: !providerRegistry.getProvider(account2.provider),
|
|
3472
|
+
resetCreditsSupported: providerRegistry.getProvider(account2.provider)?.supportsResetCredits?.(account2) ?? false,
|
|
3331
3473
|
auth_method: account2.auth_method,
|
|
3332
3474
|
base_url: account2.base_url,
|
|
3333
3475
|
requestCount: account2.request_count,
|
|
@@ -3835,6 +3977,129 @@ var init_paths = __esm(() => {
|
|
|
3835
3977
|
init_paths_common();
|
|
3836
3978
|
});
|
|
3837
3979
|
|
|
3980
|
+
// ../../packages/config/src/window-warmup.ts
|
|
3981
|
+
function isLocalTimes(value) {
|
|
3982
|
+
return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
|
|
3983
|
+
}
|
|
3984
|
+
function isTimeZone(value) {
|
|
3985
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 64) {
|
|
3986
|
+
return false;
|
|
3987
|
+
}
|
|
3988
|
+
try {
|
|
3989
|
+
new Intl.DateTimeFormat("en-US", { timeZone: value });
|
|
3990
|
+
return true;
|
|
3991
|
+
} catch {
|
|
3992
|
+
return false;
|
|
3993
|
+
}
|
|
3994
|
+
}
|
|
3995
|
+
function sanitizeWindowWarmup(value) {
|
|
3996
|
+
if (!isRecord(value))
|
|
3997
|
+
return;
|
|
3998
|
+
const result = {};
|
|
3999
|
+
if (typeof value.enabled === "boolean")
|
|
4000
|
+
result.enabled = value.enabled;
|
|
4001
|
+
if (isLocalTimes(value.times))
|
|
4002
|
+
result.times = [...new Set(value.times)];
|
|
4003
|
+
if (isTimeZone(value.time_zone))
|
|
4004
|
+
result.time_zone = value.time_zone;
|
|
4005
|
+
if (typeof value.weekdays_only === "boolean") {
|
|
4006
|
+
result.weekdays_only = value.weekdays_only;
|
|
4007
|
+
}
|
|
4008
|
+
if (typeof value.model === "string" && MODEL_NAME.test(value.model)) {
|
|
4009
|
+
result.model = value.model;
|
|
4010
|
+
}
|
|
4011
|
+
return Object.keys(value).every((key) => (key in result)) ? result : undefined;
|
|
4012
|
+
}
|
|
4013
|
+
function windowWarmupConfig(file) {
|
|
4014
|
+
return {
|
|
4015
|
+
enabled: file?.enabled ?? WINDOW_WARMUP_DEFAULTS.enabled,
|
|
4016
|
+
times: [...file?.times ?? WINDOW_WARMUP_DEFAULTS.times],
|
|
4017
|
+
timeZone: file?.time_zone ?? WINDOW_WARMUP_DEFAULTS.timeZone,
|
|
4018
|
+
weekdaysOnly: file?.weekdays_only ?? WINDOW_WARMUP_DEFAULTS.weekdaysOnly,
|
|
4019
|
+
model: file?.model ?? WINDOW_WARMUP_DEFAULTS.model
|
|
4020
|
+
};
|
|
4021
|
+
}
|
|
4022
|
+
function windowWarmupFileConfig(config) {
|
|
4023
|
+
return {
|
|
4024
|
+
enabled: config.enabled,
|
|
4025
|
+
times: [...config.times],
|
|
4026
|
+
time_zone: config.timeZone,
|
|
4027
|
+
weekdays_only: config.weekdaysOnly,
|
|
4028
|
+
...config.model && { model: config.model }
|
|
4029
|
+
};
|
|
4030
|
+
}
|
|
4031
|
+
function wallClockFormat(timeZone) {
|
|
4032
|
+
let format = wallClockFormats.get(timeZone);
|
|
4033
|
+
if (!format) {
|
|
4034
|
+
format = new Intl.DateTimeFormat("en-US", {
|
|
4035
|
+
timeZone,
|
|
4036
|
+
hourCycle: "h23",
|
|
4037
|
+
year: "numeric",
|
|
4038
|
+
month: "numeric",
|
|
4039
|
+
day: "numeric",
|
|
4040
|
+
hour: "numeric",
|
|
4041
|
+
minute: "numeric",
|
|
4042
|
+
second: "numeric"
|
|
4043
|
+
});
|
|
4044
|
+
wallClockFormats.set(timeZone, format);
|
|
4045
|
+
}
|
|
4046
|
+
return format;
|
|
4047
|
+
}
|
|
4048
|
+
function wallClock(at, timeZone) {
|
|
4049
|
+
const parts = wallClockFormat(timeZone).formatToParts(at);
|
|
4050
|
+
const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
|
|
4051
|
+
return {
|
|
4052
|
+
year: part("year"),
|
|
4053
|
+
month: part("month"),
|
|
4054
|
+
day: part("day"),
|
|
4055
|
+
hour: part("hour") % 24,
|
|
4056
|
+
minute: part("minute"),
|
|
4057
|
+
second: part("second")
|
|
4058
|
+
};
|
|
4059
|
+
}
|
|
4060
|
+
function zoneOffsetMs(at, timeZone) {
|
|
4061
|
+
const wall = wallClock(at, timeZone);
|
|
4062
|
+
return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
|
|
4063
|
+
}
|
|
4064
|
+
function zonedInstant(wall, timeZone) {
|
|
4065
|
+
return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
|
|
4066
|
+
}
|
|
4067
|
+
function nextWindowWarmupAt(routing, after) {
|
|
4068
|
+
const warmup = routing.windowWarmup;
|
|
4069
|
+
if (!routing.enabled || !warmup.enabled)
|
|
4070
|
+
return null;
|
|
4071
|
+
const today = wallClock(after, warmup.timeZone);
|
|
4072
|
+
for (let offset = 0;offset < 8; offset++) {
|
|
4073
|
+
const day = Date.UTC(today.year, today.month - 1, today.day + offset);
|
|
4074
|
+
const weekday = new Date(day).getUTCDay();
|
|
4075
|
+
if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
|
|
4076
|
+
continue;
|
|
4077
|
+
}
|
|
4078
|
+
const instants = warmup.times.map((time) => {
|
|
4079
|
+
const [hour = 0, minute = 0] = time.split(":").map(Number);
|
|
4080
|
+
return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
|
|
4081
|
+
}).filter((at) => at > after);
|
|
4082
|
+
if (instants.length > 0)
|
|
4083
|
+
return Math.min(...instants);
|
|
4084
|
+
}
|
|
4085
|
+
return null;
|
|
4086
|
+
}
|
|
4087
|
+
var WINDOW_WARMUP_DEFAULTS, LOCAL_TIME, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0, wallClockFormats;
|
|
4088
|
+
var init_window_warmup = __esm(() => {
|
|
4089
|
+
init_src2();
|
|
4090
|
+
init_src();
|
|
4091
|
+
WINDOW_WARMUP_DEFAULTS = {
|
|
4092
|
+
enabled: false,
|
|
4093
|
+
times: ["06:00"],
|
|
4094
|
+
timeZone: "Europe/Paris",
|
|
4095
|
+
weekdaysOnly: true,
|
|
4096
|
+
model: null
|
|
4097
|
+
};
|
|
4098
|
+
LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
4099
|
+
MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
|
|
4100
|
+
wallClockFormats = new Map;
|
|
4101
|
+
});
|
|
4102
|
+
|
|
3838
4103
|
// ../../packages/config/src/index.ts
|
|
3839
4104
|
import { EventEmitter as EventEmitter3 } from "events";
|
|
3840
4105
|
import {
|
|
@@ -3861,10 +4126,20 @@ function normalizeEnrollmentEmail(value) {
|
|
|
3861
4126
|
const email = value.trim().toLowerCase();
|
|
3862
4127
|
return email.length <= 254 && patterns.email.test(email) ? email : undefined;
|
|
3863
4128
|
}
|
|
4129
|
+
function normalizeEnrollmentRule(value) {
|
|
4130
|
+
const rule = normalizeEnrollmentEmail(value);
|
|
4131
|
+
if (!rule?.includes("*"))
|
|
4132
|
+
return rule;
|
|
4133
|
+
if (!rule.startsWith("*@"))
|
|
4134
|
+
return;
|
|
4135
|
+
const labels = rule.slice(2).split(".");
|
|
4136
|
+
const label = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
4137
|
+
return labels.length >= 2 && labels.every((part) => label.test(part)) ? rule : undefined;
|
|
4138
|
+
}
|
|
3864
4139
|
function sanitizeEnrollmentEmails(value) {
|
|
3865
4140
|
if (!Array.isArray(value))
|
|
3866
4141
|
return;
|
|
3867
|
-
const emails = value.map(
|
|
4142
|
+
const emails = value.map(normalizeEnrollmentRule).filter((email) => email !== undefined);
|
|
3868
4143
|
return [...new Set(emails)].slice(0, MAX_ENROLLMENT_EMAILS);
|
|
3869
4144
|
}
|
|
3870
4145
|
function sanitizeConfigData(value) {
|
|
@@ -4009,6 +4284,12 @@ function sanitizeClientRouting(value) {
|
|
|
4009
4284
|
if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
|
|
4010
4285
|
client2.proxy_key_file = value.proxy_key_file;
|
|
4011
4286
|
}
|
|
4287
|
+
if (typeof value.keep_claude_login === "boolean") {
|
|
4288
|
+
client2.keep_claude_login = value.keep_claude_login;
|
|
4289
|
+
}
|
|
4290
|
+
if (typeof value.pool_ssh_host === "string" && POOL_SSH_HOST_PATTERN.test(value.pool_ssh_host)) {
|
|
4291
|
+
client2.pool_ssh_host = value.pool_ssh_host;
|
|
4292
|
+
}
|
|
4012
4293
|
return Object.keys(client2).length > 0 ? client2 : undefined;
|
|
4013
4294
|
}
|
|
4014
4295
|
function sanitizeProviderModels(value) {
|
|
@@ -4076,12 +4357,25 @@ function sanitizeTeamRouting(value) {
|
|
|
4076
4357
|
if (typeof value.distribution_enabled === "boolean") {
|
|
4077
4358
|
result.distribution_enabled = value.distribution_enabled;
|
|
4078
4359
|
}
|
|
4360
|
+
if (typeof value.prefer_expiring_quota === "boolean") {
|
|
4361
|
+
result.prefer_expiring_quota = value.prefer_expiring_quota;
|
|
4362
|
+
}
|
|
4079
4363
|
if (Array.isArray(value.allowlisted_account_uuids) && value.allowlisted_account_uuids.every((entry) => typeof entry === "string" && entry.length > 0 && entry.length <= 200)) {
|
|
4080
4364
|
result.allowlisted_account_uuids = [...value.allowlisted_account_uuids];
|
|
4081
4365
|
}
|
|
4082
4366
|
if (isFiniteNumber(value.max_usage) && value.max_usage > 0 && value.max_usage <= 0.9) {
|
|
4083
4367
|
result.max_usage = value.max_usage;
|
|
4084
4368
|
}
|
|
4369
|
+
if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
|
|
4370
|
+
result.weekly_max_usage = value.weekly_max_usage;
|
|
4371
|
+
}
|
|
4372
|
+
if (isRecord(value.weekly_max_usage_by_email)) {
|
|
4373
|
+
const entries = Object.entries(value.weekly_max_usage_by_email);
|
|
4374
|
+
const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
|
|
4375
|
+
if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 0.95) && new Set(normalized.map(([email]) => email)).size === entries.length) {
|
|
4376
|
+
result.weekly_max_usage_by_email = Object.fromEntries(normalized);
|
|
4377
|
+
}
|
|
4378
|
+
}
|
|
4085
4379
|
if (isNonNegativeFiniteNumber(value.admission_cap)) {
|
|
4086
4380
|
result.admission_cap = Math.floor(value.admission_cap);
|
|
4087
4381
|
}
|
|
@@ -4097,16 +4391,42 @@ function sanitizeTeamRouting(value) {
|
|
|
4097
4391
|
if (isNonNegativeFiniteNumber(value.quota_probe_seconds)) {
|
|
4098
4392
|
result.quota_probe_seconds = Math.min(Math.floor(value.quota_probe_seconds), 7 * 24 * 60 * 60);
|
|
4099
4393
|
}
|
|
4394
|
+
const windowWarmup = sanitizeWindowWarmup(value.window_warmup);
|
|
4395
|
+
if (windowWarmup)
|
|
4396
|
+
result.window_warmup = windowWarmup;
|
|
4100
4397
|
return result;
|
|
4101
4398
|
}
|
|
4102
|
-
|
|
4399
|
+
function readClientRouting(configPath = resolveConfigPath()) {
|
|
4400
|
+
let data;
|
|
4401
|
+
try {
|
|
4402
|
+
data = JSON.parse(readFileSync(configPath, "utf8"));
|
|
4403
|
+
} catch {
|
|
4404
|
+
throw new Error("Agent Smith client config could not be read");
|
|
4405
|
+
}
|
|
4406
|
+
if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
|
|
4407
|
+
throw new Error("Agent Smith client config is invalid");
|
|
4408
|
+
}
|
|
4409
|
+
return clientRouting(sanitizeClientRouting(data.client));
|
|
4410
|
+
}
|
|
4411
|
+
function clientRouting(client2) {
|
|
4412
|
+
return {
|
|
4413
|
+
enabled: client2?.enabled === true,
|
|
4414
|
+
...client2?.base_url && { baseUrl: client2.base_url },
|
|
4415
|
+
...client2?.proxy_key_file && { proxyKeyFile: client2.proxy_key_file },
|
|
4416
|
+
...client2?.keep_claude_login === true && { keepClaudeLogin: true },
|
|
4417
|
+
...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
|
|
4418
|
+
};
|
|
4419
|
+
}
|
|
4420
|
+
var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
4103
4421
|
var init_src7 = __esm(() => {
|
|
4104
4422
|
init_src2();
|
|
4105
4423
|
init_src4();
|
|
4106
4424
|
init_src();
|
|
4107
4425
|
init_paths();
|
|
4426
|
+
init_window_warmup();
|
|
4108
4427
|
init_paths();
|
|
4109
4428
|
init_paths_common();
|
|
4429
|
+
init_window_warmup();
|
|
4110
4430
|
log6 = new Logger("Config");
|
|
4111
4431
|
PROVIDER_STRATEGIES = [
|
|
4112
4432
|
"anthropic-api",
|
|
@@ -4122,16 +4442,21 @@ var init_src7 = __esm(() => {
|
|
|
4122
4442
|
];
|
|
4123
4443
|
BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
|
|
4124
4444
|
PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
|
|
4445
|
+
POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
|
|
4125
4446
|
TEAM_ROUTING_DEFAULTS = {
|
|
4126
4447
|
enabled: false,
|
|
4127
4448
|
distributionEnabled: true,
|
|
4449
|
+
preferExpiringQuota: false,
|
|
4128
4450
|
allowlistedAccountUuids: [],
|
|
4129
4451
|
maxUsage: 0.9,
|
|
4452
|
+
weeklyMaxUsage: 0.95,
|
|
4453
|
+
weeklyMaxUsageByEmail: {},
|
|
4130
4454
|
admissionCap: 5,
|
|
4131
4455
|
admissionQueueLimit: 25,
|
|
4132
4456
|
admissionWaitMs: 30000,
|
|
4133
4457
|
holdSeconds: 0,
|
|
4134
|
-
quotaProbeSeconds: 0
|
|
4458
|
+
quotaProbeSeconds: 0,
|
|
4459
|
+
windowWarmup: WINDOW_WARMUP_DEFAULTS
|
|
4135
4460
|
};
|
|
4136
4461
|
Config = class Config extends EventEmitter3 {
|
|
4137
4462
|
configPath;
|
|
@@ -4237,17 +4562,20 @@ var init_src7 = __esm(() => {
|
|
|
4237
4562
|
if (fromEnv) {
|
|
4238
4563
|
const n = parseInt(fromEnv, 10);
|
|
4239
4564
|
if (!Number.isNaN(n))
|
|
4240
|
-
return this.clamp(n,
|
|
4565
|
+
return this.clamp(n, 0, 365);
|
|
4241
4566
|
}
|
|
4242
4567
|
const fromFile = this.data.data_retention_days;
|
|
4243
4568
|
if (typeof fromFile === "number")
|
|
4244
|
-
return this.clamp(fromFile,
|
|
4569
|
+
return this.clamp(fromFile, 0, 365);
|
|
4245
4570
|
return 7;
|
|
4246
4571
|
}
|
|
4247
4572
|
setDataRetentionDays(days) {
|
|
4248
|
-
const clamped = this.clamp(days,
|
|
4573
|
+
const clamped = this.clamp(days, 0, 365);
|
|
4249
4574
|
this.set("data_retention_days", clamped);
|
|
4250
4575
|
}
|
|
4576
|
+
storesRequestPayloads() {
|
|
4577
|
+
return this.getDataRetentionDays() > 0;
|
|
4578
|
+
}
|
|
4251
4579
|
getRequestRetentionDays() {
|
|
4252
4580
|
const fromEnv = process.env.AGENT_SMITH_REQUEST_RETENTION_DAYS;
|
|
4253
4581
|
if (fromEnv) {
|
|
@@ -4278,15 +4606,19 @@ var init_src7 = __esm(() => {
|
|
|
4278
4606
|
return {
|
|
4279
4607
|
enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
|
|
4280
4608
|
distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
|
|
4609
|
+
preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
|
|
4281
4610
|
allowlistedAccountUuids: [
|
|
4282
4611
|
...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
|
|
4283
4612
|
],
|
|
4284
4613
|
maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
|
|
4614
|
+
weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
|
|
4615
|
+
weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
|
|
4285
4616
|
admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
|
|
4286
4617
|
admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
|
|
4287
4618
|
admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
|
|
4288
4619
|
holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
|
|
4289
|
-
quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
|
|
4620
|
+
quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds,
|
|
4621
|
+
windowWarmup: windowWarmupConfig(file?.window_warmup)
|
|
4290
4622
|
};
|
|
4291
4623
|
}
|
|
4292
4624
|
getAlerts() {
|
|
@@ -4301,14 +4633,10 @@ var init_src7 = __esm(() => {
|
|
|
4301
4633
|
};
|
|
4302
4634
|
}
|
|
4303
4635
|
getClientRouting() {
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
...client2?.proxy_key_file && {
|
|
4309
|
-
proxyKeyFile: client2.proxy_key_file
|
|
4310
|
-
}
|
|
4311
|
-
};
|
|
4636
|
+
return clientRouting(this.data.client);
|
|
4637
|
+
}
|
|
4638
|
+
setClientRoutingEnabled(enabled) {
|
|
4639
|
+
this.persistStrictly("client", { ...this.data.client, enabled });
|
|
4312
4640
|
}
|
|
4313
4641
|
getBlockWhenAllFull() {
|
|
4314
4642
|
return this.data.block_when_all_full !== false;
|
|
@@ -4349,13 +4677,17 @@ var init_src7 = __esm(() => {
|
|
|
4349
4677
|
const allowed = new Set([
|
|
4350
4678
|
"enabled",
|
|
4351
4679
|
"distribution_enabled",
|
|
4680
|
+
"prefer_expiring_quota",
|
|
4352
4681
|
"allowlisted_account_uuids",
|
|
4353
4682
|
"max_usage",
|
|
4683
|
+
"weekly_max_usage",
|
|
4684
|
+
"weekly_max_usage_by_email",
|
|
4354
4685
|
"admission_cap",
|
|
4355
4686
|
"admission_queue_limit",
|
|
4356
4687
|
"admission_wait_ms",
|
|
4357
4688
|
"hold_seconds",
|
|
4358
|
-
"quota_probe_seconds"
|
|
4689
|
+
"quota_probe_seconds",
|
|
4690
|
+
"window_warmup"
|
|
4359
4691
|
]);
|
|
4360
4692
|
if (Object.keys(value).some((key) => !allowed.has(key))) {
|
|
4361
4693
|
throw new Error("team routing configuration contains an unknown field");
|
|
@@ -4370,13 +4702,12 @@ var init_src7 = __esm(() => {
|
|
|
4370
4702
|
}
|
|
4371
4703
|
}
|
|
4372
4704
|
const oldValue = this.data.team_routing;
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
});
|
|
4705
|
+
if (!("weekly_max_usage_by_email" in value) && oldValue?.weekly_max_usage_by_email) {
|
|
4706
|
+
sanitized.weekly_max_usage_by_email = {
|
|
4707
|
+
...oldValue.weekly_max_usage_by_email
|
|
4708
|
+
};
|
|
4709
|
+
}
|
|
4710
|
+
this.persistStrictly("team_routing", sanitized);
|
|
4380
4711
|
}
|
|
4381
4712
|
allowAccountUuid(accountUuid) {
|
|
4382
4713
|
const current = this.getTeamRouting().allowlistedAccountUuids;
|
|
@@ -4399,10 +4730,18 @@ var init_src7 = __esm(() => {
|
|
|
4399
4730
|
getEnrollmentEmails() {
|
|
4400
4731
|
return [...this.data.enrollment_emails ?? []];
|
|
4401
4732
|
}
|
|
4733
|
+
isEnrollmentEmailAllowed(value) {
|
|
4734
|
+
const email = normalizeEnrollmentEmail(value);
|
|
4735
|
+
if (!email || email.includes("*"))
|
|
4736
|
+
return false;
|
|
4737
|
+
const rules = this.data.enrollment_emails ?? [];
|
|
4738
|
+
const domainRule = `*${email.slice(email.indexOf("@"))}`;
|
|
4739
|
+
return rules.includes(email) || rules.includes(domainRule);
|
|
4740
|
+
}
|
|
4402
4741
|
setEnrollmentEmails(emails) {
|
|
4403
|
-
const normalized = emails.map(
|
|
4742
|
+
const normalized = emails.map(normalizeEnrollmentRule);
|
|
4404
4743
|
if (normalized.some((email) => email === undefined)) {
|
|
4405
|
-
throw new ValidationError("Invalid enrollment email", "enrollment_emails");
|
|
4744
|
+
throw new ValidationError("Invalid enrollment email or exact-domain rule (use *@example.com)", "enrollment_emails");
|
|
4406
4745
|
}
|
|
4407
4746
|
const unique = [...new Set(normalized)];
|
|
4408
4747
|
if (unique.length > MAX_ENROLLMENT_EMAILS) {
|
|
@@ -4432,6 +4771,7 @@ var init_src7 = __esm(() => {
|
|
|
4432
4771
|
},
|
|
4433
4772
|
sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
|
|
4434
4773
|
port: NETWORK.DEFAULT_PORT,
|
|
4774
|
+
storeRequestPayloads: this.storesRequestPayloads(),
|
|
4435
4775
|
teamRouting: this.getTeamRouting()
|
|
4436
4776
|
};
|
|
4437
4777
|
if (process.env.AGENT_SMITH_CLIENT_ID) {
|
|
@@ -4955,7 +5295,7 @@ function backfillRequestLinkageColumns(db) {
|
|
|
4955
5295
|
FROM requests r
|
|
4956
5296
|
LEFT JOIN request_payloads rp ON rp.id = r.id
|
|
4957
5297
|
ORDER BY r.timestamp ASC
|
|
4958
|
-
`).
|
|
5298
|
+
`).iterate();
|
|
4959
5299
|
const responseToChain = new Map;
|
|
4960
5300
|
let updatedRows = 0;
|
|
4961
5301
|
const updateStmt = db.prepare(`
|
|
@@ -6113,7 +6453,7 @@ var init_request_repository = __esm(() => {
|
|
|
6113
6453
|
}
|
|
6114
6454
|
save(data) {
|
|
6115
6455
|
const { usage, timings } = data;
|
|
6116
|
-
const payloadJson = data.payload === undefined ? undefined : JSON.stringify(data.payload);
|
|
6456
|
+
const payloadJson = data.payload === undefined || data.storePayload === false ? undefined : JSON.stringify(data.payload);
|
|
6117
6457
|
const linkage = requestLinkageFromPayload(data.payload);
|
|
6118
6458
|
const responseChainId = this.resolveResponseChainId(linkage.previousResponseId, linkage.responseId, data.id);
|
|
6119
6459
|
this.db.run("BEGIN");
|
|
@@ -6493,7 +6833,11 @@ var init_request_repository = __esm(() => {
|
|
|
6493
6833
|
return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
|
|
6494
6834
|
}
|
|
6495
6835
|
deletePayloadsOlderThan(cutoffTs) {
|
|
6496
|
-
return this.runWithChanges(`DELETE FROM request_payloads
|
|
6836
|
+
return this.runWithChanges(`DELETE FROM request_payloads
|
|
6837
|
+
WHERE EXISTS (
|
|
6838
|
+
SELECT 1 FROM requests r
|
|
6839
|
+
WHERE r.id = request_payloads.id AND r.timestamp < ?
|
|
6840
|
+
)`, [cutoffTs]);
|
|
6497
6841
|
}
|
|
6498
6842
|
};
|
|
6499
6843
|
});
|
|
@@ -6620,11 +6964,16 @@ var init_strategy_repository = __esm(() => {
|
|
|
6620
6964
|
|
|
6621
6965
|
// ../../packages/database/src/database-operations.ts
|
|
6622
6966
|
import { Database } from "bun:sqlite";
|
|
6623
|
-
import { mkdirSync as mkdirSync3 } from "fs";
|
|
6967
|
+
import { mkdirSync as mkdirSync3, statfsSync } from "fs";
|
|
6624
6968
|
import { dirname as dirname2 } from "path";
|
|
6969
|
+
function freeDiskBytes(directory) {
|
|
6970
|
+
const { bavail, bsize } = statfsSync(directory);
|
|
6971
|
+
return bavail * bsize;
|
|
6972
|
+
}
|
|
6625
6973
|
|
|
6626
6974
|
class DatabaseOperations {
|
|
6627
6975
|
db;
|
|
6976
|
+
dbPath;
|
|
6628
6977
|
runtime;
|
|
6629
6978
|
closed = false;
|
|
6630
6979
|
accounts;
|
|
@@ -6636,6 +6985,7 @@ class DatabaseOperations {
|
|
|
6636
6985
|
stats;
|
|
6637
6986
|
constructor(dbPath) {
|
|
6638
6987
|
const resolvedPath = dbPath ?? resolveDbPath();
|
|
6988
|
+
this.dbPath = resolvedPath;
|
|
6639
6989
|
const dir = dirname2(resolvedPath);
|
|
6640
6990
|
mkdirSync3(dir, { recursive: true });
|
|
6641
6991
|
this.db = new Database(resolvedPath, { create: true });
|
|
@@ -6768,6 +7118,7 @@ class DatabaseOperations {
|
|
|
6768
7118
|
usage,
|
|
6769
7119
|
timestamp: options?.timestamp,
|
|
6770
7120
|
payload: options?.payload,
|
|
7121
|
+
storePayload: options?.storePayload,
|
|
6771
7122
|
timings: options?.timings
|
|
6772
7123
|
});
|
|
6773
7124
|
}
|
|
@@ -6852,7 +7203,7 @@ class DatabaseOperations {
|
|
|
6852
7203
|
return;
|
|
6853
7204
|
}
|
|
6854
7205
|
this.closed = true;
|
|
6855
|
-
this.
|
|
7206
|
+
this.checkpointWal();
|
|
6856
7207
|
this.db.close();
|
|
6857
7208
|
}
|
|
6858
7209
|
dispose() {
|
|
@@ -6862,9 +7213,23 @@ class DatabaseOperations {
|
|
|
6862
7213
|
this.db.exec("PRAGMA optimize");
|
|
6863
7214
|
this.db.exec("PRAGMA wal_checkpoint(PASSIVE)");
|
|
6864
7215
|
}
|
|
6865
|
-
|
|
7216
|
+
checkpointWal() {
|
|
6866
7217
|
this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
7218
|
+
}
|
|
7219
|
+
compact(freeBytes = freeDiskBytes(dirname2(this.dbPath))) {
|
|
7220
|
+
this.checkpointWal();
|
|
7221
|
+
const requiredBytes = 2 * this.liveDataBytes();
|
|
7222
|
+
if (freeBytes < requiredBytes) {
|
|
7223
|
+
return { vacuumed: false, freeBytes, requiredBytes };
|
|
7224
|
+
}
|
|
6867
7225
|
this.db.exec("VACUUM");
|
|
7226
|
+
this.checkpointWal();
|
|
7227
|
+
return { vacuumed: true, freeBytes, requiredBytes };
|
|
7228
|
+
}
|
|
7229
|
+
liveDataBytes() {
|
|
7230
|
+
const row = this.db.query(`SELECT (page_count - freelist_count) * page_size AS bytes
|
|
7231
|
+
FROM pragma_page_count(), pragma_freelist_count(), pragma_page_size()`).get();
|
|
7232
|
+
return row.bytes;
|
|
6868
7233
|
}
|
|
6869
7234
|
getStatsRepository() {
|
|
6870
7235
|
return this.stats;
|
|
@@ -7096,7 +7461,10 @@ function createConfigHandlers(config) {
|
|
|
7096
7461
|
getStrategies: () => {
|
|
7097
7462
|
return jsonResponse(LB_STRATEGIES);
|
|
7098
7463
|
},
|
|
7099
|
-
getTeamRouting: () =>
|
|
7464
|
+
getTeamRouting: () => {
|
|
7465
|
+
const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
|
|
7466
|
+
return jsonResponse(routing);
|
|
7467
|
+
},
|
|
7100
7468
|
setTeamRouting: async (req) => {
|
|
7101
7469
|
try {
|
|
7102
7470
|
const body = await parseJsonObject(req);
|
|
@@ -7126,7 +7494,7 @@ function createConfigHandlers(config) {
|
|
|
7126
7494
|
let updated = false;
|
|
7127
7495
|
if (body.payloadDays !== undefined) {
|
|
7128
7496
|
const payloadDays = validateNumber(body.payloadDays, "payloadDays", {
|
|
7129
|
-
min:
|
|
7497
|
+
min: 0,
|
|
7130
7498
|
max: 365,
|
|
7131
7499
|
integer: true
|
|
7132
7500
|
});
|
|
@@ -7192,7 +7560,7 @@ function enrollmentPage() {
|
|
|
7192
7560
|
<section class="card" id="step-email" hidden>
|
|
7193
7561
|
<div class="avatar">${icon("mail")}</div>
|
|
7194
7562
|
<h1 tabindex="-1">Connect your Claude subscription</h1>
|
|
7195
|
-
<p class="lead">
|
|
7563
|
+
<p class="lead">Connect or reconnect your subscription to the shared agents pool. Already connected or paused? Use the same email to renew your login without adding a second account.</p>
|
|
7196
7564
|
<form id="request">
|
|
7197
7565
|
<p class="notice err" id="email-error" role="alert" hidden></p>
|
|
7198
7566
|
<label for="email">Work email<input id="email" type="email" autocomplete="email" spellcheck="false" required maxlength="254"></label>
|
|
@@ -7205,16 +7573,16 @@ function enrollmentPage() {
|
|
|
7205
7573
|
<h1 tabindex="-1">Sign in with Claude</h1>
|
|
7206
7574
|
<p class="lead" id="signin-for" hidden>Use the Claude account of <strong id="signin-email"></strong>. Only connect an account you have permission to share.</p>
|
|
7207
7575
|
<ul class="facts">
|
|
7208
|
-
<li>Claude opens in a new tab. Sign in
|
|
7576
|
+
<li>Claude opens in a new tab. Sign in with the email shown above.</li>
|
|
7209
7577
|
<li>Your password stays with Claude. The pool only keeps the authorization it needs to run agents.</li>
|
|
7210
|
-
<li>Claude then
|
|
7578
|
+
<li>Copy the code Claude shows, then return to this page to paste it. Reopening this link in the same browser brings you back to your current step.</li>
|
|
7211
7579
|
</ul>
|
|
7212
7580
|
<button class="button" id="start" type="button">Continue to Claude ${icon("open")}</button>
|
|
7213
7581
|
</section>
|
|
7214
7582
|
<section class="card" id="step-code" hidden>
|
|
7215
7583
|
<div class="avatar">${icon("code")}</div>
|
|
7216
7584
|
<h1 tabindex="-1">Paste the code from Claude</h1>
|
|
7217
|
-
<p class="lead" id="code-lead">
|
|
7585
|
+
<p class="lead" id="code-lead">Finish signing in in the Claude tab, copy its authorization code, then return here to paste it. Reopened this page? Your current step is restored.</p>
|
|
7218
7586
|
<form id="verify">
|
|
7219
7587
|
<label for="code">Authorization code<input id="code" type="password" autocomplete="off" spellcheck="false" required maxlength="4096"><span class="hint">The code stays hidden on screen. Never paste it into chat.</span></label>
|
|
7220
7588
|
<button class="button" type="submit">Verify account</button>
|
|
@@ -7224,42 +7592,47 @@ function enrollmentPage() {
|
|
|
7224
7592
|
<section class="card" id="step-confirm" hidden>
|
|
7225
7593
|
<div class="avatar">${icon("person")}</div>
|
|
7226
7594
|
<h1 tabindex="-1">Is this the right account?</h1>
|
|
7227
|
-
<p class="lead">Claude verified
|
|
7595
|
+
<p class="lead">Claude verified this account. Confirm to save its login. An existing account is updated, not duplicated; an operator's manual pause stays in place.</p>
|
|
7228
7596
|
<form id="confirm">
|
|
7229
7597
|
<div class="account">${icon("check")}<span id="account"></span></div>
|
|
7230
7598
|
<label class="consent"><input id="consent" type="checkbox" required><span>I authorize the shared agents pool to use this subscription.</span></label>
|
|
7231
|
-
<button class="button" type="submit">
|
|
7599
|
+
<button class="button" type="submit">Confirm connection</button>
|
|
7232
7600
|
</form>
|
|
7233
|
-
<p class="aside">Wrong account? Do not confirm
|
|
7601
|
+
<p class="aside">Wrong account? Do not confirm. Use \u201CStart again\u201D below to choose the right one.</p>
|
|
7234
7602
|
</section>
|
|
7235
7603
|
<section class="card" id="step-done" hidden>
|
|
7236
7604
|
<div class="avatar ok">${icon("check")}</div>
|
|
7237
|
-
<h1 tabindex="-1">Subscription connected</h1>
|
|
7238
|
-
<p class="lead"><strong id="connected-account"></strong
|
|
7239
|
-
<div class="aside"><strong>Changed your mind?</strong> Disconnect removes this account's saved authorization and pool membership.
|
|
7605
|
+
<h1 id="done-title" tabindex="-1">Subscription connected</h1>
|
|
7606
|
+
<p class="lead"><strong id="connected-account"></strong><span id="connected-message"></span></p>
|
|
7607
|
+
<div class="aside"><strong>Changed your mind?</strong> Disconnect removes this account's saved authorization and pool membership. This browser can disconnect it for 24 hours, unless the server restarts or the account reconnects elsewhere. It does not sign you out of Claude or cancel your subscription.<button class="button secondary" id="disconnect" type="button">Disconnect</button></div>
|
|
7240
7608
|
</section>
|
|
7241
7609
|
<section class="card" id="step-error" hidden>
|
|
7242
7610
|
<div class="avatar err">${icon("alert")}</div>
|
|
7243
7611
|
<h1 tabindex="-1">This sign-in can't continue</h1>
|
|
7244
7612
|
<p class="lead" id="error-message"></p>
|
|
7245
|
-
<p class="aside">
|
|
7613
|
+
<p class="aside">Resume to check your progress. Starting again does not disconnect a saved subscription.</p>
|
|
7614
|
+
<button class="button" id="recover" type="button">Resume sign-in</button>
|
|
7246
7615
|
</section>
|
|
7247
7616
|
<p id="status" class="notice err" role="alert" hidden></p>
|
|
7617
|
+
<p id="recovery" class="notice" role="status" hidden></p>
|
|
7618
|
+
<button class="button secondary" id="restart" type="button" hidden>Start again</button>
|
|
7248
7619
|
</main>
|
|
7249
|
-
<footer>
|
|
7620
|
+
<footer>Sign-in steps expire after 10 minutes and can be resumed in the same browser. Allow cookies for this site. No subscription is added or updated until you confirm.</footer>
|
|
7250
7621
|
<noscript><p class="notice err">JavaScript is required for this sign-in.</p></noscript>
|
|
7251
7622
|
<script nonce="${nonce}">
|
|
7252
7623
|
let token = location.hash.slice(1);
|
|
7253
|
-
history.replaceState(null, '', location.pathname);
|
|
7624
|
+
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) { token = ''; history.replaceState(null, '', location.pathname); }
|
|
7254
7625
|
addEventListener('hashchange', () => { if (location.hash) location.reload(); });
|
|
7255
7626
|
const get = id => document.getElementById(id);
|
|
7256
7627
|
const steps = ['email', 'signin', 'code', 'confirm', 'done'];
|
|
7257
7628
|
let current = 'email';
|
|
7629
|
+
let pending = 0;
|
|
7258
7630
|
function show(step) {
|
|
7259
7631
|
const failed = step === 'error';
|
|
7260
7632
|
const index = steps.indexOf(failed ? current : step);
|
|
7261
7633
|
if (!failed) current = step;
|
|
7262
7634
|
for (const name of [...steps, 'error']) get('step-' + name).hidden = name !== step;
|
|
7635
|
+
get('restart').hidden = step === 'email';
|
|
7263
7636
|
document.querySelectorAll('#stepper li').forEach((item, position) => {
|
|
7264
7637
|
item.className = position < index || step === 'done' ? 'done' : position === index ? (failed ? 'failed' : 'active') : '';
|
|
7265
7638
|
item.querySelector('.dot').innerHTML = item.className === 'done' ? '${icon("check")}' : String(position + 1);
|
|
@@ -7269,23 +7642,78 @@ function show(step) {
|
|
|
7269
7642
|
(step === 'email' ? get('email') : get('step-' + step).querySelector('h1')).focus();
|
|
7270
7643
|
}
|
|
7271
7644
|
async function send(step, body) {
|
|
7272
|
-
|
|
7273
|
-
|
|
7274
|
-
|
|
7275
|
-
|
|
7645
|
+
pending++;
|
|
7646
|
+
try {
|
|
7647
|
+
const response = await fetch('/pool-enroll/' + step, {method:'POST', credentials:'same-origin', cache:'no-store', redirect:'error', headers:{'content-type':'application/json'}, body:JSON.stringify(body)});
|
|
7648
|
+
const data = await response.json();
|
|
7649
|
+
if (!response.ok) { const error = new Error(data.error || 'Sign-in failed. Try resuming.'); error.status = response.status; throw error; }
|
|
7650
|
+
return data;
|
|
7651
|
+
} finally { pending--; }
|
|
7652
|
+
}
|
|
7653
|
+
async function post(step, values) {
|
|
7654
|
+
const data = await send(step, {...(token ? {token} : {}), ...values});
|
|
7655
|
+
token = ''; history.replaceState(null, '', location.pathname);
|
|
7276
7656
|
return data;
|
|
7277
7657
|
}
|
|
7278
|
-
|
|
7279
|
-
|
|
7658
|
+
function destination(value) {
|
|
7659
|
+
const url = new URL(value);
|
|
7660
|
+
if (url.origin !== 'https://claude.ai' || url.pathname !== '/oauth/authorize') throw new Error('Invalid sign-in destination. Ask for help.');
|
|
7661
|
+
return url.href;
|
|
7662
|
+
}
|
|
7663
|
+
function connected(data) {
|
|
7664
|
+
get('connected-account').textContent = data.email || '';
|
|
7665
|
+
get('done-title').textContent = data.paused ? 'Login saved \u2014 account still paused' : !data.inPool ? 'Login saved \u2014 account not in pool' : data.reconnected ? 'Subscription reconnected' : 'Subscription connected';
|
|
7666
|
+
get('connected-message').textContent = data.paused ? ' has a renewed login, but is still paused. Ask the pool operator to resume it.' : !data.inPool ? ' has a renewed login, but the operator has kept it outside the pool.' : ' is connected to the shared agents pool. You can close this page.';
|
|
7667
|
+
get('disconnect').disabled = false;
|
|
7668
|
+
show('done');
|
|
7669
|
+
}
|
|
7670
|
+
function restore(data) {
|
|
7671
|
+
get('signin-email').textContent = data.email || ''; get('signin-for').hidden = !data.email;
|
|
7672
|
+
get('consent').checked = false;
|
|
7673
|
+
if (data.stage === 'invited') show('signin');
|
|
7674
|
+
else if (data.stage === 'started') { get('reopen').href = destination(data.authUrl); show('code'); }
|
|
7675
|
+
else if (data.stage === 'verified') { get('account').textContent = data.email; show('confirm'); }
|
|
7676
|
+
else if (data.stage === 'connected') connected(data);
|
|
7677
|
+
else throw new Error('Sign-in state could not be restored. Start again.');
|
|
7678
|
+
}
|
|
7679
|
+
async function recover() {
|
|
7680
|
+
const data = await send('resume', {});
|
|
7681
|
+
token = ''; restore(data);
|
|
7682
|
+
get('recovery').textContent = 'Your progress is restored in this browser. Continue from this step.'; get('recovery').hidden = false;
|
|
7683
|
+
get('status').hidden = true;
|
|
7684
|
+
}
|
|
7685
|
+
function showError(error) {
|
|
7280
7686
|
token = ''; get('code').value = '';
|
|
7281
|
-
get('
|
|
7687
|
+
get('recovery').hidden = true;
|
|
7688
|
+
get('error-message').textContent = error instanceof Error ? error.message : 'Sign-in failed. Try resuming.';
|
|
7282
7689
|
show('error');
|
|
7283
7690
|
}
|
|
7284
|
-
|
|
7691
|
+
async function fail(error) {
|
|
7692
|
+
try { await recover(); } catch { showError(error); }
|
|
7693
|
+
}
|
|
7694
|
+
if (/^[A-Za-z0-9_-]{43}$/.test(token)) show('signin');
|
|
7695
|
+
else { token = ''; recover().catch(error => { if (error.status === 410) show('email'); else showError(error); }); }
|
|
7696
|
+
addEventListener('pageshow', event => { if (event.persisted && !pending && !token) recover().catch(showError); });
|
|
7697
|
+
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible' && !pending && !token) recover().catch(error => { if (error.status === 410) show('email'); else showError(error); }); });
|
|
7698
|
+
get('recover').addEventListener('click', async () => {
|
|
7699
|
+
get('recover').disabled = true;
|
|
7700
|
+
try { await recover(); } catch (error) { showError(error); }
|
|
7701
|
+
finally { get('recover').disabled = false; }
|
|
7702
|
+
});
|
|
7703
|
+
get('restart').addEventListener('click', async () => {
|
|
7704
|
+
get('restart').disabled = true;
|
|
7705
|
+
try {
|
|
7706
|
+
await send('reset', {}); token = ''; get('code').value = ''; get('consent').checked = false;
|
|
7707
|
+
get('recovery').hidden = true; get('status').hidden = true; get('email-error').hidden = true; get('signin-notice').hidden = true;
|
|
7708
|
+
show('email');
|
|
7709
|
+
} catch (error) { showError(error); }
|
|
7710
|
+
finally { get('restart').disabled = false; }
|
|
7711
|
+
});
|
|
7285
7712
|
get('request').addEventListener('submit', async event => {
|
|
7286
7713
|
event.preventDefault(); event.submitter.disabled = true; get('email-error').hidden = true;
|
|
7287
7714
|
try {
|
|
7288
7715
|
const data = await send('request', {email: get('email').value});
|
|
7716
|
+
token = ''; history.replaceState(null, '', location.pathname); get('recovery').hidden = true;
|
|
7289
7717
|
get('signin-email').textContent = data.email; get('signin-for').hidden = false;
|
|
7290
7718
|
show('signin');
|
|
7291
7719
|
} catch (error) {
|
|
@@ -7298,24 +7726,26 @@ get('start').addEventListener('click', async () => {
|
|
|
7298
7726
|
get('start').disabled = true;
|
|
7299
7727
|
try {
|
|
7300
7728
|
const data = await post('start', {});
|
|
7301
|
-
const url =
|
|
7302
|
-
|
|
7303
|
-
|
|
7304
|
-
|
|
7305
|
-
else get('code-lead').textContent = 'Your browser blocked the new tab. Open Claude sign-in with the link below, sign in, then paste the code it shows.';
|
|
7729
|
+
const url = destination(data.authUrl);
|
|
7730
|
+
get('reopen').href = url;
|
|
7731
|
+
if (tab) { tab.opener = null; tab.location.href = url; }
|
|
7732
|
+
else get('code-lead').textContent = 'The new tab was blocked. Use \u201COpen Claude sign-in again\u201D below. Copy the code Claude shows, then come back here to paste it.';
|
|
7306
7733
|
show('code');
|
|
7307
|
-
} catch (error) { if (tab) tab.close(); fail(error); }
|
|
7734
|
+
} catch (error) { if (tab) tab.close(); await fail(error); }
|
|
7735
|
+
finally { get('start').disabled = false; }
|
|
7308
7736
|
});
|
|
7309
7737
|
get('verify').addEventListener('submit', async event => {
|
|
7310
7738
|
event.preventDefault(); event.submitter.disabled = true;
|
|
7311
7739
|
const code = get('code').value.trim(); get('code').value = '';
|
|
7312
7740
|
try { const data = await post('verify', {code}); get('account').textContent = data.email; show('confirm'); }
|
|
7313
|
-
catch (error) { fail(error); }
|
|
7741
|
+
catch (error) { await fail(error); }
|
|
7742
|
+
finally { event.submitter.disabled = false; }
|
|
7314
7743
|
});
|
|
7315
7744
|
get('confirm').addEventListener('submit', async event => {
|
|
7316
7745
|
event.preventDefault(); if (!get('consent').checked) return; event.submitter.disabled = true;
|
|
7317
|
-
try { await post('confirm', {consent:true})
|
|
7318
|
-
catch (error) { fail(error); }
|
|
7746
|
+
try { connected(await post('confirm', {consent:true})); }
|
|
7747
|
+
catch (error) { await fail(error); }
|
|
7748
|
+
finally { event.submitter.disabled = false; }
|
|
7319
7749
|
});
|
|
7320
7750
|
get('disconnect').addEventListener('click', async () => {
|
|
7321
7751
|
get('disconnect').disabled = true; get('status').hidden = true;
|
|
@@ -7427,12 +7857,68 @@ class EnrollmentHandlers {
|
|
|
7427
7857
|
if (entry.expiresAt <= this.now())
|
|
7428
7858
|
this.entries.delete(key);
|
|
7429
7859
|
}
|
|
7430
|
-
mint(details, state, duration) {
|
|
7860
|
+
mint(details, state, duration, browserSession) {
|
|
7431
7861
|
const token = randomBytes2(32).toString("base64url");
|
|
7432
7862
|
const expiresAt = this.now() + duration;
|
|
7433
|
-
this.entries.set(hash(token), {
|
|
7863
|
+
this.entries.set(hash(token), {
|
|
7864
|
+
details,
|
|
7865
|
+
state,
|
|
7866
|
+
expiresAt,
|
|
7867
|
+
browserSession
|
|
7868
|
+
});
|
|
7434
7869
|
return { token, expiresAt };
|
|
7435
7870
|
}
|
|
7871
|
+
cookieToken(req) {
|
|
7872
|
+
const cookies = (req.headers.get("cookie") ?? "").split(";").map((part) => part.trim()).filter((part) => part.startsWith(`${sessionCookie}=`));
|
|
7873
|
+
const token = cookies.length === 1 ? cookies[0]?.slice(sessionCookie.length + 1) ?? "" : "";
|
|
7874
|
+
return /^[A-Za-z0-9_-]{43}$/.test(token) ? token : "";
|
|
7875
|
+
}
|
|
7876
|
+
cookieHeader(token, duration) {
|
|
7877
|
+
return `${sessionCookie}=${token}; Path=/pool-enroll; HttpOnly; SameSite=Strict; Max-Age=${Math.floor(duration / 1000)}${this.origin.protocol === "https:" ? "; Secure" : ""}`;
|
|
7878
|
+
}
|
|
7879
|
+
browserEntry(req) {
|
|
7880
|
+
const token = this.cookieToken(req);
|
|
7881
|
+
if (!token)
|
|
7882
|
+
return;
|
|
7883
|
+
const session = hash(token);
|
|
7884
|
+
return [...this.entries].find(([, entry]) => entry.browserSession === session);
|
|
7885
|
+
}
|
|
7886
|
+
mintBrowser(details, state, duration, extra, session = randomBytes2(32).toString("base64url")) {
|
|
7887
|
+
const response = json({
|
|
7888
|
+
...this.mint(details, state, duration, hash(session)),
|
|
7889
|
+
...extra
|
|
7890
|
+
});
|
|
7891
|
+
response.headers.set("set-cookie", this.cookieHeader(session, duration));
|
|
7892
|
+
return response;
|
|
7893
|
+
}
|
|
7894
|
+
next(entry, state, duration, req, extra) {
|
|
7895
|
+
const session = this.cookieToken(req);
|
|
7896
|
+
return this.mintBrowser(entry.details, state, duration, extra, session && entry.browserSession === hash(session) ? session : undefined);
|
|
7897
|
+
}
|
|
7898
|
+
resume(req) {
|
|
7899
|
+
const found = this.browserEntry(req);
|
|
7900
|
+
if (!found)
|
|
7901
|
+
throw new EnrollmentError(410, "No active sign-in. Enter your email to start again.");
|
|
7902
|
+
const [, entry] = found;
|
|
7903
|
+
const { state, details, expiresAt } = entry;
|
|
7904
|
+
if (state.kind === "busy")
|
|
7905
|
+
throw new EnrollmentError(409, "Sign-in is being updated in another tab. Try resuming in a moment.");
|
|
7906
|
+
if (state.kind === "connected") {
|
|
7907
|
+
const account2 = this.context.dbOps.getAccount(state.accountId);
|
|
7908
|
+
if (!account2 || account2.account_uuid !== state.accountUuid)
|
|
7909
|
+
throw new EnrollmentError(410, "This subscription has changed or was removed. Start again.");
|
|
7910
|
+
}
|
|
7911
|
+
return json({
|
|
7912
|
+
stage: state.kind,
|
|
7913
|
+
expiresAt,
|
|
7914
|
+
email: state.kind === "verified" ? state.seat.identity.email : state.kind === "connected" ? state.email : details.email,
|
|
7915
|
+
...state.kind === "started" ? { authUrl: state.flow.authUrl } : {},
|
|
7916
|
+
...state.kind === "connected" ? {
|
|
7917
|
+
reconnected: !!details.reconnect,
|
|
7918
|
+
...this.connectionStatus(state.accountId)
|
|
7919
|
+
} : {}
|
|
7920
|
+
});
|
|
7921
|
+
}
|
|
7436
7922
|
async guarded(action) {
|
|
7437
7923
|
try {
|
|
7438
7924
|
this.prune();
|
|
@@ -7447,14 +7933,14 @@ class EnrollmentHandlers {
|
|
|
7447
7933
|
if (!this.context.providerRegistry.getOAuthProvider("claude-code"))
|
|
7448
7934
|
throw new EnrollmentError(400, "Provider 'claude-code' is disabled. Set providers.claude-code.enabled to true in your config.");
|
|
7449
7935
|
}
|
|
7450
|
-
reserve(name) {
|
|
7451
|
-
if (this.context.dbOps.getAccountByName(name))
|
|
7936
|
+
reserve(name, reconnect = false) {
|
|
7937
|
+
if (!reconnect && this.context.dbOps.getAccountByName(name))
|
|
7452
7938
|
throw new EnrollmentError(409, "This seat is already in the pool.");
|
|
7453
7939
|
for (const entry of this.entries.values())
|
|
7454
7940
|
if (entry.details.name === name && entry.state.kind === "busy")
|
|
7455
7941
|
throw new EnrollmentError(409, "Sign-in is already in progress");
|
|
7456
7942
|
for (const [key, entry] of this.entries)
|
|
7457
|
-
if (entry.details.name === name)
|
|
7943
|
+
if (entry.details.name === name && entry.state.kind !== "connected")
|
|
7458
7944
|
this.entries.delete(key);
|
|
7459
7945
|
if (this.entries.size >= 100)
|
|
7460
7946
|
throw new EnrollmentError(429, "Too many pending invitations");
|
|
@@ -7464,12 +7950,32 @@ class EnrollmentHandlers {
|
|
|
7464
7950
|
if (Object.keys(body).some((key) => key !== "email"))
|
|
7465
7951
|
throw new EnrollmentError(400, "Unknown request field");
|
|
7466
7952
|
const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
|
7467
|
-
if (!this.context.config.
|
|
7468
|
-
throw new EnrollmentError(403, "This email is not
|
|
7953
|
+
if (!this.context.config.isEnrollmentEmailAllowed(email))
|
|
7954
|
+
throw new EnrollmentError(403, "This email is not allowed. Ask the operator to add its address or domain.");
|
|
7469
7955
|
const name = email.slice(0, email.indexOf("@")).replace(/[^a-z0-9._+-]/g, "-").slice(0, 64);
|
|
7470
|
-
this.
|
|
7471
|
-
const
|
|
7472
|
-
|
|
7956
|
+
const { dbOps } = this.context;
|
|
7957
|
+
const contacts = dbOps.getAccountsByProvider("claude-code").filter((account2) => dbOps.getEnrollmentContact(account2.id)?.email?.toLowerCase() === email);
|
|
7958
|
+
if (contacts.length > 1)
|
|
7959
|
+
throw new EnrollmentError(409, "This email matches several seats. Ask the operator to check them.");
|
|
7960
|
+
const existing = contacts[0] ?? dbOps.getAccountByName(name);
|
|
7961
|
+
if (existing && (existing.provider !== "claude-code" || existing.auth_method !== "oauth" || !existing.account_uuid))
|
|
7962
|
+
throw new EnrollmentError(409, "This seat needs the operator's help to reconnect.");
|
|
7963
|
+
const details = {
|
|
7964
|
+
name: existing?.name ?? name,
|
|
7965
|
+
email,
|
|
7966
|
+
contactEmail: email,
|
|
7967
|
+
...existing ? {
|
|
7968
|
+
reconnect: {
|
|
7969
|
+
id: existing.id,
|
|
7970
|
+
accountUuid: existing.account_uuid ?? null,
|
|
7971
|
+
organizationUuid: existing.organization_uuid ?? null
|
|
7972
|
+
}
|
|
7973
|
+
} : {}
|
|
7974
|
+
};
|
|
7975
|
+
this.reserve(details.name, !!existing);
|
|
7976
|
+
return this.mintBrowser(details, { kind: "invited" }, tenMinutes, {
|
|
7977
|
+
email
|
|
7978
|
+
});
|
|
7473
7979
|
}
|
|
7474
7980
|
emails = (req) => this.guarded(async () => {
|
|
7475
7981
|
const body = await readBody(req);
|
|
@@ -7538,9 +8044,20 @@ class EnrollmentHandlers {
|
|
|
7538
8044
|
const body = await readBody(req);
|
|
7539
8045
|
if (url.pathname === "/pool-enroll/request")
|
|
7540
8046
|
return this.request(body);
|
|
8047
|
+
if (url.pathname === "/pool-enroll/resume" || url.pathname === "/pool-enroll/reset") {
|
|
8048
|
+
if (Object.keys(body).length)
|
|
8049
|
+
throw new EnrollmentError(400, "No fields expected");
|
|
8050
|
+
if (url.pathname === "/pool-enroll/resume")
|
|
8051
|
+
return this.resume(req);
|
|
8052
|
+
const found = this.browserEntry(req);
|
|
8053
|
+
if (found)
|
|
8054
|
+
this.entries.delete(found[0]);
|
|
8055
|
+
const response = json({ reset: true });
|
|
8056
|
+
response.headers.set("set-cookie", this.cookieHeader("", 0));
|
|
8057
|
+
return response;
|
|
8058
|
+
}
|
|
7541
8059
|
const token = typeof body.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(body.token) ? body.token : "";
|
|
7542
|
-
const key = hash(token);
|
|
7543
|
-
const entry = this.entries.get(key);
|
|
8060
|
+
const [key, entry] = body.token === undefined ? this.browserEntry(req) ?? ["", undefined] : [hash(token), this.entries.get(hash(token))];
|
|
7544
8061
|
const expected = url.pathname === "/pool-enroll/start" ? "invited" : url.pathname === "/pool-enroll/verify" ? "started" : url.pathname === "/pool-enroll/confirm" ? "verified" : "connected";
|
|
7545
8062
|
if (!entry || entry.expiresAt <= this.now() || entry.state.kind !== expected)
|
|
7546
8063
|
throw new EnrollmentError(410, "This sign-in has expired or was already used. Start again.");
|
|
@@ -7550,8 +8067,7 @@ class EnrollmentHandlers {
|
|
|
7550
8067
|
if (state.kind === "invited") {
|
|
7551
8068
|
const flow = await this.oauth.beginClaudeSeat();
|
|
7552
8069
|
this.assertCurrent(key, entry);
|
|
7553
|
-
return
|
|
7554
|
-
...this.mint(entry.details, { kind: "started", flow }, tenMinutes),
|
|
8070
|
+
return this.next(entry, { kind: "started", flow }, tenMinutes, req, {
|
|
7555
8071
|
authUrl: flow.authUrl
|
|
7556
8072
|
});
|
|
7557
8073
|
}
|
|
@@ -7568,9 +8084,8 @@ class EnrollmentHandlers {
|
|
|
7568
8084
|
const { email } = seat.identity;
|
|
7569
8085
|
if (!email || entry.details.email && email.toLowerCase() !== entry.details.email.toLowerCase())
|
|
7570
8086
|
throw new EnrollmentError(400, "This Claude account does not match your email. Start again and sign in with the matching account.");
|
|
7571
|
-
this.
|
|
7572
|
-
return
|
|
7573
|
-
...this.mint(entry.details, { kind: "verified", seat }, tenMinutes),
|
|
8087
|
+
this.assertSeat(entry.details, seat);
|
|
8088
|
+
return this.next(entry, { kind: "verified", seat }, tenMinutes, req, {
|
|
7574
8089
|
email
|
|
7575
8090
|
});
|
|
7576
8091
|
}
|
|
@@ -7578,13 +8093,16 @@ class EnrollmentHandlers {
|
|
|
7578
8093
|
if (body.consent !== true)
|
|
7579
8094
|
throw new EnrollmentError(400, "Confirm the displayed account before adding it");
|
|
7580
8095
|
const accountId = this.save(entry.details, state.seat);
|
|
7581
|
-
return
|
|
8096
|
+
return this.next(entry, {
|
|
8097
|
+
kind: "connected",
|
|
8098
|
+
accountId,
|
|
8099
|
+
accountUuid: state.seat.identity.accountUuid,
|
|
8100
|
+
email: state.seat.identity.email ?? ""
|
|
8101
|
+
}, oneDay, req, {
|
|
7582
8102
|
connected: true,
|
|
7583
|
-
|
|
7584
|
-
|
|
7585
|
-
|
|
7586
|
-
accountUuid: state.seat.identity.accountUuid
|
|
7587
|
-
}, oneDay)
|
|
8103
|
+
email: state.seat.identity.email,
|
|
8104
|
+
reconnected: !!entry.details.reconnect,
|
|
8105
|
+
...this.connectionStatus(accountId)
|
|
7588
8106
|
});
|
|
7589
8107
|
}
|
|
7590
8108
|
if (state.kind === "connected") {
|
|
@@ -7596,9 +8114,8 @@ class EnrollmentHandlers {
|
|
|
7596
8114
|
entry.state = state;
|
|
7597
8115
|
throw new EnrollmentError(500, "Removal could not be saved. Retry here or ask the operator to check this seat.");
|
|
7598
8116
|
}
|
|
7599
|
-
return
|
|
7600
|
-
disconnected: true
|
|
7601
|
-
...this.mint(entry.details, { kind: "invited" }, oneDay)
|
|
8117
|
+
return this.next({ ...entry, details: { ...entry.details, reconnect: undefined } }, { kind: "invited" }, oneDay, req, {
|
|
8118
|
+
disconnected: true
|
|
7602
8119
|
});
|
|
7603
8120
|
}
|
|
7604
8121
|
throw new EnrollmentError(410, "Link already used");
|
|
@@ -7612,14 +8129,40 @@ class EnrollmentHandlers {
|
|
|
7612
8129
|
if (this.entries.get(key) !== entry || entry.expiresAt <= this.now())
|
|
7613
8130
|
throw new EnrollmentError(410, "Sign-in expired. Start again.");
|
|
7614
8131
|
}
|
|
7615
|
-
|
|
7616
|
-
if (
|
|
8132
|
+
assertSeat(details, seat) {
|
|
8133
|
+
if (details.reconnect) {
|
|
8134
|
+
const account2 = this.context.dbOps.getAccount(details.reconnect.id);
|
|
8135
|
+
if (!account2 || account2.provider !== "claude-code" || account2.auth_method !== "oauth" || account2.account_uuid !== details.reconnect.accountUuid || account2.organization_uuid !== details.reconnect.organizationUuid || account2.account_uuid !== seat.identity.accountUuid || account2.organization_uuid && account2.organization_uuid !== seat.identity.organizationUuid)
|
|
8136
|
+
throw new EnrollmentError(409, "This is not the saved Claude account, or the seat has changed. Ask the operator to check it.");
|
|
8137
|
+
return account2;
|
|
8138
|
+
}
|
|
8139
|
+
if (this.context.dbOps.getAccountByName(details.name) || this.context.dbOps.getAccountsByProvider("claude-code").some((account2) => account2.account_uuid === seat.identity.accountUuid))
|
|
7617
8140
|
throw new EnrollmentError(409, "This seat is already connected. Ask the operator for help.");
|
|
8141
|
+
return null;
|
|
8142
|
+
}
|
|
8143
|
+
connectionStatus(accountId) {
|
|
8144
|
+
const account2 = this.context.dbOps.getAccount(accountId);
|
|
8145
|
+
return {
|
|
8146
|
+
paused: account2?.paused ?? false,
|
|
8147
|
+
inPool: !!account2?.account_uuid && this.context.config.getTeamRouting().allowlistedAccountUuids.includes(account2.account_uuid)
|
|
8148
|
+
};
|
|
7618
8149
|
}
|
|
7619
8150
|
save(details, seat) {
|
|
7620
8151
|
const { dbOps, config } = this.context;
|
|
7621
8152
|
return dbOps.getDatabase().transaction(() => {
|
|
7622
|
-
this.
|
|
8153
|
+
const existing = this.assertSeat(details, seat);
|
|
8154
|
+
if (existing) {
|
|
8155
|
+
dbOps.updateAccountTokens(existing.id, seat.tokens.accessToken, seat.tokens.expiresAt ?? null, seat.tokens.refreshToken ?? undefined);
|
|
8156
|
+
if ([
|
|
8157
|
+
"OAuth refresh was rejected by the upstream",
|
|
8158
|
+
"missing OAuth refresh token"
|
|
8159
|
+
].includes(existing.error_reason ?? ""))
|
|
8160
|
+
dbOps.resumeAccount(existing.id);
|
|
8161
|
+
for (const [key, entry] of this.entries)
|
|
8162
|
+
if (entry.state.kind === "connected" && entry.state.accountId === existing.id)
|
|
8163
|
+
this.entries.delete(key);
|
|
8164
|
+
return existing.id;
|
|
8165
|
+
}
|
|
7623
8166
|
const account2 = dbOps.createOAuthAccount({
|
|
7624
8167
|
name: details.name,
|
|
7625
8168
|
provider: "claude-code",
|
|
@@ -7688,7 +8231,7 @@ async function readBody(req) {
|
|
|
7688
8231
|
reader.releaseLock();
|
|
7689
8232
|
}
|
|
7690
8233
|
}
|
|
7691
|
-
var paths, tenMinutes = 600000, oneDay = 86400000, headers2, json = (value, status = 200) => Response.json(value, { status, headers: headers2 }), hash = (token) => createHash("sha256").update(token).digest("hex"), EnrollmentError;
|
|
8234
|
+
var paths, tenMinutes = 600000, oneDay = 86400000, sessionCookie = "agent_smith_enrollment", headers2, json = (value, status = 200) => Response.json(value, { status, headers: headers2 }), hash = (token) => createHash("sha256").update(token).digest("hex"), EnrollmentError;
|
|
7692
8235
|
var init_enrollment = __esm(() => {
|
|
7693
8236
|
init_src2();
|
|
7694
8237
|
init_src6();
|
|
@@ -7700,7 +8243,9 @@ var init_enrollment = __esm(() => {
|
|
|
7700
8243
|
"/pool-enroll/start",
|
|
7701
8244
|
"/pool-enroll/verify",
|
|
7702
8245
|
"/pool-enroll/confirm",
|
|
7703
|
-
"/pool-enroll/disconnect"
|
|
8246
|
+
"/pool-enroll/disconnect",
|
|
8247
|
+
"/pool-enroll/resume",
|
|
8248
|
+
"/pool-enroll/reset"
|
|
7704
8249
|
]);
|
|
7705
8250
|
headers2 = {
|
|
7706
8251
|
"cache-control": "no-store",
|
|
@@ -7853,7 +8398,13 @@ function createCleanupHandler(dbOps, config) {
|
|
|
7853
8398
|
function createCompactHandler(dbOps) {
|
|
7854
8399
|
return () => {
|
|
7855
8400
|
try {
|
|
7856
|
-
dbOps.compact();
|
|
8401
|
+
const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
|
|
8402
|
+
if (!vacuumed) {
|
|
8403
|
+
return errorResponse(ServiceUnavailable("Not enough free disk space to compact", {
|
|
8404
|
+
freeBytes,
|
|
8405
|
+
requiredBytes
|
|
8406
|
+
}));
|
|
8407
|
+
}
|
|
7857
8408
|
const result = {
|
|
7858
8409
|
success: true,
|
|
7859
8410
|
message: "Database compacted successfully"
|
|
@@ -7873,10 +8424,10 @@ var init_maintenance = __esm(() => {
|
|
|
7873
8424
|
});
|
|
7874
8425
|
|
|
7875
8426
|
// ../../packages/api/src/serializers/request.ts
|
|
7876
|
-
function serializeRequestResponse(
|
|
8427
|
+
function serializeRequestResponse(request3) {
|
|
7877
8428
|
return {
|
|
7878
|
-
...toRequestSummary(
|
|
7879
|
-
accountName:
|
|
8429
|
+
...toRequestSummary(request3),
|
|
8430
|
+
accountName: request3.accountName ?? null
|
|
7880
8431
|
};
|
|
7881
8432
|
}
|
|
7882
8433
|
function enrichRequestPayload(payload, accountName = null) {
|
|
@@ -7998,6 +8549,94 @@ var init_requests_stream = __esm(() => {
|
|
|
7998
8549
|
init_src();
|
|
7999
8550
|
});
|
|
8000
8551
|
|
|
8552
|
+
// ../../packages/api/src/handlers/reset-credits.ts
|
|
8553
|
+
function createResetCreditHandlers(context2) {
|
|
8554
|
+
const pending = new Set;
|
|
8555
|
+
const accountFor = (id) => {
|
|
8556
|
+
const account2 = context2.dbOps.getAccount(id);
|
|
8557
|
+
if (!account2)
|
|
8558
|
+
return { error: reply({ error: "Account not found" }, 404) };
|
|
8559
|
+
const provider = context2.providerRegistry.getProvider(account2.provider);
|
|
8560
|
+
if (!provider?.supportsResetCredits?.(account2) || !provider.listResetCredits || !provider.consumeResetCredit || !provider.readResetQuota)
|
|
8561
|
+
return {
|
|
8562
|
+
error: reply({ error: "Reset credits require a direct Codex subscription" }, 400)
|
|
8563
|
+
};
|
|
8564
|
+
return { account: account2, provider };
|
|
8565
|
+
};
|
|
8566
|
+
const accessToken = async (account2) => {
|
|
8567
|
+
if (!context2.getAccountAccessToken)
|
|
8568
|
+
throw new Error("Token service unavailable");
|
|
8569
|
+
return context2.getAccountAccessToken(account2);
|
|
8570
|
+
};
|
|
8571
|
+
return {
|
|
8572
|
+
list: async (id) => {
|
|
8573
|
+
const resolved = accountFor(id);
|
|
8574
|
+
if (resolved.error)
|
|
8575
|
+
return resolved.error;
|
|
8576
|
+
try {
|
|
8577
|
+
const { account: account2, provider } = resolved;
|
|
8578
|
+
return reply(await provider.listResetCredits?.(account2, await accessToken(account2)));
|
|
8579
|
+
} catch {
|
|
8580
|
+
return reply({
|
|
8581
|
+
error: "Could not read Codex reset credits. Check this account's sign-in and try again."
|
|
8582
|
+
}, 502);
|
|
8583
|
+
}
|
|
8584
|
+
},
|
|
8585
|
+
consume: async (req, id) => {
|
|
8586
|
+
const resolved = accountFor(id);
|
|
8587
|
+
if (resolved.error)
|
|
8588
|
+
return resolved.error;
|
|
8589
|
+
let attempt;
|
|
8590
|
+
try {
|
|
8591
|
+
const body = await parseJsonObject(req);
|
|
8592
|
+
if (body.confirmed !== true || typeof body.creditId !== "string" || body.creditId.trim().length === 0 || body.creditId.length > 256 || typeof body.requestId !== "string" || !UUID.test(body.requestId) || Object.keys(body).some((key) => !["confirmed", "creditId", "requestId"].includes(key)))
|
|
8593
|
+
return reply({
|
|
8594
|
+
error: "Confirm the selected creditId and supply a UUID requestId"
|
|
8595
|
+
}, 400);
|
|
8596
|
+
attempt = { creditId: body.creditId, requestId: body.requestId };
|
|
8597
|
+
} catch {
|
|
8598
|
+
return reply({ error: "Invalid reset request" }, 400);
|
|
8599
|
+
}
|
|
8600
|
+
if (pending.has(id))
|
|
8601
|
+
return reply({ error: "A reset is already in progress for this account" }, 409);
|
|
8602
|
+
pending.add(id);
|
|
8603
|
+
try {
|
|
8604
|
+
const { account: account2, provider } = resolved;
|
|
8605
|
+
const token = await accessToken(account2);
|
|
8606
|
+
const result = await provider.consumeResetCredit?.(account2, token, attempt);
|
|
8607
|
+
if (!result)
|
|
8608
|
+
throw new Error("Reset service unavailable");
|
|
8609
|
+
let quotaRefreshed = false;
|
|
8610
|
+
if (result.code === "reset" || result.code === "already_redeemed") {
|
|
8611
|
+
try {
|
|
8612
|
+
const quota2 = await provider.readResetQuota?.(account2, token);
|
|
8613
|
+
const saved = context2.dbOps.getAccount(id);
|
|
8614
|
+
if (quota2 && saved && saved.account_uuid === account2.account_uuid && saved.provider === account2.provider) {
|
|
8615
|
+
context2.dbOps.updateAccountQuotaState(id, {
|
|
8616
|
+
...saved.quota_state,
|
|
8617
|
+
windows: { ...saved.quota_state?.windows, ...quota2.windows }
|
|
8618
|
+
});
|
|
8619
|
+
quotaRefreshed = true;
|
|
8620
|
+
}
|
|
8621
|
+
} catch {}
|
|
8622
|
+
}
|
|
8623
|
+
return reply({ ...result, quotaRefreshed });
|
|
8624
|
+
} catch {
|
|
8625
|
+
return reply({
|
|
8626
|
+
error: "Codex reset outcome is unconfirmed. Retry the same creditId and requestId; do not use another reset to test."
|
|
8627
|
+
}, 502);
|
|
8628
|
+
} finally {
|
|
8629
|
+
pending.delete(id);
|
|
8630
|
+
}
|
|
8631
|
+
}
|
|
8632
|
+
};
|
|
8633
|
+
}
|
|
8634
|
+
var UUID, reply = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
|
|
8635
|
+
var init_reset_credits2 = __esm(() => {
|
|
8636
|
+
init_json();
|
|
8637
|
+
UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8638
|
+
});
|
|
8639
|
+
|
|
8001
8640
|
// ../../packages/api/src/handlers/stats.ts
|
|
8002
8641
|
function createStatsHandler(dbOps) {
|
|
8003
8642
|
return () => {
|
|
@@ -8073,17 +8712,22 @@ function blockedReason(account2, threshold, now) {
|
|
|
8073
8712
|
function createFleetStatusHandler(dbOps, config, providerRegistry) {
|
|
8074
8713
|
return () => {
|
|
8075
8714
|
const now = Date.now();
|
|
8076
|
-
const quotaThreshold = config.getRuntime()
|
|
8715
|
+
const { quotaThreshold, teamRouting } = config.getRuntime();
|
|
8077
8716
|
const accounts = dbOps.getAllAccounts().map((account2) => ({
|
|
8078
8717
|
...serializeAccount(account2, providerRegistry, now),
|
|
8079
8718
|
blockedReason: blockedReason(account2, quotaThreshold, now),
|
|
8080
8719
|
quotaWindows: account2.quota_state?.windows ?? {},
|
|
8081
8720
|
outsideSpend: account2.quota_state?.outsideSpend ?? {}
|
|
8082
8721
|
}));
|
|
8083
|
-
return jsonResponse({
|
|
8722
|
+
return jsonResponse({
|
|
8723
|
+
accounts,
|
|
8724
|
+
quotaThreshold,
|
|
8725
|
+
nextWindowWarmupAt: nextWindowWarmupAt(teamRouting, now)
|
|
8726
|
+
});
|
|
8084
8727
|
};
|
|
8085
8728
|
}
|
|
8086
8729
|
var init_status = __esm(() => {
|
|
8730
|
+
init_src7();
|
|
8087
8731
|
init_src3();
|
|
8088
8732
|
init_src();
|
|
8089
8733
|
init_account();
|
|
@@ -8135,6 +8779,9 @@ class APIRouter {
|
|
|
8135
8779
|
const statsResetHandler = createStatsResetHandler(dbOps);
|
|
8136
8780
|
const fleetStatusHandler = createFleetStatusHandler(dbOps, config, providerRegistry);
|
|
8137
8781
|
const accountsHandler = createAccountsListHandler(dbOps, providerRegistry);
|
|
8782
|
+
const resetCredits = createResetCreditHandlers(this.context);
|
|
8783
|
+
this.addDynamicRoute("GET", "/api/accounts/:accountId/reset-credits", (_req, _url, params) => resetCredits.list(params.accountId));
|
|
8784
|
+
this.addDynamicRoute("POST", "/api/accounts/:accountId/reset-credits/consume", (req, _url, params) => resetCredits.consume(req, params.accountId));
|
|
8138
8785
|
const accountAddHandler = createAccountAddHandler(dbOps, config, providerRegistry);
|
|
8139
8786
|
const requestsSummaryHandler = createRequestsSummaryHandler(dbOps);
|
|
8140
8787
|
const requestsDetailHandler = createRequestsDetailHandler(dbOps);
|
|
@@ -8293,6 +8940,7 @@ var init_router = __esm(() => {
|
|
|
8293
8940
|
init_oauth6();
|
|
8294
8941
|
init_requests();
|
|
8295
8942
|
init_requests_stream();
|
|
8943
|
+
init_reset_credits2();
|
|
8296
8944
|
init_stats2();
|
|
8297
8945
|
init_status();
|
|
8298
8946
|
});
|
|
@@ -8323,6 +8971,14 @@ var init_background_tasks = __esm(() => {
|
|
|
8323
8971
|
});
|
|
8324
8972
|
|
|
8325
8973
|
// ../../packages/proxy/src/seat-usage.ts
|
|
8974
|
+
function expiringReset(provider, account2, model, now) {
|
|
8975
|
+
const buckets = provider.quotaBucketsFor(model);
|
|
8976
|
+
const resets = Object.entries(account2.quota_state?.windows ?? {}).flatMap(([bucket, window2]) => {
|
|
8977
|
+
const horizon = provider.isFiveHourBucket(bucket) ? 60 * 60000 : provider.isWeeklyBucket(bucket) ? 24 * 60 * 60000 : 0;
|
|
8978
|
+
return horizon > 0 && (buckets?.includes(bucket) ?? true) && window2.resetAt !== null && window2.resetAt > now && window2.resetAt - now <= horizon && window2.seenAt <= now && isCurrentQuotaWindow(window2, now) && window2.status !== "rejected" && window2.utilization !== null && window2.utilization >= 0 && window2.utilization < 1 ? [window2.resetAt] : [];
|
|
8979
|
+
});
|
|
8980
|
+
return Math.min(...resets, Number.POSITIVE_INFINITY);
|
|
8981
|
+
}
|
|
8326
8982
|
function liveUtilization(window2, now) {
|
|
8327
8983
|
if (window2.utilization === null)
|
|
8328
8984
|
return 0;
|
|
@@ -8345,11 +9001,11 @@ function soonestWeeklyReset(provider, account2, now) {
|
|
|
8345
9001
|
const resets = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => provider.isWeeklyBucket(bucket) && window2.resetAt !== null && window2.resetAt > now).map(([, window2]) => window2.resetAt);
|
|
8346
9002
|
return Math.min(...resets, Number.POSITIVE_INFINITY);
|
|
8347
9003
|
}
|
|
8348
|
-
function compareSeatUsage(provider, model, now) {
|
|
9004
|
+
function compareSeatUsage(provider, model, now, preferExpiringQuota = false) {
|
|
8349
9005
|
return (left, right) => {
|
|
8350
9006
|
const a = seatUsage(provider, left, model, now);
|
|
8351
9007
|
const b = seatUsage(provider, right, model, now);
|
|
8352
|
-
return a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
|
|
9008
|
+
return (preferExpiringQuota ? expiringReset(provider, left, model, now) - expiringReset(provider, right, model, now) : 0) || a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
|
|
8353
9009
|
};
|
|
8354
9010
|
}
|
|
8355
9011
|
var init_seat_usage = __esm(() => {
|
|
@@ -8361,12 +9017,12 @@ import { createHash as createHash2 } from "crypto";
|
|
|
8361
9017
|
function isRecord5(value) {
|
|
8362
9018
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8363
9019
|
}
|
|
8364
|
-
function openingDigest(
|
|
8365
|
-
if (!
|
|
9020
|
+
function openingDigest(request3, provider) {
|
|
9021
|
+
if (!request3.body || request3.body.byteLength > MAX_OPENING_BYTES || !request3.contentType?.toLowerCase().includes("application/json")) {
|
|
8366
9022
|
return null;
|
|
8367
9023
|
}
|
|
8368
9024
|
try {
|
|
8369
|
-
const parsed = JSON.parse(new TextDecoder().decode(
|
|
9025
|
+
const parsed = JSON.parse(new TextDecoder().decode(request3.body));
|
|
8370
9026
|
if (!isRecord5(parsed))
|
|
8371
9027
|
return null;
|
|
8372
9028
|
const opening = provider.getConversationOpening?.(parsed);
|
|
@@ -8377,14 +9033,14 @@ function openingDigest(request2, provider) {
|
|
|
8377
9033
|
return null;
|
|
8378
9034
|
}
|
|
8379
9035
|
}
|
|
8380
|
-
function pinKey(
|
|
8381
|
-
if (!
|
|
9036
|
+
function pinKey(request3, provider) {
|
|
9037
|
+
if (!request3.sessionId)
|
|
8382
9038
|
return null;
|
|
8383
|
-
const digest = openingDigest(
|
|
9039
|
+
const digest = openingDigest(request3, provider) ?? "no-opening";
|
|
8384
9040
|
return createHash2("sha256").update([
|
|
8385
|
-
|
|
8386
|
-
|
|
8387
|
-
|
|
9041
|
+
request3.pinScope ?? request3.provider,
|
|
9042
|
+
request3.pinBucket ?? provider.weeklyBucketFor(request3.model) ?? "",
|
|
9043
|
+
request3.sessionId,
|
|
8388
9044
|
digest
|
|
8389
9045
|
].join("\x00")).digest("hex");
|
|
8390
9046
|
}
|
|
@@ -8395,15 +9051,15 @@ function isAllowlisted(account2, config) {
|
|
|
8395
9051
|
class TeamRouter {
|
|
8396
9052
|
inFlight = new Map;
|
|
8397
9053
|
pins = new Map;
|
|
8398
|
-
order(accounts,
|
|
8399
|
-
if (!config.enabled || !
|
|
9054
|
+
order(accounts, request3, config, provider, store, now = Date.now()) {
|
|
9055
|
+
if (!config.enabled || !request3)
|
|
8400
9056
|
return accounts;
|
|
8401
9057
|
this.removeExpiredPins(now, store);
|
|
8402
|
-
const eligible = this.eligibleAccounts(accounts,
|
|
9058
|
+
const eligible = this.eligibleAccounts(accounts, request3, config);
|
|
8403
9059
|
if (eligible.length === 0)
|
|
8404
9060
|
return [];
|
|
8405
|
-
const key = pinKey(
|
|
8406
|
-
const pinnedId = this.getPinnedAccountId(
|
|
9061
|
+
const key = pinKey(request3, provider);
|
|
9062
|
+
const pinnedId = this.getPinnedAccountId(request3, config, provider, store, now);
|
|
8407
9063
|
const pinned = pinnedId ? eligible.find((account2) => account2.id === pinnedId) : undefined;
|
|
8408
9064
|
if (pinned && key) {
|
|
8409
9065
|
this.touchPin(key, pinned.id, now, store);
|
|
@@ -8414,27 +9070,27 @@ class TeamRouter {
|
|
|
8414
9070
|
}
|
|
8415
9071
|
if (!config.distributionEnabled || !key)
|
|
8416
9072
|
return eligible;
|
|
8417
|
-
const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider,
|
|
9073
|
+
const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
|
|
8418
9074
|
this.touchPin(key, selected.id, now, store);
|
|
8419
9075
|
return [
|
|
8420
9076
|
selected,
|
|
8421
9077
|
...eligible.filter((account2) => account2.id !== selected.id)
|
|
8422
9078
|
];
|
|
8423
9079
|
}
|
|
8424
|
-
eligibleAccounts(accounts,
|
|
9080
|
+
eligibleAccounts(accounts, request3, config) {
|
|
8425
9081
|
if (!config.enabled)
|
|
8426
9082
|
return accounts;
|
|
8427
9083
|
const eligible = accounts.filter((account2) => isAllowlisted(account2, config));
|
|
8428
|
-
if (!
|
|
9084
|
+
if (!request3?.manualAccountName)
|
|
8429
9085
|
return eligible;
|
|
8430
|
-
return eligible.filter((account2) => account2.name ===
|
|
9086
|
+
return eligible.filter((account2) => account2.name === request3.manualAccountName);
|
|
8431
9087
|
}
|
|
8432
|
-
getPinnedAccountId(
|
|
8433
|
-
if (!config.enabled || !
|
|
9088
|
+
getPinnedAccountId(request3, config, provider, store, now = Date.now()) {
|
|
9089
|
+
if (!config.enabled || !request3?.sessionId || request3.manualAccountName) {
|
|
8434
9090
|
return;
|
|
8435
9091
|
}
|
|
8436
9092
|
this.removeExpiredPins(now, store);
|
|
8437
|
-
const key = pinKey(
|
|
9093
|
+
const key = pinKey(request3, provider);
|
|
8438
9094
|
return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
|
|
8439
9095
|
}
|
|
8440
9096
|
begin(accountId) {
|
|
@@ -8448,10 +9104,10 @@ class TeamRouter {
|
|
|
8448
9104
|
}
|
|
8449
9105
|
this.inFlight.set(accountId, current - 1);
|
|
8450
9106
|
}
|
|
8451
|
-
rebind(
|
|
8452
|
-
if (!config.enabled ||
|
|
9107
|
+
rebind(request3, accountId, config, provider, store, now = Date.now()) {
|
|
9108
|
+
if (!config.enabled || request3?.manualAccountName)
|
|
8453
9109
|
return;
|
|
8454
|
-
const key =
|
|
9110
|
+
const key = request3 ? pinKey(request3, provider) : null;
|
|
8455
9111
|
if (key)
|
|
8456
9112
|
this.touchPin(key, accountId, now, store);
|
|
8457
9113
|
}
|
|
@@ -8522,18 +9178,32 @@ var init_proxy_types = __esm(() => {
|
|
|
8522
9178
|
});
|
|
8523
9179
|
|
|
8524
9180
|
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8525
|
-
function refreshBackoffUntil(
|
|
8526
|
-
const failure = refreshFailures.get(
|
|
9181
|
+
function refreshBackoffUntil(account2, now = Date.now()) {
|
|
9182
|
+
const failure = refreshFailures.get(account2.id);
|
|
9183
|
+
if (failure && (failure.accessToken !== account2.access_token || failure.refreshToken !== account2.refresh_token)) {
|
|
9184
|
+
refreshFailures.delete(account2.id);
|
|
9185
|
+
return null;
|
|
9186
|
+
}
|
|
8527
9187
|
return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
|
|
8528
9188
|
}
|
|
8529
9189
|
function quarantineAccount(account2, ctx, reason) {
|
|
9190
|
+
const { access_token: accessToken, refresh_token: refreshToken } = account2;
|
|
8530
9191
|
account2.paused = true;
|
|
8531
9192
|
account2.error_reason = reason;
|
|
8532
|
-
ctx.asyncWriter.enqueue(() =>
|
|
9193
|
+
ctx.asyncWriter.enqueue(() => {
|
|
9194
|
+
const saved = ctx.dbOps.getAccount(account2.id);
|
|
9195
|
+
if (saved?.access_token === accessToken && saved.refresh_token === refreshToken && !(saved.paused && !saved.error_reason))
|
|
9196
|
+
ctx.dbOps.markAccountError(account2.id, reason);
|
|
9197
|
+
});
|
|
8533
9198
|
}
|
|
8534
9199
|
function recordRefreshFailure(account2, ctx, error) {
|
|
8535
9200
|
const refreshError = new TokenRefreshError(account2.id, error);
|
|
8536
|
-
refreshFailures.set(account2.id, {
|
|
9201
|
+
refreshFailures.set(account2.id, {
|
|
9202
|
+
at: Date.now(),
|
|
9203
|
+
error: refreshError,
|
|
9204
|
+
accessToken: account2.access_token,
|
|
9205
|
+
refreshToken: account2.refresh_token
|
|
9206
|
+
});
|
|
8537
9207
|
const status = error?.status;
|
|
8538
9208
|
if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
|
8539
9209
|
quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
|
|
@@ -8543,7 +9213,7 @@ function recordRefreshFailure(account2, ctx, error) {
|
|
|
8543
9213
|
}
|
|
8544
9214
|
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8545
9215
|
const lastFailure = refreshFailures.get(account2.id);
|
|
8546
|
-
if (lastFailure && refreshBackoffUntil(account2
|
|
9216
|
+
if (lastFailure && refreshBackoffUntil(account2) !== null) {
|
|
8547
9217
|
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8548
9218
|
throw lastFailure.error;
|
|
8549
9219
|
}
|
|
@@ -8551,8 +9221,20 @@ async function refreshAccessTokenSafe(account2, ctx) {
|
|
|
8551
9221
|
if (!ctx.provider.refreshToken) {
|
|
8552
9222
|
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8553
9223
|
}
|
|
9224
|
+
const { access_token: accessToken, refresh_token: refreshToken } = account2;
|
|
9225
|
+
const reconnected = () => {
|
|
9226
|
+
const saved = ctx.dbOps.getAccount(account2.id);
|
|
9227
|
+
return saved && (saved.access_token !== accessToken || saved.refresh_token !== refreshToken) ? saved : null;
|
|
9228
|
+
};
|
|
8554
9229
|
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8555
|
-
|
|
9230
|
+
const saved = reconnected();
|
|
9231
|
+
if (saved?.access_token)
|
|
9232
|
+
return saved.access_token;
|
|
9233
|
+
ctx.asyncWriter.enqueue(() => {
|
|
9234
|
+
if (reconnected())
|
|
9235
|
+
return;
|
|
9236
|
+
ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken);
|
|
9237
|
+
});
|
|
8556
9238
|
account2.access_token = result.accessToken;
|
|
8557
9239
|
account2.expires_at = result.expiresAt;
|
|
8558
9240
|
if (result.refreshToken) {
|
|
@@ -8563,6 +9245,9 @@ async function refreshAccessTokenSafe(account2, ctx) {
|
|
|
8563
9245
|
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8564
9246
|
return result.accessToken;
|
|
8565
9247
|
}).catch((error) => {
|
|
9248
|
+
const saved = reconnected();
|
|
9249
|
+
if (saved?.access_token)
|
|
9250
|
+
return saved.access_token;
|
|
8566
9251
|
throw recordRefreshFailure(account2, ctx, error);
|
|
8567
9252
|
}).finally(() => {
|
|
8568
9253
|
ctx.refreshInFlight.delete(account2.id);
|
|
@@ -8601,32 +9286,44 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
|
|
|
8601
9286
|
const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
|
|
8602
9287
|
return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
|
|
8603
9288
|
}
|
|
8604
|
-
function pooledMaxUsage(account2, ctx) {
|
|
9289
|
+
function pooledMaxUsage(provider, account2, bucket, ctx) {
|
|
8605
9290
|
const teamRouting = ctx.runtime.teamRouting;
|
|
8606
|
-
|
|
9291
|
+
if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
|
|
9292
|
+
return;
|
|
9293
|
+
if (!provider.isWeeklyBucket(bucket))
|
|
9294
|
+
return teamRouting.maxUsage;
|
|
9295
|
+
const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
|
|
9296
|
+
const override = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
|
|
9297
|
+
return Math.min(teamRouting.weeklyMaxUsage, override ?? teamRouting.weeklyMaxUsage);
|
|
8607
9298
|
}
|
|
8608
9299
|
function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
|
|
8609
9300
|
const quota2 = account2.quota_state;
|
|
8610
9301
|
if (!quota2)
|
|
8611
9302
|
return true;
|
|
8612
9303
|
for (const [name, window2] of Object.entries(quota2.windows)) {
|
|
8613
|
-
if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(account2, ctx))) {
|
|
9304
|
+
if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx))) {
|
|
8614
9305
|
return false;
|
|
8615
9306
|
}
|
|
8616
9307
|
}
|
|
8617
9308
|
return true;
|
|
8618
9309
|
}
|
|
8619
9310
|
function fleetAccounts(provider, ctx) {
|
|
9311
|
+
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
|
|
9312
|
+
}
|
|
9313
|
+
function isFleetSeat(account2, ctx) {
|
|
8620
9314
|
const teamRouting = ctx.runtime.teamRouting;
|
|
8621
|
-
return
|
|
9315
|
+
return !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting));
|
|
8622
9316
|
}
|
|
8623
9317
|
function cooldownEnd(account2, now) {
|
|
8624
9318
|
const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
|
|
8625
|
-
const refreshEnd = refreshBackoffUntil(account2
|
|
9319
|
+
const refreshEnd = refreshBackoffUntil(account2, now);
|
|
8626
9320
|
return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
|
|
8627
9321
|
}
|
|
9322
|
+
function isServableSeat(provider, account2, model, ctx, now) {
|
|
9323
|
+
return isFleetSeat(account2, ctx) && cooldownEnd(account2, now) === null && isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
|
|
9324
|
+
}
|
|
8628
9325
|
function blockingResets(provider, account2, model, ctx, now) {
|
|
8629
|
-
return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt);
|
|
9326
|
+
return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket, ctx))).map(([, window2]) => window2.resetAt);
|
|
8630
9327
|
}
|
|
8631
9328
|
function servableAt(provider, account2, model, ctx, now) {
|
|
8632
9329
|
const cooldown = cooldownEnd(account2, now);
|
|
@@ -8653,7 +9350,7 @@ function getPoolStatus(provider, model, ctx) {
|
|
|
8653
9350
|
const config = ctx.runtime.teamRouting;
|
|
8654
9351
|
const now = Date.now();
|
|
8655
9352
|
const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
|
|
8656
|
-
const eligibleAccounts = accounts.filter((account2) =>
|
|
9353
|
+
const eligibleAccounts = accounts.filter((account2) => isServableSeat(providerStrategy, account2, model, ctx, now)).length;
|
|
8657
9354
|
return {
|
|
8658
9355
|
version: 1,
|
|
8659
9356
|
provider,
|
|
@@ -8671,14 +9368,14 @@ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
|
|
|
8671
9368
|
function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
|
|
8672
9369
|
return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8673
9370
|
}
|
|
8674
|
-
function selectRevalidationProbe(accounts, ctx, now) {
|
|
9371
|
+
function selectRevalidationProbe(accounts, ctx, now, model) {
|
|
8675
9372
|
const probes = ctx.quotaProbeAt;
|
|
8676
9373
|
const lastProbeAt = probes?.get(ctx.providerName);
|
|
8677
9374
|
if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
|
|
8678
9375
|
return [];
|
|
8679
9376
|
}
|
|
8680
9377
|
const [probe] = accounts.filter((account2) => {
|
|
8681
|
-
return
|
|
9378
|
+
return ctx.runtime.teamRouting?.enabled !== true || !isAllowlisted(account2, ctx.runtime.teamRouting) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
|
|
8682
9379
|
}).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
|
|
8683
9380
|
if (!probe)
|
|
8684
9381
|
return [];
|
|
@@ -8687,9 +9384,9 @@ function selectRevalidationProbe(accounts, ctx, now) {
|
|
|
8687
9384
|
}
|
|
8688
9385
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
8689
9386
|
const now = Date.now();
|
|
8690
|
-
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2
|
|
9387
|
+
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
|
|
8691
9388
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8692
|
-
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
|
|
9389
|
+
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model);
|
|
8693
9390
|
const prioritized = [...candidates].sort((left, right) => {
|
|
8694
9391
|
const priority = (left.priority ?? 0) - (right.priority ?? 0);
|
|
8695
9392
|
return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
|
|
@@ -8998,13 +9695,17 @@ class TeamAdmission {
|
|
|
8998
9695
|
const account2 = this.account(accountId, {
|
|
8999
9696
|
enabled: true,
|
|
9000
9697
|
distributionEnabled: true,
|
|
9698
|
+
preferExpiringQuota: false,
|
|
9001
9699
|
allowlistedAccountUuids: [],
|
|
9002
9700
|
maxUsage: 0.9,
|
|
9701
|
+
weeklyMaxUsage: 0.95,
|
|
9702
|
+
weeklyMaxUsageByEmail: {},
|
|
9003
9703
|
admissionCap: 1,
|
|
9004
9704
|
admissionQueueLimit: 0,
|
|
9005
9705
|
admissionWaitMs: 0,
|
|
9006
9706
|
holdSeconds: 0,
|
|
9007
|
-
quotaProbeSeconds: 0
|
|
9707
|
+
quotaProbeSeconds: 0,
|
|
9708
|
+
windowWarmup: WINDOW_WARMUP_DEFAULTS
|
|
9008
9709
|
});
|
|
9009
9710
|
if (account2.active > 0 || account2.queue.length > 0)
|
|
9010
9711
|
return;
|
|
@@ -9097,6 +9798,7 @@ class TeamAdmission {
|
|
|
9097
9798
|
}
|
|
9098
9799
|
var RAMP_INTERVAL_MS = 250, RAMP_WINDOW_MS = 30000, TeamAdmissionError;
|
|
9099
9800
|
var init_team_admission = __esm(() => {
|
|
9801
|
+
init_src7();
|
|
9100
9802
|
TeamAdmissionError = class TeamAdmissionError extends Error {
|
|
9101
9803
|
constructor(message) {
|
|
9102
9804
|
super(message);
|
|
@@ -9150,7 +9852,8 @@ async function forwardToClient(options, ctx) {
|
|
|
9150
9852
|
isStream,
|
|
9151
9853
|
providerName: ctx.providerName,
|
|
9152
9854
|
retryAttempt,
|
|
9153
|
-
failoverAttempts
|
|
9855
|
+
failoverAttempts,
|
|
9856
|
+
storePayload: ctx.runtime.storeRequestPayloads
|
|
9154
9857
|
};
|
|
9155
9858
|
ctx.usageWorker.postMessage(startMessage);
|
|
9156
9859
|
requestEvents.emit("event", {
|
|
@@ -9453,8 +10156,8 @@ function retryAfterMs(response) {
|
|
|
9453
10156
|
if (Number.isFinite(seconds)) {
|
|
9454
10157
|
return Math.max(0, seconds) * 1000;
|
|
9455
10158
|
}
|
|
9456
|
-
const
|
|
9457
|
-
return Number.isNaN(
|
|
10159
|
+
const date2 = Date.parse(value);
|
|
10160
|
+
return Number.isNaN(date2) ? undefined : Math.max(0, date2 - Date.now());
|
|
9458
10161
|
}
|
|
9459
10162
|
async function isQuotaRejection(response, provider) {
|
|
9460
10163
|
return await provider.isQuotaRejection?.(response) ?? false;
|
|
@@ -9911,37 +10614,37 @@ function quotaExhaustionResponse(resetAt2) {
|
|
|
9911
10614
|
headers: { "retry-after": String(retryAfterSeconds) }
|
|
9912
10615
|
});
|
|
9913
10616
|
}
|
|
9914
|
-
async function attemptAccount(
|
|
9915
|
-
|
|
9916
|
-
const admission =
|
|
10617
|
+
async function attemptAccount(request3, account2, failoverAttempts) {
|
|
10618
|
+
request3.req.signal.throwIfAborted();
|
|
10619
|
+
const admission = request3.ctx.teamAdmission;
|
|
9917
10620
|
let permit;
|
|
9918
10621
|
try {
|
|
9919
|
-
permit =
|
|
10622
|
+
permit = request3.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request3.ctx.runtime.teamRouting, request3.req.signal) : undefined;
|
|
9920
10623
|
} catch (error) {
|
|
9921
10624
|
if (error instanceof TeamAdmissionError) {
|
|
9922
|
-
throw new ServiceUnavailableError(error.message,
|
|
10625
|
+
throw new ServiceUnavailableError(error.message, request3.ctx.providerName, admissionRetrySeconds(request3.req));
|
|
9923
10626
|
}
|
|
9924
10627
|
throw error;
|
|
9925
10628
|
}
|
|
9926
10629
|
if (permit)
|
|
9927
|
-
|
|
9928
|
-
|
|
10630
|
+
request3.ctx.teamRouter?.begin(account2.id);
|
|
10631
|
+
request3.ctx.outsideSpendTracker?.begin(account2.id);
|
|
9929
10632
|
const release = () => {
|
|
9930
10633
|
permit?.release();
|
|
9931
10634
|
if (permit)
|
|
9932
|
-
|
|
9933
|
-
|
|
10635
|
+
request3.ctx.teamRouter?.end(account2.id);
|
|
10636
|
+
request3.ctx.outsideSpendTracker?.end(account2.id);
|
|
9934
10637
|
};
|
|
9935
10638
|
try {
|
|
9936
|
-
const attempt = await proxyWithAccount(
|
|
10639
|
+
const attempt = await proxyWithAccount(request3.req, request3.url, account2, request3.meta, request3.body, (body) => createBodyStream(body), request3.thread, failoverAttempts, request3.mappedModel, request3.ctx);
|
|
9937
10640
|
if (attempt.kind === "response") {
|
|
9938
|
-
const spentExtraUsage =
|
|
10641
|
+
const spentExtraUsage = request3.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
|
|
9939
10642
|
return {
|
|
9940
10643
|
...attempt,
|
|
9941
10644
|
response: releaseAfterResponse(attempt.response, () => {
|
|
9942
10645
|
release();
|
|
9943
10646
|
if (spentExtraUsage) {
|
|
9944
|
-
|
|
10647
|
+
request3.ctx.seatAlerts?.extraUsageSpent(account2, request3.ctx.providerName);
|
|
9945
10648
|
}
|
|
9946
10649
|
})
|
|
9947
10650
|
};
|
|
@@ -9953,14 +10656,14 @@ async function attemptAccount(request2, account2, failoverAttempts) {
|
|
|
9953
10656
|
throw error;
|
|
9954
10657
|
}
|
|
9955
10658
|
}
|
|
9956
|
-
async function resolvePerMinuteRateLimit(
|
|
10659
|
+
async function resolvePerMinuteRateLimit(request3, account2, failoverAttempts, attempt) {
|
|
9957
10660
|
if (attempt.retryAfterMs > MAX_INLINE_RATE_LIMIT_RETRY_MS) {
|
|
9958
10661
|
return await attempt.forward();
|
|
9959
10662
|
}
|
|
9960
10663
|
if (attempt.retryAfterMs > 0) {
|
|
9961
10664
|
await Bun.sleep(attempt.retryAfterMs);
|
|
9962
10665
|
}
|
|
9963
|
-
const retryAttempt = await attemptAccount(
|
|
10666
|
+
const retryAttempt = await attemptAccount(request3, account2, failoverAttempts);
|
|
9964
10667
|
if (retryAttempt.kind === "response") {
|
|
9965
10668
|
return retryAttempt.response;
|
|
9966
10669
|
}
|
|
@@ -9969,26 +10672,26 @@ async function resolvePerMinuteRateLimit(request2, account2, failoverAttempts, a
|
|
|
9969
10672
|
}
|
|
9970
10673
|
return await attempt.forward();
|
|
9971
10674
|
}
|
|
9972
|
-
async function resolveRequestScopedRateLimit(
|
|
10675
|
+
async function resolveRequestScopedRateLimit(request3, accounts, index, attempt) {
|
|
9973
10676
|
const sibling = accounts[index + 1];
|
|
9974
10677
|
if (!sibling) {
|
|
9975
10678
|
return await attempt.forward();
|
|
9976
10679
|
}
|
|
9977
|
-
|
|
9978
|
-
const siblingAttempt = await attemptAccount(
|
|
10680
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10681
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
9979
10682
|
if (siblingAttempt.kind === "response") {
|
|
9980
10683
|
return siblingAttempt.response;
|
|
9981
10684
|
}
|
|
9982
10685
|
if (siblingAttempt.kind === "per-minute-rate-limit") {
|
|
9983
|
-
return await resolvePerMinuteRateLimit(
|
|
10686
|
+
return await resolvePerMinuteRateLimit(request3, sibling, index + 1, siblingAttempt);
|
|
9984
10687
|
}
|
|
9985
10688
|
if (siblingAttempt.kind !== "request-scoped-rate-limit") {
|
|
9986
10689
|
return await attempt.forward();
|
|
9987
10690
|
}
|
|
9988
|
-
if (
|
|
9989
|
-
await Bun.sleep(
|
|
10691
|
+
if (request3.ctx.runtime.requestScopedRetryDelayMs > 0) {
|
|
10692
|
+
await Bun.sleep(request3.ctx.runtime.requestScopedRetryDelayMs);
|
|
9990
10693
|
}
|
|
9991
|
-
const retryAttempt = await attemptAccount(
|
|
10694
|
+
const retryAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
9992
10695
|
if (retryAttempt.kind === "response") {
|
|
9993
10696
|
return retryAttempt.response;
|
|
9994
10697
|
}
|
|
@@ -9997,14 +10700,14 @@ async function resolveRequestScopedRateLimit(request2, accounts, index, attempt)
|
|
|
9997
10700
|
}
|
|
9998
10701
|
return await attempt.forward();
|
|
9999
10702
|
}
|
|
10000
|
-
async function resolveQuotaRateLimit(
|
|
10703
|
+
async function resolveQuotaRateLimit(request3, accounts, index, attempt) {
|
|
10001
10704
|
const sibling = accounts[index + 1];
|
|
10002
10705
|
if (!sibling)
|
|
10003
10706
|
return await attempt.forward();
|
|
10004
|
-
|
|
10005
|
-
const siblingAttempt = await attemptAccount(
|
|
10707
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10708
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10006
10709
|
if (siblingAttempt.kind === "response") {
|
|
10007
|
-
|
|
10710
|
+
request3.ctx.teamRouter?.rebind(request3.teamRequest, sibling.id, request3.ctx.runtime.teamRouting, request3.ctx.provider, request3.ctx.dbOps);
|
|
10008
10711
|
return siblingAttempt.response;
|
|
10009
10712
|
}
|
|
10010
10713
|
if (siblingAttempt.kind === "authentication-failure") {
|
|
@@ -10020,13 +10723,13 @@ async function resolveQuotaRateLimit(request2, accounts, index, attempt) {
|
|
|
10020
10723
|
return await attempt.forward();
|
|
10021
10724
|
}
|
|
10022
10725
|
}
|
|
10023
|
-
async function resolveUpstreamFailure(
|
|
10726
|
+
async function resolveUpstreamFailure(request3, accounts, index, attempt) {
|
|
10024
10727
|
const sibling = accounts[index + 1];
|
|
10025
10728
|
if (!sibling) {
|
|
10026
10729
|
return await attempt.forward();
|
|
10027
10730
|
}
|
|
10028
|
-
|
|
10029
|
-
const siblingAttempt = await attemptAccount(
|
|
10731
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10732
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10030
10733
|
if (siblingAttempt.kind === "response") {
|
|
10031
10734
|
await discardAttempt(attempt);
|
|
10032
10735
|
return siblingAttempt.response;
|
|
@@ -10053,12 +10756,12 @@ async function discardAttempt(attempt) {
|
|
|
10053
10756
|
log21.warn(`Could not close a discarded upstream stream: ${error instanceof Error ? error.message : String(error)}`);
|
|
10054
10757
|
}
|
|
10055
10758
|
}
|
|
10056
|
-
async function resolveTransportFailure(
|
|
10759
|
+
async function resolveTransportFailure(request3, accounts, index) {
|
|
10057
10760
|
const sibling = accounts[index + 1];
|
|
10058
10761
|
if (!sibling)
|
|
10059
10762
|
return new Response("Bad Gateway", { status: 502 });
|
|
10060
|
-
|
|
10061
|
-
const siblingAttempt = await attemptAccount(
|
|
10763
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10764
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10062
10765
|
if (siblingAttempt.kind === "response")
|
|
10063
10766
|
return siblingAttempt.response;
|
|
10064
10767
|
switch (siblingAttempt.kind) {
|
|
@@ -10070,31 +10773,31 @@ async function resolveTransportFailure(request2, accounts, index) {
|
|
|
10070
10773
|
return new Response("Bad Gateway", { status: 502 });
|
|
10071
10774
|
}
|
|
10072
10775
|
}
|
|
10073
|
-
async function proxySelectedAccounts(
|
|
10776
|
+
async function proxySelectedAccounts(request3, accounts) {
|
|
10074
10777
|
for (let index = 0;index < accounts.length; index += 1) {
|
|
10075
|
-
const attempt = await attemptAccount(
|
|
10778
|
+
const attempt = await attemptAccount(request3, accounts[index], index);
|
|
10076
10779
|
if (attempt.kind === "response")
|
|
10077
10780
|
return attempt.response;
|
|
10078
10781
|
if (attempt.kind === "authentication-failure") {
|
|
10079
10782
|
return new Response("Bad Gateway", { status: 502 });
|
|
10080
10783
|
}
|
|
10081
10784
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10082
|
-
return await resolvePerMinuteRateLimit(
|
|
10785
|
+
return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
|
|
10083
10786
|
}
|
|
10084
10787
|
if (attempt.kind === "request-scoped-rate-limit") {
|
|
10085
|
-
return await resolveRequestScopedRateLimit(
|
|
10788
|
+
return await resolveRequestScopedRateLimit(request3, accounts, index, attempt);
|
|
10086
10789
|
}
|
|
10087
10790
|
if (attempt.kind === "quota-rate-limit") {
|
|
10088
|
-
return await resolveQuotaRateLimit(
|
|
10791
|
+
return await resolveQuotaRateLimit(request3, accounts, index, attempt);
|
|
10089
10792
|
}
|
|
10090
10793
|
if (attempt.kind === "upstream-failure") {
|
|
10091
|
-
return await resolveUpstreamFailure(
|
|
10794
|
+
return await resolveUpstreamFailure(request3, accounts, index, attempt);
|
|
10092
10795
|
}
|
|
10093
10796
|
if (attempt.kind === "transport-failure") {
|
|
10094
|
-
return await resolveTransportFailure(
|
|
10797
|
+
return await resolveTransportFailure(request3, accounts, index);
|
|
10095
10798
|
}
|
|
10096
10799
|
}
|
|
10097
|
-
throw new ServiceUnavailableError(`${ERROR_MESSAGES.ALL_ACCOUNTS_FAILED} (${accounts.length} attempted)`,
|
|
10800
|
+
throw new ServiceUnavailableError(`${ERROR_MESSAGES.ALL_ACCOUNTS_FAILED} (${accounts.length} attempted)`, request3.ctx.providerName);
|
|
10098
10801
|
}
|
|
10099
10802
|
var log21;
|
|
10100
10803
|
var init_proxy_attempts = __esm(() => {
|
|
@@ -10119,7 +10822,7 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
10119
10822
|
provider: ctx.providerName,
|
|
10120
10823
|
sessionId
|
|
10121
10824
|
};
|
|
10122
|
-
const
|
|
10825
|
+
const request3 = {
|
|
10123
10826
|
body,
|
|
10124
10827
|
ctx,
|
|
10125
10828
|
mappedModel,
|
|
@@ -10130,20 +10833,20 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
10130
10833
|
url
|
|
10131
10834
|
};
|
|
10132
10835
|
return {
|
|
10133
|
-
accounts: selectRequestAccounts(
|
|
10134
|
-
request:
|
|
10836
|
+
accounts: selectRequestAccounts(request3, selectionOptions),
|
|
10837
|
+
request: request3
|
|
10135
10838
|
};
|
|
10136
10839
|
}
|
|
10137
|
-
function onThreadSeat(
|
|
10138
|
-
const threadAccountId = getThreadBoundAccountId(
|
|
10840
|
+
function onThreadSeat(request3, accounts) {
|
|
10841
|
+
const threadAccountId = getThreadBoundAccountId(request3.ctx.messageThreads, request3.thread);
|
|
10139
10842
|
return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
|
|
10140
10843
|
}
|
|
10141
|
-
function selectRequestAccounts(
|
|
10142
|
-
return onThreadSeat(
|
|
10844
|
+
function selectRequestAccounts(request3, selectionOptions) {
|
|
10845
|
+
return onThreadSeat(request3, selectAccountsForRequest(request3.meta, request3.ctx, request3.teamRequest, selectionOptions));
|
|
10143
10846
|
}
|
|
10144
|
-
function getRequestRetryAt(
|
|
10145
|
-
const { ctx, teamRequest } =
|
|
10146
|
-
return getSoonestQuotaReset(
|
|
10847
|
+
function getRequestRetryAt(request3) {
|
|
10848
|
+
const { ctx, teamRequest } = request3;
|
|
10849
|
+
return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
|
|
10147
10850
|
}
|
|
10148
10851
|
var init_proxy_request = __esm(() => {
|
|
10149
10852
|
init_account_selector();
|
|
@@ -10188,10 +10891,10 @@ function preferPinnedProvider(pool, pinnedAccount) {
|
|
|
10188
10891
|
const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
|
|
10189
10892
|
return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
|
|
10190
10893
|
}
|
|
10191
|
-
async function proxyPoolCandidate(
|
|
10894
|
+
async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
|
|
10192
10895
|
for (let index = 0;index < accounts.length; index += 1) {
|
|
10193
10896
|
const account2 = accounts[index];
|
|
10194
|
-
const attempt = await attemptAccount(
|
|
10897
|
+
const attempt = await attemptAccount(request3, account2, index);
|
|
10195
10898
|
if (attempt.kind === "response") {
|
|
10196
10899
|
return { account: account2, kind: "response", response: attempt.response };
|
|
10197
10900
|
}
|
|
@@ -10204,13 +10907,13 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10204
10907
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10205
10908
|
return {
|
|
10206
10909
|
kind: "response",
|
|
10207
|
-
response: await resolvePerMinuteRateLimit(
|
|
10910
|
+
response: await resolvePerMinuteRateLimit(request3, account2, index, attempt)
|
|
10208
10911
|
};
|
|
10209
10912
|
}
|
|
10210
10913
|
if (attempt.kind === "request-scoped-rate-limit") {
|
|
10211
10914
|
return {
|
|
10212
10915
|
kind: "response",
|
|
10213
|
-
response: await resolveRequestScopedRateLimit(
|
|
10916
|
+
response: await resolveRequestScopedRateLimit(request3, accounts, index, attempt)
|
|
10214
10917
|
};
|
|
10215
10918
|
}
|
|
10216
10919
|
if (attempt.kind === "quota-rate-limit") {
|
|
@@ -10223,7 +10926,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10223
10926
|
}
|
|
10224
10927
|
return {
|
|
10225
10928
|
kind: "response",
|
|
10226
|
-
response: await resolveQuotaRateLimit(
|
|
10929
|
+
response: await resolveQuotaRateLimit(request3, accounts, index, attempt)
|
|
10227
10930
|
};
|
|
10228
10931
|
}
|
|
10229
10932
|
if (attempt.kind === "upstream-failure") {
|
|
@@ -10236,7 +10939,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10236
10939
|
}
|
|
10237
10940
|
return {
|
|
10238
10941
|
kind: "response",
|
|
10239
|
-
response: await resolveUpstreamFailure(
|
|
10942
|
+
response: await resolveUpstreamFailure(request3, accounts, index, attempt)
|
|
10240
10943
|
};
|
|
10241
10944
|
}
|
|
10242
10945
|
if (attempt.kind === "transport-failure") {
|
|
@@ -10248,7 +10951,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10248
10951
|
}
|
|
10249
10952
|
return {
|
|
10250
10953
|
kind: "response",
|
|
10251
|
-
response: await resolveTransportFailure(
|
|
10954
|
+
response: await resolveTransportFailure(request3, accounts, index)
|
|
10252
10955
|
};
|
|
10253
10956
|
}
|
|
10254
10957
|
}
|
|
@@ -10271,10 +10974,10 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
|
|
|
10271
10974
|
let everyCandidateFull = true;
|
|
10272
10975
|
let emittedIngress = false;
|
|
10273
10976
|
const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
|
|
10274
|
-
const recordUnserved = (
|
|
10275
|
-
everyCandidateFull &&= isEveryAccountQuotaBlocked(
|
|
10276
|
-
soonestRetry = earliest(soonestRetry, getRequestRetryAt(
|
|
10277
|
-
soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(
|
|
10977
|
+
const recordUnserved = (request3) => {
|
|
10978
|
+
everyCandidateFull &&= isEveryAccountQuotaBlocked(request3.meta, request3.ctx);
|
|
10979
|
+
soonestRetry = earliest(soonestRetry, getRequestRetryAt(request3));
|
|
10980
|
+
soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request3.meta, request3.ctx));
|
|
10278
10981
|
};
|
|
10279
10982
|
const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
|
|
10280
10983
|
for (const [candidateIndex, candidate] of candidates.entries()) {
|
|
@@ -10436,9 +11139,9 @@ class SeatAlerts {
|
|
|
10436
11139
|
}
|
|
10437
11140
|
if (!delivery.repliesOk)
|
|
10438
11141
|
return;
|
|
10439
|
-
const
|
|
10440
|
-
if (
|
|
10441
|
-
const code = typeof
|
|
11142
|
+
const reply2 = await response.json();
|
|
11143
|
+
if (reply2.ok !== true) {
|
|
11144
|
+
const code = typeof reply2.error === "string" && SLACK_ERROR_CODE.test(reply2.error) ? reply2.error : "no reason given";
|
|
10442
11145
|
log23.warn(`${delivery.channel} alert was refused (${code})`);
|
|
10443
11146
|
}
|
|
10444
11147
|
} catch (error) {
|
|
@@ -10904,17 +11607,17 @@ async function handleProxy(req, url, ctx) {
|
|
|
10904
11607
|
const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
|
|
10905
11608
|
const body = buffer ?? null;
|
|
10906
11609
|
requestMeta.model = readRequestModel(body);
|
|
10907
|
-
const { accounts: initiallySelectedAccounts, request:
|
|
11610
|
+
const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
|
|
10908
11611
|
let accounts = initiallySelectedAccounts;
|
|
10909
11612
|
if (accounts.length === 0) {
|
|
10910
11613
|
const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
|
|
10911
11614
|
alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
|
|
10912
|
-
const retryAt = getRequestRetryAt(
|
|
11615
|
+
const retryAt = getRequestRetryAt(request3);
|
|
10913
11616
|
if (retryAt !== null) {
|
|
10914
11617
|
const holdMs = holdSeconds * 1000;
|
|
10915
11618
|
if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
|
|
10916
11619
|
await requestContext.quotaHold.waitUntil(retryAt, req.signal);
|
|
10917
|
-
const resumedAccounts = selectRequestAccounts(
|
|
11620
|
+
const resumedAccounts = selectRequestAccounts(request3);
|
|
10918
11621
|
if (resumedAccounts.length > 0) {
|
|
10919
11622
|
accounts = resumedAccounts;
|
|
10920
11623
|
}
|
|
@@ -10936,7 +11639,7 @@ async function handleProxy(req, url, ctx) {
|
|
|
10936
11639
|
});
|
|
10937
11640
|
log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
|
|
10938
11641
|
log24.info(`Request: ${req.method} ${url.pathname}`);
|
|
10939
|
-
return await proxySelectedAccounts(
|
|
11642
|
+
return await proxySelectedAccounts(request3, accounts);
|
|
10940
11643
|
}
|
|
10941
11644
|
var log24, usageWorkerInstance = null;
|
|
10942
11645
|
var init_proxy = __esm(() => {
|
|
@@ -10999,6 +11702,12 @@ class QuotaHold {
|
|
|
10999
11702
|
}
|
|
11000
11703
|
|
|
11001
11704
|
// ../../packages/proxy/src/quota-probe.ts
|
|
11705
|
+
function recordSeatQuota(store, outsideSpend, provider, account2, quota2) {
|
|
11706
|
+
const observed = outsideSpend.observe(account2, quota2, provider);
|
|
11707
|
+
account2.quota_state = observed;
|
|
11708
|
+
store.updateAccountQuotaState(account2.id, observed);
|
|
11709
|
+
}
|
|
11710
|
+
|
|
11002
11711
|
class QuotaProbe {
|
|
11003
11712
|
config;
|
|
11004
11713
|
store;
|
|
@@ -11065,9 +11774,7 @@ class QuotaProbe {
|
|
|
11065
11774
|
const quota2 = await provider.probeQuota(account2, accessToken);
|
|
11066
11775
|
if (!quota2)
|
|
11067
11776
|
return;
|
|
11068
|
-
|
|
11069
|
-
account2.quota_state = observed;
|
|
11070
|
-
this.store.updateAccountQuotaState(account2.id, observed);
|
|
11777
|
+
recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
|
|
11071
11778
|
} catch {}
|
|
11072
11779
|
}
|
|
11073
11780
|
}
|
|
@@ -11341,7 +12048,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
|
|
|
11341
12048
|
isStream: true,
|
|
11342
12049
|
providerName: session.providerName,
|
|
11343
12050
|
retryAttempt: 0,
|
|
11344
|
-
failoverAttempts: Math.max(0, session.nextAccountIndex - 1)
|
|
12051
|
+
failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
|
|
12052
|
+
storePayload: session.requestContext.runtime.storeRequestPayloads
|
|
11345
12053
|
};
|
|
11346
12054
|
session.activeTurn = {
|
|
11347
12055
|
requestId,
|
|
@@ -11698,6 +12406,106 @@ var init_websocket_proxy = __esm(() => {
|
|
|
11698
12406
|
};
|
|
11699
12407
|
});
|
|
11700
12408
|
|
|
12409
|
+
// ../../packages/proxy/src/window-warmup.ts
|
|
12410
|
+
function fiveHourWindowRuns(provider, account2, now) {
|
|
12411
|
+
return Object.entries(account2.quota_state?.windows ?? {}).some(([bucket, window2]) => provider.isFiveHourBucket(bucket) && window2.resetAt !== null && isOpenQuotaWindow(window2, now));
|
|
12412
|
+
}
|
|
12413
|
+
|
|
12414
|
+
class WindowWarmup {
|
|
12415
|
+
runtime;
|
|
12416
|
+
store;
|
|
12417
|
+
outsideSpend;
|
|
12418
|
+
providers;
|
|
12419
|
+
readToken;
|
|
12420
|
+
now;
|
|
12421
|
+
running = false;
|
|
12422
|
+
timer;
|
|
12423
|
+
constructor(runtime, store, outsideSpend, providers2, readToken, now = Date.now) {
|
|
12424
|
+
this.runtime = runtime;
|
|
12425
|
+
this.store = store;
|
|
12426
|
+
this.outsideSpend = outsideSpend;
|
|
12427
|
+
this.providers = providers2;
|
|
12428
|
+
this.readToken = readToken;
|
|
12429
|
+
this.now = now;
|
|
12430
|
+
}
|
|
12431
|
+
start() {
|
|
12432
|
+
this.reschedule();
|
|
12433
|
+
}
|
|
12434
|
+
reschedule() {
|
|
12435
|
+
this.scheduleAfter(this.now());
|
|
12436
|
+
}
|
|
12437
|
+
async run() {
|
|
12438
|
+
const runtime = this.runtime();
|
|
12439
|
+
const routing = runtime.teamRouting;
|
|
12440
|
+
if (this.running || !routing.enabled || !routing.windowWarmup.enabled) {
|
|
12441
|
+
return;
|
|
12442
|
+
}
|
|
12443
|
+
this.running = true;
|
|
12444
|
+
try {
|
|
12445
|
+
const now = this.now();
|
|
12446
|
+
await Promise.all(this.store.getAllAccounts().flatMap((account2) => {
|
|
12447
|
+
const provider = this.providers.getProvider(account2.provider);
|
|
12448
|
+
return provider && this.needsWarmup(provider, account2, runtime, now) ? [this.warm(provider, account2, routing.windowWarmup.model)] : [];
|
|
12449
|
+
}));
|
|
12450
|
+
} finally {
|
|
12451
|
+
this.running = false;
|
|
12452
|
+
}
|
|
12453
|
+
}
|
|
12454
|
+
dispose() {
|
|
12455
|
+
if (this.timer)
|
|
12456
|
+
clearTimeout(this.timer);
|
|
12457
|
+
this.timer = undefined;
|
|
12458
|
+
}
|
|
12459
|
+
scheduleAfter(after) {
|
|
12460
|
+
this.dispose();
|
|
12461
|
+
const dueAt = nextWindowWarmupAt(this.runtime().teamRouting, after);
|
|
12462
|
+
if (dueAt === null)
|
|
12463
|
+
return;
|
|
12464
|
+
this.timer = setTimeout(() => void this.fire(dueAt), Math.max(0, dueAt - this.now()));
|
|
12465
|
+
this.timer.unref?.();
|
|
12466
|
+
}
|
|
12467
|
+
async fire(dueAt) {
|
|
12468
|
+
await this.run();
|
|
12469
|
+
this.scheduleAfter(Math.max(this.now(), dueAt));
|
|
12470
|
+
}
|
|
12471
|
+
needsWarmup(provider, account2, runtime, now) {
|
|
12472
|
+
return provider.startQuotaWindow !== undefined && provider.supportsQuotaProbe(account2) && !fiveHourWindowRuns(provider, account2, now) && isServableSeat(provider, account2, runtime.teamRouting.windowWarmup.model ?? undefined, { runtime, dbOps: this.store }, now);
|
|
12473
|
+
}
|
|
12474
|
+
async warm(provider, account2, model) {
|
|
12475
|
+
try {
|
|
12476
|
+
const accessToken = await this.readToken(account2);
|
|
12477
|
+
if (!accessToken) {
|
|
12478
|
+
log26.warn(`Window warm-up skipped ${account2.name}: no access token`);
|
|
12479
|
+
return;
|
|
12480
|
+
}
|
|
12481
|
+
const quota2 = await this.startWindow(provider, account2, accessToken, model);
|
|
12482
|
+
log26.info(`Window warm-up started ${account2.name}'s five-hour window`);
|
|
12483
|
+
if (quota2) {
|
|
12484
|
+
recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
|
|
12485
|
+
}
|
|
12486
|
+
} catch (error) {
|
|
12487
|
+
log26.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
12488
|
+
}
|
|
12489
|
+
}
|
|
12490
|
+
async startWindow(provider, account2, accessToken, model) {
|
|
12491
|
+
this.outsideSpend.begin(account2.id);
|
|
12492
|
+
try {
|
|
12493
|
+
return await provider.startQuotaWindow?.(account2, accessToken, model) ?? null;
|
|
12494
|
+
} finally {
|
|
12495
|
+
this.outsideSpend.end(account2.id);
|
|
12496
|
+
}
|
|
12497
|
+
}
|
|
12498
|
+
}
|
|
12499
|
+
var log26;
|
|
12500
|
+
var init_window_warmup2 = __esm(() => {
|
|
12501
|
+
init_src7();
|
|
12502
|
+
init_src4();
|
|
12503
|
+
init_src();
|
|
12504
|
+
init_account_selector();
|
|
12505
|
+
init_quota_probe();
|
|
12506
|
+
log26 = new Logger("WindowWarmup");
|
|
12507
|
+
});
|
|
12508
|
+
|
|
11701
12509
|
// ../../packages/proxy/src/index.ts
|
|
11702
12510
|
var init_src10 = __esm(() => {
|
|
11703
12511
|
init_background_tasks();
|
|
@@ -11712,6 +12520,7 @@ var init_src10 = __esm(() => {
|
|
|
11712
12520
|
init_team_admission();
|
|
11713
12521
|
init_team_router();
|
|
11714
12522
|
init_websocket_proxy();
|
|
12523
|
+
init_window_warmup2();
|
|
11715
12524
|
});
|
|
11716
12525
|
|
|
11717
12526
|
// ../../packages/runtime-server/src/device-keys.ts
|
|
@@ -11890,7 +12699,7 @@ function exposureFailure(req, url, server, config) {
|
|
|
11890
12699
|
if (!isSameOriginManagementRequest(req, url)) {
|
|
11891
12700
|
return jsonError(403, "Cross-origin management requests are not allowed");
|
|
11892
12701
|
}
|
|
11893
|
-
if (url.pathname === "/api/drain" || MUTATING_METHODS.has(req.method)) {
|
|
12702
|
+
if (url.pathname === "/api/drain" || /^\/api\/accounts\/[^/]+\/reset-credits(?:\/consume)?$/.test(url.pathname) || MUTATING_METHODS.has(req.method)) {
|
|
11894
12703
|
if (role !== "admin") {
|
|
11895
12704
|
return jsonError(401, "An admin key is required for management writes");
|
|
11896
12705
|
}
|
|
@@ -11926,13 +12735,14 @@ function createRuntimeConfig(config, port) {
|
|
|
11926
12735
|
},
|
|
11927
12736
|
sessionDurationMs: config.get("session_duration_ms", TIME_CONSTANTS.SESSION_DURATION_DEFAULT),
|
|
11928
12737
|
port,
|
|
12738
|
+
storeRequestPayloads: config.storesRequestPayloads(),
|
|
11929
12739
|
teamRouting: config.getTeamRouting()
|
|
11930
12740
|
};
|
|
11931
12741
|
}
|
|
11932
|
-
function wireStrategyHotReload(config,
|
|
12742
|
+
function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
|
|
11933
12743
|
config.on("change", (change) => {
|
|
11934
12744
|
if (change.key === "lb_strategy") {
|
|
11935
|
-
|
|
12745
|
+
log27.info("Strategy configuration changed");
|
|
11936
12746
|
const newStrategyName = config.getStrategy();
|
|
11937
12747
|
if (newStrategyName === "session") {
|
|
11938
12748
|
const strategy3 = new SessionStrategy;
|
|
@@ -11940,13 +12750,38 @@ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig
|
|
|
11940
12750
|
proxyContext.strategy = strategy3;
|
|
11941
12751
|
}
|
|
11942
12752
|
}
|
|
12753
|
+
if (change.key === "data_retention_days") {
|
|
12754
|
+
runtimeConfig2.storeRequestPayloads = config.storesRequestPayloads();
|
|
12755
|
+
}
|
|
11943
12756
|
if (change.key === "team_routing") {
|
|
11944
12757
|
runtimeConfig2.teamRouting = config.getTeamRouting();
|
|
11945
12758
|
quotaProbe.reschedule();
|
|
11946
|
-
|
|
12759
|
+
windowWarmup.reschedule();
|
|
12760
|
+
log27.info("Team routing configuration changed");
|
|
11947
12761
|
}
|
|
11948
12762
|
});
|
|
11949
12763
|
}
|
|
12764
|
+
function startSeatSchedulers(config, proxyContext, outsideSpendTracker) {
|
|
12765
|
+
const { dbOps, providerRegistry, runtime } = proxyContext;
|
|
12766
|
+
const readSeatToken = async (account2) => {
|
|
12767
|
+
const provider = providerRegistry.getProvider(account2.provider);
|
|
12768
|
+
if (!provider)
|
|
12769
|
+
return null;
|
|
12770
|
+
return await getValidAccessToken(account2, {
|
|
12771
|
+
...proxyContext,
|
|
12772
|
+
provider,
|
|
12773
|
+
providerName: account2.provider,
|
|
12774
|
+
upstreamPath: "/"
|
|
12775
|
+
});
|
|
12776
|
+
};
|
|
12777
|
+
const quotaProbe = new QuotaProbe(() => config.getTeamRouting(), dbOps, outsideSpendTracker, providerRegistry, readSeatToken);
|
|
12778
|
+
const windowWarmup = new WindowWarmup(() => runtime, dbOps, outsideSpendTracker, providerRegistry, readSeatToken);
|
|
12779
|
+
for (const scheduler of [quotaProbe, windowWarmup]) {
|
|
12780
|
+
scheduler.start();
|
|
12781
|
+
registerDisposable(scheduler);
|
|
12782
|
+
}
|
|
12783
|
+
return { quotaProbe, windowWarmup };
|
|
12784
|
+
}
|
|
11950
12785
|
function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
11951
12786
|
container.registerInstance(SERVICE_KEYS.Config, new Config);
|
|
11952
12787
|
container.registerInstance(SERVICE_KEYS.Logger, serverLog);
|
|
@@ -11957,7 +12792,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
11957
12792
|
sessionDurationMs: runtimeConfig2.sessionDurationMs
|
|
11958
12793
|
});
|
|
11959
12794
|
const dbOps = DatabaseFactory.getInstance();
|
|
11960
|
-
const
|
|
12795
|
+
const log27 = container.resolve(SERVICE_KEYS.Logger);
|
|
11961
12796
|
container.registerInstance(SERVICE_KEYS.Database, dbOps);
|
|
11962
12797
|
const asyncWriter = new AsyncDbWriter;
|
|
11963
12798
|
container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
|
|
@@ -11972,6 +12807,17 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
11972
12807
|
dbOps,
|
|
11973
12808
|
providerRegistry,
|
|
11974
12809
|
getProviders: () => providerRegistry.listProviders(),
|
|
12810
|
+
getAccountAccessToken: async (account2) => {
|
|
12811
|
+
const provider = providerRegistry.getProvider(account2.provider);
|
|
12812
|
+
if (!provider)
|
|
12813
|
+
throw new Error("Provider unavailable");
|
|
12814
|
+
return getValidAccessToken(account2, {
|
|
12815
|
+
...proxyContext,
|
|
12816
|
+
provider,
|
|
12817
|
+
providerName: account2.provider,
|
|
12818
|
+
upstreamPath: "/"
|
|
12819
|
+
});
|
|
12820
|
+
},
|
|
11975
12821
|
getPoolStatus: (provider, model) => getPoolStatus(provider, model, {
|
|
11976
12822
|
dbOps,
|
|
11977
12823
|
runtime: runtimeConfig2,
|
|
@@ -12010,24 +12856,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12010
12856
|
asyncWriter,
|
|
12011
12857
|
usageWorker: getUsageWorker()
|
|
12012
12858
|
};
|
|
12013
|
-
const quotaProbe =
|
|
12014
|
-
|
|
12015
|
-
if (!provider)
|
|
12016
|
-
return null;
|
|
12017
|
-
return await getValidAccessToken(account2, {
|
|
12018
|
-
...proxyContext,
|
|
12019
|
-
provider,
|
|
12020
|
-
providerName: account2.provider,
|
|
12021
|
-
upstreamPath: "/"
|
|
12022
|
-
});
|
|
12023
|
-
});
|
|
12024
|
-
quotaProbe.start();
|
|
12025
|
-
registerDisposable(quotaProbe);
|
|
12026
|
-
wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
|
|
12859
|
+
const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
|
|
12860
|
+
wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
|
|
12027
12861
|
return {
|
|
12028
12862
|
config,
|
|
12029
12863
|
dbOps,
|
|
12030
|
-
log:
|
|
12864
|
+
log: log27,
|
|
12031
12865
|
asyncWriter,
|
|
12032
12866
|
apiRouter,
|
|
12033
12867
|
exposureConfig,
|
|
@@ -12036,12 +12870,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12036
12870
|
runtimeConfig: runtimeConfig2
|
|
12037
12871
|
};
|
|
12038
12872
|
}
|
|
12039
|
-
function logInitialAccountStatus(
|
|
12873
|
+
function logInitialAccountStatus(log27, dbOps) {
|
|
12040
12874
|
const accounts = dbOps.getAllAccounts();
|
|
12041
12875
|
const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
|
|
12042
|
-
|
|
12876
|
+
log27.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
|
|
12043
12877
|
if (activeAccounts.length === 0) {
|
|
12044
|
-
|
|
12878
|
+
log27.warn("No active accounts available - requests will be refused with a 503 until an account is added");
|
|
12045
12879
|
}
|
|
12046
12880
|
}
|
|
12047
12881
|
var init_bootstrap_runtime = __esm(() => {
|
|
@@ -12282,6 +13116,44 @@ var init_fetch_handler = __esm(() => {
|
|
|
12282
13116
|
init_oauth_token();
|
|
12283
13117
|
});
|
|
12284
13118
|
|
|
13119
|
+
// ../../packages/runtime-server/src/retention-maintenance.ts
|
|
13120
|
+
function removeExpiredRequests(config, dbOps, log27, label) {
|
|
13121
|
+
try {
|
|
13122
|
+
const payloadDays = config.getDataRetentionDays();
|
|
13123
|
+
const requestDays = config.getRequestRetentionDays();
|
|
13124
|
+
const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
|
|
13125
|
+
log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
|
|
13126
|
+
} catch (err) {
|
|
13127
|
+
log27.error(`${label} cleanup error: ${err}`);
|
|
13128
|
+
}
|
|
13129
|
+
}
|
|
13130
|
+
function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
|
|
13131
|
+
const log27 = new Logger("RetentionMaintenance");
|
|
13132
|
+
removeExpiredRequests(config, dbOps, log27, "Startup");
|
|
13133
|
+
try {
|
|
13134
|
+
const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
|
|
13135
|
+
log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
|
|
13136
|
+
} catch (err) {
|
|
13137
|
+
log27.error(`Database compaction error: ${err}`);
|
|
13138
|
+
}
|
|
13139
|
+
const timer = setInterval(() => {
|
|
13140
|
+
removeExpiredRequests(config, dbOps, log27, "Periodic");
|
|
13141
|
+
try {
|
|
13142
|
+
dbOps.checkpointWal();
|
|
13143
|
+
} catch (err) {
|
|
13144
|
+
log27.error(`WAL checkpoint error: ${err}`);
|
|
13145
|
+
}
|
|
13146
|
+
}, intervalMs);
|
|
13147
|
+
timer.unref?.();
|
|
13148
|
+
return () => clearInterval(timer);
|
|
13149
|
+
}
|
|
13150
|
+
var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
|
|
13151
|
+
var init_retention_maintenance = __esm(() => {
|
|
13152
|
+
init_src4();
|
|
13153
|
+
DAY_MS2 = 24 * 60 * 60 * 1000;
|
|
13154
|
+
RETENTION_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
|
|
13155
|
+
});
|
|
13156
|
+
|
|
12285
13157
|
// ../../packages/runtime-server/src/startup-banner.ts
|
|
12286
13158
|
function createStartupBanner(options) {
|
|
12287
13159
|
const { version, port, withDashboard, strategy: strategy3, providers: providers2 } = options;
|
|
@@ -12312,29 +13184,6 @@ var init_startup_banner = __esm(() => {
|
|
|
12312
13184
|
init_src2();
|
|
12313
13185
|
});
|
|
12314
13186
|
|
|
12315
|
-
// ../../packages/runtime-server/src/startup-maintenance.ts
|
|
12316
|
-
function runStartupMaintenance(config, dbOps) {
|
|
12317
|
-
const log26 = new Logger("StartupMaintenance");
|
|
12318
|
-
try {
|
|
12319
|
-
const payloadDays = config.getDataRetentionDays();
|
|
12320
|
-
const requestDays = config.getRequestRetentionDays();
|
|
12321
|
-
const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
|
|
12322
|
-
log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
|
|
12323
|
-
} catch (err) {
|
|
12324
|
-
log26.error(`Startup cleanup error: ${err}`);
|
|
12325
|
-
}
|
|
12326
|
-
try {
|
|
12327
|
-
dbOps.compact();
|
|
12328
|
-
log26.info("Database compacted at startup");
|
|
12329
|
-
} catch (err) {
|
|
12330
|
-
log26.error(`Database compaction error: ${err}`);
|
|
12331
|
-
}
|
|
12332
|
-
return () => {};
|
|
12333
|
-
}
|
|
12334
|
-
var init_startup_maintenance = __esm(() => {
|
|
12335
|
-
init_src4();
|
|
12336
|
-
});
|
|
12337
|
-
|
|
12338
13187
|
// ../../packages/runtime-server/src/index.ts
|
|
12339
13188
|
import { isAbsolute as isAbsolute4 } from "path";
|
|
12340
13189
|
var {serve } = globalThis.Bun;
|
|
@@ -12450,14 +13299,14 @@ function startServer(options) {
|
|
|
12450
13299
|
const {
|
|
12451
13300
|
config,
|
|
12452
13301
|
dbOps,
|
|
12453
|
-
log:
|
|
13302
|
+
log: log27,
|
|
12454
13303
|
apiRouter,
|
|
12455
13304
|
exposureConfig,
|
|
12456
13305
|
proxyContext,
|
|
12457
13306
|
providerRegistry,
|
|
12458
13307
|
runtimeConfig: runtimeConfig2
|
|
12459
13308
|
} = bootstrapRuntime(port, serverLog, drain.control);
|
|
12460
|
-
stopRetentionJob =
|
|
13309
|
+
stopRetentionJob = startRetentionMaintenance(config, dbOps);
|
|
12461
13310
|
const fetchHandler = createServerFetchHandler({
|
|
12462
13311
|
apiRouter,
|
|
12463
13312
|
exposureConfig,
|
|
@@ -12495,7 +13344,7 @@ function startServer(options) {
|
|
|
12495
13344
|
strategy: config.getStrategy(),
|
|
12496
13345
|
providers: providerRegistry.listProviders()
|
|
12497
13346
|
}));
|
|
12498
|
-
logInitialAccountStatus(
|
|
13347
|
+
logInitialAccountStatus(log27, dbOps);
|
|
12499
13348
|
return {
|
|
12500
13349
|
port: activePort,
|
|
12501
13350
|
stop: () => stopServerRuntime(),
|
|
@@ -12528,8 +13377,8 @@ var init_src11 = __esm(() => {
|
|
|
12528
13377
|
init_dashboard_assets();
|
|
12529
13378
|
init_deployment_drain();
|
|
12530
13379
|
init_fetch_handler();
|
|
13380
|
+
init_retention_maintenance();
|
|
12531
13381
|
init_startup_banner();
|
|
12532
|
-
init_startup_maintenance();
|
|
12533
13382
|
init_fetch_handler();
|
|
12534
13383
|
init_startup_banner();
|
|
12535
13384
|
serverLog = new Logger("Server");
|