@certalis/agent-smith 0.1.4 → 0.1.6
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 +58 -6
- package/dist/bin.js +492 -118
- package/dist/post-processor.worker.js +128 -18
- package/dist/server.js +408 -92
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -1619,6 +1619,12 @@ var init_provider = __esm(() => {
|
|
|
1619
1619
|
hasRateLimitSignal(headerName) {
|
|
1620
1620
|
return super.hasRateLimitSignal(headerName) || headerName.toLowerCase().startsWith("anthropic-ratelimit-unified-");
|
|
1621
1621
|
}
|
|
1622
|
+
spendsExtraUsage(response) {
|
|
1623
|
+
if (!response.ok)
|
|
1624
|
+
return false;
|
|
1625
|
+
const overageStatus = response.headers.get("anthropic-ratelimit-unified-overage-status");
|
|
1626
|
+
return response.headers.get("anthropic-ratelimit-unified-overage-in-use") === "true" || response.headers.get("anthropic-ratelimit-unified-status") === "rejected" && (overageStatus === "allowed" || overageStatus === "allowed_warning");
|
|
1627
|
+
}
|
|
1622
1628
|
quotaBucketsFor(model) {
|
|
1623
1629
|
const familyBucket = familyQuotaBucket(model);
|
|
1624
1630
|
return familyBucket ? [...SHARED_QUOTA_BUCKETS, familyBucket] : SHARED_QUOTA_BUCKETS;
|
|
@@ -3828,11 +3834,13 @@ var init_paths = __esm(() => {
|
|
|
3828
3834
|
// ../../packages/config/src/index.ts
|
|
3829
3835
|
import { EventEmitter as EventEmitter3 } from "events";
|
|
3830
3836
|
import {
|
|
3837
|
+
chmodSync,
|
|
3831
3838
|
existsSync as existsSync2,
|
|
3832
3839
|
mkdirSync as mkdirSync2,
|
|
3833
3840
|
readFileSync,
|
|
3834
3841
|
renameSync,
|
|
3835
3842
|
rmSync,
|
|
3843
|
+
statSync as statSync2,
|
|
3836
3844
|
writeFileSync
|
|
3837
3845
|
} from "fs";
|
|
3838
3846
|
import { dirname } from "path";
|
|
@@ -3885,6 +3893,18 @@ function sanitizeConfigData(value) {
|
|
|
3885
3893
|
sanitized.provider_pools = providerPools;
|
|
3886
3894
|
continue;
|
|
3887
3895
|
}
|
|
3896
|
+
if (key === "client") {
|
|
3897
|
+
const client2 = sanitizeClientRouting(entry);
|
|
3898
|
+
if (client2)
|
|
3899
|
+
sanitized.client = client2;
|
|
3900
|
+
continue;
|
|
3901
|
+
}
|
|
3902
|
+
if (key === "alerts") {
|
|
3903
|
+
const alerts = sanitizeAlerts(entry);
|
|
3904
|
+
if (alerts)
|
|
3905
|
+
sanitized.alerts = alerts;
|
|
3906
|
+
continue;
|
|
3907
|
+
}
|
|
3888
3908
|
if (typeof entry === "string" || typeof entry === "boolean" || isFiniteNumber(entry)) {
|
|
3889
3909
|
sanitized[key] = entry;
|
|
3890
3910
|
}
|
|
@@ -3915,6 +3935,46 @@ function sanitizeConfigData(value) {
|
|
|
3915
3935
|
}
|
|
3916
3936
|
return sanitized;
|
|
3917
3937
|
}
|
|
3938
|
+
function filledText(value) {
|
|
3939
|
+
if (typeof value !== "string")
|
|
3940
|
+
return;
|
|
3941
|
+
const text = value.trim();
|
|
3942
|
+
return text.length > 0 && text.length <= MAX_ALERT_VALUE_LENGTH ? text : undefined;
|
|
3943
|
+
}
|
|
3944
|
+
function sanitizeHttpsUrl(value) {
|
|
3945
|
+
const text = filledText(value);
|
|
3946
|
+
if (!text)
|
|
3947
|
+
return;
|
|
3948
|
+
try {
|
|
3949
|
+
return new URL(text).protocol === "https:" ? text : undefined;
|
|
3950
|
+
} catch {
|
|
3951
|
+
return;
|
|
3952
|
+
}
|
|
3953
|
+
}
|
|
3954
|
+
function sanitizeAlerts(value) {
|
|
3955
|
+
if (!isRecord(value))
|
|
3956
|
+
return;
|
|
3957
|
+
const alerts = {};
|
|
3958
|
+
const slackWebhookUrl = sanitizeHttpsUrl(value.slack_webhook_url);
|
|
3959
|
+
if (slackWebhookUrl)
|
|
3960
|
+
alerts.slack_webhook_url = slackWebhookUrl;
|
|
3961
|
+
const slackBotToken = filledText(value.slack_bot_token);
|
|
3962
|
+
if (slackBotToken)
|
|
3963
|
+
alerts.slack_bot_token = slackBotToken;
|
|
3964
|
+
const slackChannel = filledText(value.slack_channel);
|
|
3965
|
+
if (slackChannel)
|
|
3966
|
+
alerts.slack_channel = slackChannel;
|
|
3967
|
+
const email = normalizeEnrollmentEmail(value.email);
|
|
3968
|
+
if (email)
|
|
3969
|
+
alerts.email = email;
|
|
3970
|
+
const emailFrom = filledText(value.email_from);
|
|
3971
|
+
if (emailFrom)
|
|
3972
|
+
alerts.email_from = emailFrom;
|
|
3973
|
+
const resendApiKey = filledText(value.resend_api_key);
|
|
3974
|
+
if (resendApiKey)
|
|
3975
|
+
alerts.resend_api_key = resendApiKey;
|
|
3976
|
+
return alerts;
|
|
3977
|
+
}
|
|
3918
3978
|
function isProviderStrategy(value) {
|
|
3919
3979
|
return typeof value === "string" && PROVIDER_STRATEGIES.includes(value);
|
|
3920
3980
|
}
|
|
@@ -3928,6 +3988,23 @@ function sanitizeProviderBaseUrl(value) {
|
|
|
3928
3988
|
return;
|
|
3929
3989
|
}
|
|
3930
3990
|
}
|
|
3991
|
+
function sanitizeClientRouting(value) {
|
|
3992
|
+
if (!isRecord(value))
|
|
3993
|
+
return;
|
|
3994
|
+
const client2 = {};
|
|
3995
|
+
if (typeof value.base_url === "string") {
|
|
3996
|
+
try {
|
|
3997
|
+
const url = new URL(value.base_url);
|
|
3998
|
+
if ((url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && url.search === "" && url.hash === "" && url.username === "" && url.password === "") {
|
|
3999
|
+
client2.base_url = url.origin;
|
|
4000
|
+
}
|
|
4001
|
+
} catch {}
|
|
4002
|
+
}
|
|
4003
|
+
if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
|
|
4004
|
+
client2.proxy_key_file = value.proxy_key_file;
|
|
4005
|
+
}
|
|
4006
|
+
return Object.keys(client2).length > 0 ? client2 : undefined;
|
|
4007
|
+
}
|
|
3931
4008
|
function sanitizeProviderModels(value) {
|
|
3932
4009
|
if (!isRecord(value))
|
|
3933
4010
|
return;
|
|
@@ -4016,7 +4093,7 @@ function sanitizeTeamRouting(value) {
|
|
|
4016
4093
|
}
|
|
4017
4094
|
return result;
|
|
4018
4095
|
}
|
|
4019
|
-
var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, Config;
|
|
4096
|
+
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;
|
|
4020
4097
|
var init_src7 = __esm(() => {
|
|
4021
4098
|
init_src2();
|
|
4022
4099
|
init_src4();
|
|
@@ -4063,17 +4140,30 @@ var init_src7 = __esm(() => {
|
|
|
4063
4140
|
try {
|
|
4064
4141
|
const content = readFileSync(this.configPath, "utf8");
|
|
4065
4142
|
this.data = sanitizeConfigData(JSON.parse(content));
|
|
4066
|
-
if ("default_agent_model" in this.data) {
|
|
4067
|
-
delete this.data.default_agent_model;
|
|
4068
|
-
this.saveConfig();
|
|
4069
|
-
}
|
|
4070
4143
|
} catch (error) {
|
|
4071
4144
|
log6.error(`Failed to parse config file: ${error}`);
|
|
4072
4145
|
this.data = {};
|
|
4146
|
+
return;
|
|
4147
|
+
}
|
|
4148
|
+
try {
|
|
4149
|
+
chmodSync(this.configPath, 384);
|
|
4150
|
+
} catch {
|
|
4151
|
+
let ownerOnly = false;
|
|
4152
|
+
try {
|
|
4153
|
+
ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
|
|
4154
|
+
} catch {}
|
|
4155
|
+
if (!ownerOnly) {
|
|
4156
|
+
throw new Error("Config file must be owner-only");
|
|
4157
|
+
}
|
|
4158
|
+
}
|
|
4159
|
+
if ("default_agent_model" in this.data) {
|
|
4160
|
+
delete this.data.default_agent_model;
|
|
4161
|
+
this.saveConfig();
|
|
4073
4162
|
}
|
|
4074
4163
|
} else {
|
|
4075
4164
|
const dir = dirname(this.configPath);
|
|
4076
|
-
mkdirSync2(dir, { recursive: true });
|
|
4165
|
+
mkdirSync2(dir, { recursive: true, mode: 448 });
|
|
4166
|
+
chmodSync(dir, 448);
|
|
4077
4167
|
this.data = {
|
|
4078
4168
|
lb_strategy: DEFAULT_STRATEGY
|
|
4079
4169
|
};
|
|
@@ -4082,12 +4172,23 @@ var init_src7 = __esm(() => {
|
|
|
4082
4172
|
}
|
|
4083
4173
|
saveConfig() {
|
|
4084
4174
|
try {
|
|
4085
|
-
|
|
4086
|
-
writeFileSync(this.configPath, content, "utf8");
|
|
4175
|
+
this.writePrivately(this.data);
|
|
4087
4176
|
} catch (error) {
|
|
4088
4177
|
log6.error(`Failed to save config file: ${error}`);
|
|
4089
4178
|
}
|
|
4090
4179
|
}
|
|
4180
|
+
writePrivately(data) {
|
|
4181
|
+
const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
|
|
4182
|
+
try {
|
|
4183
|
+
writeFileSync(temporary, JSON.stringify(data, null, 2), {
|
|
4184
|
+
mode: 384,
|
|
4185
|
+
flag: "wx"
|
|
4186
|
+
});
|
|
4187
|
+
renameSync(temporary, this.configPath);
|
|
4188
|
+
} finally {
|
|
4189
|
+
rmSync(temporary, { force: true });
|
|
4190
|
+
}
|
|
4191
|
+
}
|
|
4091
4192
|
get(key, defaultValue) {
|
|
4092
4193
|
const value = this.data[key];
|
|
4093
4194
|
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
@@ -4182,6 +4283,29 @@ var init_src7 = __esm(() => {
|
|
|
4182
4283
|
quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
|
|
4183
4284
|
};
|
|
4184
4285
|
}
|
|
4286
|
+
getAlerts() {
|
|
4287
|
+
const file = this.data.alerts;
|
|
4288
|
+
return {
|
|
4289
|
+
slackWebhookUrl: file?.slack_webhook_url ?? null,
|
|
4290
|
+
slackBotToken: file?.slack_bot_token ?? null,
|
|
4291
|
+
slackChannel: file?.slack_channel ?? null,
|
|
4292
|
+
email: file?.email ?? null,
|
|
4293
|
+
emailFrom: file?.email_from ?? null,
|
|
4294
|
+
resendApiKey: file?.resend_api_key ?? null
|
|
4295
|
+
};
|
|
4296
|
+
}
|
|
4297
|
+
getClientRouting() {
|
|
4298
|
+
const client2 = this.data.client;
|
|
4299
|
+
return {
|
|
4300
|
+
...client2?.base_url && { baseUrl: client2.base_url },
|
|
4301
|
+
...client2?.proxy_key_file && {
|
|
4302
|
+
proxyKeyFile: client2.proxy_key_file
|
|
4303
|
+
}
|
|
4304
|
+
};
|
|
4305
|
+
}
|
|
4306
|
+
getBlockWhenAllFull() {
|
|
4307
|
+
return this.data.block_when_all_full !== false;
|
|
4308
|
+
}
|
|
4185
4309
|
getProviderConfig(name) {
|
|
4186
4310
|
const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
|
|
4187
4311
|
const configured = this.data.providers?.[name];
|
|
@@ -4282,22 +4406,14 @@ var init_src7 = __esm(() => {
|
|
|
4282
4406
|
}
|
|
4283
4407
|
persistStrictly(key, value) {
|
|
4284
4408
|
const next = { ...this.data, [key]: value };
|
|
4285
|
-
|
|
4286
|
-
try {
|
|
4287
|
-
writeFileSync(temporary, JSON.stringify(next, null, 2), {
|
|
4288
|
-
mode: 384,
|
|
4289
|
-
flag: "wx"
|
|
4290
|
-
});
|
|
4291
|
-
renameSync(temporary, this.configPath);
|
|
4292
|
-
} finally {
|
|
4293
|
-
rmSync(temporary, { force: true });
|
|
4294
|
-
}
|
|
4409
|
+
this.writePrivately(next);
|
|
4295
4410
|
const oldValue = this.data[key];
|
|
4296
4411
|
this.data = next;
|
|
4297
4412
|
this.emit("change", { key, oldValue, newValue: value });
|
|
4298
4413
|
}
|
|
4299
4414
|
getRuntime() {
|
|
4300
4415
|
const defaults = {
|
|
4416
|
+
blockWhenAllFull: this.getBlockWhenAllFull(),
|
|
4301
4417
|
clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
|
|
4302
4418
|
maxBodyBytes: 64 * 1024 * 1024,
|
|
4303
4419
|
quotaThreshold: 0.98,
|
|
@@ -8366,28 +8482,58 @@ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
|
|
|
8366
8482
|
}
|
|
8367
8483
|
return true;
|
|
8368
8484
|
}
|
|
8485
|
+
function fleetAccounts(provider, ctx) {
|
|
8486
|
+
const teamRouting = ctx.runtime.teamRouting;
|
|
8487
|
+
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
|
|
8488
|
+
}
|
|
8489
|
+
function cooldownEnd(account2, now) {
|
|
8490
|
+
return account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
|
|
8491
|
+
}
|
|
8492
|
+
function blockingResets(provider, account2, model, ctx, now) {
|
|
8493
|
+
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);
|
|
8494
|
+
}
|
|
8495
|
+
function servableAt(provider, account2, model, ctx, now) {
|
|
8496
|
+
const cooldown = cooldownEnd(account2, now);
|
|
8497
|
+
if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
|
|
8498
|
+
return cooldown;
|
|
8499
|
+
}
|
|
8500
|
+
const resets = blockingResets(provider, account2, model, ctx, now);
|
|
8501
|
+
return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
|
|
8502
|
+
}
|
|
8503
|
+
function soonestServableAt(provider, fleet, seats, model, ctx, now) {
|
|
8504
|
+
if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
|
|
8505
|
+
return null;
|
|
8506
|
+
}
|
|
8507
|
+
const times = seats.flatMap((account2) => {
|
|
8508
|
+
const at = servableAt(provider, account2, model, ctx, now);
|
|
8509
|
+
return at === null ? [] : [at];
|
|
8510
|
+
});
|
|
8511
|
+
return times.length > 0 ? Math.min(...times) : null;
|
|
8512
|
+
}
|
|
8369
8513
|
function getPoolStatus(provider, model, ctx) {
|
|
8370
8514
|
const providerStrategy = ctx.providerRegistry.getProvider(provider);
|
|
8371
8515
|
if (!providerStrategy)
|
|
8372
8516
|
throw new Error(`Unknown provider '${provider}'`);
|
|
8373
8517
|
const config = ctx.runtime.teamRouting;
|
|
8374
8518
|
const now = Date.now();
|
|
8375
|
-
const accounts = config?.enabled ?
|
|
8376
|
-
const eligibleAccounts = accounts.filter((account2) => isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
|
|
8377
|
-
const resets = accounts.flatMap((account2) => Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(providerStrategy, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt));
|
|
8519
|
+
const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
|
|
8520
|
+
const eligibleAccounts = accounts.filter((account2) => cooldownEnd(account2, now) === null && isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
|
|
8378
8521
|
return {
|
|
8379
8522
|
version: 1,
|
|
8380
8523
|
provider,
|
|
8381
8524
|
routingEnabled: config?.enabled === true,
|
|
8382
8525
|
eligibleAccounts,
|
|
8383
|
-
retryAtMs: eligibleAccounts === 0
|
|
8526
|
+
retryAtMs: eligibleAccounts === 0 ? soonestServableAt(providerStrategy, accounts, accounts, model, ctx, now) : null,
|
|
8384
8527
|
holdSeconds: config?.holdSeconds ?? 0,
|
|
8385
8528
|
admissionWaitMs: config?.admissionWaitMs ?? 0
|
|
8386
8529
|
};
|
|
8387
8530
|
}
|
|
8388
|
-
function getSoonestQuotaReset(meta, ctx,
|
|
8389
|
-
const
|
|
8390
|
-
return
|
|
8531
|
+
function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
|
|
8532
|
+
const fleet = fleetAccounts(ctx.providerName, ctx);
|
|
8533
|
+
return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
|
|
8534
|
+
}
|
|
8535
|
+
function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
|
|
8536
|
+
return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8391
8537
|
}
|
|
8392
8538
|
function selectRevalidationProbe(accounts, ctx, now) {
|
|
8393
8539
|
const probes = ctx.quotaProbeAt;
|
|
@@ -8407,7 +8553,7 @@ function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
|
8407
8553
|
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
|
|
8408
8554
|
const now = Date.now();
|
|
8409
8555
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8410
|
-
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
|
|
8556
|
+
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
|
|
8411
8557
|
const prioritized = [...candidates].sort((left, right) => {
|
|
8412
8558
|
const priority = (left.priority ?? 0) - (right.priority ?? 0);
|
|
8413
8559
|
return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
|
|
@@ -9744,9 +9890,15 @@ async function attemptAccount(request2, account2, failoverAttempts) {
|
|
|
9744
9890
|
try {
|
|
9745
9891
|
const attempt = await proxyWithAccount(request2.req, request2.url, account2, request2.meta, request2.body, (body) => createBodyStream(body), request2.thread, failoverAttempts, request2.mappedModel, request2.ctx);
|
|
9746
9892
|
if (attempt.kind === "response") {
|
|
9893
|
+
const spentExtraUsage = request2.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
|
|
9747
9894
|
return {
|
|
9748
9895
|
...attempt,
|
|
9749
|
-
response: releaseAfterResponse(attempt.response,
|
|
9896
|
+
response: releaseAfterResponse(attempt.response, () => {
|
|
9897
|
+
release();
|
|
9898
|
+
if (spentExtraUsage) {
|
|
9899
|
+
request2.ctx.seatAlerts?.extraUsageSpent(account2, request2.ctx.providerName);
|
|
9900
|
+
}
|
|
9901
|
+
})
|
|
9750
9902
|
};
|
|
9751
9903
|
}
|
|
9752
9904
|
release();
|
|
@@ -9922,23 +10074,32 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
9922
10074
|
provider: ctx.providerName,
|
|
9923
10075
|
sessionId
|
|
9924
10076
|
};
|
|
9925
|
-
const
|
|
9926
|
-
|
|
9927
|
-
|
|
10077
|
+
const request2 = {
|
|
10078
|
+
body,
|
|
10079
|
+
ctx,
|
|
10080
|
+
mappedModel,
|
|
10081
|
+
meta,
|
|
10082
|
+
req,
|
|
10083
|
+
teamRequest,
|
|
10084
|
+
thread,
|
|
10085
|
+
url
|
|
10086
|
+
};
|
|
9928
10087
|
return {
|
|
9929
|
-
accounts,
|
|
9930
|
-
request:
|
|
9931
|
-
body,
|
|
9932
|
-
ctx,
|
|
9933
|
-
mappedModel,
|
|
9934
|
-
meta,
|
|
9935
|
-
req,
|
|
9936
|
-
teamRequest,
|
|
9937
|
-
thread,
|
|
9938
|
-
url
|
|
9939
|
-
}
|
|
10088
|
+
accounts: selectRequestAccounts(request2, selectionOptions),
|
|
10089
|
+
request: request2
|
|
9940
10090
|
};
|
|
9941
10091
|
}
|
|
10092
|
+
function onThreadSeat(request2, accounts) {
|
|
10093
|
+
const threadAccountId = getThreadBoundAccountId(request2.ctx.messageThreads, request2.thread);
|
|
10094
|
+
return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
|
|
10095
|
+
}
|
|
10096
|
+
function selectRequestAccounts(request2, selectionOptions) {
|
|
10097
|
+
return onThreadSeat(request2, selectAccountsForRequest(request2.meta, request2.ctx, request2.teamRequest, selectionOptions));
|
|
10098
|
+
}
|
|
10099
|
+
function getRequestRetryAt(request2) {
|
|
10100
|
+
const { ctx, teamRequest } = request2;
|
|
10101
|
+
return getSoonestQuotaReset(request2.meta, ctx, (fleet) => onThreadSeat(request2, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
|
|
10102
|
+
}
|
|
9942
10103
|
var init_proxy_request = __esm(() => {
|
|
9943
10104
|
init_account_selector();
|
|
9944
10105
|
init_message_thread();
|
|
@@ -10060,8 +10221,16 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
|
|
|
10060
10221
|
const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
|
|
10061
10222
|
const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
|
|
10062
10223
|
const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
|
|
10063
|
-
let
|
|
10224
|
+
let soonestRetry = null;
|
|
10225
|
+
let soonestFleetReset = null;
|
|
10226
|
+
let everyCandidateFull = true;
|
|
10064
10227
|
let emittedIngress = false;
|
|
10228
|
+
const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
|
|
10229
|
+
const recordUnserved = (request2) => {
|
|
10230
|
+
everyCandidateFull &&= isEveryAccountQuotaBlocked(request2.meta, request2.ctx);
|
|
10231
|
+
soonestRetry = earliest(soonestRetry, getRequestRetryAt(request2));
|
|
10232
|
+
soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request2.meta, request2.ctx));
|
|
10233
|
+
};
|
|
10065
10234
|
const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
|
|
10066
10235
|
for (const [candidateIndex, candidate] of candidates.entries()) {
|
|
10067
10236
|
const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
|
|
@@ -10073,8 +10242,7 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
|
|
|
10073
10242
|
}
|
|
10074
10243
|
accounts = preferPinnedAccount(accounts, pinnedId);
|
|
10075
10244
|
if (accounts.length === 0) {
|
|
10076
|
-
|
|
10077
|
-
soonestReset = resetAt3 !== null && (soonestReset === null || resetAt3 < soonestReset) ? resetAt3 : soonestReset;
|
|
10245
|
+
recordUnserved(prepared.request);
|
|
10078
10246
|
continue;
|
|
10079
10247
|
}
|
|
10080
10248
|
if (!emittedIngress) {
|
|
@@ -10095,11 +10263,13 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
|
|
|
10095
10263
|
}
|
|
10096
10264
|
return result.response;
|
|
10097
10265
|
}
|
|
10098
|
-
|
|
10099
|
-
soonestReset = resetAt2 !== null && (soonestReset === null || resetAt2 < soonestReset) ? resetAt2 : soonestReset;
|
|
10266
|
+
recordUnserved(prepared.request);
|
|
10100
10267
|
}
|
|
10101
|
-
if (
|
|
10102
|
-
|
|
10268
|
+
if (everyCandidateFull && soonestFleetReset !== null) {
|
|
10269
|
+
ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, soonestFleetReset, { blocked: true, holdSeconds: 0 });
|
|
10270
|
+
}
|
|
10271
|
+
if (soonestRetry !== null)
|
|
10272
|
+
return quotaExhaustionResponse(soonestRetry);
|
|
10103
10273
|
log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
|
|
10104
10274
|
throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
|
|
10105
10275
|
}
|
|
@@ -10113,6 +10283,133 @@ var init_provider_pool = __esm(() => {
|
|
|
10113
10283
|
log22 = new Logger("Proxy");
|
|
10114
10284
|
});
|
|
10115
10285
|
|
|
10286
|
+
// ../../packages/proxy/src/seat-alerts.ts
|
|
10287
|
+
function alertWhenFleetFull(meta, ctx, holdSeconds) {
|
|
10288
|
+
const resetAt2 = getSoonestQuotaReset(meta, ctx);
|
|
10289
|
+
if (resetAt2 === null || !isEveryAccountQuotaBlocked(meta, ctx))
|
|
10290
|
+
return;
|
|
10291
|
+
ctx.seatAlerts?.allAccountsFull(ctx.providerName, resetAt2, {
|
|
10292
|
+
blocked: ctx.runtime.blockWhenAllFull,
|
|
10293
|
+
holdSeconds
|
|
10294
|
+
});
|
|
10295
|
+
}
|
|
10296
|
+
function utc(at) {
|
|
10297
|
+
return `${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
|
10298
|
+
}
|
|
10299
|
+
|
|
10300
|
+
class SeatAlerts {
|
|
10301
|
+
config;
|
|
10302
|
+
send;
|
|
10303
|
+
fullUntil = new Map;
|
|
10304
|
+
constructor(config, send = (url, init) => fetch(url, init)) {
|
|
10305
|
+
this.config = config;
|
|
10306
|
+
this.send = send;
|
|
10307
|
+
if (config.email && !(config.emailFrom && config.resendApiKey)) {
|
|
10308
|
+
log23.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
|
|
10309
|
+
}
|
|
10310
|
+
if (!config.slackBotToken !== !config.slackChannel) {
|
|
10311
|
+
log23.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
|
|
10312
|
+
}
|
|
10313
|
+
}
|
|
10314
|
+
extraUsageSpent(account2, provider) {
|
|
10315
|
+
const claim = account2.quota_state?.representativeClaim;
|
|
10316
|
+
const resetAt2 = account2.quota_state?.windows.unified?.resetAt;
|
|
10317
|
+
this.notify({
|
|
10318
|
+
subject: `agent-smith: ${account2.name} spent extra usage`,
|
|
10319
|
+
text: `${account2.name} (${provider}) is past its plan limit${claim ? ` (${claim})` : ""} and a response it just served was billed to extra usage.${resetAt2 ? ` The limit resets at ${utc(resetAt2)}.` : ""}`
|
|
10320
|
+
});
|
|
10321
|
+
}
|
|
10322
|
+
allAccountsFull(scope, resetAt2, policy) {
|
|
10323
|
+
if ((this.fullUntil.get(scope) ?? 0) > Date.now())
|
|
10324
|
+
return;
|
|
10325
|
+
this.fullUntil.set(scope, resetAt2);
|
|
10326
|
+
const probe = policy.blocked ? "" : ", except one a minute that revalidates and may spend extra usage";
|
|
10327
|
+
const hold = policy.holdSeconds > 0 ? `; one within ${policy.holdSeconds}s of the reset waits for it instead` : "";
|
|
10328
|
+
this.notify({
|
|
10329
|
+
subject: `agent-smith: every ${scope} account is full`,
|
|
10330
|
+
text: `Every ${scope} account is out of quota until ${utc(resetAt2)}. Requests are refused until then${probe}${hold}.`
|
|
10331
|
+
});
|
|
10332
|
+
}
|
|
10333
|
+
notify(alert) {
|
|
10334
|
+
log23.warn(alert.text);
|
|
10335
|
+
for (const delivery of this.deliveries(alert)) {
|
|
10336
|
+
trackProxyBackgroundTask(this.deliver(delivery));
|
|
10337
|
+
}
|
|
10338
|
+
}
|
|
10339
|
+
deliveries(alert) {
|
|
10340
|
+
const {
|
|
10341
|
+
email,
|
|
10342
|
+
emailFrom,
|
|
10343
|
+
resendApiKey,
|
|
10344
|
+
slackBotToken,
|
|
10345
|
+
slackChannel,
|
|
10346
|
+
slackWebhookUrl
|
|
10347
|
+
} = this.config;
|
|
10348
|
+
const deliveries = [];
|
|
10349
|
+
if (slackWebhookUrl) {
|
|
10350
|
+
deliveries.push({
|
|
10351
|
+
channel: "Slack",
|
|
10352
|
+
url: slackWebhookUrl,
|
|
10353
|
+
body: { text: alert.text }
|
|
10354
|
+
});
|
|
10355
|
+
}
|
|
10356
|
+
if (slackBotToken && slackChannel) {
|
|
10357
|
+
deliveries.push({
|
|
10358
|
+
channel: "Slack",
|
|
10359
|
+
url: SLACK_POST_MESSAGE_URL,
|
|
10360
|
+
headers: { authorization: `Bearer ${slackBotToken}` },
|
|
10361
|
+
body: { channel: slackChannel, text: alert.text },
|
|
10362
|
+
repliesOk: true
|
|
10363
|
+
});
|
|
10364
|
+
}
|
|
10365
|
+
if (email && emailFrom && resendApiKey) {
|
|
10366
|
+
deliveries.push({
|
|
10367
|
+
channel: "email",
|
|
10368
|
+
url: RESEND_EMAILS_URL,
|
|
10369
|
+
headers: { authorization: `Bearer ${resendApiKey}` },
|
|
10370
|
+
body: {
|
|
10371
|
+
from: emailFrom,
|
|
10372
|
+
to: [email],
|
|
10373
|
+
subject: alert.subject,
|
|
10374
|
+
text: alert.text
|
|
10375
|
+
}
|
|
10376
|
+
});
|
|
10377
|
+
}
|
|
10378
|
+
return deliveries;
|
|
10379
|
+
}
|
|
10380
|
+
async deliver(delivery) {
|
|
10381
|
+
try {
|
|
10382
|
+
const response = await this.send(delivery.url, {
|
|
10383
|
+
method: "POST",
|
|
10384
|
+
headers: { "content-type": "application/json", ...delivery.headers },
|
|
10385
|
+
body: JSON.stringify(delivery.body),
|
|
10386
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
|
|
10387
|
+
});
|
|
10388
|
+
if (!response.ok) {
|
|
10389
|
+
log23.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
|
|
10390
|
+
return;
|
|
10391
|
+
}
|
|
10392
|
+
if (!delivery.repliesOk)
|
|
10393
|
+
return;
|
|
10394
|
+
const reply = await response.json();
|
|
10395
|
+
if (reply.ok !== true) {
|
|
10396
|
+
const code = typeof reply.error === "string" && SLACK_ERROR_CODE.test(reply.error) ? reply.error : "no reason given";
|
|
10397
|
+
log23.warn(`${delivery.channel} alert was refused (${code})`);
|
|
10398
|
+
}
|
|
10399
|
+
} catch (error) {
|
|
10400
|
+
log23.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
|
|
10401
|
+
}
|
|
10402
|
+
}
|
|
10403
|
+
}
|
|
10404
|
+
var log23, RESEND_EMAILS_URL = "https://api.resend.com/emails", SLACK_POST_MESSAGE_URL = "https://slack.com/api/chat.postMessage", SEND_TIMEOUT_MS = 1e4, SLACK_ERROR_CODE;
|
|
10405
|
+
var init_seat_alerts = __esm(() => {
|
|
10406
|
+
init_src4();
|
|
10407
|
+
init_background_tasks();
|
|
10408
|
+
init_account_selector();
|
|
10409
|
+
log23 = new Logger("SeatAlerts");
|
|
10410
|
+
SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
|
|
10411
|
+
});
|
|
10412
|
+
|
|
10116
10413
|
// ../../packages/proxy/src/usage-worker.ts
|
|
10117
10414
|
import { isAbsolute, resolve } from "path";
|
|
10118
10415
|
import { pathToFileURL } from "url";
|
|
@@ -10494,7 +10791,7 @@ function getUsageWorker() {
|
|
|
10494
10791
|
}
|
|
10495
10792
|
if (!usageWorkerInstance) {
|
|
10496
10793
|
usageWorkerInstance = new UsageWorkerController({
|
|
10497
|
-
logger:
|
|
10794
|
+
logger: log24,
|
|
10498
10795
|
shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
|
|
10499
10796
|
onWorkerMessage: (data) => {
|
|
10500
10797
|
if (data.type === "summary" && isRequestSummary(data.summary)) {
|
|
@@ -10565,21 +10862,23 @@ async function handleProxy(req, url, ctx) {
|
|
|
10565
10862
|
const { accounts: initiallySelectedAccounts, request: request2 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
|
|
10566
10863
|
let accounts = initiallySelectedAccounts;
|
|
10567
10864
|
if (accounts.length === 0) {
|
|
10568
|
-
const
|
|
10569
|
-
|
|
10570
|
-
|
|
10571
|
-
|
|
10572
|
-
|
|
10573
|
-
|
|
10865
|
+
const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
|
|
10866
|
+
alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
|
|
10867
|
+
const retryAt = getRequestRetryAt(request2);
|
|
10868
|
+
if (retryAt !== null) {
|
|
10869
|
+
const holdMs = holdSeconds * 1000;
|
|
10870
|
+
if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
|
|
10871
|
+
await requestContext.quotaHold.waitUntil(retryAt, req.signal);
|
|
10872
|
+
const resumedAccounts = selectRequestAccounts(request2);
|
|
10574
10873
|
if (resumedAccounts.length > 0) {
|
|
10575
10874
|
accounts = resumedAccounts;
|
|
10576
10875
|
}
|
|
10577
10876
|
}
|
|
10578
10877
|
if (accounts.length === 0)
|
|
10579
|
-
return quotaExhaustionResponse(
|
|
10878
|
+
return quotaExhaustionResponse(retryAt);
|
|
10580
10879
|
}
|
|
10581
10880
|
if (accounts.length === 0) {
|
|
10582
|
-
|
|
10881
|
+
log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
|
|
10583
10882
|
throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
|
|
10584
10883
|
}
|
|
10585
10884
|
}
|
|
@@ -10590,19 +10889,20 @@ async function handleProxy(req, url, ctx) {
|
|
|
10590
10889
|
method: requestMeta.method,
|
|
10591
10890
|
path: requestMeta.path
|
|
10592
10891
|
});
|
|
10593
|
-
|
|
10594
|
-
|
|
10892
|
+
log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
|
|
10893
|
+
log24.info(`Request: ${req.method} ${url.pathname}`);
|
|
10595
10894
|
return await proxySelectedAccounts(request2, accounts);
|
|
10596
10895
|
}
|
|
10597
|
-
var
|
|
10896
|
+
var log24, usageWorkerInstance = null;
|
|
10598
10897
|
var init_proxy = __esm(() => {
|
|
10599
10898
|
init_src2();
|
|
10600
10899
|
init_src4();
|
|
10601
10900
|
init_src();
|
|
10602
10901
|
init_handlers();
|
|
10603
10902
|
init_provider_pool();
|
|
10903
|
+
init_seat_alerts();
|
|
10604
10904
|
init_usage_worker();
|
|
10605
|
-
|
|
10905
|
+
log24 = new Logger("Proxy");
|
|
10606
10906
|
});
|
|
10607
10907
|
|
|
10608
10908
|
// ../../packages/proxy/src/quota-hold.ts
|
|
@@ -10950,7 +11250,7 @@ function endActiveTurn(session, success, error) {
|
|
|
10950
11250
|
if (!activeTurn) {
|
|
10951
11251
|
return;
|
|
10952
11252
|
}
|
|
10953
|
-
|
|
11253
|
+
log25.debug("Ending tracked websocket turn", {
|
|
10954
11254
|
requestId: activeTurn.requestId,
|
|
10955
11255
|
provider: session.providerName,
|
|
10956
11256
|
path: session.path,
|
|
@@ -11003,7 +11303,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
|
|
|
11003
11303
|
timestamp,
|
|
11004
11304
|
model: getEventModel(parsed)
|
|
11005
11305
|
};
|
|
11006
|
-
|
|
11306
|
+
log25.debug("Starting tracked websocket turn", {
|
|
11007
11307
|
requestId,
|
|
11008
11308
|
provider: session.providerName,
|
|
11009
11309
|
path: session.path,
|
|
@@ -11033,7 +11333,7 @@ function handleTrackedUpstreamText(session, data) {
|
|
|
11033
11333
|
if (!messageType) {
|
|
11034
11334
|
return;
|
|
11035
11335
|
}
|
|
11036
|
-
|
|
11336
|
+
log25.debug("Processing tracked websocket message", {
|
|
11037
11337
|
provider: session.providerName,
|
|
11038
11338
|
path: session.path,
|
|
11039
11339
|
messageType,
|
|
@@ -11074,7 +11374,7 @@ function capturePendingRequestBody(session, message) {
|
|
|
11074
11374
|
}
|
|
11075
11375
|
session.pendingRequestBody = Buffer.from(message).toString("base64");
|
|
11076
11376
|
session.pendingRequestTimestamp = Date.now();
|
|
11077
|
-
|
|
11377
|
+
log25.debug("Captured websocket request body for next tracked turn", {
|
|
11078
11378
|
provider: session.providerName,
|
|
11079
11379
|
path: session.path,
|
|
11080
11380
|
size: message.length
|
|
@@ -11147,7 +11447,7 @@ async function connectToNextUpstream(ws) {
|
|
|
11147
11447
|
plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
|
|
11148
11448
|
} catch (error) {
|
|
11149
11449
|
session.connecting = false;
|
|
11150
|
-
|
|
11450
|
+
log25.warn("Skipping websocket account during upstream connection", {
|
|
11151
11451
|
account: account2.name,
|
|
11152
11452
|
error: error instanceof Error ? error.message : String(error)
|
|
11153
11453
|
});
|
|
@@ -11206,7 +11506,7 @@ async function connectToNextUpstream(ws) {
|
|
|
11206
11506
|
}
|
|
11207
11507
|
});
|
|
11208
11508
|
upstream.addEventListener("error", () => {
|
|
11209
|
-
|
|
11509
|
+
log25.warn("Upstream websocket error", {
|
|
11210
11510
|
account: plan.account.name,
|
|
11211
11511
|
provider: session.providerName,
|
|
11212
11512
|
path: session.path
|
|
@@ -11215,7 +11515,7 @@ async function connectToNextUpstream(ws) {
|
|
|
11215
11515
|
} catch (error) {
|
|
11216
11516
|
session.connecting = false;
|
|
11217
11517
|
clearConnectTimeout(session);
|
|
11218
|
-
|
|
11518
|
+
log25.warn("Failed to create upstream websocket", {
|
|
11219
11519
|
account: plan.account.name,
|
|
11220
11520
|
error: error instanceof Error ? error.message : String(error)
|
|
11221
11521
|
});
|
|
@@ -11258,7 +11558,8 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
|
|
|
11258
11558
|
};
|
|
11259
11559
|
const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
|
|
11260
11560
|
if (accounts.length === 0) {
|
|
11261
|
-
|
|
11561
|
+
alertWhenFleetFull(requestMeta, requestContext, 0);
|
|
11562
|
+
log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
|
|
11262
11563
|
return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
|
|
11263
11564
|
}
|
|
11264
11565
|
const protocols = getProtocols(req.headers);
|
|
@@ -11296,7 +11597,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
|
|
|
11296
11597
|
}
|
|
11297
11598
|
return;
|
|
11298
11599
|
}
|
|
11299
|
-
var
|
|
11600
|
+
var log25, CONNECT_TIMEOUT_MS = 5000, PENDING_MESSAGE_LIMIT = 128, CLOSE_CODE_NORMAL = 1000, CLOSE_CODE_INTERNAL_ERROR = 1011, CLOSE_CODE_TRY_AGAIN_LATER = 1013, websocketSessions, textEncoder, websocketProxyHandler;
|
|
11300
11601
|
var init_websocket_proxy = __esm(() => {
|
|
11301
11602
|
init_src2();
|
|
11302
11603
|
init_src3();
|
|
@@ -11306,7 +11607,8 @@ var init_websocket_proxy = __esm(() => {
|
|
|
11306
11607
|
init_request_handler();
|
|
11307
11608
|
init_token_manager();
|
|
11308
11609
|
init_openai_usage();
|
|
11309
|
-
|
|
11610
|
+
init_seat_alerts();
|
|
11611
|
+
log25 = new Logger("WebSocketProxy");
|
|
11310
11612
|
websocketSessions = new Map;
|
|
11311
11613
|
textEncoder = new TextEncoder;
|
|
11312
11614
|
websocketProxyHandler = {
|
|
@@ -11360,6 +11662,7 @@ var init_src10 = __esm(() => {
|
|
|
11360
11662
|
init_proxy();
|
|
11361
11663
|
init_quota_probe();
|
|
11362
11664
|
init_response_handler();
|
|
11665
|
+
init_seat_alerts();
|
|
11363
11666
|
init_strategies();
|
|
11364
11667
|
init_team_admission();
|
|
11365
11668
|
init_team_router();
|
|
@@ -11405,12 +11708,23 @@ function safeKeyEqual(candidate, expected) {
|
|
|
11405
11708
|
}
|
|
11406
11709
|
return timingSafeEqual(Buffer.from(candidate), Buffer.from(expected));
|
|
11407
11710
|
}
|
|
11408
|
-
function
|
|
11409
|
-
const
|
|
11410
|
-
|
|
11711
|
+
function bearerToken(req) {
|
|
11712
|
+
const authorization = req.headers.get("authorization");
|
|
11713
|
+
const match = authorization?.match(/^Bearer ([^\s]+)$/);
|
|
11714
|
+
return match?.[1] ?? null;
|
|
11715
|
+
}
|
|
11716
|
+
function isResponsesInferenceRoute(pathname) {
|
|
11717
|
+
return pathname === "/v1/codex/responses" || pathname === "/v1/pool/openai-responses/responses";
|
|
11718
|
+
}
|
|
11719
|
+
function keyRole(req, url, config) {
|
|
11720
|
+
const apiKey = req.headers.get("x-api-key");
|
|
11721
|
+
if (safeKeyEqual(apiKey, config.adminKey)) {
|
|
11411
11722
|
return "admin";
|
|
11412
11723
|
}
|
|
11413
|
-
if (safeKeyEqual(
|
|
11724
|
+
if (safeKeyEqual(apiKey, config.proxyKey)) {
|
|
11725
|
+
return "proxy";
|
|
11726
|
+
}
|
|
11727
|
+
if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
|
|
11414
11728
|
return "proxy";
|
|
11415
11729
|
}
|
|
11416
11730
|
return null;
|
|
@@ -11450,7 +11764,7 @@ function jsonError(status, message) {
|
|
|
11450
11764
|
function exposureFailure(req, url, server, config) {
|
|
11451
11765
|
const remote = requestAddress(server, req);
|
|
11452
11766
|
const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
|
|
11453
|
-
const role = keyRole(req, config);
|
|
11767
|
+
const role = keyRole(req, url, config);
|
|
11454
11768
|
if (!role && !loopbackExempt) {
|
|
11455
11769
|
return jsonError(401, "A proxy key is required for this request");
|
|
11456
11770
|
}
|
|
@@ -11483,6 +11797,7 @@ var init_exposure = __esm(() => {
|
|
|
11483
11797
|
// ../../packages/runtime-server/src/bootstrap-runtime.ts
|
|
11484
11798
|
function createRuntimeConfig(config, port) {
|
|
11485
11799
|
return {
|
|
11800
|
+
blockWhenAllFull: config.getBlockWhenAllFull(),
|
|
11486
11801
|
clientId: config.get("client_id", "9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
|
|
11487
11802
|
maxBodyBytes: config.get("max_body_bytes", 64 * 1024 * 1024),
|
|
11488
11803
|
requestScopedRetryDelayMs: config.get("request_scoped_429_retry_delay_ms", 2000),
|
|
@@ -11497,10 +11812,10 @@ function createRuntimeConfig(config, port) {
|
|
|
11497
11812
|
teamRouting: config.getTeamRouting()
|
|
11498
11813
|
};
|
|
11499
11814
|
}
|
|
11500
|
-
function wireStrategyHotReload(config,
|
|
11815
|
+
function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
|
|
11501
11816
|
config.on("change", (change) => {
|
|
11502
11817
|
if (change.key === "lb_strategy") {
|
|
11503
|
-
|
|
11818
|
+
log26.info("Strategy configuration changed");
|
|
11504
11819
|
const newStrategyName = config.getStrategy();
|
|
11505
11820
|
if (newStrategyName === "session") {
|
|
11506
11821
|
const strategy3 = new SessionStrategy;
|
|
@@ -11511,7 +11826,7 @@ function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig
|
|
|
11511
11826
|
if (change.key === "team_routing") {
|
|
11512
11827
|
runtimeConfig2.teamRouting = config.getTeamRouting();
|
|
11513
11828
|
quotaProbe.reschedule();
|
|
11514
|
-
|
|
11829
|
+
log26.info("Team routing configuration changed");
|
|
11515
11830
|
}
|
|
11516
11831
|
});
|
|
11517
11832
|
}
|
|
@@ -11525,7 +11840,7 @@ function bootstrapRuntime(port, serverLog) {
|
|
|
11525
11840
|
sessionDurationMs: runtimeConfig2.sessionDurationMs
|
|
11526
11841
|
});
|
|
11527
11842
|
const dbOps = DatabaseFactory.getInstance();
|
|
11528
|
-
const
|
|
11843
|
+
const log26 = container.resolve(SERVICE_KEYS.Logger);
|
|
11529
11844
|
container.registerInstance(SERVICE_KEYS.Database, dbOps);
|
|
11530
11845
|
const asyncWriter = new AsyncDbWriter;
|
|
11531
11846
|
container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
|
|
@@ -11573,6 +11888,7 @@ function bootstrapRuntime(port, serverLog) {
|
|
|
11573
11888
|
teamAdmission,
|
|
11574
11889
|
quotaHold,
|
|
11575
11890
|
outsideSpendTracker,
|
|
11891
|
+
seatAlerts: new SeatAlerts(config.getAlerts()),
|
|
11576
11892
|
asyncWriter,
|
|
11577
11893
|
usageWorker: getUsageWorker()
|
|
11578
11894
|
};
|
|
@@ -11589,11 +11905,11 @@ function bootstrapRuntime(port, serverLog) {
|
|
|
11589
11905
|
});
|
|
11590
11906
|
quotaProbe.start();
|
|
11591
11907
|
registerDisposable(quotaProbe);
|
|
11592
|
-
wireStrategyHotReload(config,
|
|
11908
|
+
wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
|
|
11593
11909
|
return {
|
|
11594
11910
|
config,
|
|
11595
11911
|
dbOps,
|
|
11596
|
-
log:
|
|
11912
|
+
log: log26,
|
|
11597
11913
|
asyncWriter,
|
|
11598
11914
|
apiRouter,
|
|
11599
11915
|
exposureConfig,
|
|
@@ -11602,12 +11918,12 @@ function bootstrapRuntime(port, serverLog) {
|
|
|
11602
11918
|
runtimeConfig: runtimeConfig2
|
|
11603
11919
|
};
|
|
11604
11920
|
}
|
|
11605
|
-
function logInitialAccountStatus(
|
|
11921
|
+
function logInitialAccountStatus(log26, dbOps) {
|
|
11606
11922
|
const accounts = dbOps.getAllAccounts();
|
|
11607
11923
|
const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
|
|
11608
|
-
|
|
11924
|
+
log26.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
|
|
11609
11925
|
if (activeAccounts.length === 0) {
|
|
11610
|
-
|
|
11926
|
+
log26.warn("No active accounts available - requests will be refused with a 503 until an account is added");
|
|
11611
11927
|
}
|
|
11612
11928
|
}
|
|
11613
11929
|
var init_bootstrap_runtime = __esm(() => {
|
|
@@ -11834,20 +12150,20 @@ var init_startup_banner = __esm(() => {
|
|
|
11834
12150
|
|
|
11835
12151
|
// ../../packages/runtime-server/src/startup-maintenance.ts
|
|
11836
12152
|
function runStartupMaintenance(config, dbOps) {
|
|
11837
|
-
const
|
|
12153
|
+
const log26 = new Logger("StartupMaintenance");
|
|
11838
12154
|
try {
|
|
11839
12155
|
const payloadDays = config.getDataRetentionDays();
|
|
11840
12156
|
const requestDays = config.getRequestRetentionDays();
|
|
11841
12157
|
const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
|
|
11842
|
-
|
|
12158
|
+
log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
|
|
11843
12159
|
} catch (err) {
|
|
11844
|
-
|
|
12160
|
+
log26.error(`Startup cleanup error: ${err}`);
|
|
11845
12161
|
}
|
|
11846
12162
|
try {
|
|
11847
12163
|
dbOps.compact();
|
|
11848
|
-
|
|
12164
|
+
log26.info("Database compacted at startup");
|
|
11849
12165
|
} catch (err) {
|
|
11850
|
-
|
|
12166
|
+
log26.error(`Database compaction error: ${err}`);
|
|
11851
12167
|
}
|
|
11852
12168
|
return () => {};
|
|
11853
12169
|
}
|
|
@@ -11944,7 +12260,7 @@ function startServer(options) {
|
|
|
11944
12260
|
const {
|
|
11945
12261
|
config,
|
|
11946
12262
|
dbOps,
|
|
11947
|
-
log:
|
|
12263
|
+
log: log26,
|
|
11948
12264
|
apiRouter,
|
|
11949
12265
|
exposureConfig,
|
|
11950
12266
|
proxyContext,
|
|
@@ -11987,7 +12303,7 @@ function startServer(options) {
|
|
|
11987
12303
|
strategy: config.getStrategy(),
|
|
11988
12304
|
providers: providerRegistry.listProviders()
|
|
11989
12305
|
}));
|
|
11990
|
-
logInitialAccountStatus(
|
|
12306
|
+
logInitialAccountStatus(log26, dbOps);
|
|
11991
12307
|
return {
|
|
11992
12308
|
port: activePort,
|
|
11993
12309
|
stop: () => stopServerRuntime(),
|