@certalis/agent-smith 0.1.15 → 0.1.17
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 +13 -1
- package/dist/bin.js +1473 -301
- package/dist/client-launcher.js +197 -19
- 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 +13 -2
- package/dist/pool-status.js +170 -0
- package/dist/pool.js +1097 -267
- package/dist/post-processor.worker.js +229 -25
- package/dist/server.js +1097 -267
- 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) {
|
|
@@ -4012,6 +4287,9 @@ function sanitizeClientRouting(value) {
|
|
|
4012
4287
|
if (typeof value.keep_claude_login === "boolean") {
|
|
4013
4288
|
client2.keep_claude_login = value.keep_claude_login;
|
|
4014
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
|
+
}
|
|
4015
4293
|
return Object.keys(client2).length > 0 ? client2 : undefined;
|
|
4016
4294
|
}
|
|
4017
4295
|
function sanitizeProviderModels(value) {
|
|
@@ -4079,12 +4357,25 @@ function sanitizeTeamRouting(value) {
|
|
|
4079
4357
|
if (typeof value.distribution_enabled === "boolean") {
|
|
4080
4358
|
result.distribution_enabled = value.distribution_enabled;
|
|
4081
4359
|
}
|
|
4360
|
+
if (typeof value.prefer_expiring_quota === "boolean") {
|
|
4361
|
+
result.prefer_expiring_quota = value.prefer_expiring_quota;
|
|
4362
|
+
}
|
|
4082
4363
|
if (Array.isArray(value.allowlisted_account_uuids) && value.allowlisted_account_uuids.every((entry) => typeof entry === "string" && entry.length > 0 && entry.length <= 200)) {
|
|
4083
4364
|
result.allowlisted_account_uuids = [...value.allowlisted_account_uuids];
|
|
4084
4365
|
}
|
|
4085
4366
|
if (isFiniteNumber(value.max_usage) && value.max_usage > 0 && value.max_usage <= 0.9) {
|
|
4086
4367
|
result.max_usage = value.max_usage;
|
|
4087
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
|
+
}
|
|
4088
4379
|
if (isNonNegativeFiniteNumber(value.admission_cap)) {
|
|
4089
4380
|
result.admission_cap = Math.floor(value.admission_cap);
|
|
4090
4381
|
}
|
|
@@ -4100,6 +4391,9 @@ function sanitizeTeamRouting(value) {
|
|
|
4100
4391
|
if (isNonNegativeFiniteNumber(value.quota_probe_seconds)) {
|
|
4101
4392
|
result.quota_probe_seconds = Math.min(Math.floor(value.quota_probe_seconds), 7 * 24 * 60 * 60);
|
|
4102
4393
|
}
|
|
4394
|
+
const windowWarmup = sanitizeWindowWarmup(value.window_warmup);
|
|
4395
|
+
if (windowWarmup)
|
|
4396
|
+
result.window_warmup = windowWarmup;
|
|
4103
4397
|
return result;
|
|
4104
4398
|
}
|
|
4105
4399
|
function readClientRouting(configPath = resolveConfigPath()) {
|
|
@@ -4119,17 +4413,20 @@ function clientRouting(client2) {
|
|
|
4119
4413
|
enabled: client2?.enabled === true,
|
|
4120
4414
|
...client2?.base_url && { baseUrl: client2.base_url },
|
|
4121
4415
|
...client2?.proxy_key_file && { proxyKeyFile: client2.proxy_key_file },
|
|
4122
|
-
...client2?.keep_claude_login === true && { keepClaudeLogin: true }
|
|
4416
|
+
...client2?.keep_claude_login === true && { keepClaudeLogin: true },
|
|
4417
|
+
...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
|
|
4123
4418
|
};
|
|
4124
4419
|
}
|
|
4125
|
-
var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
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;
|
|
4126
4421
|
var init_src7 = __esm(() => {
|
|
4127
4422
|
init_src2();
|
|
4128
4423
|
init_src4();
|
|
4129
4424
|
init_src();
|
|
4130
4425
|
init_paths();
|
|
4426
|
+
init_window_warmup();
|
|
4131
4427
|
init_paths();
|
|
4132
4428
|
init_paths_common();
|
|
4429
|
+
init_window_warmup();
|
|
4133
4430
|
log6 = new Logger("Config");
|
|
4134
4431
|
PROVIDER_STRATEGIES = [
|
|
4135
4432
|
"anthropic-api",
|
|
@@ -4145,16 +4442,21 @@ var init_src7 = __esm(() => {
|
|
|
4145
4442
|
];
|
|
4146
4443
|
BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
|
|
4147
4444
|
PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
|
|
4445
|
+
POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
|
|
4148
4446
|
TEAM_ROUTING_DEFAULTS = {
|
|
4149
4447
|
enabled: false,
|
|
4150
4448
|
distributionEnabled: true,
|
|
4449
|
+
preferExpiringQuota: false,
|
|
4151
4450
|
allowlistedAccountUuids: [],
|
|
4152
4451
|
maxUsage: 0.9,
|
|
4452
|
+
weeklyMaxUsage: 0.95,
|
|
4453
|
+
weeklyMaxUsageByEmail: {},
|
|
4153
4454
|
admissionCap: 5,
|
|
4154
4455
|
admissionQueueLimit: 25,
|
|
4155
4456
|
admissionWaitMs: 30000,
|
|
4156
4457
|
holdSeconds: 0,
|
|
4157
|
-
quotaProbeSeconds: 0
|
|
4458
|
+
quotaProbeSeconds: 0,
|
|
4459
|
+
windowWarmup: WINDOW_WARMUP_DEFAULTS
|
|
4158
4460
|
};
|
|
4159
4461
|
Config = class Config extends EventEmitter3 {
|
|
4160
4462
|
configPath;
|
|
@@ -4260,17 +4562,20 @@ var init_src7 = __esm(() => {
|
|
|
4260
4562
|
if (fromEnv) {
|
|
4261
4563
|
const n = parseInt(fromEnv, 10);
|
|
4262
4564
|
if (!Number.isNaN(n))
|
|
4263
|
-
return this.clamp(n,
|
|
4565
|
+
return this.clamp(n, 0, 365);
|
|
4264
4566
|
}
|
|
4265
4567
|
const fromFile = this.data.data_retention_days;
|
|
4266
4568
|
if (typeof fromFile === "number")
|
|
4267
|
-
return this.clamp(fromFile,
|
|
4569
|
+
return this.clamp(fromFile, 0, 365);
|
|
4268
4570
|
return 7;
|
|
4269
4571
|
}
|
|
4270
4572
|
setDataRetentionDays(days) {
|
|
4271
|
-
const clamped = this.clamp(days,
|
|
4573
|
+
const clamped = this.clamp(days, 0, 365);
|
|
4272
4574
|
this.set("data_retention_days", clamped);
|
|
4273
4575
|
}
|
|
4576
|
+
storesRequestPayloads() {
|
|
4577
|
+
return this.getDataRetentionDays() > 0;
|
|
4578
|
+
}
|
|
4274
4579
|
getRequestRetentionDays() {
|
|
4275
4580
|
const fromEnv = process.env.AGENT_SMITH_REQUEST_RETENTION_DAYS;
|
|
4276
4581
|
if (fromEnv) {
|
|
@@ -4301,15 +4606,19 @@ var init_src7 = __esm(() => {
|
|
|
4301
4606
|
return {
|
|
4302
4607
|
enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
|
|
4303
4608
|
distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
|
|
4609
|
+
preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
|
|
4304
4610
|
allowlistedAccountUuids: [
|
|
4305
4611
|
...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
|
|
4306
4612
|
],
|
|
4307
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 },
|
|
4308
4616
|
admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
|
|
4309
4617
|
admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
|
|
4310
4618
|
admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
|
|
4311
4619
|
holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
|
|
4312
|
-
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)
|
|
4313
4622
|
};
|
|
4314
4623
|
}
|
|
4315
4624
|
getAlerts() {
|
|
@@ -4368,13 +4677,17 @@ var init_src7 = __esm(() => {
|
|
|
4368
4677
|
const allowed = new Set([
|
|
4369
4678
|
"enabled",
|
|
4370
4679
|
"distribution_enabled",
|
|
4680
|
+
"prefer_expiring_quota",
|
|
4371
4681
|
"allowlisted_account_uuids",
|
|
4372
4682
|
"max_usage",
|
|
4683
|
+
"weekly_max_usage",
|
|
4684
|
+
"weekly_max_usage_by_email",
|
|
4373
4685
|
"admission_cap",
|
|
4374
4686
|
"admission_queue_limit",
|
|
4375
4687
|
"admission_wait_ms",
|
|
4376
4688
|
"hold_seconds",
|
|
4377
|
-
"quota_probe_seconds"
|
|
4689
|
+
"quota_probe_seconds",
|
|
4690
|
+
"window_warmup"
|
|
4378
4691
|
]);
|
|
4379
4692
|
if (Object.keys(value).some((key) => !allowed.has(key))) {
|
|
4380
4693
|
throw new Error("team routing configuration contains an unknown field");
|
|
@@ -4389,13 +4702,12 @@ var init_src7 = __esm(() => {
|
|
|
4389
4702
|
}
|
|
4390
4703
|
}
|
|
4391
4704
|
const oldValue = this.data.team_routing;
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
4395
|
-
|
|
4396
|
-
|
|
4397
|
-
|
|
4398
|
-
});
|
|
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);
|
|
4399
4711
|
}
|
|
4400
4712
|
allowAccountUuid(accountUuid) {
|
|
4401
4713
|
const current = this.getTeamRouting().allowlistedAccountUuids;
|
|
@@ -4418,10 +4730,18 @@ var init_src7 = __esm(() => {
|
|
|
4418
4730
|
getEnrollmentEmails() {
|
|
4419
4731
|
return [...this.data.enrollment_emails ?? []];
|
|
4420
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
|
+
}
|
|
4421
4741
|
setEnrollmentEmails(emails) {
|
|
4422
|
-
const normalized = emails.map(
|
|
4742
|
+
const normalized = emails.map(normalizeEnrollmentRule);
|
|
4423
4743
|
if (normalized.some((email) => email === undefined)) {
|
|
4424
|
-
throw new ValidationError("Invalid enrollment email", "enrollment_emails");
|
|
4744
|
+
throw new ValidationError("Invalid enrollment email or exact-domain rule (use *@example.com)", "enrollment_emails");
|
|
4425
4745
|
}
|
|
4426
4746
|
const unique = [...new Set(normalized)];
|
|
4427
4747
|
if (unique.length > MAX_ENROLLMENT_EMAILS) {
|
|
@@ -4451,6 +4771,7 @@ var init_src7 = __esm(() => {
|
|
|
4451
4771
|
},
|
|
4452
4772
|
sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
|
|
4453
4773
|
port: NETWORK.DEFAULT_PORT,
|
|
4774
|
+
storeRequestPayloads: this.storesRequestPayloads(),
|
|
4454
4775
|
teamRouting: this.getTeamRouting()
|
|
4455
4776
|
};
|
|
4456
4777
|
if (process.env.AGENT_SMITH_CLIENT_ID) {
|
|
@@ -4974,7 +5295,7 @@ function backfillRequestLinkageColumns(db) {
|
|
|
4974
5295
|
FROM requests r
|
|
4975
5296
|
LEFT JOIN request_payloads rp ON rp.id = r.id
|
|
4976
5297
|
ORDER BY r.timestamp ASC
|
|
4977
|
-
`).
|
|
5298
|
+
`).iterate();
|
|
4978
5299
|
const responseToChain = new Map;
|
|
4979
5300
|
let updatedRows = 0;
|
|
4980
5301
|
const updateStmt = db.prepare(`
|
|
@@ -6132,7 +6453,7 @@ var init_request_repository = __esm(() => {
|
|
|
6132
6453
|
}
|
|
6133
6454
|
save(data) {
|
|
6134
6455
|
const { usage, timings } = data;
|
|
6135
|
-
const payloadJson = data.payload === undefined ? undefined : JSON.stringify(data.payload);
|
|
6456
|
+
const payloadJson = data.payload === undefined || data.storePayload === false ? undefined : JSON.stringify(data.payload);
|
|
6136
6457
|
const linkage = requestLinkageFromPayload(data.payload);
|
|
6137
6458
|
const responseChainId = this.resolveResponseChainId(linkage.previousResponseId, linkage.responseId, data.id);
|
|
6138
6459
|
this.db.run("BEGIN");
|
|
@@ -6512,7 +6833,11 @@ var init_request_repository = __esm(() => {
|
|
|
6512
6833
|
return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
|
|
6513
6834
|
}
|
|
6514
6835
|
deletePayloadsOlderThan(cutoffTs) {
|
|
6515
|
-
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]);
|
|
6516
6841
|
}
|
|
6517
6842
|
};
|
|
6518
6843
|
});
|
|
@@ -6639,11 +6964,16 @@ var init_strategy_repository = __esm(() => {
|
|
|
6639
6964
|
|
|
6640
6965
|
// ../../packages/database/src/database-operations.ts
|
|
6641
6966
|
import { Database } from "bun:sqlite";
|
|
6642
|
-
import { mkdirSync as mkdirSync3 } from "fs";
|
|
6967
|
+
import { mkdirSync as mkdirSync3, statfsSync } from "fs";
|
|
6643
6968
|
import { dirname as dirname2 } from "path";
|
|
6969
|
+
function freeDiskBytes(directory) {
|
|
6970
|
+
const { bavail, bsize } = statfsSync(directory);
|
|
6971
|
+
return bavail * bsize;
|
|
6972
|
+
}
|
|
6644
6973
|
|
|
6645
6974
|
class DatabaseOperations {
|
|
6646
6975
|
db;
|
|
6976
|
+
dbPath;
|
|
6647
6977
|
runtime;
|
|
6648
6978
|
closed = false;
|
|
6649
6979
|
accounts;
|
|
@@ -6655,6 +6985,7 @@ class DatabaseOperations {
|
|
|
6655
6985
|
stats;
|
|
6656
6986
|
constructor(dbPath) {
|
|
6657
6987
|
const resolvedPath = dbPath ?? resolveDbPath();
|
|
6988
|
+
this.dbPath = resolvedPath;
|
|
6658
6989
|
const dir = dirname2(resolvedPath);
|
|
6659
6990
|
mkdirSync3(dir, { recursive: true });
|
|
6660
6991
|
this.db = new Database(resolvedPath, { create: true });
|
|
@@ -6787,6 +7118,7 @@ class DatabaseOperations {
|
|
|
6787
7118
|
usage,
|
|
6788
7119
|
timestamp: options?.timestamp,
|
|
6789
7120
|
payload: options?.payload,
|
|
7121
|
+
storePayload: options?.storePayload,
|
|
6790
7122
|
timings: options?.timings
|
|
6791
7123
|
});
|
|
6792
7124
|
}
|
|
@@ -6871,7 +7203,7 @@ class DatabaseOperations {
|
|
|
6871
7203
|
return;
|
|
6872
7204
|
}
|
|
6873
7205
|
this.closed = true;
|
|
6874
|
-
this.
|
|
7206
|
+
this.checkpointWal();
|
|
6875
7207
|
this.db.close();
|
|
6876
7208
|
}
|
|
6877
7209
|
dispose() {
|
|
@@ -6881,9 +7213,23 @@ class DatabaseOperations {
|
|
|
6881
7213
|
this.db.exec("PRAGMA optimize");
|
|
6882
7214
|
this.db.exec("PRAGMA wal_checkpoint(PASSIVE)");
|
|
6883
7215
|
}
|
|
6884
|
-
|
|
7216
|
+
checkpointWal() {
|
|
6885
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
|
+
}
|
|
6886
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;
|
|
6887
7233
|
}
|
|
6888
7234
|
getStatsRepository() {
|
|
6889
7235
|
return this.stats;
|
|
@@ -7115,7 +7461,10 @@ function createConfigHandlers(config) {
|
|
|
7115
7461
|
getStrategies: () => {
|
|
7116
7462
|
return jsonResponse(LB_STRATEGIES);
|
|
7117
7463
|
},
|
|
7118
|
-
getTeamRouting: () =>
|
|
7464
|
+
getTeamRouting: () => {
|
|
7465
|
+
const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
|
|
7466
|
+
return jsonResponse(routing);
|
|
7467
|
+
},
|
|
7119
7468
|
setTeamRouting: async (req) => {
|
|
7120
7469
|
try {
|
|
7121
7470
|
const body = await parseJsonObject(req);
|
|
@@ -7145,7 +7494,7 @@ function createConfigHandlers(config) {
|
|
|
7145
7494
|
let updated = false;
|
|
7146
7495
|
if (body.payloadDays !== undefined) {
|
|
7147
7496
|
const payloadDays = validateNumber(body.payloadDays, "payloadDays", {
|
|
7148
|
-
min:
|
|
7497
|
+
min: 0,
|
|
7149
7498
|
max: 365,
|
|
7150
7499
|
integer: true
|
|
7151
7500
|
});
|
|
@@ -7211,7 +7560,7 @@ function enrollmentPage() {
|
|
|
7211
7560
|
<section class="card" id="step-email" hidden>
|
|
7212
7561
|
<div class="avatar">${icon("mail")}</div>
|
|
7213
7562
|
<h1 tabindex="-1">Connect your Claude subscription</h1>
|
|
7214
|
-
<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>
|
|
7215
7564
|
<form id="request">
|
|
7216
7565
|
<p class="notice err" id="email-error" role="alert" hidden></p>
|
|
7217
7566
|
<label for="email">Work email<input id="email" type="email" autocomplete="email" spellcheck="false" required maxlength="254"></label>
|
|
@@ -7224,16 +7573,16 @@ function enrollmentPage() {
|
|
|
7224
7573
|
<h1 tabindex="-1">Sign in with Claude</h1>
|
|
7225
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>
|
|
7226
7575
|
<ul class="facts">
|
|
7227
|
-
<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>
|
|
7228
7577
|
<li>Your password stays with Claude. The pool only keeps the authorization it needs to run agents.</li>
|
|
7229
|
-
<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>
|
|
7230
7579
|
</ul>
|
|
7231
7580
|
<button class="button" id="start" type="button">Continue to Claude ${icon("open")}</button>
|
|
7232
7581
|
</section>
|
|
7233
7582
|
<section class="card" id="step-code" hidden>
|
|
7234
7583
|
<div class="avatar">${icon("code")}</div>
|
|
7235
7584
|
<h1 tabindex="-1">Paste the code from Claude</h1>
|
|
7236
|
-
<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>
|
|
7237
7586
|
<form id="verify">
|
|
7238
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>
|
|
7239
7588
|
<button class="button" type="submit">Verify account</button>
|
|
@@ -7243,42 +7592,47 @@ function enrollmentPage() {
|
|
|
7243
7592
|
<section class="card" id="step-confirm" hidden>
|
|
7244
7593
|
<div class="avatar">${icon("person")}</div>
|
|
7245
7594
|
<h1 tabindex="-1">Is this the right account?</h1>
|
|
7246
|
-
<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>
|
|
7247
7596
|
<form id="confirm">
|
|
7248
7597
|
<div class="account">${icon("check")}<span id="account"></span></div>
|
|
7249
7598
|
<label class="consent"><input id="consent" type="checkbox" required><span>I authorize the shared agents pool to use this subscription.</span></label>
|
|
7250
|
-
<button class="button" type="submit">
|
|
7599
|
+
<button class="button" type="submit">Confirm connection</button>
|
|
7251
7600
|
</form>
|
|
7252
|
-
<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>
|
|
7253
7602
|
</section>
|
|
7254
7603
|
<section class="card" id="step-done" hidden>
|
|
7255
7604
|
<div class="avatar ok">${icon("check")}</div>
|
|
7256
|
-
<h1 tabindex="-1">Subscription connected</h1>
|
|
7257
|
-
<p class="lead"><strong id="connected-account"></strong
|
|
7258
|
-
<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>
|
|
7259
7608
|
</section>
|
|
7260
7609
|
<section class="card" id="step-error" hidden>
|
|
7261
7610
|
<div class="avatar err">${icon("alert")}</div>
|
|
7262
7611
|
<h1 tabindex="-1">This sign-in can't continue</h1>
|
|
7263
7612
|
<p class="lead" id="error-message"></p>
|
|
7264
|
-
<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>
|
|
7265
7615
|
</section>
|
|
7266
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>
|
|
7267
7619
|
</main>
|
|
7268
|
-
<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>
|
|
7269
7621
|
<noscript><p class="notice err">JavaScript is required for this sign-in.</p></noscript>
|
|
7270
7622
|
<script nonce="${nonce}">
|
|
7271
7623
|
let token = location.hash.slice(1);
|
|
7272
|
-
history.replaceState(null, '', location.pathname);
|
|
7624
|
+
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) { token = ''; history.replaceState(null, '', location.pathname); }
|
|
7273
7625
|
addEventListener('hashchange', () => { if (location.hash) location.reload(); });
|
|
7274
7626
|
const get = id => document.getElementById(id);
|
|
7275
7627
|
const steps = ['email', 'signin', 'code', 'confirm', 'done'];
|
|
7276
7628
|
let current = 'email';
|
|
7629
|
+
let pending = 0;
|
|
7277
7630
|
function show(step) {
|
|
7278
7631
|
const failed = step === 'error';
|
|
7279
7632
|
const index = steps.indexOf(failed ? current : step);
|
|
7280
7633
|
if (!failed) current = step;
|
|
7281
7634
|
for (const name of [...steps, 'error']) get('step-' + name).hidden = name !== step;
|
|
7635
|
+
get('restart').hidden = step === 'email';
|
|
7282
7636
|
document.querySelectorAll('#stepper li').forEach((item, position) => {
|
|
7283
7637
|
item.className = position < index || step === 'done' ? 'done' : position === index ? (failed ? 'failed' : 'active') : '';
|
|
7284
7638
|
item.querySelector('.dot').innerHTML = item.className === 'done' ? '${icon("check")}' : String(position + 1);
|
|
@@ -7288,23 +7642,78 @@ function show(step) {
|
|
|
7288
7642
|
(step === 'email' ? get('email') : get('step-' + step).querySelector('h1')).focus();
|
|
7289
7643
|
}
|
|
7290
7644
|
async function send(step, body) {
|
|
7291
|
-
|
|
7292
|
-
|
|
7293
|
-
|
|
7294
|
-
|
|
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);
|
|
7295
7656
|
return data;
|
|
7296
7657
|
}
|
|
7297
|
-
|
|
7298
|
-
|
|
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) {
|
|
7299
7686
|
token = ''; get('code').value = '';
|
|
7300
|
-
get('
|
|
7687
|
+
get('recovery').hidden = true;
|
|
7688
|
+
get('error-message').textContent = error instanceof Error ? error.message : 'Sign-in failed. Try resuming.';
|
|
7301
7689
|
show('error');
|
|
7302
7690
|
}
|
|
7303
|
-
|
|
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
|
+
});
|
|
7304
7712
|
get('request').addEventListener('submit', async event => {
|
|
7305
7713
|
event.preventDefault(); event.submitter.disabled = true; get('email-error').hidden = true;
|
|
7306
7714
|
try {
|
|
7307
7715
|
const data = await send('request', {email: get('email').value});
|
|
7716
|
+
token = ''; history.replaceState(null, '', location.pathname); get('recovery').hidden = true;
|
|
7308
7717
|
get('signin-email').textContent = data.email; get('signin-for').hidden = false;
|
|
7309
7718
|
show('signin');
|
|
7310
7719
|
} catch (error) {
|
|
@@ -7317,24 +7726,26 @@ get('start').addEventListener('click', async () => {
|
|
|
7317
7726
|
get('start').disabled = true;
|
|
7318
7727
|
try {
|
|
7319
7728
|
const data = await post('start', {});
|
|
7320
|
-
const url =
|
|
7321
|
-
|
|
7322
|
-
|
|
7323
|
-
|
|
7324
|
-
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.';
|
|
7325
7733
|
show('code');
|
|
7326
|
-
} catch (error) { if (tab) tab.close(); fail(error); }
|
|
7734
|
+
} catch (error) { if (tab) tab.close(); await fail(error); }
|
|
7735
|
+
finally { get('start').disabled = false; }
|
|
7327
7736
|
});
|
|
7328
7737
|
get('verify').addEventListener('submit', async event => {
|
|
7329
7738
|
event.preventDefault(); event.submitter.disabled = true;
|
|
7330
7739
|
const code = get('code').value.trim(); get('code').value = '';
|
|
7331
7740
|
try { const data = await post('verify', {code}); get('account').textContent = data.email; show('confirm'); }
|
|
7332
|
-
catch (error) { fail(error); }
|
|
7741
|
+
catch (error) { await fail(error); }
|
|
7742
|
+
finally { event.submitter.disabled = false; }
|
|
7333
7743
|
});
|
|
7334
7744
|
get('confirm').addEventListener('submit', async event => {
|
|
7335
7745
|
event.preventDefault(); if (!get('consent').checked) return; event.submitter.disabled = true;
|
|
7336
|
-
try { await post('confirm', {consent:true})
|
|
7337
|
-
catch (error) { fail(error); }
|
|
7746
|
+
try { connected(await post('confirm', {consent:true})); }
|
|
7747
|
+
catch (error) { await fail(error); }
|
|
7748
|
+
finally { event.submitter.disabled = false; }
|
|
7338
7749
|
});
|
|
7339
7750
|
get('disconnect').addEventListener('click', async () => {
|
|
7340
7751
|
get('disconnect').disabled = true; get('status').hidden = true;
|
|
@@ -7446,12 +7857,68 @@ class EnrollmentHandlers {
|
|
|
7446
7857
|
if (entry.expiresAt <= this.now())
|
|
7447
7858
|
this.entries.delete(key);
|
|
7448
7859
|
}
|
|
7449
|
-
mint(details, state, duration) {
|
|
7860
|
+
mint(details, state, duration, browserSession) {
|
|
7450
7861
|
const token = randomBytes2(32).toString("base64url");
|
|
7451
7862
|
const expiresAt = this.now() + duration;
|
|
7452
|
-
this.entries.set(hash(token), {
|
|
7863
|
+
this.entries.set(hash(token), {
|
|
7864
|
+
details,
|
|
7865
|
+
state,
|
|
7866
|
+
expiresAt,
|
|
7867
|
+
browserSession
|
|
7868
|
+
});
|
|
7453
7869
|
return { token, expiresAt };
|
|
7454
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
|
+
}
|
|
7455
7922
|
async guarded(action) {
|
|
7456
7923
|
try {
|
|
7457
7924
|
this.prune();
|
|
@@ -7466,14 +7933,14 @@ class EnrollmentHandlers {
|
|
|
7466
7933
|
if (!this.context.providerRegistry.getOAuthProvider("claude-code"))
|
|
7467
7934
|
throw new EnrollmentError(400, "Provider 'claude-code' is disabled. Set providers.claude-code.enabled to true in your config.");
|
|
7468
7935
|
}
|
|
7469
|
-
reserve(name) {
|
|
7470
|
-
if (this.context.dbOps.getAccountByName(name))
|
|
7936
|
+
reserve(name, reconnect = false) {
|
|
7937
|
+
if (!reconnect && this.context.dbOps.getAccountByName(name))
|
|
7471
7938
|
throw new EnrollmentError(409, "This seat is already in the pool.");
|
|
7472
7939
|
for (const entry of this.entries.values())
|
|
7473
7940
|
if (entry.details.name === name && entry.state.kind === "busy")
|
|
7474
7941
|
throw new EnrollmentError(409, "Sign-in is already in progress");
|
|
7475
7942
|
for (const [key, entry] of this.entries)
|
|
7476
|
-
if (entry.details.name === name)
|
|
7943
|
+
if (entry.details.name === name && entry.state.kind !== "connected")
|
|
7477
7944
|
this.entries.delete(key);
|
|
7478
7945
|
if (this.entries.size >= 100)
|
|
7479
7946
|
throw new EnrollmentError(429, "Too many pending invitations");
|
|
@@ -7483,12 +7950,32 @@ class EnrollmentHandlers {
|
|
|
7483
7950
|
if (Object.keys(body).some((key) => key !== "email"))
|
|
7484
7951
|
throw new EnrollmentError(400, "Unknown request field");
|
|
7485
7952
|
const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
|
7486
|
-
if (!this.context.config.
|
|
7487
|
-
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.");
|
|
7488
7955
|
const name = email.slice(0, email.indexOf("@")).replace(/[^a-z0-9._+-]/g, "-").slice(0, 64);
|
|
7489
|
-
this.
|
|
7490
|
-
const
|
|
7491
|
-
|
|
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
|
+
});
|
|
7492
7979
|
}
|
|
7493
7980
|
emails = (req) => this.guarded(async () => {
|
|
7494
7981
|
const body = await readBody(req);
|
|
@@ -7557,9 +8044,20 @@ class EnrollmentHandlers {
|
|
|
7557
8044
|
const body = await readBody(req);
|
|
7558
8045
|
if (url.pathname === "/pool-enroll/request")
|
|
7559
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
|
+
}
|
|
7560
8059
|
const token = typeof body.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(body.token) ? body.token : "";
|
|
7561
|
-
const key = hash(token);
|
|
7562
|
-
const entry = this.entries.get(key);
|
|
8060
|
+
const [key, entry] = body.token === undefined ? this.browserEntry(req) ?? ["", undefined] : [hash(token), this.entries.get(hash(token))];
|
|
7563
8061
|
const expected = url.pathname === "/pool-enroll/start" ? "invited" : url.pathname === "/pool-enroll/verify" ? "started" : url.pathname === "/pool-enroll/confirm" ? "verified" : "connected";
|
|
7564
8062
|
if (!entry || entry.expiresAt <= this.now() || entry.state.kind !== expected)
|
|
7565
8063
|
throw new EnrollmentError(410, "This sign-in has expired or was already used. Start again.");
|
|
@@ -7569,8 +8067,7 @@ class EnrollmentHandlers {
|
|
|
7569
8067
|
if (state.kind === "invited") {
|
|
7570
8068
|
const flow = await this.oauth.beginClaudeSeat();
|
|
7571
8069
|
this.assertCurrent(key, entry);
|
|
7572
|
-
return
|
|
7573
|
-
...this.mint(entry.details, { kind: "started", flow }, tenMinutes),
|
|
8070
|
+
return this.next(entry, { kind: "started", flow }, tenMinutes, req, {
|
|
7574
8071
|
authUrl: flow.authUrl
|
|
7575
8072
|
});
|
|
7576
8073
|
}
|
|
@@ -7587,9 +8084,8 @@ class EnrollmentHandlers {
|
|
|
7587
8084
|
const { email } = seat.identity;
|
|
7588
8085
|
if (!email || entry.details.email && email.toLowerCase() !== entry.details.email.toLowerCase())
|
|
7589
8086
|
throw new EnrollmentError(400, "This Claude account does not match your email. Start again and sign in with the matching account.");
|
|
7590
|
-
this.
|
|
7591
|
-
return
|
|
7592
|
-
...this.mint(entry.details, { kind: "verified", seat }, tenMinutes),
|
|
8087
|
+
this.assertSeat(entry.details, seat);
|
|
8088
|
+
return this.next(entry, { kind: "verified", seat }, tenMinutes, req, {
|
|
7593
8089
|
email
|
|
7594
8090
|
});
|
|
7595
8091
|
}
|
|
@@ -7597,13 +8093,16 @@ class EnrollmentHandlers {
|
|
|
7597
8093
|
if (body.consent !== true)
|
|
7598
8094
|
throw new EnrollmentError(400, "Confirm the displayed account before adding it");
|
|
7599
8095
|
const accountId = this.save(entry.details, state.seat);
|
|
7600
|
-
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, {
|
|
7601
8102
|
connected: true,
|
|
7602
|
-
|
|
7603
|
-
|
|
7604
|
-
|
|
7605
|
-
accountUuid: state.seat.identity.accountUuid
|
|
7606
|
-
}, oneDay)
|
|
8103
|
+
email: state.seat.identity.email,
|
|
8104
|
+
reconnected: !!entry.details.reconnect,
|
|
8105
|
+
...this.connectionStatus(accountId)
|
|
7607
8106
|
});
|
|
7608
8107
|
}
|
|
7609
8108
|
if (state.kind === "connected") {
|
|
@@ -7615,9 +8114,8 @@ class EnrollmentHandlers {
|
|
|
7615
8114
|
entry.state = state;
|
|
7616
8115
|
throw new EnrollmentError(500, "Removal could not be saved. Retry here or ask the operator to check this seat.");
|
|
7617
8116
|
}
|
|
7618
|
-
return
|
|
7619
|
-
disconnected: true
|
|
7620
|
-
...this.mint(entry.details, { kind: "invited" }, oneDay)
|
|
8117
|
+
return this.next({ ...entry, details: { ...entry.details, reconnect: undefined } }, { kind: "invited" }, oneDay, req, {
|
|
8118
|
+
disconnected: true
|
|
7621
8119
|
});
|
|
7622
8120
|
}
|
|
7623
8121
|
throw new EnrollmentError(410, "Link already used");
|
|
@@ -7631,14 +8129,40 @@ class EnrollmentHandlers {
|
|
|
7631
8129
|
if (this.entries.get(key) !== entry || entry.expiresAt <= this.now())
|
|
7632
8130
|
throw new EnrollmentError(410, "Sign-in expired. Start again.");
|
|
7633
8131
|
}
|
|
7634
|
-
|
|
7635
|
-
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))
|
|
7636
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
|
+
};
|
|
7637
8149
|
}
|
|
7638
8150
|
save(details, seat) {
|
|
7639
8151
|
const { dbOps, config } = this.context;
|
|
7640
8152
|
return dbOps.getDatabase().transaction(() => {
|
|
7641
|
-
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
|
+
}
|
|
7642
8166
|
const account2 = dbOps.createOAuthAccount({
|
|
7643
8167
|
name: details.name,
|
|
7644
8168
|
provider: "claude-code",
|
|
@@ -7707,7 +8231,7 @@ async function readBody(req) {
|
|
|
7707
8231
|
reader.releaseLock();
|
|
7708
8232
|
}
|
|
7709
8233
|
}
|
|
7710
|
-
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;
|
|
7711
8235
|
var init_enrollment = __esm(() => {
|
|
7712
8236
|
init_src2();
|
|
7713
8237
|
init_src6();
|
|
@@ -7719,7 +8243,9 @@ var init_enrollment = __esm(() => {
|
|
|
7719
8243
|
"/pool-enroll/start",
|
|
7720
8244
|
"/pool-enroll/verify",
|
|
7721
8245
|
"/pool-enroll/confirm",
|
|
7722
|
-
"/pool-enroll/disconnect"
|
|
8246
|
+
"/pool-enroll/disconnect",
|
|
8247
|
+
"/pool-enroll/resume",
|
|
8248
|
+
"/pool-enroll/reset"
|
|
7723
8249
|
]);
|
|
7724
8250
|
headers2 = {
|
|
7725
8251
|
"cache-control": "no-store",
|
|
@@ -7872,7 +8398,13 @@ function createCleanupHandler(dbOps, config) {
|
|
|
7872
8398
|
function createCompactHandler(dbOps) {
|
|
7873
8399
|
return () => {
|
|
7874
8400
|
try {
|
|
7875
|
-
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
|
+
}
|
|
7876
8408
|
const result = {
|
|
7877
8409
|
success: true,
|
|
7878
8410
|
message: "Database compacted successfully"
|
|
@@ -7892,10 +8424,10 @@ var init_maintenance = __esm(() => {
|
|
|
7892
8424
|
});
|
|
7893
8425
|
|
|
7894
8426
|
// ../../packages/api/src/serializers/request.ts
|
|
7895
|
-
function serializeRequestResponse(
|
|
8427
|
+
function serializeRequestResponse(request3) {
|
|
7896
8428
|
return {
|
|
7897
|
-
...toRequestSummary(
|
|
7898
|
-
accountName:
|
|
8429
|
+
...toRequestSummary(request3),
|
|
8430
|
+
accountName: request3.accountName ?? null
|
|
7899
8431
|
};
|
|
7900
8432
|
}
|
|
7901
8433
|
function enrichRequestPayload(payload, accountName = null) {
|
|
@@ -8017,6 +8549,94 @@ var init_requests_stream = __esm(() => {
|
|
|
8017
8549
|
init_src();
|
|
8018
8550
|
});
|
|
8019
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
|
+
|
|
8020
8640
|
// ../../packages/api/src/handlers/stats.ts
|
|
8021
8641
|
function createStatsHandler(dbOps) {
|
|
8022
8642
|
return () => {
|
|
@@ -8092,17 +8712,22 @@ function blockedReason(account2, threshold, now) {
|
|
|
8092
8712
|
function createFleetStatusHandler(dbOps, config, providerRegistry) {
|
|
8093
8713
|
return () => {
|
|
8094
8714
|
const now = Date.now();
|
|
8095
|
-
const quotaThreshold = config.getRuntime()
|
|
8715
|
+
const { quotaThreshold, teamRouting } = config.getRuntime();
|
|
8096
8716
|
const accounts = dbOps.getAllAccounts().map((account2) => ({
|
|
8097
8717
|
...serializeAccount(account2, providerRegistry, now),
|
|
8098
8718
|
blockedReason: blockedReason(account2, quotaThreshold, now),
|
|
8099
8719
|
quotaWindows: account2.quota_state?.windows ?? {},
|
|
8100
8720
|
outsideSpend: account2.quota_state?.outsideSpend ?? {}
|
|
8101
8721
|
}));
|
|
8102
|
-
return jsonResponse({
|
|
8722
|
+
return jsonResponse({
|
|
8723
|
+
accounts,
|
|
8724
|
+
quotaThreshold,
|
|
8725
|
+
nextWindowWarmupAt: nextWindowWarmupAt(teamRouting, now)
|
|
8726
|
+
});
|
|
8103
8727
|
};
|
|
8104
8728
|
}
|
|
8105
8729
|
var init_status = __esm(() => {
|
|
8730
|
+
init_src7();
|
|
8106
8731
|
init_src3();
|
|
8107
8732
|
init_src();
|
|
8108
8733
|
init_account();
|
|
@@ -8154,6 +8779,9 @@ class APIRouter {
|
|
|
8154
8779
|
const statsResetHandler = createStatsResetHandler(dbOps);
|
|
8155
8780
|
const fleetStatusHandler = createFleetStatusHandler(dbOps, config, providerRegistry);
|
|
8156
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));
|
|
8157
8785
|
const accountAddHandler = createAccountAddHandler(dbOps, config, providerRegistry);
|
|
8158
8786
|
const requestsSummaryHandler = createRequestsSummaryHandler(dbOps);
|
|
8159
8787
|
const requestsDetailHandler = createRequestsDetailHandler(dbOps);
|
|
@@ -8312,6 +8940,7 @@ var init_router = __esm(() => {
|
|
|
8312
8940
|
init_oauth6();
|
|
8313
8941
|
init_requests();
|
|
8314
8942
|
init_requests_stream();
|
|
8943
|
+
init_reset_credits2();
|
|
8315
8944
|
init_stats2();
|
|
8316
8945
|
init_status();
|
|
8317
8946
|
});
|
|
@@ -8342,6 +8971,14 @@ var init_background_tasks = __esm(() => {
|
|
|
8342
8971
|
});
|
|
8343
8972
|
|
|
8344
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
|
+
}
|
|
8345
8982
|
function liveUtilization(window2, now) {
|
|
8346
8983
|
if (window2.utilization === null)
|
|
8347
8984
|
return 0;
|
|
@@ -8364,11 +9001,11 @@ function soonestWeeklyReset(provider, account2, now) {
|
|
|
8364
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);
|
|
8365
9002
|
return Math.min(...resets, Number.POSITIVE_INFINITY);
|
|
8366
9003
|
}
|
|
8367
|
-
function compareSeatUsage(provider, model, now) {
|
|
9004
|
+
function compareSeatUsage(provider, model, now, preferExpiringQuota = false) {
|
|
8368
9005
|
return (left, right) => {
|
|
8369
9006
|
const a = seatUsage(provider, left, model, now);
|
|
8370
9007
|
const b = seatUsage(provider, right, model, now);
|
|
8371
|
-
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);
|
|
8372
9009
|
};
|
|
8373
9010
|
}
|
|
8374
9011
|
var init_seat_usage = __esm(() => {
|
|
@@ -8380,12 +9017,12 @@ import { createHash as createHash2 } from "crypto";
|
|
|
8380
9017
|
function isRecord5(value) {
|
|
8381
9018
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8382
9019
|
}
|
|
8383
|
-
function openingDigest(
|
|
8384
|
-
if (!
|
|
9020
|
+
function openingDigest(request3, provider) {
|
|
9021
|
+
if (!request3.body || request3.body.byteLength > MAX_OPENING_BYTES || !request3.contentType?.toLowerCase().includes("application/json")) {
|
|
8385
9022
|
return null;
|
|
8386
9023
|
}
|
|
8387
9024
|
try {
|
|
8388
|
-
const parsed = JSON.parse(new TextDecoder().decode(
|
|
9025
|
+
const parsed = JSON.parse(new TextDecoder().decode(request3.body));
|
|
8389
9026
|
if (!isRecord5(parsed))
|
|
8390
9027
|
return null;
|
|
8391
9028
|
const opening = provider.getConversationOpening?.(parsed);
|
|
@@ -8396,14 +9033,14 @@ function openingDigest(request2, provider) {
|
|
|
8396
9033
|
return null;
|
|
8397
9034
|
}
|
|
8398
9035
|
}
|
|
8399
|
-
function pinKey(
|
|
8400
|
-
if (!
|
|
9036
|
+
function pinKey(request3, provider) {
|
|
9037
|
+
if (!request3.sessionId)
|
|
8401
9038
|
return null;
|
|
8402
|
-
const digest = openingDigest(
|
|
9039
|
+
const digest = openingDigest(request3, provider) ?? "no-opening";
|
|
8403
9040
|
return createHash2("sha256").update([
|
|
8404
|
-
|
|
8405
|
-
|
|
8406
|
-
|
|
9041
|
+
request3.pinScope ?? request3.provider,
|
|
9042
|
+
request3.pinBucket ?? provider.weeklyBucketFor(request3.model) ?? "",
|
|
9043
|
+
request3.sessionId,
|
|
8407
9044
|
digest
|
|
8408
9045
|
].join("\x00")).digest("hex");
|
|
8409
9046
|
}
|
|
@@ -8414,15 +9051,15 @@ function isAllowlisted(account2, config) {
|
|
|
8414
9051
|
class TeamRouter {
|
|
8415
9052
|
inFlight = new Map;
|
|
8416
9053
|
pins = new Map;
|
|
8417
|
-
order(accounts,
|
|
8418
|
-
if (!config.enabled || !
|
|
9054
|
+
order(accounts, request3, config, provider, store, now = Date.now()) {
|
|
9055
|
+
if (!config.enabled || !request3)
|
|
8419
9056
|
return accounts;
|
|
8420
9057
|
this.removeExpiredPins(now, store);
|
|
8421
|
-
const eligible = this.eligibleAccounts(accounts,
|
|
9058
|
+
const eligible = this.eligibleAccounts(accounts, request3, config);
|
|
8422
9059
|
if (eligible.length === 0)
|
|
8423
9060
|
return [];
|
|
8424
|
-
const key = pinKey(
|
|
8425
|
-
const pinnedId = this.getPinnedAccountId(
|
|
9061
|
+
const key = pinKey(request3, provider);
|
|
9062
|
+
const pinnedId = this.getPinnedAccountId(request3, config, provider, store, now);
|
|
8426
9063
|
const pinned = pinnedId ? eligible.find((account2) => account2.id === pinnedId) : undefined;
|
|
8427
9064
|
if (pinned && key) {
|
|
8428
9065
|
this.touchPin(key, pinned.id, now, store);
|
|
@@ -8433,27 +9070,27 @@ class TeamRouter {
|
|
|
8433
9070
|
}
|
|
8434
9071
|
if (!config.distributionEnabled || !key)
|
|
8435
9072
|
return eligible;
|
|
8436
|
-
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));
|
|
8437
9074
|
this.touchPin(key, selected.id, now, store);
|
|
8438
9075
|
return [
|
|
8439
9076
|
selected,
|
|
8440
9077
|
...eligible.filter((account2) => account2.id !== selected.id)
|
|
8441
9078
|
];
|
|
8442
9079
|
}
|
|
8443
|
-
eligibleAccounts(accounts,
|
|
9080
|
+
eligibleAccounts(accounts, request3, config) {
|
|
8444
9081
|
if (!config.enabled)
|
|
8445
9082
|
return accounts;
|
|
8446
9083
|
const eligible = accounts.filter((account2) => isAllowlisted(account2, config));
|
|
8447
|
-
if (!
|
|
9084
|
+
if (!request3?.manualAccountName)
|
|
8448
9085
|
return eligible;
|
|
8449
|
-
return eligible.filter((account2) => account2.name ===
|
|
9086
|
+
return eligible.filter((account2) => account2.name === request3.manualAccountName);
|
|
8450
9087
|
}
|
|
8451
|
-
getPinnedAccountId(
|
|
8452
|
-
if (!config.enabled || !
|
|
9088
|
+
getPinnedAccountId(request3, config, provider, store, now = Date.now()) {
|
|
9089
|
+
if (!config.enabled || !request3?.sessionId || request3.manualAccountName) {
|
|
8453
9090
|
return;
|
|
8454
9091
|
}
|
|
8455
9092
|
this.removeExpiredPins(now, store);
|
|
8456
|
-
const key = pinKey(
|
|
9093
|
+
const key = pinKey(request3, provider);
|
|
8457
9094
|
return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
|
|
8458
9095
|
}
|
|
8459
9096
|
begin(accountId) {
|
|
@@ -8467,10 +9104,10 @@ class TeamRouter {
|
|
|
8467
9104
|
}
|
|
8468
9105
|
this.inFlight.set(accountId, current - 1);
|
|
8469
9106
|
}
|
|
8470
|
-
rebind(
|
|
8471
|
-
if (!config.enabled ||
|
|
9107
|
+
rebind(request3, accountId, config, provider, store, now = Date.now()) {
|
|
9108
|
+
if (!config.enabled || request3?.manualAccountName)
|
|
8472
9109
|
return;
|
|
8473
|
-
const key =
|
|
9110
|
+
const key = request3 ? pinKey(request3, provider) : null;
|
|
8474
9111
|
if (key)
|
|
8475
9112
|
this.touchPin(key, accountId, now, store);
|
|
8476
9113
|
}
|
|
@@ -8541,18 +9178,32 @@ var init_proxy_types = __esm(() => {
|
|
|
8541
9178
|
});
|
|
8542
9179
|
|
|
8543
9180
|
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8544
|
-
function refreshBackoffUntil(
|
|
8545
|
-
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
|
+
}
|
|
8546
9187
|
return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
|
|
8547
9188
|
}
|
|
8548
9189
|
function quarantineAccount(account2, ctx, reason) {
|
|
9190
|
+
const { access_token: accessToken, refresh_token: refreshToken } = account2;
|
|
8549
9191
|
account2.paused = true;
|
|
8550
9192
|
account2.error_reason = reason;
|
|
8551
|
-
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
|
+
});
|
|
8552
9198
|
}
|
|
8553
9199
|
function recordRefreshFailure(account2, ctx, error) {
|
|
8554
9200
|
const refreshError = new TokenRefreshError(account2.id, error);
|
|
8555
|
-
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
|
+
});
|
|
8556
9207
|
const status = error?.status;
|
|
8557
9208
|
if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
|
8558
9209
|
quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
|
|
@@ -8562,7 +9213,7 @@ function recordRefreshFailure(account2, ctx, error) {
|
|
|
8562
9213
|
}
|
|
8563
9214
|
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8564
9215
|
const lastFailure = refreshFailures.get(account2.id);
|
|
8565
|
-
if (lastFailure && refreshBackoffUntil(account2
|
|
9216
|
+
if (lastFailure && refreshBackoffUntil(account2) !== null) {
|
|
8566
9217
|
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8567
9218
|
throw lastFailure.error;
|
|
8568
9219
|
}
|
|
@@ -8570,8 +9221,20 @@ async function refreshAccessTokenSafe(account2, ctx) {
|
|
|
8570
9221
|
if (!ctx.provider.refreshToken) {
|
|
8571
9222
|
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8572
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
|
+
};
|
|
8573
9229
|
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8574
|
-
|
|
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
|
+
});
|
|
8575
9238
|
account2.access_token = result.accessToken;
|
|
8576
9239
|
account2.expires_at = result.expiresAt;
|
|
8577
9240
|
if (result.refreshToken) {
|
|
@@ -8582,6 +9245,9 @@ async function refreshAccessTokenSafe(account2, ctx) {
|
|
|
8582
9245
|
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8583
9246
|
return result.accessToken;
|
|
8584
9247
|
}).catch((error) => {
|
|
9248
|
+
const saved = reconnected();
|
|
9249
|
+
if (saved?.access_token)
|
|
9250
|
+
return saved.access_token;
|
|
8585
9251
|
throw recordRefreshFailure(account2, ctx, error);
|
|
8586
9252
|
}).finally(() => {
|
|
8587
9253
|
ctx.refreshInFlight.delete(account2.id);
|
|
@@ -8620,32 +9286,44 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
|
|
|
8620
9286
|
const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
|
|
8621
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);
|
|
8622
9288
|
}
|
|
8623
|
-
function pooledMaxUsage(account2, ctx) {
|
|
9289
|
+
function pooledMaxUsage(provider, account2, bucket, ctx) {
|
|
8624
9290
|
const teamRouting = ctx.runtime.teamRouting;
|
|
8625
|
-
|
|
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);
|
|
8626
9298
|
}
|
|
8627
9299
|
function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
|
|
8628
9300
|
const quota2 = account2.quota_state;
|
|
8629
9301
|
if (!quota2)
|
|
8630
9302
|
return true;
|
|
8631
9303
|
for (const [name, window2] of Object.entries(quota2.windows)) {
|
|
8632
|
-
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))) {
|
|
8633
9305
|
return false;
|
|
8634
9306
|
}
|
|
8635
9307
|
}
|
|
8636
9308
|
return true;
|
|
8637
9309
|
}
|
|
8638
9310
|
function fleetAccounts(provider, ctx) {
|
|
9311
|
+
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
|
|
9312
|
+
}
|
|
9313
|
+
function isFleetSeat(account2, ctx) {
|
|
8639
9314
|
const teamRouting = ctx.runtime.teamRouting;
|
|
8640
|
-
return
|
|
9315
|
+
return !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting));
|
|
8641
9316
|
}
|
|
8642
9317
|
function cooldownEnd(account2, now) {
|
|
8643
9318
|
const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
|
|
8644
|
-
const refreshEnd = refreshBackoffUntil(account2
|
|
9319
|
+
const refreshEnd = refreshBackoffUntil(account2, now);
|
|
8645
9320
|
return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
|
|
8646
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
|
+
}
|
|
8647
9325
|
function blockingResets(provider, account2, model, ctx, now) {
|
|
8648
|
-
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);
|
|
8649
9327
|
}
|
|
8650
9328
|
function servableAt(provider, account2, model, ctx, now) {
|
|
8651
9329
|
const cooldown = cooldownEnd(account2, now);
|
|
@@ -8672,7 +9350,7 @@ function getPoolStatus(provider, model, ctx) {
|
|
|
8672
9350
|
const config = ctx.runtime.teamRouting;
|
|
8673
9351
|
const now = Date.now();
|
|
8674
9352
|
const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
|
|
8675
|
-
const eligibleAccounts = accounts.filter((account2) =>
|
|
9353
|
+
const eligibleAccounts = accounts.filter((account2) => isServableSeat(providerStrategy, account2, model, ctx, now)).length;
|
|
8676
9354
|
return {
|
|
8677
9355
|
version: 1,
|
|
8678
9356
|
provider,
|
|
@@ -8690,14 +9368,14 @@ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
|
|
|
8690
9368
|
function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
|
|
8691
9369
|
return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8692
9370
|
}
|
|
8693
|
-
function selectRevalidationProbe(accounts, ctx, now) {
|
|
9371
|
+
function selectRevalidationProbe(accounts, ctx, now, model) {
|
|
8694
9372
|
const probes = ctx.quotaProbeAt;
|
|
8695
9373
|
const lastProbeAt = probes?.get(ctx.providerName);
|
|
8696
9374
|
if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
|
|
8697
9375
|
return [];
|
|
8698
9376
|
}
|
|
8699
9377
|
const [probe] = accounts.filter((account2) => {
|
|
8700
|
-
return
|
|
9378
|
+
return ctx.runtime.teamRouting?.enabled !== true || !isAllowlisted(account2, ctx.runtime.teamRouting) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
|
|
8701
9379
|
}).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
|
|
8702
9380
|
if (!probe)
|
|
8703
9381
|
return [];
|
|
@@ -8706,9 +9384,9 @@ function selectRevalidationProbe(accounts, ctx, now) {
|
|
|
8706
9384
|
}
|
|
8707
9385
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
8708
9386
|
const now = Date.now();
|
|
8709
|
-
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);
|
|
8710
9388
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8711
|
-
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);
|
|
8712
9390
|
const prioritized = [...candidates].sort((left, right) => {
|
|
8713
9391
|
const priority = (left.priority ?? 0) - (right.priority ?? 0);
|
|
8714
9392
|
return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
|
|
@@ -9017,13 +9695,17 @@ class TeamAdmission {
|
|
|
9017
9695
|
const account2 = this.account(accountId, {
|
|
9018
9696
|
enabled: true,
|
|
9019
9697
|
distributionEnabled: true,
|
|
9698
|
+
preferExpiringQuota: false,
|
|
9020
9699
|
allowlistedAccountUuids: [],
|
|
9021
9700
|
maxUsage: 0.9,
|
|
9701
|
+
weeklyMaxUsage: 0.95,
|
|
9702
|
+
weeklyMaxUsageByEmail: {},
|
|
9022
9703
|
admissionCap: 1,
|
|
9023
9704
|
admissionQueueLimit: 0,
|
|
9024
9705
|
admissionWaitMs: 0,
|
|
9025
9706
|
holdSeconds: 0,
|
|
9026
|
-
quotaProbeSeconds: 0
|
|
9707
|
+
quotaProbeSeconds: 0,
|
|
9708
|
+
windowWarmup: WINDOW_WARMUP_DEFAULTS
|
|
9027
9709
|
});
|
|
9028
9710
|
if (account2.active > 0 || account2.queue.length > 0)
|
|
9029
9711
|
return;
|
|
@@ -9116,6 +9798,7 @@ class TeamAdmission {
|
|
|
9116
9798
|
}
|
|
9117
9799
|
var RAMP_INTERVAL_MS = 250, RAMP_WINDOW_MS = 30000, TeamAdmissionError;
|
|
9118
9800
|
var init_team_admission = __esm(() => {
|
|
9801
|
+
init_src7();
|
|
9119
9802
|
TeamAdmissionError = class TeamAdmissionError extends Error {
|
|
9120
9803
|
constructor(message) {
|
|
9121
9804
|
super(message);
|
|
@@ -9169,7 +9852,8 @@ async function forwardToClient(options, ctx) {
|
|
|
9169
9852
|
isStream,
|
|
9170
9853
|
providerName: ctx.providerName,
|
|
9171
9854
|
retryAttempt,
|
|
9172
|
-
failoverAttempts
|
|
9855
|
+
failoverAttempts,
|
|
9856
|
+
storePayload: ctx.runtime.storeRequestPayloads
|
|
9173
9857
|
};
|
|
9174
9858
|
ctx.usageWorker.postMessage(startMessage);
|
|
9175
9859
|
requestEvents.emit("event", {
|
|
@@ -9472,8 +10156,8 @@ function retryAfterMs(response) {
|
|
|
9472
10156
|
if (Number.isFinite(seconds)) {
|
|
9473
10157
|
return Math.max(0, seconds) * 1000;
|
|
9474
10158
|
}
|
|
9475
|
-
const
|
|
9476
|
-
return Number.isNaN(
|
|
10159
|
+
const date2 = Date.parse(value);
|
|
10160
|
+
return Number.isNaN(date2) ? undefined : Math.max(0, date2 - Date.now());
|
|
9477
10161
|
}
|
|
9478
10162
|
async function isQuotaRejection(response, provider) {
|
|
9479
10163
|
return await provider.isQuotaRejection?.(response) ?? false;
|
|
@@ -9930,37 +10614,37 @@ function quotaExhaustionResponse(resetAt2) {
|
|
|
9930
10614
|
headers: { "retry-after": String(retryAfterSeconds) }
|
|
9931
10615
|
});
|
|
9932
10616
|
}
|
|
9933
|
-
async function attemptAccount(
|
|
9934
|
-
|
|
9935
|
-
const admission =
|
|
10617
|
+
async function attemptAccount(request3, account2, failoverAttempts) {
|
|
10618
|
+
request3.req.signal.throwIfAborted();
|
|
10619
|
+
const admission = request3.ctx.teamAdmission;
|
|
9936
10620
|
let permit;
|
|
9937
10621
|
try {
|
|
9938
|
-
permit =
|
|
10622
|
+
permit = request3.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request3.ctx.runtime.teamRouting, request3.req.signal) : undefined;
|
|
9939
10623
|
} catch (error) {
|
|
9940
10624
|
if (error instanceof TeamAdmissionError) {
|
|
9941
|
-
throw new ServiceUnavailableError(error.message,
|
|
10625
|
+
throw new ServiceUnavailableError(error.message, request3.ctx.providerName, admissionRetrySeconds(request3.req));
|
|
9942
10626
|
}
|
|
9943
10627
|
throw error;
|
|
9944
10628
|
}
|
|
9945
10629
|
if (permit)
|
|
9946
|
-
|
|
9947
|
-
|
|
10630
|
+
request3.ctx.teamRouter?.begin(account2.id);
|
|
10631
|
+
request3.ctx.outsideSpendTracker?.begin(account2.id);
|
|
9948
10632
|
const release = () => {
|
|
9949
10633
|
permit?.release();
|
|
9950
10634
|
if (permit)
|
|
9951
|
-
|
|
9952
|
-
|
|
10635
|
+
request3.ctx.teamRouter?.end(account2.id);
|
|
10636
|
+
request3.ctx.outsideSpendTracker?.end(account2.id);
|
|
9953
10637
|
};
|
|
9954
10638
|
try {
|
|
9955
|
-
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);
|
|
9956
10640
|
if (attempt.kind === "response") {
|
|
9957
|
-
const spentExtraUsage =
|
|
10641
|
+
const spentExtraUsage = request3.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
|
|
9958
10642
|
return {
|
|
9959
10643
|
...attempt,
|
|
9960
10644
|
response: releaseAfterResponse(attempt.response, () => {
|
|
9961
10645
|
release();
|
|
9962
10646
|
if (spentExtraUsage) {
|
|
9963
|
-
|
|
10647
|
+
request3.ctx.seatAlerts?.extraUsageSpent(account2, request3.ctx.providerName);
|
|
9964
10648
|
}
|
|
9965
10649
|
})
|
|
9966
10650
|
};
|
|
@@ -9972,14 +10656,14 @@ async function attemptAccount(request2, account2, failoverAttempts) {
|
|
|
9972
10656
|
throw error;
|
|
9973
10657
|
}
|
|
9974
10658
|
}
|
|
9975
|
-
async function resolvePerMinuteRateLimit(
|
|
10659
|
+
async function resolvePerMinuteRateLimit(request3, account2, failoverAttempts, attempt) {
|
|
9976
10660
|
if (attempt.retryAfterMs > MAX_INLINE_RATE_LIMIT_RETRY_MS) {
|
|
9977
10661
|
return await attempt.forward();
|
|
9978
10662
|
}
|
|
9979
10663
|
if (attempt.retryAfterMs > 0) {
|
|
9980
10664
|
await Bun.sleep(attempt.retryAfterMs);
|
|
9981
10665
|
}
|
|
9982
|
-
const retryAttempt = await attemptAccount(
|
|
10666
|
+
const retryAttempt = await attemptAccount(request3, account2, failoverAttempts);
|
|
9983
10667
|
if (retryAttempt.kind === "response") {
|
|
9984
10668
|
return retryAttempt.response;
|
|
9985
10669
|
}
|
|
@@ -9988,26 +10672,26 @@ async function resolvePerMinuteRateLimit(request2, account2, failoverAttempts, a
|
|
|
9988
10672
|
}
|
|
9989
10673
|
return await attempt.forward();
|
|
9990
10674
|
}
|
|
9991
|
-
async function resolveRequestScopedRateLimit(
|
|
10675
|
+
async function resolveRequestScopedRateLimit(request3, accounts, index, attempt) {
|
|
9992
10676
|
const sibling = accounts[index + 1];
|
|
9993
10677
|
if (!sibling) {
|
|
9994
10678
|
return await attempt.forward();
|
|
9995
10679
|
}
|
|
9996
|
-
|
|
9997
|
-
const siblingAttempt = await attemptAccount(
|
|
10680
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10681
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
9998
10682
|
if (siblingAttempt.kind === "response") {
|
|
9999
10683
|
return siblingAttempt.response;
|
|
10000
10684
|
}
|
|
10001
10685
|
if (siblingAttempt.kind === "per-minute-rate-limit") {
|
|
10002
|
-
return await resolvePerMinuteRateLimit(
|
|
10686
|
+
return await resolvePerMinuteRateLimit(request3, sibling, index + 1, siblingAttempt);
|
|
10003
10687
|
}
|
|
10004
10688
|
if (siblingAttempt.kind !== "request-scoped-rate-limit") {
|
|
10005
10689
|
return await attempt.forward();
|
|
10006
10690
|
}
|
|
10007
|
-
if (
|
|
10008
|
-
await Bun.sleep(
|
|
10691
|
+
if (request3.ctx.runtime.requestScopedRetryDelayMs > 0) {
|
|
10692
|
+
await Bun.sleep(request3.ctx.runtime.requestScopedRetryDelayMs);
|
|
10009
10693
|
}
|
|
10010
|
-
const retryAttempt = await attemptAccount(
|
|
10694
|
+
const retryAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10011
10695
|
if (retryAttempt.kind === "response") {
|
|
10012
10696
|
return retryAttempt.response;
|
|
10013
10697
|
}
|
|
@@ -10016,14 +10700,14 @@ async function resolveRequestScopedRateLimit(request2, accounts, index, attempt)
|
|
|
10016
10700
|
}
|
|
10017
10701
|
return await attempt.forward();
|
|
10018
10702
|
}
|
|
10019
|
-
async function resolveQuotaRateLimit(
|
|
10703
|
+
async function resolveQuotaRateLimit(request3, accounts, index, attempt) {
|
|
10020
10704
|
const sibling = accounts[index + 1];
|
|
10021
10705
|
if (!sibling)
|
|
10022
10706
|
return await attempt.forward();
|
|
10023
|
-
|
|
10024
|
-
const siblingAttempt = await attemptAccount(
|
|
10707
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10708
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10025
10709
|
if (siblingAttempt.kind === "response") {
|
|
10026
|
-
|
|
10710
|
+
request3.ctx.teamRouter?.rebind(request3.teamRequest, sibling.id, request3.ctx.runtime.teamRouting, request3.ctx.provider, request3.ctx.dbOps);
|
|
10027
10711
|
return siblingAttempt.response;
|
|
10028
10712
|
}
|
|
10029
10713
|
if (siblingAttempt.kind === "authentication-failure") {
|
|
@@ -10039,13 +10723,13 @@ async function resolveQuotaRateLimit(request2, accounts, index, attempt) {
|
|
|
10039
10723
|
return await attempt.forward();
|
|
10040
10724
|
}
|
|
10041
10725
|
}
|
|
10042
|
-
async function resolveUpstreamFailure(
|
|
10726
|
+
async function resolveUpstreamFailure(request3, accounts, index, attempt) {
|
|
10043
10727
|
const sibling = accounts[index + 1];
|
|
10044
10728
|
if (!sibling) {
|
|
10045
10729
|
return await attempt.forward();
|
|
10046
10730
|
}
|
|
10047
|
-
|
|
10048
|
-
const siblingAttempt = await attemptAccount(
|
|
10731
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10732
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10049
10733
|
if (siblingAttempt.kind === "response") {
|
|
10050
10734
|
await discardAttempt(attempt);
|
|
10051
10735
|
return siblingAttempt.response;
|
|
@@ -10072,12 +10756,12 @@ async function discardAttempt(attempt) {
|
|
|
10072
10756
|
log21.warn(`Could not close a discarded upstream stream: ${error instanceof Error ? error.message : String(error)}`);
|
|
10073
10757
|
}
|
|
10074
10758
|
}
|
|
10075
|
-
async function resolveTransportFailure(
|
|
10759
|
+
async function resolveTransportFailure(request3, accounts, index) {
|
|
10076
10760
|
const sibling = accounts[index + 1];
|
|
10077
10761
|
if (!sibling)
|
|
10078
10762
|
return new Response("Bad Gateway", { status: 502 });
|
|
10079
|
-
|
|
10080
|
-
const siblingAttempt = await attemptAccount(
|
|
10763
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10764
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10081
10765
|
if (siblingAttempt.kind === "response")
|
|
10082
10766
|
return siblingAttempt.response;
|
|
10083
10767
|
switch (siblingAttempt.kind) {
|
|
@@ -10089,31 +10773,31 @@ async function resolveTransportFailure(request2, accounts, index) {
|
|
|
10089
10773
|
return new Response("Bad Gateway", { status: 502 });
|
|
10090
10774
|
}
|
|
10091
10775
|
}
|
|
10092
|
-
async function proxySelectedAccounts(
|
|
10776
|
+
async function proxySelectedAccounts(request3, accounts) {
|
|
10093
10777
|
for (let index = 0;index < accounts.length; index += 1) {
|
|
10094
|
-
const attempt = await attemptAccount(
|
|
10778
|
+
const attempt = await attemptAccount(request3, accounts[index], index);
|
|
10095
10779
|
if (attempt.kind === "response")
|
|
10096
10780
|
return attempt.response;
|
|
10097
10781
|
if (attempt.kind === "authentication-failure") {
|
|
10098
10782
|
return new Response("Bad Gateway", { status: 502 });
|
|
10099
10783
|
}
|
|
10100
10784
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10101
|
-
return await resolvePerMinuteRateLimit(
|
|
10785
|
+
return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
|
|
10102
10786
|
}
|
|
10103
10787
|
if (attempt.kind === "request-scoped-rate-limit") {
|
|
10104
|
-
return await resolveRequestScopedRateLimit(
|
|
10788
|
+
return await resolveRequestScopedRateLimit(request3, accounts, index, attempt);
|
|
10105
10789
|
}
|
|
10106
10790
|
if (attempt.kind === "quota-rate-limit") {
|
|
10107
|
-
return await resolveQuotaRateLimit(
|
|
10791
|
+
return await resolveQuotaRateLimit(request3, accounts, index, attempt);
|
|
10108
10792
|
}
|
|
10109
10793
|
if (attempt.kind === "upstream-failure") {
|
|
10110
|
-
return await resolveUpstreamFailure(
|
|
10794
|
+
return await resolveUpstreamFailure(request3, accounts, index, attempt);
|
|
10111
10795
|
}
|
|
10112
10796
|
if (attempt.kind === "transport-failure") {
|
|
10113
|
-
return await resolveTransportFailure(
|
|
10797
|
+
return await resolveTransportFailure(request3, accounts, index);
|
|
10114
10798
|
}
|
|
10115
10799
|
}
|
|
10116
|
-
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);
|
|
10117
10801
|
}
|
|
10118
10802
|
var log21;
|
|
10119
10803
|
var init_proxy_attempts = __esm(() => {
|
|
@@ -10138,7 +10822,7 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
10138
10822
|
provider: ctx.providerName,
|
|
10139
10823
|
sessionId
|
|
10140
10824
|
};
|
|
10141
|
-
const
|
|
10825
|
+
const request3 = {
|
|
10142
10826
|
body,
|
|
10143
10827
|
ctx,
|
|
10144
10828
|
mappedModel,
|
|
@@ -10149,20 +10833,20 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
10149
10833
|
url
|
|
10150
10834
|
};
|
|
10151
10835
|
return {
|
|
10152
|
-
accounts: selectRequestAccounts(
|
|
10153
|
-
request:
|
|
10836
|
+
accounts: selectRequestAccounts(request3, selectionOptions),
|
|
10837
|
+
request: request3
|
|
10154
10838
|
};
|
|
10155
10839
|
}
|
|
10156
|
-
function onThreadSeat(
|
|
10157
|
-
const threadAccountId = getThreadBoundAccountId(
|
|
10840
|
+
function onThreadSeat(request3, accounts) {
|
|
10841
|
+
const threadAccountId = getThreadBoundAccountId(request3.ctx.messageThreads, request3.thread);
|
|
10158
10842
|
return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
|
|
10159
10843
|
}
|
|
10160
|
-
function selectRequestAccounts(
|
|
10161
|
-
return onThreadSeat(
|
|
10844
|
+
function selectRequestAccounts(request3, selectionOptions) {
|
|
10845
|
+
return onThreadSeat(request3, selectAccountsForRequest(request3.meta, request3.ctx, request3.teamRequest, selectionOptions));
|
|
10162
10846
|
}
|
|
10163
|
-
function getRequestRetryAt(
|
|
10164
|
-
const { ctx, teamRequest } =
|
|
10165
|
-
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));
|
|
10166
10850
|
}
|
|
10167
10851
|
var init_proxy_request = __esm(() => {
|
|
10168
10852
|
init_account_selector();
|
|
@@ -10207,10 +10891,10 @@ function preferPinnedProvider(pool, pinnedAccount) {
|
|
|
10207
10891
|
const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
|
|
10208
10892
|
return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
|
|
10209
10893
|
}
|
|
10210
|
-
async function proxyPoolCandidate(
|
|
10894
|
+
async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
|
|
10211
10895
|
for (let index = 0;index < accounts.length; index += 1) {
|
|
10212
10896
|
const account2 = accounts[index];
|
|
10213
|
-
const attempt = await attemptAccount(
|
|
10897
|
+
const attempt = await attemptAccount(request3, account2, index);
|
|
10214
10898
|
if (attempt.kind === "response") {
|
|
10215
10899
|
return { account: account2, kind: "response", response: attempt.response };
|
|
10216
10900
|
}
|
|
@@ -10223,13 +10907,13 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10223
10907
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10224
10908
|
return {
|
|
10225
10909
|
kind: "response",
|
|
10226
|
-
response: await resolvePerMinuteRateLimit(
|
|
10910
|
+
response: await resolvePerMinuteRateLimit(request3, account2, index, attempt)
|
|
10227
10911
|
};
|
|
10228
10912
|
}
|
|
10229
10913
|
if (attempt.kind === "request-scoped-rate-limit") {
|
|
10230
10914
|
return {
|
|
10231
10915
|
kind: "response",
|
|
10232
|
-
response: await resolveRequestScopedRateLimit(
|
|
10916
|
+
response: await resolveRequestScopedRateLimit(request3, accounts, index, attempt)
|
|
10233
10917
|
};
|
|
10234
10918
|
}
|
|
10235
10919
|
if (attempt.kind === "quota-rate-limit") {
|
|
@@ -10242,7 +10926,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10242
10926
|
}
|
|
10243
10927
|
return {
|
|
10244
10928
|
kind: "response",
|
|
10245
|
-
response: await resolveQuotaRateLimit(
|
|
10929
|
+
response: await resolveQuotaRateLimit(request3, accounts, index, attempt)
|
|
10246
10930
|
};
|
|
10247
10931
|
}
|
|
10248
10932
|
if (attempt.kind === "upstream-failure") {
|
|
@@ -10255,7 +10939,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10255
10939
|
}
|
|
10256
10940
|
return {
|
|
10257
10941
|
kind: "response",
|
|
10258
|
-
response: await resolveUpstreamFailure(
|
|
10942
|
+
response: await resolveUpstreamFailure(request3, accounts, index, attempt)
|
|
10259
10943
|
};
|
|
10260
10944
|
}
|
|
10261
10945
|
if (attempt.kind === "transport-failure") {
|
|
@@ -10267,7 +10951,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10267
10951
|
}
|
|
10268
10952
|
return {
|
|
10269
10953
|
kind: "response",
|
|
10270
|
-
response: await resolveTransportFailure(
|
|
10954
|
+
response: await resolveTransportFailure(request3, accounts, index)
|
|
10271
10955
|
};
|
|
10272
10956
|
}
|
|
10273
10957
|
}
|
|
@@ -10290,10 +10974,10 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
|
|
|
10290
10974
|
let everyCandidateFull = true;
|
|
10291
10975
|
let emittedIngress = false;
|
|
10292
10976
|
const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
|
|
10293
|
-
const recordUnserved = (
|
|
10294
|
-
everyCandidateFull &&= isEveryAccountQuotaBlocked(
|
|
10295
|
-
soonestRetry = earliest(soonestRetry, getRequestRetryAt(
|
|
10296
|
-
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));
|
|
10297
10981
|
};
|
|
10298
10982
|
const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
|
|
10299
10983
|
for (const [candidateIndex, candidate] of candidates.entries()) {
|
|
@@ -10455,9 +11139,9 @@ class SeatAlerts {
|
|
|
10455
11139
|
}
|
|
10456
11140
|
if (!delivery.repliesOk)
|
|
10457
11141
|
return;
|
|
10458
|
-
const
|
|
10459
|
-
if (
|
|
10460
|
-
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";
|
|
10461
11145
|
log23.warn(`${delivery.channel} alert was refused (${code})`);
|
|
10462
11146
|
}
|
|
10463
11147
|
} catch (error) {
|
|
@@ -10923,17 +11607,17 @@ async function handleProxy(req, url, ctx) {
|
|
|
10923
11607
|
const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
|
|
10924
11608
|
const body = buffer ?? null;
|
|
10925
11609
|
requestMeta.model = readRequestModel(body);
|
|
10926
|
-
const { accounts: initiallySelectedAccounts, request:
|
|
11610
|
+
const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
|
|
10927
11611
|
let accounts = initiallySelectedAccounts;
|
|
10928
11612
|
if (accounts.length === 0) {
|
|
10929
11613
|
const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
|
|
10930
11614
|
alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
|
|
10931
|
-
const retryAt = getRequestRetryAt(
|
|
11615
|
+
const retryAt = getRequestRetryAt(request3);
|
|
10932
11616
|
if (retryAt !== null) {
|
|
10933
11617
|
const holdMs = holdSeconds * 1000;
|
|
10934
11618
|
if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
|
|
10935
11619
|
await requestContext.quotaHold.waitUntil(retryAt, req.signal);
|
|
10936
|
-
const resumedAccounts = selectRequestAccounts(
|
|
11620
|
+
const resumedAccounts = selectRequestAccounts(request3);
|
|
10937
11621
|
if (resumedAccounts.length > 0) {
|
|
10938
11622
|
accounts = resumedAccounts;
|
|
10939
11623
|
}
|
|
@@ -10955,7 +11639,7 @@ async function handleProxy(req, url, ctx) {
|
|
|
10955
11639
|
});
|
|
10956
11640
|
log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
|
|
10957
11641
|
log24.info(`Request: ${req.method} ${url.pathname}`);
|
|
10958
|
-
return await proxySelectedAccounts(
|
|
11642
|
+
return await proxySelectedAccounts(request3, accounts);
|
|
10959
11643
|
}
|
|
10960
11644
|
var log24, usageWorkerInstance = null;
|
|
10961
11645
|
var init_proxy = __esm(() => {
|
|
@@ -11018,6 +11702,12 @@ class QuotaHold {
|
|
|
11018
11702
|
}
|
|
11019
11703
|
|
|
11020
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
|
+
|
|
11021
11711
|
class QuotaProbe {
|
|
11022
11712
|
config;
|
|
11023
11713
|
store;
|
|
@@ -11084,9 +11774,7 @@ class QuotaProbe {
|
|
|
11084
11774
|
const quota2 = await provider.probeQuota(account2, accessToken);
|
|
11085
11775
|
if (!quota2)
|
|
11086
11776
|
return;
|
|
11087
|
-
|
|
11088
|
-
account2.quota_state = observed;
|
|
11089
|
-
this.store.updateAccountQuotaState(account2.id, observed);
|
|
11777
|
+
recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
|
|
11090
11778
|
} catch {}
|
|
11091
11779
|
}
|
|
11092
11780
|
}
|
|
@@ -11360,7 +12048,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
|
|
|
11360
12048
|
isStream: true,
|
|
11361
12049
|
providerName: session.providerName,
|
|
11362
12050
|
retryAttempt: 0,
|
|
11363
|
-
failoverAttempts: Math.max(0, session.nextAccountIndex - 1)
|
|
12051
|
+
failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
|
|
12052
|
+
storePayload: session.requestContext.runtime.storeRequestPayloads
|
|
11364
12053
|
};
|
|
11365
12054
|
session.activeTurn = {
|
|
11366
12055
|
requestId,
|
|
@@ -11717,6 +12406,106 @@ var init_websocket_proxy = __esm(() => {
|
|
|
11717
12406
|
};
|
|
11718
12407
|
});
|
|
11719
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
|
+
|
|
11720
12509
|
// ../../packages/proxy/src/index.ts
|
|
11721
12510
|
var init_src10 = __esm(() => {
|
|
11722
12511
|
init_background_tasks();
|
|
@@ -11731,6 +12520,7 @@ var init_src10 = __esm(() => {
|
|
|
11731
12520
|
init_team_admission();
|
|
11732
12521
|
init_team_router();
|
|
11733
12522
|
init_websocket_proxy();
|
|
12523
|
+
init_window_warmup2();
|
|
11734
12524
|
});
|
|
11735
12525
|
|
|
11736
12526
|
// ../../packages/runtime-server/src/device-keys.ts
|
|
@@ -11909,7 +12699,7 @@ function exposureFailure(req, url, server, config) {
|
|
|
11909
12699
|
if (!isSameOriginManagementRequest(req, url)) {
|
|
11910
12700
|
return jsonError(403, "Cross-origin management requests are not allowed");
|
|
11911
12701
|
}
|
|
11912
|
-
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)) {
|
|
11913
12703
|
if (role !== "admin") {
|
|
11914
12704
|
return jsonError(401, "An admin key is required for management writes");
|
|
11915
12705
|
}
|
|
@@ -11945,13 +12735,14 @@ function createRuntimeConfig(config, port) {
|
|
|
11945
12735
|
},
|
|
11946
12736
|
sessionDurationMs: config.get("session_duration_ms", TIME_CONSTANTS.SESSION_DURATION_DEFAULT),
|
|
11947
12737
|
port,
|
|
12738
|
+
storeRequestPayloads: config.storesRequestPayloads(),
|
|
11948
12739
|
teamRouting: config.getTeamRouting()
|
|
11949
12740
|
};
|
|
11950
12741
|
}
|
|
11951
|
-
function wireStrategyHotReload(config,
|
|
12742
|
+
function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
|
|
11952
12743
|
config.on("change", (change) => {
|
|
11953
12744
|
if (change.key === "lb_strategy") {
|
|
11954
|
-
|
|
12745
|
+
log27.info("Strategy configuration changed");
|
|
11955
12746
|
const newStrategyName = config.getStrategy();
|
|
11956
12747
|
if (newStrategyName === "session") {
|
|
11957
12748
|
const strategy3 = new SessionStrategy;
|
|
@@ -11959,13 +12750,38 @@ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig
|
|
|
11959
12750
|
proxyContext.strategy = strategy3;
|
|
11960
12751
|
}
|
|
11961
12752
|
}
|
|
12753
|
+
if (change.key === "data_retention_days") {
|
|
12754
|
+
runtimeConfig2.storeRequestPayloads = config.storesRequestPayloads();
|
|
12755
|
+
}
|
|
11962
12756
|
if (change.key === "team_routing") {
|
|
11963
12757
|
runtimeConfig2.teamRouting = config.getTeamRouting();
|
|
11964
12758
|
quotaProbe.reschedule();
|
|
11965
|
-
|
|
12759
|
+
windowWarmup.reschedule();
|
|
12760
|
+
log27.info("Team routing configuration changed");
|
|
11966
12761
|
}
|
|
11967
12762
|
});
|
|
11968
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
|
+
}
|
|
11969
12785
|
function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
11970
12786
|
container.registerInstance(SERVICE_KEYS.Config, new Config);
|
|
11971
12787
|
container.registerInstance(SERVICE_KEYS.Logger, serverLog);
|
|
@@ -11976,7 +12792,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
11976
12792
|
sessionDurationMs: runtimeConfig2.sessionDurationMs
|
|
11977
12793
|
});
|
|
11978
12794
|
const dbOps = DatabaseFactory.getInstance();
|
|
11979
|
-
const
|
|
12795
|
+
const log27 = container.resolve(SERVICE_KEYS.Logger);
|
|
11980
12796
|
container.registerInstance(SERVICE_KEYS.Database, dbOps);
|
|
11981
12797
|
const asyncWriter = new AsyncDbWriter;
|
|
11982
12798
|
container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
|
|
@@ -11991,6 +12807,17 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
11991
12807
|
dbOps,
|
|
11992
12808
|
providerRegistry,
|
|
11993
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
|
+
},
|
|
11994
12821
|
getPoolStatus: (provider, model) => getPoolStatus(provider, model, {
|
|
11995
12822
|
dbOps,
|
|
11996
12823
|
runtime: runtimeConfig2,
|
|
@@ -12029,24 +12856,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12029
12856
|
asyncWriter,
|
|
12030
12857
|
usageWorker: getUsageWorker()
|
|
12031
12858
|
};
|
|
12032
|
-
const quotaProbe =
|
|
12033
|
-
|
|
12034
|
-
if (!provider)
|
|
12035
|
-
return null;
|
|
12036
|
-
return await getValidAccessToken(account2, {
|
|
12037
|
-
...proxyContext,
|
|
12038
|
-
provider,
|
|
12039
|
-
providerName: account2.provider,
|
|
12040
|
-
upstreamPath: "/"
|
|
12041
|
-
});
|
|
12042
|
-
});
|
|
12043
|
-
quotaProbe.start();
|
|
12044
|
-
registerDisposable(quotaProbe);
|
|
12045
|
-
wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
|
|
12859
|
+
const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
|
|
12860
|
+
wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
|
|
12046
12861
|
return {
|
|
12047
12862
|
config,
|
|
12048
12863
|
dbOps,
|
|
12049
|
-
log:
|
|
12864
|
+
log: log27,
|
|
12050
12865
|
asyncWriter,
|
|
12051
12866
|
apiRouter,
|
|
12052
12867
|
exposureConfig,
|
|
@@ -12055,12 +12870,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12055
12870
|
runtimeConfig: runtimeConfig2
|
|
12056
12871
|
};
|
|
12057
12872
|
}
|
|
12058
|
-
function logInitialAccountStatus(
|
|
12873
|
+
function logInitialAccountStatus(log27, dbOps) {
|
|
12059
12874
|
const accounts = dbOps.getAllAccounts();
|
|
12060
12875
|
const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
|
|
12061
|
-
|
|
12876
|
+
log27.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
|
|
12062
12877
|
if (activeAccounts.length === 0) {
|
|
12063
|
-
|
|
12878
|
+
log27.warn("No active accounts available - requests will be refused with a 503 until an account is added");
|
|
12064
12879
|
}
|
|
12065
12880
|
}
|
|
12066
12881
|
var init_bootstrap_runtime = __esm(() => {
|
|
@@ -12301,6 +13116,44 @@ var init_fetch_handler = __esm(() => {
|
|
|
12301
13116
|
init_oauth_token();
|
|
12302
13117
|
});
|
|
12303
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
|
+
|
|
12304
13157
|
// ../../packages/runtime-server/src/startup-banner.ts
|
|
12305
13158
|
function createStartupBanner(options) {
|
|
12306
13159
|
const { version, port, withDashboard, strategy: strategy3, providers: providers2 } = options;
|
|
@@ -12331,29 +13184,6 @@ var init_startup_banner = __esm(() => {
|
|
|
12331
13184
|
init_src2();
|
|
12332
13185
|
});
|
|
12333
13186
|
|
|
12334
|
-
// ../../packages/runtime-server/src/startup-maintenance.ts
|
|
12335
|
-
function runStartupMaintenance(config, dbOps) {
|
|
12336
|
-
const log26 = new Logger("StartupMaintenance");
|
|
12337
|
-
try {
|
|
12338
|
-
const payloadDays = config.getDataRetentionDays();
|
|
12339
|
-
const requestDays = config.getRequestRetentionDays();
|
|
12340
|
-
const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
|
|
12341
|
-
log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
|
|
12342
|
-
} catch (err) {
|
|
12343
|
-
log26.error(`Startup cleanup error: ${err}`);
|
|
12344
|
-
}
|
|
12345
|
-
try {
|
|
12346
|
-
dbOps.compact();
|
|
12347
|
-
log26.info("Database compacted at startup");
|
|
12348
|
-
} catch (err) {
|
|
12349
|
-
log26.error(`Database compaction error: ${err}`);
|
|
12350
|
-
}
|
|
12351
|
-
return () => {};
|
|
12352
|
-
}
|
|
12353
|
-
var init_startup_maintenance = __esm(() => {
|
|
12354
|
-
init_src4();
|
|
12355
|
-
});
|
|
12356
|
-
|
|
12357
13187
|
// ../../packages/runtime-server/src/index.ts
|
|
12358
13188
|
import { isAbsolute as isAbsolute4 } from "path";
|
|
12359
13189
|
var {serve } = globalThis.Bun;
|
|
@@ -12469,14 +13299,14 @@ function startServer(options) {
|
|
|
12469
13299
|
const {
|
|
12470
13300
|
config,
|
|
12471
13301
|
dbOps,
|
|
12472
|
-
log:
|
|
13302
|
+
log: log27,
|
|
12473
13303
|
apiRouter,
|
|
12474
13304
|
exposureConfig,
|
|
12475
13305
|
proxyContext,
|
|
12476
13306
|
providerRegistry,
|
|
12477
13307
|
runtimeConfig: runtimeConfig2
|
|
12478
13308
|
} = bootstrapRuntime(port, serverLog, drain.control);
|
|
12479
|
-
stopRetentionJob =
|
|
13309
|
+
stopRetentionJob = startRetentionMaintenance(config, dbOps);
|
|
12480
13310
|
const fetchHandler = createServerFetchHandler({
|
|
12481
13311
|
apiRouter,
|
|
12482
13312
|
exposureConfig,
|
|
@@ -12514,7 +13344,7 @@ function startServer(options) {
|
|
|
12514
13344
|
strategy: config.getStrategy(),
|
|
12515
13345
|
providers: providerRegistry.listProviders()
|
|
12516
13346
|
}));
|
|
12517
|
-
logInitialAccountStatus(
|
|
13347
|
+
logInitialAccountStatus(log27, dbOps);
|
|
12518
13348
|
return {
|
|
12519
13349
|
port: activePort,
|
|
12520
13350
|
stop: () => stopServerRuntime(),
|
|
@@ -12547,8 +13377,8 @@ var init_src11 = __esm(() => {
|
|
|
12547
13377
|
init_dashboard_assets();
|
|
12548
13378
|
init_deployment_drain();
|
|
12549
13379
|
init_fetch_handler();
|
|
13380
|
+
init_retention_maintenance();
|
|
12550
13381
|
init_startup_banner();
|
|
12551
|
-
init_startup_maintenance();
|
|
12552
13382
|
init_fetch_handler();
|
|
12553
13383
|
init_startup_banner();
|
|
12554
13384
|
serverLog = new Logger("Server");
|