@certalis/agent-smith 0.1.17 → 0.1.19
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 +17 -9
- package/dist/bin.js +1140 -186
- package/dist/claude-companion/.claude-plugin/plugin.json +8 -0
- package/dist/claude-companion/hooks/hooks.json +4 -0
- package/dist/claude-companion/hooks/provider-choice.js +320 -0
- package/dist/claude-companion/hooks/register.js +74 -0
- package/dist/client-launcher.js +86 -12
- package/dist/edge.js +13 -2
- package/dist/https.js +13 -2
- package/dist/pool.js +1064 -156
- package/dist/post-processor.worker.js +164 -2
- package/dist/server.js +1064 -156
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -2779,6 +2779,112 @@ var init_provider4 = __esm(() => {
|
|
|
2779
2779
|
};
|
|
2780
2780
|
});
|
|
2781
2781
|
|
|
2782
|
+
// ../../packages/providers/src/connectors/model-studio-capacity.ts
|
|
2783
|
+
function retryAtFromHeader(response, now = Date.now()) {
|
|
2784
|
+
const retryAfter = response.headers.get("retry-after");
|
|
2785
|
+
if (!retryAfter)
|
|
2786
|
+
return;
|
|
2787
|
+
const seconds = Number(retryAfter);
|
|
2788
|
+
if (Number.isFinite(seconds))
|
|
2789
|
+
return now + Math.max(0, seconds) * 1000;
|
|
2790
|
+
const date2 = Date.parse(retryAfter);
|
|
2791
|
+
return Number.isNaN(date2) ? undefined : Math.max(now, date2);
|
|
2792
|
+
}
|
|
2793
|
+
async function readSmallJsonBody(response) {
|
|
2794
|
+
const contentLength = Number(response.headers.get("content-length"));
|
|
2795
|
+
if (Number.isFinite(contentLength) && contentLength > MAX_BLOCK_BODY_BYTES) {
|
|
2796
|
+
return null;
|
|
2797
|
+
}
|
|
2798
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
2799
|
+
if (!contentType.toLowerCase().includes("application/json"))
|
|
2800
|
+
return null;
|
|
2801
|
+
const reader = response.clone().body?.getReader();
|
|
2802
|
+
if (!reader)
|
|
2803
|
+
return null;
|
|
2804
|
+
const chunks = [];
|
|
2805
|
+
let length = 0;
|
|
2806
|
+
try {
|
|
2807
|
+
while (true) {
|
|
2808
|
+
const { done, value } = await reader.read();
|
|
2809
|
+
if (done)
|
|
2810
|
+
break;
|
|
2811
|
+
length += value.byteLength;
|
|
2812
|
+
if (length > MAX_BLOCK_BODY_BYTES) {
|
|
2813
|
+
await reader.cancel();
|
|
2814
|
+
return null;
|
|
2815
|
+
}
|
|
2816
|
+
chunks.push(value);
|
|
2817
|
+
}
|
|
2818
|
+
} catch {
|
|
2819
|
+
return null;
|
|
2820
|
+
}
|
|
2821
|
+
const bytes = new Uint8Array(length);
|
|
2822
|
+
let offset = 0;
|
|
2823
|
+
for (const chunk of chunks) {
|
|
2824
|
+
bytes.set(chunk, offset);
|
|
2825
|
+
offset += chunk.byteLength;
|
|
2826
|
+
}
|
|
2827
|
+
try {
|
|
2828
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
2829
|
+
} catch {
|
|
2830
|
+
return null;
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
function errorCode(payload) {
|
|
2834
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
|
|
2835
|
+
return;
|
|
2836
|
+
}
|
|
2837
|
+
const record2 = payload;
|
|
2838
|
+
if (typeof record2.code === "string")
|
|
2839
|
+
return record2.code;
|
|
2840
|
+
const error = record2.error;
|
|
2841
|
+
if (typeof error !== "object" || error === null || Array.isArray(error)) {
|
|
2842
|
+
return;
|
|
2843
|
+
}
|
|
2844
|
+
return typeof error.code === "string" ? error.code : undefined;
|
|
2845
|
+
}
|
|
2846
|
+
async function classifyModelStudioCapacityBlock(response, now = Date.now()) {
|
|
2847
|
+
if (response.status !== 429 && response.status !== 503)
|
|
2848
|
+
return null;
|
|
2849
|
+
const code = errorCode(await readSmallJsonBody(response));
|
|
2850
|
+
const category = code ? MODEL_STUDIO_BLOCK_CATEGORIES[code] : undefined;
|
|
2851
|
+
if (!category) {
|
|
2852
|
+
return response.status === 429 ? { category: "unknown" } : null;
|
|
2853
|
+
}
|
|
2854
|
+
const retryAt = retryAtFromHeader(response, now);
|
|
2855
|
+
return retryAt === undefined ? { category } : { category, retryAt };
|
|
2856
|
+
}
|
|
2857
|
+
var MAX_BLOCK_BODY_BYTES, MODEL_STUDIO_BLOCK_CATEGORIES;
|
|
2858
|
+
var init_model_studio_capacity = __esm(() => {
|
|
2859
|
+
MAX_BLOCK_BODY_BYTES = 64 * 1024;
|
|
2860
|
+
MODEL_STUDIO_BLOCK_CATEGORIES = {
|
|
2861
|
+
"Throttling.RateQuota": "request-rate",
|
|
2862
|
+
"Throttling.AllocationQuota": "token-allocation",
|
|
2863
|
+
"Throttling.BurstRate": "burst",
|
|
2864
|
+
"Throttling.ResourceExhausted": "dynamic-throughput",
|
|
2865
|
+
"Throttling.ServiceOverloaded": "dynamic-throughput",
|
|
2866
|
+
ServiceUnavailable: "temporary-capacity"
|
|
2867
|
+
};
|
|
2868
|
+
});
|
|
2869
|
+
|
|
2870
|
+
// ../../packages/providers/src/providers/model-studio/provider.ts
|
|
2871
|
+
var ModelStudioAnthropicProvider;
|
|
2872
|
+
var init_provider5 = __esm(() => {
|
|
2873
|
+
init_model_studio_capacity();
|
|
2874
|
+
init_provider();
|
|
2875
|
+
ModelStudioAnthropicProvider = class ModelStudioAnthropicProvider extends AnthropicProvider {
|
|
2876
|
+
async getCapacityBlock(response) {
|
|
2877
|
+
return await classifyModelStudioCapacityBlock(response);
|
|
2878
|
+
}
|
|
2879
|
+
parseRateLimit(response) {
|
|
2880
|
+
if (response.status !== 429)
|
|
2881
|
+
return super.parseRateLimit(response);
|
|
2882
|
+
const resetTime = retryAtFromHeader(response);
|
|
2883
|
+
return resetTime === undefined ? { isRateLimited: true } : { isRateLimited: true, resetTime };
|
|
2884
|
+
}
|
|
2885
|
+
};
|
|
2886
|
+
});
|
|
2887
|
+
|
|
2782
2888
|
// ../../packages/providers/src/registry.ts
|
|
2783
2889
|
function supportsOAuth(provider) {
|
|
2784
2890
|
return "supportsOAuth" in provider && typeof provider.supportsOAuth === "function" && "getOAuthProvider" in provider && typeof provider.getOAuthProvider === "function";
|
|
@@ -2896,6 +3002,8 @@ function createProvider(definition) {
|
|
|
2896
3002
|
switch (definition.strategy) {
|
|
2897
3003
|
case "anthropic-api":
|
|
2898
3004
|
return new AnthropicProvider;
|
|
3005
|
+
case "model-studio-anthropic-api":
|
|
3006
|
+
return new ModelStudioAnthropicProvider;
|
|
2899
3007
|
case "openai-api":
|
|
2900
3008
|
return new OpenAIProvider;
|
|
2901
3009
|
case "claude-code":
|
|
@@ -2923,6 +3031,7 @@ var init_configured_registry = __esm(() => {
|
|
|
2923
3031
|
init_provider();
|
|
2924
3032
|
init_provider2();
|
|
2925
3033
|
init_provider4();
|
|
3034
|
+
init_provider5();
|
|
2926
3035
|
init_provider3();
|
|
2927
3036
|
init_registry();
|
|
2928
3037
|
});
|
|
@@ -2970,6 +3079,11 @@ var init_codex = __esm(() => {
|
|
|
2970
3079
|
init_provider4();
|
|
2971
3080
|
});
|
|
2972
3081
|
|
|
3082
|
+
// ../../packages/providers/src/providers/model-studio/index.ts
|
|
3083
|
+
var init_model_studio = __esm(() => {
|
|
3084
|
+
init_provider5();
|
|
3085
|
+
});
|
|
3086
|
+
|
|
2973
3087
|
// ../../packages/providers/src/providers/openai/index.ts
|
|
2974
3088
|
var init_openai = __esm(() => {
|
|
2975
3089
|
init_oauth2();
|
|
@@ -2981,6 +3095,7 @@ var init_providers = __esm(() => {
|
|
|
2981
3095
|
init_anthropic();
|
|
2982
3096
|
init_claude_code();
|
|
2983
3097
|
init_codex();
|
|
3098
|
+
init_model_studio();
|
|
2984
3099
|
init_openai();
|
|
2985
3100
|
});
|
|
2986
3101
|
// ../../packages/providers/src/index.ts
|
|
@@ -4343,7 +4458,7 @@ function sanitizeProviderPools(value) {
|
|
|
4343
4458
|
return pools;
|
|
4344
4459
|
}
|
|
4345
4460
|
function wireForStrategy(strategy3) {
|
|
4346
|
-
return strategy3 === "anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
|
|
4461
|
+
return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
|
|
4347
4462
|
}
|
|
4348
4463
|
function isNonNegativeFiniteNumber(value) {
|
|
4349
4464
|
return isFiniteNumber(value) && value >= 0;
|
|
@@ -4376,6 +4491,18 @@ function sanitizeTeamRouting(value) {
|
|
|
4376
4491
|
result.weekly_max_usage_by_email = Object.fromEntries(normalized);
|
|
4377
4492
|
}
|
|
4378
4493
|
}
|
|
4494
|
+
if (isRecord(value.caller_weekly_max_usage)) {
|
|
4495
|
+
const entries = Object.entries(value.caller_weekly_max_usage);
|
|
4496
|
+
if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
|
|
4497
|
+
result.caller_weekly_max_usage = Object.fromEntries(entries);
|
|
4498
|
+
}
|
|
4499
|
+
}
|
|
4500
|
+
if (isRecord(value.caller_provider_fallback)) {
|
|
4501
|
+
const entries = Object.entries(value.caller_provider_fallback);
|
|
4502
|
+
if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
|
|
4503
|
+
result.caller_provider_fallback = Object.fromEntries(entries);
|
|
4504
|
+
}
|
|
4505
|
+
}
|
|
4379
4506
|
if (isNonNegativeFiniteNumber(value.admission_cap)) {
|
|
4380
4507
|
result.admission_cap = Math.floor(value.admission_cap);
|
|
4381
4508
|
}
|
|
@@ -4417,7 +4544,7 @@ function clientRouting(client2) {
|
|
|
4417
4544
|
...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
|
|
4418
4545
|
};
|
|
4419
4546
|
}
|
|
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;
|
|
4547
|
+
var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
4421
4548
|
var init_src7 = __esm(() => {
|
|
4422
4549
|
init_src2();
|
|
4423
4550
|
init_src4();
|
|
@@ -4430,6 +4557,7 @@ var init_src7 = __esm(() => {
|
|
|
4430
4557
|
log6 = new Logger("Config");
|
|
4431
4558
|
PROVIDER_STRATEGIES = [
|
|
4432
4559
|
"anthropic-api",
|
|
4560
|
+
"model-studio-anthropic-api",
|
|
4433
4561
|
"openai-api",
|
|
4434
4562
|
"claude-code",
|
|
4435
4563
|
"codex"
|
|
@@ -4443,6 +4571,7 @@ var init_src7 = __esm(() => {
|
|
|
4443
4571
|
BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
|
|
4444
4572
|
PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
|
|
4445
4573
|
POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
|
|
4574
|
+
CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
|
|
4446
4575
|
TEAM_ROUTING_DEFAULTS = {
|
|
4447
4576
|
enabled: false,
|
|
4448
4577
|
distributionEnabled: true,
|
|
@@ -4451,6 +4580,8 @@ var init_src7 = __esm(() => {
|
|
|
4451
4580
|
maxUsage: 0.9,
|
|
4452
4581
|
weeklyMaxUsage: 0.95,
|
|
4453
4582
|
weeklyMaxUsageByEmail: {},
|
|
4583
|
+
callerWeeklyMaxUsage: {},
|
|
4584
|
+
callerProviderFallback: {},
|
|
4454
4585
|
admissionCap: 5,
|
|
4455
4586
|
admissionQueueLimit: 25,
|
|
4456
4587
|
admissionWaitMs: 30000,
|
|
@@ -4613,6 +4744,8 @@ var init_src7 = __esm(() => {
|
|
|
4613
4744
|
maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
|
|
4614
4745
|
weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
|
|
4615
4746
|
weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
|
|
4747
|
+
callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
|
|
4748
|
+
callerProviderFallback: { ...file?.caller_provider_fallback },
|
|
4616
4749
|
admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
|
|
4617
4750
|
admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
|
|
4618
4751
|
admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
|
|
@@ -4682,6 +4815,8 @@ var init_src7 = __esm(() => {
|
|
|
4682
4815
|
"max_usage",
|
|
4683
4816
|
"weekly_max_usage",
|
|
4684
4817
|
"weekly_max_usage_by_email",
|
|
4818
|
+
"caller_weekly_max_usage",
|
|
4819
|
+
"caller_provider_fallback",
|
|
4685
4820
|
"admission_cap",
|
|
4686
4821
|
"admission_queue_limit",
|
|
4687
4822
|
"admission_wait_ms",
|
|
@@ -4707,6 +4842,16 @@ var init_src7 = __esm(() => {
|
|
|
4707
4842
|
...oldValue.weekly_max_usage_by_email
|
|
4708
4843
|
};
|
|
4709
4844
|
}
|
|
4845
|
+
if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
|
|
4846
|
+
sanitized.caller_weekly_max_usage = {
|
|
4847
|
+
...oldValue.caller_weekly_max_usage
|
|
4848
|
+
};
|
|
4849
|
+
}
|
|
4850
|
+
if (!("caller_provider_fallback" in value) && oldValue?.caller_provider_fallback) {
|
|
4851
|
+
sanitized.caller_provider_fallback = {
|
|
4852
|
+
...oldValue.caller_provider_fallback
|
|
4853
|
+
};
|
|
4854
|
+
}
|
|
4710
4855
|
this.persistStrictly("team_routing", sanitized);
|
|
4711
4856
|
}
|
|
4712
4857
|
allowAccountUuid(accountUuid) {
|
|
@@ -5532,6 +5677,30 @@ function ensureConversationPinsTable(db) {
|
|
|
5532
5677
|
db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_account ON conversation_pins(account_id)`);
|
|
5533
5678
|
db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_last_seen ON conversation_pins(last_seen_at)`);
|
|
5534
5679
|
}
|
|
5680
|
+
function ensureConversationProviderPreferencesTable(db) {
|
|
5681
|
+
db.run(`
|
|
5682
|
+
CREATE TABLE IF NOT EXISTS conversation_provider_preferences (
|
|
5683
|
+
pin_key TEXT PRIMARY KEY,
|
|
5684
|
+
provider TEXT NOT NULL,
|
|
5685
|
+
promotion_declined INTEGER NOT NULL DEFAULT 0,
|
|
5686
|
+
last_seen_at INTEGER NOT NULL
|
|
5687
|
+
)
|
|
5688
|
+
`);
|
|
5689
|
+
db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_preferences_last_seen ON conversation_provider_preferences(last_seen_at)`);
|
|
5690
|
+
}
|
|
5691
|
+
function ensureConversationProviderBlocksTable(db) {
|
|
5692
|
+
db.run(`
|
|
5693
|
+
CREATE TABLE IF NOT EXISTS conversation_provider_blocks (
|
|
5694
|
+
pin_key TEXT NOT NULL,
|
|
5695
|
+
provider TEXT NOT NULL,
|
|
5696
|
+
category TEXT NOT NULL DEFAULT 'unknown',
|
|
5697
|
+
retry_at INTEGER,
|
|
5698
|
+
last_seen_at INTEGER NOT NULL,
|
|
5699
|
+
PRIMARY KEY (pin_key, provider)
|
|
5700
|
+
)
|
|
5701
|
+
`);
|
|
5702
|
+
db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_blocks_last_seen ON conversation_provider_blocks(last_seen_at)`);
|
|
5703
|
+
}
|
|
5535
5704
|
function remediateDuplicateAccountNames(db) {
|
|
5536
5705
|
const accounts = db.query(`
|
|
5537
5706
|
SELECT id, name, created_at
|
|
@@ -5657,6 +5826,8 @@ function ensureSchema(db) {
|
|
|
5657
5826
|
`);
|
|
5658
5827
|
ensureAuthSessionsTable(db);
|
|
5659
5828
|
ensureConversationPinsTable(db);
|
|
5829
|
+
ensureConversationProviderPreferencesTable(db);
|
|
5830
|
+
ensureConversationProviderBlocksTable(db);
|
|
5660
5831
|
}
|
|
5661
5832
|
function runMigrations(db) {
|
|
5662
5833
|
ensureSchema(db);
|
|
@@ -5676,6 +5847,8 @@ function runMigrations(db) {
|
|
|
5676
5847
|
db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
|
|
5677
5848
|
ensureAuthSessionsTable(db);
|
|
5678
5849
|
ensureConversationPinsTable(db);
|
|
5850
|
+
ensureConversationProviderPreferencesTable(db);
|
|
5851
|
+
ensureConversationProviderBlocksTable(db);
|
|
5679
5852
|
ensureAccountsNameUniqueness(db);
|
|
5680
5853
|
db.run(`CREATE TABLE IF NOT EXISTS enrollment_contacts (
|
|
5681
5854
|
account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
|
|
@@ -6371,6 +6544,85 @@ var init_conversation_pin_repository = __esm(() => {
|
|
|
6371
6544
|
};
|
|
6372
6545
|
});
|
|
6373
6546
|
|
|
6547
|
+
// ../../packages/database/src/repositories/conversation-provider-block.repository.ts
|
|
6548
|
+
var ConversationProviderBlockRepository;
|
|
6549
|
+
var init_conversation_provider_block_repository = __esm(() => {
|
|
6550
|
+
ConversationProviderBlockRepository = class ConversationProviderBlockRepository extends BaseRepository {
|
|
6551
|
+
find(pinKey, provider) {
|
|
6552
|
+
const row = this.get(`SELECT category, retry_at, last_seen_at FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
|
|
6553
|
+
return row ? {
|
|
6554
|
+
category: row.category,
|
|
6555
|
+
lastSeenAt: row.last_seen_at,
|
|
6556
|
+
retryAt: row.retry_at ?? undefined
|
|
6557
|
+
} : null;
|
|
6558
|
+
}
|
|
6559
|
+
upsert(pinKey, provider, category, retryAt, lastSeenAt) {
|
|
6560
|
+
this.run(`
|
|
6561
|
+
INSERT INTO conversation_provider_blocks (
|
|
6562
|
+
pin_key, provider, category, retry_at, last_seen_at
|
|
6563
|
+
)
|
|
6564
|
+
VALUES (?, ?, ?, ?, ?)
|
|
6565
|
+
ON CONFLICT(pin_key, provider) DO UPDATE SET
|
|
6566
|
+
category = excluded.category,
|
|
6567
|
+
retry_at = excluded.retry_at,
|
|
6568
|
+
last_seen_at = excluded.last_seen_at
|
|
6569
|
+
`, [pinKey, provider, category, retryAt ?? null, lastSeenAt]);
|
|
6570
|
+
}
|
|
6571
|
+
delete(pinKey, provider) {
|
|
6572
|
+
this.run(`DELETE FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
|
|
6573
|
+
}
|
|
6574
|
+
deleteExpired(before) {
|
|
6575
|
+
this.run(`DELETE FROM conversation_provider_blocks WHERE last_seen_at < ?`, [before]);
|
|
6576
|
+
}
|
|
6577
|
+
deleteForAccount(accountId) {
|
|
6578
|
+
this.run(`
|
|
6579
|
+
DELETE FROM conversation_provider_blocks
|
|
6580
|
+
WHERE pin_key IN (
|
|
6581
|
+
SELECT pin_key FROM conversation_pins WHERE account_id = ?
|
|
6582
|
+
)
|
|
6583
|
+
`, [accountId]);
|
|
6584
|
+
}
|
|
6585
|
+
};
|
|
6586
|
+
});
|
|
6587
|
+
|
|
6588
|
+
// ../../packages/database/src/repositories/conversation-provider-preference.repository.ts
|
|
6589
|
+
var ConversationProviderPreferenceRepository;
|
|
6590
|
+
var init_conversation_provider_preference_repository = __esm(() => {
|
|
6591
|
+
ConversationProviderPreferenceRepository = class ConversationProviderPreferenceRepository extends BaseRepository {
|
|
6592
|
+
find(pinKey) {
|
|
6593
|
+
const row = this.get(`SELECT provider, promotion_declined, last_seen_at FROM conversation_provider_preferences WHERE pin_key = ?`, [pinKey]);
|
|
6594
|
+
return row ? {
|
|
6595
|
+
provider: row.provider,
|
|
6596
|
+
promotionDeclined: row.promotion_declined === 1,
|
|
6597
|
+
lastSeenAt: row.last_seen_at
|
|
6598
|
+
} : null;
|
|
6599
|
+
}
|
|
6600
|
+
upsert(pinKey, provider, promotionDeclined, lastSeenAt) {
|
|
6601
|
+
this.run(`
|
|
6602
|
+
INSERT INTO conversation_provider_preferences (
|
|
6603
|
+
pin_key, provider, promotion_declined, last_seen_at
|
|
6604
|
+
)
|
|
6605
|
+
VALUES (?, ?, ?, ?)
|
|
6606
|
+
ON CONFLICT(pin_key) DO UPDATE SET
|
|
6607
|
+
provider = excluded.provider,
|
|
6608
|
+
promotion_declined = excluded.promotion_declined,
|
|
6609
|
+
last_seen_at = excluded.last_seen_at
|
|
6610
|
+
`, [pinKey, provider, promotionDeclined ? 1 : 0, lastSeenAt]);
|
|
6611
|
+
}
|
|
6612
|
+
deleteExpired(before) {
|
|
6613
|
+
this.run(`DELETE FROM conversation_provider_preferences WHERE last_seen_at < ?`, [before]);
|
|
6614
|
+
}
|
|
6615
|
+
deleteForAccount(accountId) {
|
|
6616
|
+
this.run(`
|
|
6617
|
+
DELETE FROM conversation_provider_preferences
|
|
6618
|
+
WHERE pin_key IN (
|
|
6619
|
+
SELECT pin_key FROM conversation_pins WHERE account_id = ?
|
|
6620
|
+
)
|
|
6621
|
+
`, [accountId]);
|
|
6622
|
+
}
|
|
6623
|
+
};
|
|
6624
|
+
});
|
|
6625
|
+
|
|
6374
6626
|
// ../../packages/database/src/models/request-row.ts
|
|
6375
6627
|
function toRequest(row) {
|
|
6376
6628
|
return {
|
|
@@ -6981,6 +7233,8 @@ class DatabaseOperations {
|
|
|
6981
7233
|
requests;
|
|
6982
7234
|
authSessions;
|
|
6983
7235
|
conversationPins;
|
|
7236
|
+
conversationProviderBlocks;
|
|
7237
|
+
conversationProviderPreferences;
|
|
6984
7238
|
strategy;
|
|
6985
7239
|
stats;
|
|
6986
7240
|
constructor(dbPath) {
|
|
@@ -7000,6 +7254,8 @@ class DatabaseOperations {
|
|
|
7000
7254
|
this.requests = new RequestRepository(this.db);
|
|
7001
7255
|
this.authSessions = new AuthSessionRepository(this.db);
|
|
7002
7256
|
this.conversationPins = new ConversationPinRepository(this.db);
|
|
7257
|
+
this.conversationProviderBlocks = new ConversationProviderBlockRepository(this.db);
|
|
7258
|
+
this.conversationProviderPreferences = new ConversationProviderPreferenceRepository(this.db);
|
|
7003
7259
|
this.strategy = new StrategyRepository(this.db);
|
|
7004
7260
|
this.stats = new StatsRepository(this.db);
|
|
7005
7261
|
}
|
|
@@ -7043,6 +7299,8 @@ class DatabaseOperations {
|
|
|
7043
7299
|
return this.accounts.update(accountId, data);
|
|
7044
7300
|
}
|
|
7045
7301
|
deleteAccount(accountId) {
|
|
7302
|
+
this.conversationProviderBlocks.deleteForAccount(accountId);
|
|
7303
|
+
this.conversationProviderPreferences.deleteForAccount(accountId);
|
|
7046
7304
|
this.conversationPins.deleteForAccount(accountId);
|
|
7047
7305
|
return this.accounts.delete(accountId);
|
|
7048
7306
|
}
|
|
@@ -7057,6 +7315,23 @@ class DatabaseOperations {
|
|
|
7057
7315
|
}
|
|
7058
7316
|
deleteExpiredConversationPins(before) {
|
|
7059
7317
|
this.conversationPins.deleteExpired(before);
|
|
7318
|
+
this.conversationProviderBlocks.deleteExpired(before);
|
|
7319
|
+
this.conversationProviderPreferences.deleteExpired(before);
|
|
7320
|
+
}
|
|
7321
|
+
getConversationProviderPreference(pinKey) {
|
|
7322
|
+
return this.conversationProviderPreferences.find(pinKey);
|
|
7323
|
+
}
|
|
7324
|
+
upsertConversationProviderPreference(pinKey, provider, promotionDeclined, lastSeenAt) {
|
|
7325
|
+
this.conversationProviderPreferences.upsert(pinKey, provider, promotionDeclined, lastSeenAt);
|
|
7326
|
+
}
|
|
7327
|
+
getConversationProviderBlock(pinKey, provider) {
|
|
7328
|
+
return this.conversationProviderBlocks.find(pinKey, provider);
|
|
7329
|
+
}
|
|
7330
|
+
upsertConversationProviderBlock(pinKey, provider, category, retryAt, lastSeenAt) {
|
|
7331
|
+
this.conversationProviderBlocks.upsert(pinKey, provider, category, retryAt, lastSeenAt);
|
|
7332
|
+
}
|
|
7333
|
+
deleteConversationProviderBlock(pinKey, provider) {
|
|
7334
|
+
this.conversationProviderBlocks.delete(pinKey, provider);
|
|
7060
7335
|
}
|
|
7061
7336
|
countAccounts() {
|
|
7062
7337
|
return this.accounts.count();
|
|
@@ -7242,6 +7517,8 @@ var init_database_operations = __esm(() => {
|
|
|
7242
7517
|
init_analytics_repository();
|
|
7243
7518
|
init_auth_session_repository();
|
|
7244
7519
|
init_conversation_pin_repository();
|
|
7520
|
+
init_conversation_provider_block_repository();
|
|
7521
|
+
init_conversation_provider_preference_repository();
|
|
7245
7522
|
init_request_repository();
|
|
7246
7523
|
init_stats_repository();
|
|
7247
7524
|
init_strategy_repository();
|
|
@@ -7421,6 +7698,15 @@ var init_analytics = __esm(() => {
|
|
|
7421
7698
|
});
|
|
7422
7699
|
|
|
7423
7700
|
// ../../packages/api/src/handlers/config.ts
|
|
7701
|
+
function publicTeamRouting(config) {
|
|
7702
|
+
const {
|
|
7703
|
+
callerProviderFallback: _callerProviderFallback,
|
|
7704
|
+
callerWeeklyMaxUsage: _callerWeeklyMaxUsage,
|
|
7705
|
+
weeklyMaxUsageByEmail: _weeklyMaxUsageByEmail,
|
|
7706
|
+
...routing
|
|
7707
|
+
} = config.getTeamRouting();
|
|
7708
|
+
return routing;
|
|
7709
|
+
}
|
|
7424
7710
|
function createConfigHandlers(config) {
|
|
7425
7711
|
return {
|
|
7426
7712
|
getConfig: () => {
|
|
@@ -7461,10 +7747,7 @@ function createConfigHandlers(config) {
|
|
|
7461
7747
|
getStrategies: () => {
|
|
7462
7748
|
return jsonResponse(LB_STRATEGIES);
|
|
7463
7749
|
},
|
|
7464
|
-
getTeamRouting: () =>
|
|
7465
|
-
const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
|
|
7466
|
-
return jsonResponse(routing);
|
|
7467
|
-
},
|
|
7750
|
+
getTeamRouting: () => jsonResponse(publicTeamRouting(config)),
|
|
7468
7751
|
setTeamRouting: async (req) => {
|
|
7469
7752
|
try {
|
|
7470
7753
|
const body = await parseJsonObject(req);
|
|
@@ -7472,7 +7755,7 @@ function createConfigHandlers(config) {
|
|
|
7472
7755
|
return jsonResponse({
|
|
7473
7756
|
success: true,
|
|
7474
7757
|
message: "Team routing settings updated",
|
|
7475
|
-
data: config
|
|
7758
|
+
data: publicTeamRouting(config)
|
|
7476
7759
|
});
|
|
7477
7760
|
} catch (error) {
|
|
7478
7761
|
if (error instanceof ValidationError || error instanceof Error) {
|
|
@@ -9044,6 +9327,11 @@ function pinKey(request3, provider) {
|
|
|
9044
9327
|
digest
|
|
9045
9328
|
].join("\x00")).digest("hex");
|
|
9046
9329
|
}
|
|
9330
|
+
function providerConversationKey(request3) {
|
|
9331
|
+
if (!request3.sessionId)
|
|
9332
|
+
return null;
|
|
9333
|
+
return createHash2("sha256").update([request3.pinScope ?? request3.provider, request3.sessionId].join("\x00")).digest("hex");
|
|
9334
|
+
}
|
|
9047
9335
|
function isAllowlisted(account2, config) {
|
|
9048
9336
|
return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
|
|
9049
9337
|
}
|
|
@@ -9090,9 +9378,20 @@ class TeamRouter {
|
|
|
9090
9378
|
return;
|
|
9091
9379
|
}
|
|
9092
9380
|
this.removeExpiredPins(now, store);
|
|
9093
|
-
const key =
|
|
9381
|
+
const key = this.getConversationPinKey(request3, config, provider);
|
|
9094
9382
|
return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
|
|
9095
9383
|
}
|
|
9384
|
+
getConversationPinKey(request3, _config, provider) {
|
|
9385
|
+
if (!request3?.sessionId || request3.manualAccountName) {
|
|
9386
|
+
return;
|
|
9387
|
+
}
|
|
9388
|
+
return pinKey(request3, provider) ?? undefined;
|
|
9389
|
+
}
|
|
9390
|
+
getConversationProviderKey(request3, _config) {
|
|
9391
|
+
if (!request3?.sessionId || request3.manualAccountName)
|
|
9392
|
+
return;
|
|
9393
|
+
return providerConversationKey(request3) ?? undefined;
|
|
9394
|
+
}
|
|
9096
9395
|
begin(accountId) {
|
|
9097
9396
|
this.inFlight.set(accountId, (this.inFlight.get(accountId) ?? 0) + 1);
|
|
9098
9397
|
}
|
|
@@ -9286,22 +9585,23 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
|
|
|
9286
9585
|
const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
|
|
9287
9586
|
return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
|
|
9288
9587
|
}
|
|
9289
|
-
function pooledMaxUsage(provider, account2, bucket, ctx) {
|
|
9588
|
+
function pooledMaxUsage(provider, account2, bucket, ctx, callerId) {
|
|
9290
9589
|
const teamRouting = ctx.runtime.teamRouting;
|
|
9291
9590
|
if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
|
|
9292
9591
|
return;
|
|
9293
9592
|
if (!provider.isWeeklyBucket(bucket))
|
|
9294
9593
|
return teamRouting.maxUsage;
|
|
9295
9594
|
const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
|
|
9296
|
-
const
|
|
9297
|
-
|
|
9595
|
+
const accountOverride = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
|
|
9596
|
+
const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
|
|
9597
|
+
return Math.min(teamRouting.weeklyMaxUsage, accountOverride ?? Number.POSITIVE_INFINITY, callerOverride ?? Number.POSITIVE_INFINITY);
|
|
9298
9598
|
}
|
|
9299
|
-
function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
|
|
9599
|
+
function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
|
|
9300
9600
|
const quota2 = account2.quota_state;
|
|
9301
9601
|
if (!quota2)
|
|
9302
9602
|
return true;
|
|
9303
9603
|
for (const [name, window2] of Object.entries(quota2.windows)) {
|
|
9304
|
-
if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx))) {
|
|
9604
|
+
if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, callerId))) {
|
|
9305
9605
|
return false;
|
|
9306
9606
|
}
|
|
9307
9607
|
}
|
|
@@ -9322,23 +9622,42 @@ function cooldownEnd(account2, now) {
|
|
|
9322
9622
|
function isServableSeat(provider, account2, model, ctx, now) {
|
|
9323
9623
|
return isFleetSeat(account2, ctx) && cooldownEnd(account2, now) === null && isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
|
|
9324
9624
|
}
|
|
9325
|
-
function blockingResets(provider, account2, model, ctx, now) {
|
|
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);
|
|
9625
|
+
function blockingResets(provider, account2, model, ctx, now, callerId) {
|
|
9626
|
+
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, callerId))).map(([, window2]) => window2.resetAt);
|
|
9327
9627
|
}
|
|
9328
|
-
function
|
|
9628
|
+
function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
|
|
9629
|
+
const blocking = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket2, window3]) => isQuotaBlocking(provider, account2, bucket2, window3, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket2, ctx, callerId)));
|
|
9630
|
+
if (blocking.length === 0)
|
|
9631
|
+
return null;
|
|
9632
|
+
const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
|
|
9633
|
+
const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
|
|
9634
|
+
const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
|
|
9635
|
+
return rightReset - leftReset;
|
|
9636
|
+
})[0];
|
|
9637
|
+
const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
|
|
9638
|
+
return window2.resetAt === null ? { category } : { category, retryAt: window2.resetAt };
|
|
9639
|
+
}
|
|
9640
|
+
function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
|
|
9641
|
+
const now = Date.now();
|
|
9642
|
+
const blocks = seatsFor(fleetAccounts(ctx.providerName, ctx)).map((account2) => quotaBlockForAccount(ctx.provider, account2, meta.model, ctx, now, callerId)).filter((block) => block !== null);
|
|
9643
|
+
if (blocks.length === 0)
|
|
9644
|
+
return null;
|
|
9645
|
+
return [...blocks].sort((left, right) => (left.retryAt ?? Number.POSITIVE_INFINITY) - (right.retryAt ?? Number.POSITIVE_INFINITY))[0];
|
|
9646
|
+
}
|
|
9647
|
+
function servableAt(provider, account2, model, ctx, now, callerId) {
|
|
9329
9648
|
const cooldown = cooldownEnd(account2, now);
|
|
9330
|
-
if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
|
|
9649
|
+
if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId)) {
|
|
9331
9650
|
return cooldown;
|
|
9332
9651
|
}
|
|
9333
|
-
const resets = blockingResets(provider, account2, model, ctx, now);
|
|
9652
|
+
const resets = blockingResets(provider, account2, model, ctx, now, callerId);
|
|
9334
9653
|
return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
|
|
9335
9654
|
}
|
|
9336
|
-
function soonestServableAt(provider, fleet, seats, model, ctx, now) {
|
|
9337
|
-
if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
|
|
9655
|
+
function soonestServableAt(provider, fleet, seats, model, ctx, now, callerId) {
|
|
9656
|
+
if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now, callerId).length > 0)) {
|
|
9338
9657
|
return null;
|
|
9339
9658
|
}
|
|
9340
9659
|
const times = seats.flatMap((account2) => {
|
|
9341
|
-
const at = servableAt(provider, account2, model, ctx, now);
|
|
9660
|
+
const at = servableAt(provider, account2, model, ctx, now, callerId);
|
|
9342
9661
|
return at === null ? [] : [at];
|
|
9343
9662
|
});
|
|
9344
9663
|
return times.length > 0 ? Math.min(...times) : null;
|
|
@@ -9361,21 +9680,22 @@ function getPoolStatus(provider, model, ctx) {
|
|
|
9361
9680
|
admissionWaitMs: config?.admissionWaitMs ?? 0
|
|
9362
9681
|
};
|
|
9363
9682
|
}
|
|
9364
|
-
function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
|
|
9683
|
+
function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
|
|
9365
9684
|
const fleet = fleetAccounts(ctx.providerName, ctx);
|
|
9366
|
-
return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
|
|
9685
|
+
return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now(), callerId);
|
|
9367
9686
|
}
|
|
9368
|
-
function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
|
|
9369
|
-
return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
9687
|
+
function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now(), callerId) {
|
|
9688
|
+
return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
|
|
9370
9689
|
}
|
|
9371
|
-
function selectRevalidationProbe(accounts, ctx, now, model) {
|
|
9690
|
+
function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
|
|
9372
9691
|
const probes = ctx.quotaProbeAt;
|
|
9373
9692
|
const lastProbeAt = probes?.get(ctx.providerName);
|
|
9374
9693
|
if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
|
|
9375
9694
|
return [];
|
|
9376
9695
|
}
|
|
9377
9696
|
const [probe] = accounts.filter((account2) => {
|
|
9378
|
-
|
|
9697
|
+
const routing = ctx.runtime.teamRouting;
|
|
9698
|
+
return routing?.enabled !== true || !isAllowlisted(account2, routing) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId);
|
|
9379
9699
|
}).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
|
|
9380
9700
|
if (!probe)
|
|
9381
9701
|
return [];
|
|
@@ -9384,9 +9704,10 @@ function selectRevalidationProbe(accounts, ctx, now, model) {
|
|
|
9384
9704
|
}
|
|
9385
9705
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
9386
9706
|
const now = Date.now();
|
|
9707
|
+
const callerId = teamRequest?.callerId;
|
|
9387
9708
|
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
|
|
9388
|
-
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
9389
|
-
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model);
|
|
9709
|
+
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
|
|
9710
|
+
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
|
|
9390
9711
|
const prioritized = [...candidates].sort((left, right) => {
|
|
9391
9712
|
const priority = (left.priority ?? 0) - (right.priority ?? 0);
|
|
9392
9713
|
return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
|
|
@@ -9700,6 +10021,8 @@ class TeamAdmission {
|
|
|
9700
10021
|
maxUsage: 0.9,
|
|
9701
10022
|
weeklyMaxUsage: 0.95,
|
|
9702
10023
|
weeklyMaxUsageByEmail: {},
|
|
10024
|
+
callerWeeklyMaxUsage: {},
|
|
10025
|
+
callerProviderFallback: {},
|
|
9703
10026
|
admissionCap: 1,
|
|
9704
10027
|
admissionQueueLimit: 0,
|
|
9705
10028
|
admissionWaitMs: 0,
|
|
@@ -9807,6 +10130,206 @@ var init_team_admission = __esm(() => {
|
|
|
9807
10130
|
};
|
|
9808
10131
|
});
|
|
9809
10132
|
|
|
10133
|
+
// ../../packages/routing/src/conversation-provider-routing.ts
|
|
10134
|
+
class ConversationProviderRouting {
|
|
10135
|
+
store;
|
|
10136
|
+
constructor(store) {
|
|
10137
|
+
this.store = store;
|
|
10138
|
+
}
|
|
10139
|
+
getPreference(conversationKey) {
|
|
10140
|
+
return this.store.getPreference(conversationKey);
|
|
10141
|
+
}
|
|
10142
|
+
getBlock(conversationKey, provider) {
|
|
10143
|
+
return this.store.getBlock(conversationKey, provider);
|
|
10144
|
+
}
|
|
10145
|
+
selectProvider(conversationKey, provider, now) {
|
|
10146
|
+
this.store.upsertPreference(conversationKey, {
|
|
10147
|
+
lastSeenAt: now,
|
|
10148
|
+
promotionDeclined: false,
|
|
10149
|
+
provider
|
|
10150
|
+
});
|
|
10151
|
+
}
|
|
10152
|
+
declinePromotion(conversationKey, now) {
|
|
10153
|
+
const preference = this.store.getPreference(conversationKey);
|
|
10154
|
+
if (!preference)
|
|
10155
|
+
return;
|
|
10156
|
+
this.store.upsertPreference(conversationKey, {
|
|
10157
|
+
...preference,
|
|
10158
|
+
lastSeenAt: now,
|
|
10159
|
+
promotionDeclined: true
|
|
10160
|
+
});
|
|
10161
|
+
}
|
|
10162
|
+
recordBlock(conversationKey, provider, block, now) {
|
|
10163
|
+
this.store.upsertBlock(conversationKey, provider, {
|
|
10164
|
+
...block,
|
|
10165
|
+
lastSeenAt: now
|
|
10166
|
+
});
|
|
10167
|
+
}
|
|
10168
|
+
clearBlock(conversationKey, provider) {
|
|
10169
|
+
this.store.deleteBlock(conversationKey, provider);
|
|
10170
|
+
}
|
|
10171
|
+
canOfferProvider(conversationKey, provider, now) {
|
|
10172
|
+
const block = this.store.getBlock(conversationKey, provider);
|
|
10173
|
+
return block === null || block.retryAt !== undefined && block.retryAt <= now;
|
|
10174
|
+
}
|
|
10175
|
+
}
|
|
10176
|
+
|
|
10177
|
+
// ../../packages/routing/src/provider-choice.ts
|
|
10178
|
+
function encodeCapacityDetails(problem) {
|
|
10179
|
+
return Buffer.from(JSON.stringify({
|
|
10180
|
+
kind: problem.kind,
|
|
10181
|
+
blockedProvider: problem.blockedProvider,
|
|
10182
|
+
category: problem.category,
|
|
10183
|
+
choices: problem.choices,
|
|
10184
|
+
wait: problem.retryAt === undefined ? null : { retryAt: problem.retryAt }
|
|
10185
|
+
})).toString("base64url");
|
|
10186
|
+
}
|
|
10187
|
+
function interactiveProviderChoiceRequested(headers3) {
|
|
10188
|
+
return headers3.get(INTERACTIVE_PROVIDER_CHOICE_HEADER) === "v1";
|
|
10189
|
+
}
|
|
10190
|
+
function manualProviderChoiceRequested(headers3) {
|
|
10191
|
+
return headers3.get(PROVIDER_CHOICE_MENU_HEADER) === "v1";
|
|
10192
|
+
}
|
|
10193
|
+
function providerWaitRequested(headers3) {
|
|
10194
|
+
return headers3.get(PROVIDER_WAIT_HEADER) === "v1";
|
|
10195
|
+
}
|
|
10196
|
+
function capacityChoices(candidates, blockedProvider, eligibleProviders) {
|
|
10197
|
+
return candidates.filter((candidate) => candidate.provider !== blockedProvider && eligibleProviders.has(candidate.provider));
|
|
10198
|
+
}
|
|
10199
|
+
function readProviderChoice(headers3, choices) {
|
|
10200
|
+
const selected = headers3.get(PROVIDER_CHOICE_HEADER);
|
|
10201
|
+
return selected && choices.some((choice) => choice.provider === selected) ? selected : null;
|
|
10202
|
+
}
|
|
10203
|
+
function providerPromotionDeclined(headers3) {
|
|
10204
|
+
return headers3.get(PROVIDER_PROMOTION_DECLINED_HEADER) === "v1";
|
|
10205
|
+
}
|
|
10206
|
+
function stripProviderChoiceHeaders(headers3) {
|
|
10207
|
+
const forwarded = new Headers(headers3);
|
|
10208
|
+
forwarded.delete(INTERACTIVE_PROVIDER_CHOICE_HEADER);
|
|
10209
|
+
forwarded.delete(PROVIDER_CHOICE_HEADER);
|
|
10210
|
+
forwarded.delete(PROVIDER_CHOICE_MENU_HEADER);
|
|
10211
|
+
forwarded.delete(PROVIDER_WAIT_HEADER);
|
|
10212
|
+
forwarded.delete(PROVIDER_PROMOTION_DECLINED_HEADER);
|
|
10213
|
+
return forwarded;
|
|
10214
|
+
}
|
|
10215
|
+
function withServedProviderHeaders(response, choice) {
|
|
10216
|
+
const headers3 = new Headers(response.headers);
|
|
10217
|
+
headers3.set(SERVED_PROVIDER_HEADER, choice.provider);
|
|
10218
|
+
headers3.set(SERVED_MODEL_HEADER, choice.model);
|
|
10219
|
+
return new Response(response.body, {
|
|
10220
|
+
status: response.status,
|
|
10221
|
+
statusText: response.statusText,
|
|
10222
|
+
headers: headers3
|
|
10223
|
+
});
|
|
10224
|
+
}
|
|
10225
|
+
function withProviderPromotionDetails(response, choices) {
|
|
10226
|
+
if (choices.length === 0)
|
|
10227
|
+
return response;
|
|
10228
|
+
const headers3 = new Headers(response.headers);
|
|
10229
|
+
headers3.set(PROVIDER_PROMOTION_DETAILS_HEADER, Buffer.from(JSON.stringify({ choices })).toString("base64url"));
|
|
10230
|
+
return new Response(response.body, {
|
|
10231
|
+
status: response.status,
|
|
10232
|
+
statusText: response.statusText,
|
|
10233
|
+
headers: headers3
|
|
10234
|
+
});
|
|
10235
|
+
}
|
|
10236
|
+
function createProviderCapacityProblem({
|
|
10237
|
+
blockedProvider,
|
|
10238
|
+
category,
|
|
10239
|
+
choices,
|
|
10240
|
+
retryAt
|
|
10241
|
+
}) {
|
|
10242
|
+
const retryAfter = retryAt === undefined ? undefined : String(Math.max(1, Math.ceil((retryAt - Date.now()) / 1000)));
|
|
10243
|
+
return Response.json({
|
|
10244
|
+
type: "urn:agent-smith:provider-capacity:v1",
|
|
10245
|
+
title: "Current provider cannot serve this turn",
|
|
10246
|
+
status: 429,
|
|
10247
|
+
blockedProvider,
|
|
10248
|
+
category,
|
|
10249
|
+
choices,
|
|
10250
|
+
wait: retryAt === undefined ? null : { retryAt }
|
|
10251
|
+
}, {
|
|
10252
|
+
status: 429,
|
|
10253
|
+
headers: {
|
|
10254
|
+
"cache-control": "no-store",
|
|
10255
|
+
"content-type": "application/problem+json",
|
|
10256
|
+
"x-should-retry": "false",
|
|
10257
|
+
...retryAfter ? { "retry-after": retryAfter } : {},
|
|
10258
|
+
[PROVIDER_CAPACITY_HEADER]: "v1",
|
|
10259
|
+
[PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
|
|
10260
|
+
kind: "capacity",
|
|
10261
|
+
blockedProvider,
|
|
10262
|
+
category,
|
|
10263
|
+
choices,
|
|
10264
|
+
retryAt
|
|
10265
|
+
})
|
|
10266
|
+
}
|
|
10267
|
+
});
|
|
10268
|
+
}
|
|
10269
|
+
function createProviderChoiceProblem({
|
|
10270
|
+
activeProvider,
|
|
10271
|
+
choices
|
|
10272
|
+
}) {
|
|
10273
|
+
return Response.json({
|
|
10274
|
+
type: "urn:agent-smith:provider-choice:v1",
|
|
10275
|
+
title: "Choose provider for this conversation",
|
|
10276
|
+
status: 409,
|
|
10277
|
+
activeProvider,
|
|
10278
|
+
choices,
|
|
10279
|
+
wait: null
|
|
10280
|
+
}, {
|
|
10281
|
+
status: 409,
|
|
10282
|
+
headers: {
|
|
10283
|
+
"cache-control": "no-store",
|
|
10284
|
+
"content-type": "application/problem+json",
|
|
10285
|
+
"x-should-retry": "false",
|
|
10286
|
+
[PROVIDER_CAPACITY_HEADER]: "v1",
|
|
10287
|
+
[PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
|
|
10288
|
+
kind: "manual",
|
|
10289
|
+
blockedProvider: activeProvider,
|
|
10290
|
+
category: "unknown",
|
|
10291
|
+
choices
|
|
10292
|
+
})
|
|
10293
|
+
}
|
|
10294
|
+
});
|
|
10295
|
+
}
|
|
10296
|
+
var INTERACTIVE_PROVIDER_CHOICE_HEADER = "x-agent-smith-interactive-provider-choice", PROVIDER_CHOICE_HEADER = "x-agent-smith-provider-choice", PROVIDER_CHOICE_MENU_HEADER = "x-agent-smith-provider-menu", PROVIDER_WAIT_HEADER = "x-agent-smith-provider-wait", PROVIDER_PROMOTION_DECLINED_HEADER = "x-agent-smith-provider-promotion-declined", PROVIDER_CAPACITY_HEADER = "x-agent-smith-provider-capacity", PROVIDER_CAPACITY_DETAILS_HEADER = "x-agent-smith-provider-capacity-details", PROVIDER_PROMOTION_DETAILS_HEADER = "x-agent-smith-provider-promotion-details", SERVED_PROVIDER_HEADER = "x-agent-smith-served-provider", SERVED_MODEL_HEADER = "x-agent-smith-served-model";
|
|
10297
|
+
|
|
10298
|
+
// ../../packages/routing/src/provider-selection.ts
|
|
10299
|
+
function preferProviders(providers2, providerName, pinnedProvider, preferredProvider) {
|
|
10300
|
+
const pinFirst = pinnedProvider ? [
|
|
10301
|
+
...providers2.filter((provider) => providerName(provider) === pinnedProvider),
|
|
10302
|
+
...providers2.filter((provider) => providerName(provider) !== pinnedProvider)
|
|
10303
|
+
] : [...providers2];
|
|
10304
|
+
if (!preferredProvider)
|
|
10305
|
+
return pinFirst;
|
|
10306
|
+
return [
|
|
10307
|
+
...pinFirst.filter((provider) => providerName(provider) === preferredProvider),
|
|
10308
|
+
...pinFirst.filter((provider) => providerName(provider) !== preferredProvider)
|
|
10309
|
+
];
|
|
10310
|
+
}
|
|
10311
|
+
function selectPoolProviders(providers2, providerName, selection) {
|
|
10312
|
+
if (selection.requestedProvider) {
|
|
10313
|
+
return providers2.filter((provider) => providerName(provider) === selection.requestedProvider);
|
|
10314
|
+
}
|
|
10315
|
+
const preferred = preferProviders(providers2, providerName, selection.pinnedProvider, selection.preferredProvider);
|
|
10316
|
+
if (selection.orderedFallback) {
|
|
10317
|
+
const currentProvider = selection.pinnedProvider ?? selection.preferredProvider;
|
|
10318
|
+
const currentIndex = currentProvider ? providers2.findIndex((provider) => providerName(provider) === currentProvider) : -1;
|
|
10319
|
+
return currentIndex < 0 ? [...providers2] : providers2.slice(currentIndex);
|
|
10320
|
+
}
|
|
10321
|
+
return preferred.slice(0, 1);
|
|
10322
|
+
}
|
|
10323
|
+
function higherRankedProviderChoices(choices, selectedProvider, eligibleProviders, canOffer) {
|
|
10324
|
+
const selectedIndex = choices.findIndex((choice) => choice.provider === selectedProvider);
|
|
10325
|
+
if (selectedIndex <= 0)
|
|
10326
|
+
return [];
|
|
10327
|
+
return choices.slice(0, selectedIndex).filter((choice) => eligibleProviders.has(choice.provider) && canOffer(choice.provider));
|
|
10328
|
+
}
|
|
10329
|
+
|
|
10330
|
+
// ../../packages/routing/src/index.ts
|
|
10331
|
+
var init_src10 = () => {};
|
|
10332
|
+
|
|
9810
10333
|
// ../../packages/proxy/src/response-handler.ts
|
|
9811
10334
|
function isExpectedResponse(path, response) {
|
|
9812
10335
|
if (path.startsWith("/.well-known/") && response.status === 404) {
|
|
@@ -10410,7 +10933,7 @@ function createUpstreamSender(input) {
|
|
|
10410
10933
|
const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
|
|
10411
10934
|
return async (token) => {
|
|
10412
10935
|
const requestAccount = token === input.account.access_token ? input.account : { ...input.account, access_token: token };
|
|
10413
|
-
const headers3 = input.ctx.provider.prepareHeaders(input.req.headers, requestAccount);
|
|
10936
|
+
const headers3 = input.ctx.provider.prepareHeaders(stripProviderChoiceHeaders(input.req.headers), requestAccount);
|
|
10414
10937
|
const upstreamRequestStartedAt = Date.now();
|
|
10415
10938
|
const response = await makeProxyRequest(targetUrl, input.req.method, headers3, () => input.createBodyStream(input.requestBody), !!input.req.body, input.req.signal);
|
|
10416
10939
|
return {
|
|
@@ -10477,6 +11000,28 @@ async function classifyUpstreamResponse(input, upstream) {
|
|
|
10477
11000
|
}
|
|
10478
11001
|
let response = state.response;
|
|
10479
11002
|
const forward = createForwarder(input, upstream, state);
|
|
11003
|
+
const interactive = interactiveProviderChoiceRequested(input.req.headers);
|
|
11004
|
+
const capacityBlock = await input.ctx.provider.getCapacityBlock?.(response);
|
|
11005
|
+
if (capacityBlock) {
|
|
11006
|
+
const quotaRejected2 = await isQuotaRejection(response, input.ctx.provider);
|
|
11007
|
+
processProxyResponse(response, input.account, input.ctx, quotaRejected2);
|
|
11008
|
+
const perMinuteRetryAfterMs2 = getPerMinuteRetryAfterMs(response, quotaRejected2);
|
|
11009
|
+
if (interactive && (capacityBlock.category === "request-rate" || capacityBlock.category === "burst")) {
|
|
11010
|
+
if (perMinuteRetryAfterMs2 !== undefined) {
|
|
11011
|
+
return {
|
|
11012
|
+
forward,
|
|
11013
|
+
kind: "per-minute-rate-limit",
|
|
11014
|
+
retryAfterMs: perMinuteRetryAfterMs2
|
|
11015
|
+
};
|
|
11016
|
+
}
|
|
11017
|
+
}
|
|
11018
|
+
return {
|
|
11019
|
+
block: capacityBlock,
|
|
11020
|
+
discard: discardUpstreamResponse(state),
|
|
11021
|
+
forward,
|
|
11022
|
+
kind: "provider-capacity-block"
|
|
11023
|
+
};
|
|
11024
|
+
}
|
|
10480
11025
|
if (isRequestScopedRateLimit(response, input.ctx.provider)) {
|
|
10481
11026
|
return { forward, kind: "request-scoped-rate-limit" };
|
|
10482
11027
|
}
|
|
@@ -10542,6 +11087,7 @@ var API_KEY_AUTH_COOLDOWN_MS, ORGANIZATION_QUARANTINE_MS, log20;
|
|
|
10542
11087
|
var init_proxy_operations = __esm(() => {
|
|
10543
11088
|
init_src2();
|
|
10544
11089
|
init_src4();
|
|
11090
|
+
init_src10();
|
|
10545
11091
|
init_response_handler();
|
|
10546
11092
|
init_message_thread();
|
|
10547
11093
|
init_request_handler();
|
|
@@ -10781,6 +11327,9 @@ async function proxySelectedAccounts(request3, accounts) {
|
|
|
10781
11327
|
if (attempt.kind === "authentication-failure") {
|
|
10782
11328
|
return new Response("Bad Gateway", { status: 502 });
|
|
10783
11329
|
}
|
|
11330
|
+
if (attempt.kind === "provider-capacity-block") {
|
|
11331
|
+
return await attempt.forward();
|
|
11332
|
+
}
|
|
10784
11333
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10785
11334
|
return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
|
|
10786
11335
|
}
|
|
@@ -10811,7 +11360,7 @@ var init_proxy_attempts = __esm(() => {
|
|
|
10811
11360
|
});
|
|
10812
11361
|
|
|
10813
11362
|
// ../../packages/proxy/src/handlers/proxy-request.ts
|
|
10814
|
-
function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions) {
|
|
11363
|
+
function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions, callerId) {
|
|
10815
11364
|
const thread = parseMessageThreadRequest(body, ctx.upstreamPath, req.headers.get("content-type"), ctx.provider.getClientSessionId?.(req.headers) ?? null);
|
|
10816
11365
|
const sessionId = ctx.provider.getClientSessionId?.(req.headers) ?? null;
|
|
10817
11366
|
const teamRequest = teamRequestOverride ?? {
|
|
@@ -10820,7 +11369,8 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
10820
11369
|
manualAccountName,
|
|
10821
11370
|
model: meta.model,
|
|
10822
11371
|
provider: ctx.providerName,
|
|
10823
|
-
sessionId
|
|
11372
|
+
sessionId,
|
|
11373
|
+
callerId
|
|
10824
11374
|
};
|
|
10825
11375
|
const request3 = {
|
|
10826
11376
|
body,
|
|
@@ -10846,7 +11396,11 @@ function selectRequestAccounts(request3, selectionOptions) {
|
|
|
10846
11396
|
}
|
|
10847
11397
|
function getRequestRetryAt(request3) {
|
|
10848
11398
|
const { ctx, teamRequest } = request3;
|
|
10849
|
-
return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
|
|
11399
|
+
return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
|
|
11400
|
+
}
|
|
11401
|
+
function getRequestQuotaCapacityBlock(request3) {
|
|
11402
|
+
const { ctx, teamRequest } = request3;
|
|
11403
|
+
return getQuotaCapacityBlock(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
|
|
10850
11404
|
}
|
|
10851
11405
|
var init_proxy_request = __esm(() => {
|
|
10852
11406
|
init_account_selector();
|
|
@@ -10866,31 +11420,139 @@ var init_handlers = __esm(() => {
|
|
|
10866
11420
|
init_token_manager();
|
|
10867
11421
|
});
|
|
10868
11422
|
|
|
10869
|
-
// ../../packages/
|
|
10870
|
-
function
|
|
10871
|
-
return
|
|
10872
|
-
body,
|
|
10873
|
-
contentType: req.headers.get("content-type"),
|
|
10874
|
-
manualAccountName,
|
|
10875
|
-
model: requestedModel,
|
|
10876
|
-
pinBucket: requestedModel,
|
|
10877
|
-
pinScope: `pool:${pool.wire}`,
|
|
10878
|
-
provider: `pool:${pool.wire}`,
|
|
10879
|
-
sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
|
|
10880
|
-
};
|
|
11423
|
+
// ../../packages/capacity/src/index.ts
|
|
11424
|
+
function isProviderBlockCategory(value) {
|
|
11425
|
+
return typeof value === "string" && PROVIDER_BLOCK_CATEGORIES.includes(value);
|
|
10881
11426
|
}
|
|
11427
|
+
var PROVIDER_BLOCK_CATEGORIES;
|
|
11428
|
+
var init_src11 = __esm(() => {
|
|
11429
|
+
PROVIDER_BLOCK_CATEGORIES = [
|
|
11430
|
+
"five-hour-limit",
|
|
11431
|
+
"weekly-limit",
|
|
11432
|
+
"request-rate",
|
|
11433
|
+
"token-allocation",
|
|
11434
|
+
"burst",
|
|
11435
|
+
"dynamic-throughput",
|
|
11436
|
+
"temporary-capacity",
|
|
11437
|
+
"unknown"
|
|
11438
|
+
];
|
|
11439
|
+
});
|
|
11440
|
+
|
|
11441
|
+
// ../../packages/proxy/src/pool/conversation-provider-routing-store.ts
|
|
11442
|
+
class PoolConversationProviderRoutingStore {
|
|
11443
|
+
dbOps;
|
|
11444
|
+
constructor(dbOps) {
|
|
11445
|
+
this.dbOps = dbOps;
|
|
11446
|
+
}
|
|
11447
|
+
getPreference(conversationKey) {
|
|
11448
|
+
return this.dbOps.getConversationProviderPreference(conversationKey);
|
|
11449
|
+
}
|
|
11450
|
+
upsertPreference(conversationKey, preference) {
|
|
11451
|
+
this.dbOps.upsertConversationProviderPreference(conversationKey, preference.provider, preference.promotionDeclined, preference.lastSeenAt);
|
|
11452
|
+
}
|
|
11453
|
+
getBlock(conversationKey, provider) {
|
|
11454
|
+
const block = this.dbOps.getConversationProviderBlock(conversationKey, provider);
|
|
11455
|
+
if (!block)
|
|
11456
|
+
return null;
|
|
11457
|
+
return {
|
|
11458
|
+
...block,
|
|
11459
|
+
category: isProviderBlockCategory(block.category) ? block.category : "unknown"
|
|
11460
|
+
};
|
|
11461
|
+
}
|
|
11462
|
+
upsertBlock(conversationKey, provider, block) {
|
|
11463
|
+
this.dbOps.upsertConversationProviderBlock(conversationKey, provider, block.category, block.retryAt, block.lastSeenAt);
|
|
11464
|
+
}
|
|
11465
|
+
deleteBlock(conversationKey, provider) {
|
|
11466
|
+
this.dbOps.deleteConversationProviderBlock(conversationKey, provider);
|
|
11467
|
+
}
|
|
11468
|
+
}
|
|
11469
|
+
var init_conversation_provider_routing_store = __esm(() => {
|
|
11470
|
+
init_src11();
|
|
11471
|
+
});
|
|
11472
|
+
|
|
11473
|
+
// ../../packages/proxy/src/pool/interactive-provider-pool.ts
|
|
11474
|
+
function configuredPoolChoices(pool, fallbackModel) {
|
|
11475
|
+
return pool.providers.map((candidate) => ({
|
|
11476
|
+
model: candidate.model ?? fallbackModel ?? "",
|
|
11477
|
+
provider: candidate.provider.name
|
|
11478
|
+
}));
|
|
11479
|
+
}
|
|
11480
|
+
function eligiblePoolProviders({
|
|
11481
|
+
body,
|
|
11482
|
+
ctx,
|
|
11483
|
+
manualAccountName,
|
|
11484
|
+
meta,
|
|
11485
|
+
pool,
|
|
11486
|
+
req,
|
|
11487
|
+
teamRequest,
|
|
11488
|
+
url
|
|
11489
|
+
}) {
|
|
11490
|
+
const eligibleProviders = new Set;
|
|
11491
|
+
for (const candidate of pool.providers) {
|
|
11492
|
+
const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
|
|
11493
|
+
const prepared = prepareProxyRequest(req, url, candidateContext, { ...meta, model: candidate.model }, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
|
|
11494
|
+
if (prepared.request.thread || prepared.accounts.length === 0)
|
|
11495
|
+
continue;
|
|
11496
|
+
const accounts = candidateContext.teamRouter ? candidateContext.teamRouter.eligibleAccounts(prepared.accounts, teamRequest, candidateContext.runtime.teamRouting) : prepared.accounts;
|
|
11497
|
+
if (accounts.length > 0)
|
|
11498
|
+
eligibleProviders.add(candidate.provider.name);
|
|
11499
|
+
}
|
|
11500
|
+
return eligibleProviders;
|
|
11501
|
+
}
|
|
11502
|
+
function eligiblePoolChoices(input, blockedProvider) {
|
|
11503
|
+
return capacityChoices(configuredPoolChoices(input.pool, input.meta.model), blockedProvider, eligiblePoolProviders(input));
|
|
11504
|
+
}
|
|
11505
|
+
function createManualProviderChoiceResponse(input, pinnedAccount, preferredProvider) {
|
|
11506
|
+
const ordered = preferProviders(input.pool.providers, (candidate) => candidate.provider.name, pinnedAccount?.provider, preferredProvider);
|
|
11507
|
+
const activeProvider = ordered[0]?.provider.name ?? input.pool.providers[0]?.provider.name ?? "";
|
|
11508
|
+
const eligible = eligiblePoolProviders(input);
|
|
11509
|
+
return createProviderChoiceProblem({
|
|
11510
|
+
activeProvider,
|
|
11511
|
+
choices: configuredPoolChoices(input.pool, input.meta.model).filter((choice) => eligible.has(choice.provider))
|
|
11512
|
+
});
|
|
11513
|
+
}
|
|
11514
|
+
async function waitOrReturnProviderCapacity({
|
|
11515
|
+
candidates,
|
|
11516
|
+
conversationKey,
|
|
11517
|
+
input,
|
|
11518
|
+
providerWaited,
|
|
11519
|
+
retry,
|
|
11520
|
+
routing
|
|
11521
|
+
}) {
|
|
11522
|
+
if (!providerWaitRequested(input.req.headers) || providerWaited || !candidates[0]) {
|
|
11523
|
+
return null;
|
|
11524
|
+
}
|
|
11525
|
+
const provider = candidates[0].provider.name;
|
|
11526
|
+
const blocked = conversationKey ? routing.getBlock(conversationKey, provider) : null;
|
|
11527
|
+
const retryAt = blocked?.retryAt;
|
|
11528
|
+
const holdMs = input.ctx.runtime.teamRouting.holdSeconds * 1000;
|
|
11529
|
+
if (input.ctx.quotaHold && retryAt !== undefined && retryAt > Date.now() && holdMs > 0 && retryAt - Date.now() <= holdMs) {
|
|
11530
|
+
await input.ctx.quotaHold.waitUntil(retryAt, input.req.signal);
|
|
11531
|
+
return await retry();
|
|
11532
|
+
}
|
|
11533
|
+
if (retryAt === undefined || retryAt > Date.now()) {
|
|
11534
|
+
return createProviderCapacityProblem({
|
|
11535
|
+
blockedProvider: provider,
|
|
11536
|
+
category: blocked?.category ?? "unknown",
|
|
11537
|
+
choices: eligiblePoolChoices(input, provider),
|
|
11538
|
+
...retryAt !== undefined && { retryAt }
|
|
11539
|
+
});
|
|
11540
|
+
}
|
|
11541
|
+
return null;
|
|
11542
|
+
}
|
|
11543
|
+
var init_interactive_provider_pool = __esm(() => {
|
|
11544
|
+
init_src10();
|
|
11545
|
+
init_handlers();
|
|
11546
|
+
init_proxy_request();
|
|
11547
|
+
});
|
|
11548
|
+
|
|
11549
|
+
// ../../packages/proxy/src/pool/provider-pool-attempts.ts
|
|
10882
11550
|
function preferPinnedAccount(accounts, pinnedId) {
|
|
10883
11551
|
if (!pinnedId)
|
|
10884
11552
|
return accounts;
|
|
10885
11553
|
const pinned = accounts.find((account2) => account2.id === pinnedId);
|
|
10886
11554
|
return pinned ? [pinned, ...accounts.filter((account2) => account2.id !== pinned.id)] : accounts;
|
|
10887
11555
|
}
|
|
10888
|
-
function preferPinnedProvider(pool, pinnedAccount) {
|
|
10889
|
-
if (!pinnedAccount)
|
|
10890
|
-
return pool.providers;
|
|
10891
|
-
const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
|
|
10892
|
-
return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
|
|
10893
|
-
}
|
|
10894
11556
|
async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
|
|
10895
11557
|
for (let index = 0;index < accounts.length; index += 1) {
|
|
10896
11558
|
const account2 = accounts[index];
|
|
@@ -10904,6 +11566,15 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
|
|
|
10904
11566
|
response: new Response("Bad Gateway", { status: 502 })
|
|
10905
11567
|
};
|
|
10906
11568
|
}
|
|
11569
|
+
if (attempt.kind === "provider-capacity-block") {
|
|
11570
|
+
await attempt.discard?.();
|
|
11571
|
+
if (accounts[index + 1])
|
|
11572
|
+
continue;
|
|
11573
|
+
if (allowNextProvider) {
|
|
11574
|
+
return { block: attempt.block, kind: "next-provider" };
|
|
11575
|
+
}
|
|
11576
|
+
return { block: attempt.block, kind: "capacity-block" };
|
|
11577
|
+
}
|
|
10907
11578
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10908
11579
|
return {
|
|
10909
11580
|
kind: "response",
|
|
@@ -10960,75 +11631,301 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
|
|
|
10960
11631
|
response: new Response("Bad Gateway", { status: 502 })
|
|
10961
11632
|
};
|
|
10962
11633
|
}
|
|
10963
|
-
|
|
10964
|
-
|
|
10965
|
-
|
|
10966
|
-
|
|
11634
|
+
function resolvePoolCandidateResult({
|
|
11635
|
+
candidate,
|
|
11636
|
+
candidateContext,
|
|
11637
|
+
conversationKey,
|
|
11638
|
+
interactive,
|
|
11639
|
+
interactiveInput,
|
|
11640
|
+
providerPreference,
|
|
11641
|
+
requestedChoice,
|
|
11642
|
+
result,
|
|
11643
|
+
routing
|
|
11644
|
+
}) {
|
|
11645
|
+
if (result.kind === "capacity-block") {
|
|
11646
|
+
if (conversationKey) {
|
|
11647
|
+
routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
|
|
11648
|
+
}
|
|
11649
|
+
return createProviderCapacityProblem({
|
|
11650
|
+
blockedProvider: candidate.provider.name,
|
|
11651
|
+
category: result.block.category,
|
|
11652
|
+
choices: eligiblePoolChoices(interactiveInput, candidate.provider.name),
|
|
11653
|
+
...result.block.retryAt !== undefined && {
|
|
11654
|
+
retryAt: result.block.retryAt
|
|
11655
|
+
}
|
|
11656
|
+
});
|
|
10967
11657
|
}
|
|
10968
|
-
|
|
10969
|
-
|
|
10970
|
-
|
|
10971
|
-
|
|
11658
|
+
if (result.kind !== "response")
|
|
11659
|
+
return null;
|
|
11660
|
+
if (result.account) {
|
|
11661
|
+
if (conversationKey) {
|
|
11662
|
+
routing.clearBlock(conversationKey, candidate.provider.name);
|
|
11663
|
+
}
|
|
11664
|
+
if (conversationKey && requestedChoice) {
|
|
11665
|
+
routing.selectProvider(conversationKey, candidate.provider.name, Date.now());
|
|
11666
|
+
}
|
|
11667
|
+
candidateContext.teamRouter?.rebind(interactiveInput.teamRequest, result.account.id, candidateContext.runtime.teamRouting, candidateContext.provider, candidateContext.dbOps);
|
|
11668
|
+
}
|
|
11669
|
+
if (!interactive)
|
|
11670
|
+
return result.response;
|
|
11671
|
+
const served = withServedProviderHeaders(result.response, {
|
|
11672
|
+
model: candidate.model ?? interactiveInput.meta.model ?? "",
|
|
11673
|
+
provider: candidate.provider.name
|
|
11674
|
+
});
|
|
11675
|
+
if (!conversationKey || !providerPreference || providerPreference.promotionDeclined || requestedChoice || providerPreference.provider !== candidate.provider.name) {
|
|
11676
|
+
return served;
|
|
11677
|
+
}
|
|
11678
|
+
return withProviderPromotionDetails(served, higherRankedProviderChoices(configuredPoolChoices(interactiveInput.pool, interactiveInput.meta.model), candidate.provider.name, eligiblePoolProviders(interactiveInput), (provider) => routing.canOfferProvider(conversationKey, provider, Date.now())));
|
|
11679
|
+
}
|
|
11680
|
+
function preparePoolCandidate(input, candidate, pinnedId, orderedFallback) {
|
|
11681
|
+
const context2 = createResolvedProxyContext(input.ctx, candidate.provider, input.pool.upstreamPath);
|
|
11682
|
+
const prepared = prepareProxyRequest(input.req, input.url, context2, { ...input.meta, model: candidate.model }, input.body, input.manualAccountName, input.teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
|
|
11683
|
+
const pooledAccounts = context2.teamRouter ? context2.teamRouter.eligibleAccounts(prepared.accounts, input.teamRequest, context2.runtime.teamRouting) : prepared.accounts;
|
|
11684
|
+
const eligibleAccounts = orderedFallback ? prepared.accounts.filter((account2) => account2.auth_method === "api_key" || pooledAccounts.includes(account2)) : pooledAccounts;
|
|
11685
|
+
return {
|
|
11686
|
+
accounts: preferPinnedAccount(eligibleAccounts, pinnedId),
|
|
11687
|
+
context: context2,
|
|
11688
|
+
request: prepared.request
|
|
11689
|
+
};
|
|
11690
|
+
}
|
|
11691
|
+
async function proxyPoolCandidates({
|
|
11692
|
+
candidates,
|
|
11693
|
+
conversationKey,
|
|
11694
|
+
interactive,
|
|
11695
|
+
interactiveInput,
|
|
11696
|
+
orderedFallback,
|
|
11697
|
+
pinnedId,
|
|
11698
|
+
providerPreference,
|
|
11699
|
+
requestedChoice,
|
|
11700
|
+
routing
|
|
11701
|
+
}) {
|
|
10972
11702
|
let soonestRetry = null;
|
|
10973
11703
|
let soonestFleetReset = null;
|
|
10974
11704
|
let everyCandidateFull = true;
|
|
11705
|
+
let firstCapacityBlock = null;
|
|
10975
11706
|
let emittedIngress = false;
|
|
10976
11707
|
const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
|
|
10977
11708
|
const recordUnserved = (request3) => {
|
|
11709
|
+
firstCapacityBlock ??= getRequestQuotaCapacityBlock(request3);
|
|
10978
11710
|
everyCandidateFull &&= isEveryAccountQuotaBlocked(request3.meta, request3.ctx);
|
|
10979
11711
|
soonestRetry = earliest(soonestRetry, getRequestRetryAt(request3));
|
|
10980
11712
|
soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request3.meta, request3.ctx));
|
|
10981
11713
|
};
|
|
10982
|
-
const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
|
|
10983
11714
|
for (const [candidateIndex, candidate] of candidates.entries()) {
|
|
10984
|
-
const
|
|
10985
|
-
const candidateMeta = { ...meta, model: candidate.model };
|
|
10986
|
-
const prepared = prepareProxyRequest(req, url, candidateContext, candidateMeta, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
|
|
10987
|
-
let accounts = prepared.accounts;
|
|
10988
|
-
if (candidateContext.teamRouter) {
|
|
10989
|
-
accounts = candidateContext.teamRouter.eligibleAccounts(accounts, teamRequest, candidateContext.runtime.teamRouting);
|
|
10990
|
-
}
|
|
10991
|
-
accounts = preferPinnedAccount(accounts, pinnedId);
|
|
11715
|
+
const { accounts, context: context2, request: request3 } = preparePoolCandidate(interactiveInput, candidate, pinnedId, orderedFallback);
|
|
10992
11716
|
if (accounts.length === 0) {
|
|
10993
|
-
recordUnserved(
|
|
11717
|
+
recordUnserved(request3);
|
|
10994
11718
|
continue;
|
|
10995
11719
|
}
|
|
10996
11720
|
if (!emittedIngress) {
|
|
10997
11721
|
requestEvents.emit("event", {
|
|
10998
11722
|
type: "ingress",
|
|
10999
|
-
id: meta.id,
|
|
11000
|
-
timestamp: meta.timestamp,
|
|
11001
|
-
method: meta.method,
|
|
11002
|
-
path: meta.path
|
|
11723
|
+
id: interactiveInput.meta.id,
|
|
11724
|
+
timestamp: interactiveInput.meta.timestamp,
|
|
11725
|
+
method: interactiveInput.meta.method,
|
|
11726
|
+
path: interactiveInput.meta.path
|
|
11003
11727
|
});
|
|
11004
11728
|
emittedIngress = true;
|
|
11005
11729
|
}
|
|
11006
11730
|
log22.info(`Selected ${accounts.length} accounts: ${accounts.map((account2) => account2.name).join(", ")}`);
|
|
11007
|
-
const result = await proxyPoolCandidate(
|
|
11008
|
-
if (result.kind === "
|
|
11009
|
-
|
|
11010
|
-
|
|
11011
|
-
|
|
11012
|
-
|
|
11731
|
+
const result = await proxyPoolCandidate(request3, accounts, candidateIndex < candidates.length - 1);
|
|
11732
|
+
if (result.kind === "next-provider" && result.block) {
|
|
11733
|
+
firstCapacityBlock ??= result.block;
|
|
11734
|
+
if (conversationKey) {
|
|
11735
|
+
routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
|
|
11736
|
+
}
|
|
11737
|
+
}
|
|
11738
|
+
const response = resolvePoolCandidateResult({
|
|
11739
|
+
candidate,
|
|
11740
|
+
candidateContext: context2,
|
|
11741
|
+
conversationKey,
|
|
11742
|
+
interactive,
|
|
11743
|
+
interactiveInput,
|
|
11744
|
+
providerPreference,
|
|
11745
|
+
requestedChoice,
|
|
11746
|
+
result,
|
|
11747
|
+
routing
|
|
11748
|
+
});
|
|
11749
|
+
if (response)
|
|
11750
|
+
return { kind: "response", response };
|
|
11751
|
+
recordUnserved(request3);
|
|
11752
|
+
}
|
|
11753
|
+
return {
|
|
11754
|
+
everyCandidateFull,
|
|
11755
|
+
kind: "unserved",
|
|
11756
|
+
firstCapacityBlock,
|
|
11757
|
+
soonestFleetReset,
|
|
11758
|
+
soonestRetry
|
|
11759
|
+
};
|
|
11760
|
+
}
|
|
11761
|
+
var log22;
|
|
11762
|
+
var init_provider_pool_attempts = __esm(() => {
|
|
11763
|
+
init_src2();
|
|
11764
|
+
init_src4();
|
|
11765
|
+
init_src10();
|
|
11766
|
+
init_handlers();
|
|
11767
|
+
init_proxy_attempts();
|
|
11768
|
+
init_proxy_request();
|
|
11769
|
+
init_interactive_provider_pool();
|
|
11770
|
+
log22 = new Logger("Proxy");
|
|
11771
|
+
});
|
|
11772
|
+
|
|
11773
|
+
// ../../packages/proxy/src/provider-pool.ts
|
|
11774
|
+
function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
|
|
11775
|
+
return {
|
|
11776
|
+
body,
|
|
11777
|
+
callerId,
|
|
11778
|
+
contentType: req.headers.get("content-type"),
|
|
11779
|
+
manualAccountName,
|
|
11780
|
+
model: requestedModel,
|
|
11781
|
+
pinBucket: requestedModel,
|
|
11782
|
+
pinScope: `pool:${pool.wire}`,
|
|
11783
|
+
provider: `pool:${pool.wire}`,
|
|
11784
|
+
sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
|
|
11785
|
+
};
|
|
11786
|
+
}
|
|
11787
|
+
function hasOrderedCallerFallback(ctx, callerId) {
|
|
11788
|
+
const routing = ctx.runtime.teamRouting;
|
|
11789
|
+
return routing.enabled && callerId !== undefined && Object.hasOwn(routing.callerProviderFallback, callerId) && routing.callerProviderFallback[callerId] === "ordered";
|
|
11790
|
+
}
|
|
11791
|
+
function prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
|
|
11792
|
+
const firstCandidate = pool.providers[0];
|
|
11793
|
+
if (!firstCandidate) {
|
|
11794
|
+
return {
|
|
11795
|
+
kind: "response",
|
|
11796
|
+
response: new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 })
|
|
11797
|
+
};
|
|
11798
|
+
}
|
|
11799
|
+
const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
|
|
11800
|
+
const interactiveInput = {
|
|
11801
|
+
body,
|
|
11802
|
+
ctx,
|
|
11803
|
+
manualAccountName,
|
|
11804
|
+
meta,
|
|
11805
|
+
pool,
|
|
11806
|
+
req,
|
|
11807
|
+
teamRequest,
|
|
11808
|
+
url
|
|
11809
|
+
};
|
|
11810
|
+
const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
|
|
11811
|
+
const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
|
|
11812
|
+
const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
|
|
11813
|
+
const conversationKey = firstContext.teamRouter?.getConversationProviderKey(teamRequest, firstContext.runtime.teamRouting);
|
|
11814
|
+
const routing = new ConversationProviderRouting(new PoolConversationProviderRoutingStore(ctx.dbOps));
|
|
11815
|
+
let providerPreference = conversationKey ? routing.getPreference(conversationKey) : null;
|
|
11816
|
+
const interactive = interactiveProviderChoiceRequested(req.headers);
|
|
11817
|
+
if (interactive && conversationKey && providerPreference && providerPromotionDeclined(req.headers)) {
|
|
11818
|
+
routing.declinePromotion(conversationKey, Date.now());
|
|
11819
|
+
providerPreference = routing.getPreference(conversationKey);
|
|
11820
|
+
}
|
|
11821
|
+
const requestedChoice = interactive ? req.headers.get("x-agent-smith-provider-choice") : null;
|
|
11822
|
+
const configuredChoices = configuredPoolChoices(pool, meta.model);
|
|
11823
|
+
if (requestedChoice && !readProviderChoice(req.headers, configuredChoices)) {
|
|
11824
|
+
return {
|
|
11825
|
+
kind: "response",
|
|
11826
|
+
response: new Response("Selected provider is not available for this request", { status: 409 })
|
|
11827
|
+
};
|
|
11828
|
+
}
|
|
11829
|
+
if (interactive && manualProviderChoiceRequested(req.headers)) {
|
|
11830
|
+
return {
|
|
11831
|
+
kind: "response",
|
|
11832
|
+
response: createManualProviderChoiceResponse(interactiveInput, pinnedAccount, providerPreference?.provider)
|
|
11833
|
+
};
|
|
11834
|
+
}
|
|
11835
|
+
const orderedFallback = !interactive && hasOrderedCallerFallback(ctx, callerId);
|
|
11836
|
+
return {
|
|
11837
|
+
candidates: selectPoolProviders(pool.providers, (candidate) => candidate.provider.name, {
|
|
11838
|
+
orderedFallback,
|
|
11839
|
+
pinnedProvider: pinnedAccount?.provider,
|
|
11840
|
+
preferredProvider: providerPreference?.provider,
|
|
11841
|
+
requestedProvider: requestedChoice
|
|
11842
|
+
}),
|
|
11843
|
+
conversationKey,
|
|
11844
|
+
interactive,
|
|
11845
|
+
interactiveInput,
|
|
11846
|
+
kind: "selection",
|
|
11847
|
+
orderedFallback,
|
|
11848
|
+
pinnedId,
|
|
11849
|
+
providerPreference,
|
|
11850
|
+
requestedChoice,
|
|
11851
|
+
routing
|
|
11852
|
+
};
|
|
11853
|
+
}
|
|
11854
|
+
async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, providerWaited = false) {
|
|
11855
|
+
const selection = prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId);
|
|
11856
|
+
if (selection.kind === "response")
|
|
11857
|
+
return selection.response;
|
|
11858
|
+
const {
|
|
11859
|
+
candidates,
|
|
11860
|
+
conversationKey,
|
|
11861
|
+
interactive,
|
|
11862
|
+
interactiveInput,
|
|
11863
|
+
orderedFallback,
|
|
11864
|
+
pinnedId,
|
|
11865
|
+
providerPreference,
|
|
11866
|
+
requestedChoice,
|
|
11867
|
+
routing
|
|
11868
|
+
} = selection;
|
|
11869
|
+
if (interactive) {
|
|
11870
|
+
const waitResponse = await waitOrReturnProviderCapacity({
|
|
11871
|
+
candidates,
|
|
11872
|
+
conversationKey,
|
|
11873
|
+
input: interactiveInput,
|
|
11874
|
+
providerWaited,
|
|
11875
|
+
retry: () => proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, true),
|
|
11876
|
+
routing
|
|
11877
|
+
});
|
|
11878
|
+
if (waitResponse)
|
|
11879
|
+
return waitResponse;
|
|
11880
|
+
}
|
|
11881
|
+
const candidateAttempt = await proxyPoolCandidates({
|
|
11882
|
+
candidates,
|
|
11883
|
+
conversationKey,
|
|
11884
|
+
interactive,
|
|
11885
|
+
interactiveInput,
|
|
11886
|
+
orderedFallback,
|
|
11887
|
+
pinnedId,
|
|
11888
|
+
providerPreference,
|
|
11889
|
+
requestedChoice,
|
|
11890
|
+
routing
|
|
11891
|
+
});
|
|
11892
|
+
if (candidateAttempt.kind === "response")
|
|
11893
|
+
return candidateAttempt.response;
|
|
11894
|
+
if (candidateAttempt.everyCandidateFull && candidateAttempt.soonestFleetReset !== null) {
|
|
11895
|
+
ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, candidateAttempt.soonestFleetReset, { blocked: true, holdSeconds: 0 });
|
|
11896
|
+
}
|
|
11897
|
+
if (interactive) {
|
|
11898
|
+
const blockedProvider = candidates[0]?.provider.name;
|
|
11899
|
+
if (blockedProvider) {
|
|
11900
|
+
const block = candidateAttempt.firstCapacityBlock;
|
|
11901
|
+
const retryAt = block?.retryAt ?? candidateAttempt.soonestRetry;
|
|
11902
|
+
return createProviderCapacityProblem({
|
|
11903
|
+
blockedProvider,
|
|
11904
|
+
category: block?.category ?? "unknown",
|
|
11905
|
+
choices: eligiblePoolChoices(interactiveInput, blockedProvider),
|
|
11906
|
+
...retryAt !== null && retryAt !== undefined && {
|
|
11907
|
+
retryAt
|
|
11908
|
+
}
|
|
11909
|
+
});
|
|
11013
11910
|
}
|
|
11014
|
-
recordUnserved(prepared.request);
|
|
11015
11911
|
}
|
|
11016
|
-
if (
|
|
11017
|
-
|
|
11912
|
+
if (candidateAttempt.soonestRetry !== null) {
|
|
11913
|
+
return quotaExhaustionResponse(candidateAttempt.soonestRetry);
|
|
11018
11914
|
}
|
|
11019
|
-
|
|
11020
|
-
return quotaExhaustionResponse(soonestRetry);
|
|
11021
|
-
log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
|
|
11915
|
+
log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
|
|
11022
11916
|
throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
|
|
11023
11917
|
}
|
|
11024
|
-
var
|
|
11918
|
+
var log23;
|
|
11025
11919
|
var init_provider_pool = __esm(() => {
|
|
11026
11920
|
init_src2();
|
|
11027
11921
|
init_src4();
|
|
11922
|
+
init_src10();
|
|
11028
11923
|
init_handlers();
|
|
11029
11924
|
init_proxy_attempts();
|
|
11030
|
-
|
|
11031
|
-
|
|
11925
|
+
init_conversation_provider_routing_store();
|
|
11926
|
+
init_interactive_provider_pool();
|
|
11927
|
+
init_provider_pool_attempts();
|
|
11928
|
+
log23 = new Logger("Proxy");
|
|
11032
11929
|
});
|
|
11033
11930
|
|
|
11034
11931
|
// ../../packages/proxy/src/seat-alerts.ts
|
|
@@ -11053,10 +11950,10 @@ class SeatAlerts {
|
|
|
11053
11950
|
this.config = config;
|
|
11054
11951
|
this.send = send;
|
|
11055
11952
|
if (config.email && !(config.emailFrom && config.resendApiKey)) {
|
|
11056
|
-
|
|
11953
|
+
log24.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
|
|
11057
11954
|
}
|
|
11058
11955
|
if (!config.slackBotToken !== !config.slackChannel) {
|
|
11059
|
-
|
|
11956
|
+
log24.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
|
|
11060
11957
|
}
|
|
11061
11958
|
}
|
|
11062
11959
|
extraUsageSpent(account2, provider) {
|
|
@@ -11079,7 +11976,7 @@ class SeatAlerts {
|
|
|
11079
11976
|
});
|
|
11080
11977
|
}
|
|
11081
11978
|
notify(alert) {
|
|
11082
|
-
|
|
11979
|
+
log24.warn(alert.text);
|
|
11083
11980
|
for (const delivery of this.deliveries(alert)) {
|
|
11084
11981
|
trackProxyBackgroundTask(this.deliver(delivery));
|
|
11085
11982
|
}
|
|
@@ -11134,7 +12031,7 @@ class SeatAlerts {
|
|
|
11134
12031
|
signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
|
|
11135
12032
|
});
|
|
11136
12033
|
if (!response.ok) {
|
|
11137
|
-
|
|
12034
|
+
log24.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
|
|
11138
12035
|
return;
|
|
11139
12036
|
}
|
|
11140
12037
|
if (!delivery.repliesOk)
|
|
@@ -11142,19 +12039,19 @@ class SeatAlerts {
|
|
|
11142
12039
|
const reply2 = await response.json();
|
|
11143
12040
|
if (reply2.ok !== true) {
|
|
11144
12041
|
const code = typeof reply2.error === "string" && SLACK_ERROR_CODE.test(reply2.error) ? reply2.error : "no reason given";
|
|
11145
|
-
|
|
12042
|
+
log24.warn(`${delivery.channel} alert was refused (${code})`);
|
|
11146
12043
|
}
|
|
11147
12044
|
} catch (error) {
|
|
11148
|
-
|
|
12045
|
+
log24.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
|
|
11149
12046
|
}
|
|
11150
12047
|
}
|
|
11151
12048
|
}
|
|
11152
|
-
var
|
|
12049
|
+
var log24, 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;
|
|
11153
12050
|
var init_seat_alerts = __esm(() => {
|
|
11154
12051
|
init_src4();
|
|
11155
12052
|
init_background_tasks();
|
|
11156
12053
|
init_account_selector();
|
|
11157
|
-
|
|
12054
|
+
log24 = new Logger("SeatAlerts");
|
|
11158
12055
|
SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
|
|
11159
12056
|
});
|
|
11160
12057
|
|
|
@@ -11539,7 +12436,7 @@ function getUsageWorker() {
|
|
|
11539
12436
|
}
|
|
11540
12437
|
if (!usageWorkerInstance) {
|
|
11541
12438
|
usageWorkerInstance = new UsageWorkerController({
|
|
11542
|
-
logger:
|
|
12439
|
+
logger: log25,
|
|
11543
12440
|
shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
|
|
11544
12441
|
onWorkerMessage: (data) => {
|
|
11545
12442
|
if (data.type === "summary" && isRequestSummary(data.summary)) {
|
|
@@ -11578,7 +12475,7 @@ async function terminateUsageWorker() {
|
|
|
11578
12475
|
}
|
|
11579
12476
|
}
|
|
11580
12477
|
}
|
|
11581
|
-
async function handleProxy(req, url, ctx) {
|
|
12478
|
+
async function handleProxy(req, url, ctx, callerId) {
|
|
11582
12479
|
const manualPin = manualPinFromUrl(url);
|
|
11583
12480
|
if (manualPin === "invalid")
|
|
11584
12481
|
return new Response("Not Found", { status: 404 });
|
|
@@ -11601,13 +12498,13 @@ async function handleProxy(req, url, ctx) {
|
|
|
11601
12498
|
if (pool.providers.length === 0) {
|
|
11602
12499
|
return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
|
|
11603
12500
|
}
|
|
11604
|
-
return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName);
|
|
12501
|
+
return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
|
|
11605
12502
|
}
|
|
11606
12503
|
const requestMeta = createRequestMetadata(req, upstreamUrl);
|
|
11607
12504
|
const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
|
|
11608
12505
|
const body = buffer ?? null;
|
|
11609
12506
|
requestMeta.model = readRequestModel(body);
|
|
11610
|
-
const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
|
|
12507
|
+
const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName, undefined, undefined, undefined, callerId);
|
|
11611
12508
|
let accounts = initiallySelectedAccounts;
|
|
11612
12509
|
if (accounts.length === 0) {
|
|
11613
12510
|
const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
|
|
@@ -11626,7 +12523,7 @@ async function handleProxy(req, url, ctx) {
|
|
|
11626
12523
|
return quotaExhaustionResponse(retryAt);
|
|
11627
12524
|
}
|
|
11628
12525
|
if (accounts.length === 0) {
|
|
11629
|
-
|
|
12526
|
+
log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
|
|
11630
12527
|
throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
|
|
11631
12528
|
}
|
|
11632
12529
|
}
|
|
@@ -11637,11 +12534,11 @@ async function handleProxy(req, url, ctx) {
|
|
|
11637
12534
|
method: requestMeta.method,
|
|
11638
12535
|
path: requestMeta.path
|
|
11639
12536
|
});
|
|
11640
|
-
|
|
11641
|
-
|
|
12537
|
+
log25.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
|
|
12538
|
+
log25.info(`Request: ${req.method} ${url.pathname}`);
|
|
11642
12539
|
return await proxySelectedAccounts(request3, accounts);
|
|
11643
12540
|
}
|
|
11644
|
-
var
|
|
12541
|
+
var log25, usageWorkerInstance = null;
|
|
11645
12542
|
var init_proxy = __esm(() => {
|
|
11646
12543
|
init_src2();
|
|
11647
12544
|
init_src4();
|
|
@@ -11650,7 +12547,7 @@ var init_proxy = __esm(() => {
|
|
|
11650
12547
|
init_provider_pool();
|
|
11651
12548
|
init_seat_alerts();
|
|
11652
12549
|
init_usage_worker();
|
|
11653
|
-
|
|
12550
|
+
log25 = new Logger("Proxy");
|
|
11654
12551
|
});
|
|
11655
12552
|
|
|
11656
12553
|
// ../../packages/proxy/src/quota-hold.ts
|
|
@@ -12002,7 +12899,7 @@ function endActiveTurn(session, success, error) {
|
|
|
12002
12899
|
if (!activeTurn) {
|
|
12003
12900
|
return;
|
|
12004
12901
|
}
|
|
12005
|
-
|
|
12902
|
+
log26.debug("Ending tracked websocket turn", {
|
|
12006
12903
|
requestId: activeTurn.requestId,
|
|
12007
12904
|
provider: session.providerName,
|
|
12008
12905
|
path: session.path,
|
|
@@ -12056,7 +12953,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
|
|
|
12056
12953
|
timestamp,
|
|
12057
12954
|
model: getEventModel(parsed)
|
|
12058
12955
|
};
|
|
12059
|
-
|
|
12956
|
+
log26.debug("Starting tracked websocket turn", {
|
|
12060
12957
|
requestId,
|
|
12061
12958
|
provider: session.providerName,
|
|
12062
12959
|
path: session.path,
|
|
@@ -12086,7 +12983,7 @@ function handleTrackedUpstreamText(session, data) {
|
|
|
12086
12983
|
if (!messageType) {
|
|
12087
12984
|
return;
|
|
12088
12985
|
}
|
|
12089
|
-
|
|
12986
|
+
log26.debug("Processing tracked websocket message", {
|
|
12090
12987
|
provider: session.providerName,
|
|
12091
12988
|
path: session.path,
|
|
12092
12989
|
messageType,
|
|
@@ -12127,7 +13024,7 @@ function capturePendingRequestBody(session, message) {
|
|
|
12127
13024
|
}
|
|
12128
13025
|
session.pendingRequestBody = Buffer.from(message).toString("base64");
|
|
12129
13026
|
session.pendingRequestTimestamp = Date.now();
|
|
12130
|
-
|
|
13027
|
+
log26.debug("Captured websocket request body for next tracked turn", {
|
|
12131
13028
|
provider: session.providerName,
|
|
12132
13029
|
path: session.path,
|
|
12133
13030
|
size: message.length
|
|
@@ -12200,7 +13097,7 @@ async function connectToNextUpstream(ws) {
|
|
|
12200
13097
|
plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
|
|
12201
13098
|
} catch (error) {
|
|
12202
13099
|
session.connecting = false;
|
|
12203
|
-
|
|
13100
|
+
log26.warn("Skipping websocket account during upstream connection", {
|
|
12204
13101
|
account: account2.name,
|
|
12205
13102
|
error: error instanceof Error ? error.message : String(error)
|
|
12206
13103
|
});
|
|
@@ -12259,7 +13156,7 @@ async function connectToNextUpstream(ws) {
|
|
|
12259
13156
|
}
|
|
12260
13157
|
});
|
|
12261
13158
|
upstream.addEventListener("error", () => {
|
|
12262
|
-
|
|
13159
|
+
log26.warn("Upstream websocket error", {
|
|
12263
13160
|
account: plan.account.name,
|
|
12264
13161
|
provider: session.providerName,
|
|
12265
13162
|
path: session.path
|
|
@@ -12268,7 +13165,7 @@ async function connectToNextUpstream(ws) {
|
|
|
12268
13165
|
} catch (error) {
|
|
12269
13166
|
session.connecting = false;
|
|
12270
13167
|
clearConnectTimeout(session);
|
|
12271
|
-
|
|
13168
|
+
log26.warn("Failed to create upstream websocket", {
|
|
12272
13169
|
account: plan.account.name,
|
|
12273
13170
|
error: error instanceof Error ? error.message : String(error)
|
|
12274
13171
|
});
|
|
@@ -12288,7 +13185,7 @@ function isWebSocketUpgradeRequest(req) {
|
|
|
12288
13185
|
}
|
|
12289
13186
|
return connection.toLowerCase().split(",").some((value) => value.trim() === "upgrade");
|
|
12290
13187
|
}
|
|
12291
|
-
function handleWebSocketUpgradeRequest(req, url, ctx, server) {
|
|
13188
|
+
function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
|
|
12292
13189
|
if (!isWebSocketUpgradeRequest(req)) {
|
|
12293
13190
|
return;
|
|
12294
13191
|
}
|
|
@@ -12305,6 +13202,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
|
|
|
12305
13202
|
const teamRequest = {
|
|
12306
13203
|
body: null,
|
|
12307
13204
|
contentType: null,
|
|
13205
|
+
callerId,
|
|
12308
13206
|
model: requestMeta.model,
|
|
12309
13207
|
provider: requestContext.providerName,
|
|
12310
13208
|
sessionId: requestContext.provider.getClientSessionId?.(req.headers) ?? null
|
|
@@ -12312,7 +13210,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
|
|
|
12312
13210
|
const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
|
|
12313
13211
|
if (accounts.length === 0) {
|
|
12314
13212
|
alertWhenFleetFull(requestMeta, requestContext, 0);
|
|
12315
|
-
|
|
13213
|
+
log26.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
|
|
12316
13214
|
return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
|
|
12317
13215
|
}
|
|
12318
13216
|
const protocols = getProtocols(req.headers);
|
|
@@ -12350,7 +13248,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
|
|
|
12350
13248
|
}
|
|
12351
13249
|
return;
|
|
12352
13250
|
}
|
|
12353
|
-
var
|
|
13251
|
+
var log26, 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;
|
|
12354
13252
|
var init_websocket_proxy = __esm(() => {
|
|
12355
13253
|
init_src2();
|
|
12356
13254
|
init_src3();
|
|
@@ -12361,7 +13259,7 @@ var init_websocket_proxy = __esm(() => {
|
|
|
12361
13259
|
init_token_manager();
|
|
12362
13260
|
init_openai_usage();
|
|
12363
13261
|
init_seat_alerts();
|
|
12364
|
-
|
|
13262
|
+
log26 = new Logger("WebSocketProxy");
|
|
12365
13263
|
websocketSessions = new Map;
|
|
12366
13264
|
textEncoder = new TextEncoder;
|
|
12367
13265
|
websocketProxyHandler = {
|
|
@@ -12475,16 +13373,16 @@ class WindowWarmup {
|
|
|
12475
13373
|
try {
|
|
12476
13374
|
const accessToken = await this.readToken(account2);
|
|
12477
13375
|
if (!accessToken) {
|
|
12478
|
-
|
|
13376
|
+
log27.warn(`Window warm-up skipped ${account2.name}: no access token`);
|
|
12479
13377
|
return;
|
|
12480
13378
|
}
|
|
12481
13379
|
const quota2 = await this.startWindow(provider, account2, accessToken, model);
|
|
12482
|
-
|
|
13380
|
+
log27.info(`Window warm-up started ${account2.name}'s five-hour window`);
|
|
12483
13381
|
if (quota2) {
|
|
12484
13382
|
recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
|
|
12485
13383
|
}
|
|
12486
13384
|
} catch (error) {
|
|
12487
|
-
|
|
13385
|
+
log27.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
12488
13386
|
}
|
|
12489
13387
|
}
|
|
12490
13388
|
async startWindow(provider, account2, accessToken, model) {
|
|
@@ -12496,18 +13394,18 @@ class WindowWarmup {
|
|
|
12496
13394
|
}
|
|
12497
13395
|
}
|
|
12498
13396
|
}
|
|
12499
|
-
var
|
|
13397
|
+
var log27;
|
|
12500
13398
|
var init_window_warmup2 = __esm(() => {
|
|
12501
13399
|
init_src7();
|
|
12502
13400
|
init_src4();
|
|
12503
13401
|
init_src();
|
|
12504
13402
|
init_account_selector();
|
|
12505
13403
|
init_quota_probe();
|
|
12506
|
-
|
|
13404
|
+
log27 = new Logger("WindowWarmup");
|
|
12507
13405
|
});
|
|
12508
13406
|
|
|
12509
13407
|
// ../../packages/proxy/src/index.ts
|
|
12510
|
-
var
|
|
13408
|
+
var init_src12 = __esm(() => {
|
|
12511
13409
|
init_background_tasks();
|
|
12512
13410
|
init_account_selector();
|
|
12513
13411
|
init_request_handler();
|
|
@@ -12533,30 +13431,33 @@ import {
|
|
|
12533
13431
|
readFileSync as readFileSync2
|
|
12534
13432
|
} from "fs";
|
|
12535
13433
|
import { isAbsolute as isAbsolute2 } from "path";
|
|
12536
|
-
function
|
|
13434
|
+
function deviceKeyName(key, path) {
|
|
12537
13435
|
if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
|
|
12538
|
-
return
|
|
13436
|
+
return;
|
|
12539
13437
|
let fd;
|
|
12540
13438
|
try {
|
|
12541
13439
|
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
12542
13440
|
const stat = fstatSync(fd);
|
|
12543
13441
|
if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
|
|
12544
|
-
return
|
|
13442
|
+
return;
|
|
12545
13443
|
const registry = JSON.parse(readFileSync2(fd, "utf8"));
|
|
12546
13444
|
if (!registry || typeof registry !== "object" || Array.isArray(registry))
|
|
12547
|
-
return
|
|
13445
|
+
return;
|
|
12548
13446
|
const entries = Object.entries(registry);
|
|
12549
13447
|
if (entries.length > MAX_DEVICES || entries.some(([name, digest2]) => !/^[-a-zA-Z0-9_]{1,64}$/.test(name) || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/.test(digest2)))
|
|
12550
|
-
return
|
|
13448
|
+
return;
|
|
12551
13449
|
const digest = createHash3("sha256").update(key).digest();
|
|
12552
|
-
return entries.
|
|
13450
|
+
return entries.find(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")))?.[0];
|
|
12553
13451
|
} catch {
|
|
12554
|
-
return
|
|
13452
|
+
return;
|
|
12555
13453
|
} finally {
|
|
12556
13454
|
if (fd !== undefined)
|
|
12557
13455
|
closeSync(fd);
|
|
12558
13456
|
}
|
|
12559
13457
|
}
|
|
13458
|
+
function deviceKeyMatches(key, path) {
|
|
13459
|
+
return deviceKeyName(key, path) !== undefined;
|
|
13460
|
+
}
|
|
12560
13461
|
var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
|
|
12561
13462
|
var init_device_keys = __esm(() => {
|
|
12562
13463
|
MAX_REGISTRY_BYTES = 32 * 1024;
|
|
@@ -12650,6 +13551,12 @@ function keyRole(req, url, config) {
|
|
|
12650
13551
|
}
|
|
12651
13552
|
return null;
|
|
12652
13553
|
}
|
|
13554
|
+
function callerIdForRequest(req, url, config) {
|
|
13555
|
+
if (keyRole(req, url, config) !== "device")
|
|
13556
|
+
return;
|
|
13557
|
+
const apiKey = req.headers.get("x-api-key");
|
|
13558
|
+
return deviceKeyName(apiKey, config.clientKeysFile) ?? (isResponsesInferenceRoute(url.pathname) ? deviceKeyName(bearerToken(req), config.clientKeysFile) : undefined);
|
|
13559
|
+
}
|
|
12653
13560
|
function hostnameFromHostHeader(host) {
|
|
12654
13561
|
try {
|
|
12655
13562
|
const hostname = new URL(`http://${host}`).hostname.toLowerCase();
|
|
@@ -12739,10 +13646,10 @@ function createRuntimeConfig(config, port) {
|
|
|
12739
13646
|
teamRouting: config.getTeamRouting()
|
|
12740
13647
|
};
|
|
12741
13648
|
}
|
|
12742
|
-
function wireStrategyHotReload(config,
|
|
13649
|
+
function wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
|
|
12743
13650
|
config.on("change", (change) => {
|
|
12744
13651
|
if (change.key === "lb_strategy") {
|
|
12745
|
-
|
|
13652
|
+
log28.info("Strategy configuration changed");
|
|
12746
13653
|
const newStrategyName = config.getStrategy();
|
|
12747
13654
|
if (newStrategyName === "session") {
|
|
12748
13655
|
const strategy3 = new SessionStrategy;
|
|
@@ -12757,7 +13664,7 @@ function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig
|
|
|
12757
13664
|
runtimeConfig2.teamRouting = config.getTeamRouting();
|
|
12758
13665
|
quotaProbe.reschedule();
|
|
12759
13666
|
windowWarmup.reschedule();
|
|
12760
|
-
|
|
13667
|
+
log28.info("Team routing configuration changed");
|
|
12761
13668
|
}
|
|
12762
13669
|
});
|
|
12763
13670
|
}
|
|
@@ -12792,7 +13699,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12792
13699
|
sessionDurationMs: runtimeConfig2.sessionDurationMs
|
|
12793
13700
|
});
|
|
12794
13701
|
const dbOps = DatabaseFactory.getInstance();
|
|
12795
|
-
const
|
|
13702
|
+
const log28 = container.resolve(SERVICE_KEYS.Logger);
|
|
12796
13703
|
container.registerInstance(SERVICE_KEYS.Database, dbOps);
|
|
12797
13704
|
const asyncWriter = new AsyncDbWriter;
|
|
12798
13705
|
container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
|
|
@@ -12857,11 +13764,11 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12857
13764
|
usageWorker: getUsageWorker()
|
|
12858
13765
|
};
|
|
12859
13766
|
const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
|
|
12860
|
-
wireStrategyHotReload(config,
|
|
13767
|
+
wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
|
|
12861
13768
|
return {
|
|
12862
13769
|
config,
|
|
12863
13770
|
dbOps,
|
|
12864
|
-
log:
|
|
13771
|
+
log: log28,
|
|
12865
13772
|
asyncWriter,
|
|
12866
13773
|
apiRouter,
|
|
12867
13774
|
exposureConfig,
|
|
@@ -12870,12 +13777,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12870
13777
|
runtimeConfig: runtimeConfig2
|
|
12871
13778
|
};
|
|
12872
13779
|
}
|
|
12873
|
-
function logInitialAccountStatus(
|
|
13780
|
+
function logInitialAccountStatus(log28, dbOps) {
|
|
12874
13781
|
const accounts = dbOps.getAllAccounts();
|
|
12875
13782
|
const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
|
|
12876
|
-
|
|
13783
|
+
log28.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
|
|
12877
13784
|
if (activeAccounts.length === 0) {
|
|
12878
|
-
|
|
13785
|
+
log28.warn("No active accounts available - requests will be refused with a 503 until an account is added");
|
|
12879
13786
|
}
|
|
12880
13787
|
}
|
|
12881
13788
|
var init_bootstrap_runtime = __esm(() => {
|
|
@@ -12885,7 +13792,7 @@ var init_bootstrap_runtime = __esm(() => {
|
|
|
12885
13792
|
init_src8();
|
|
12886
13793
|
init_src4();
|
|
12887
13794
|
init_src5();
|
|
12888
|
-
|
|
13795
|
+
init_src12();
|
|
12889
13796
|
init_exposure();
|
|
12890
13797
|
});
|
|
12891
13798
|
|
|
@@ -13066,6 +13973,7 @@ function createServerFetchHandler({
|
|
|
13066
13973
|
if (rejected) {
|
|
13067
13974
|
return rejected;
|
|
13068
13975
|
}
|
|
13976
|
+
const callerId = callerIdForRequest(req, url, exposureConfig);
|
|
13069
13977
|
const apiResponse = await apiRouter.handleRequest(url, req);
|
|
13070
13978
|
if (apiResponse) {
|
|
13071
13979
|
return apiResponse;
|
|
@@ -13084,7 +13992,7 @@ function createServerFetchHandler({
|
|
|
13084
13992
|
return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
|
|
13085
13993
|
}
|
|
13086
13994
|
if (server) {
|
|
13087
|
-
const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
|
|
13995
|
+
const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server, callerId);
|
|
13088
13996
|
if (websocketResponse) {
|
|
13089
13997
|
return websocketResponse;
|
|
13090
13998
|
}
|
|
@@ -13093,7 +14001,7 @@ function createServerFetchHandler({
|
|
|
13093
14001
|
}
|
|
13094
14002
|
}
|
|
13095
14003
|
try {
|
|
13096
|
-
return await handleProxyRequest(req, url, proxyContext);
|
|
14004
|
+
return await handleProxyRequest(req, url, proxyContext, callerId);
|
|
13097
14005
|
} catch (error) {
|
|
13098
14006
|
return errorResponse(error);
|
|
13099
14007
|
}
|
|
@@ -13110,38 +14018,38 @@ function createServerFetchHandler({
|
|
|
13110
14018
|
var init_fetch_handler = __esm(() => {
|
|
13111
14019
|
init_src2();
|
|
13112
14020
|
init_src3();
|
|
13113
|
-
|
|
14021
|
+
init_src12();
|
|
13114
14022
|
init_dashboard_assets();
|
|
13115
14023
|
init_exposure();
|
|
13116
14024
|
init_oauth_token();
|
|
13117
14025
|
});
|
|
13118
14026
|
|
|
13119
14027
|
// ../../packages/runtime-server/src/retention-maintenance.ts
|
|
13120
|
-
function removeExpiredRequests(config, dbOps,
|
|
14028
|
+
function removeExpiredRequests(config, dbOps, log28, label) {
|
|
13121
14029
|
try {
|
|
13122
14030
|
const payloadDays = config.getDataRetentionDays();
|
|
13123
14031
|
const requestDays = config.getRequestRetentionDays();
|
|
13124
14032
|
const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
|
|
13125
|
-
|
|
14033
|
+
log28.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
|
|
13126
14034
|
} catch (err) {
|
|
13127
|
-
|
|
14035
|
+
log28.error(`${label} cleanup error: ${err}`);
|
|
13128
14036
|
}
|
|
13129
14037
|
}
|
|
13130
14038
|
function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
|
|
13131
|
-
const
|
|
13132
|
-
removeExpiredRequests(config, dbOps,
|
|
14039
|
+
const log28 = new Logger("RetentionMaintenance");
|
|
14040
|
+
removeExpiredRequests(config, dbOps, log28, "Startup");
|
|
13133
14041
|
try {
|
|
13134
14042
|
const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
|
|
13135
|
-
|
|
14043
|
+
log28.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
|
|
13136
14044
|
} catch (err) {
|
|
13137
|
-
|
|
14045
|
+
log28.error(`Database compaction error: ${err}`);
|
|
13138
14046
|
}
|
|
13139
14047
|
const timer = setInterval(() => {
|
|
13140
|
-
removeExpiredRequests(config, dbOps,
|
|
14048
|
+
removeExpiredRequests(config, dbOps, log28, "Periodic");
|
|
13141
14049
|
try {
|
|
13142
14050
|
dbOps.checkpointWal();
|
|
13143
14051
|
} catch (err) {
|
|
13144
|
-
|
|
14052
|
+
log28.error(`WAL checkpoint error: ${err}`);
|
|
13145
14053
|
}
|
|
13146
14054
|
}, intervalMs);
|
|
13147
14055
|
timer.unref?.();
|
|
@@ -13299,7 +14207,7 @@ function startServer(options) {
|
|
|
13299
14207
|
const {
|
|
13300
14208
|
config,
|
|
13301
14209
|
dbOps,
|
|
13302
|
-
log:
|
|
14210
|
+
log: log28,
|
|
13303
14211
|
apiRouter,
|
|
13304
14212
|
exposureConfig,
|
|
13305
14213
|
proxyContext,
|
|
@@ -13344,7 +14252,7 @@ function startServer(options) {
|
|
|
13344
14252
|
strategy: config.getStrategy(),
|
|
13345
14253
|
providers: providerRegistry.listProviders()
|
|
13346
14254
|
}));
|
|
13347
|
-
logInitialAccountStatus(
|
|
14255
|
+
logInitialAccountStatus(log28, dbOps);
|
|
13348
14256
|
return {
|
|
13349
14257
|
port: activePort,
|
|
13350
14258
|
stop: () => stopServerRuntime(),
|
|
@@ -13367,12 +14275,12 @@ async function handleGracefulShutdown(signal) {
|
|
|
13367
14275
|
}
|
|
13368
14276
|
}
|
|
13369
14277
|
var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null, deploymentDrain, checkShutdownDrain;
|
|
13370
|
-
var
|
|
14278
|
+
var init_src13 = __esm(() => {
|
|
13371
14279
|
init_src9();
|
|
13372
14280
|
init_src2();
|
|
13373
14281
|
init_src8();
|
|
13374
14282
|
init_src4();
|
|
13375
|
-
|
|
14283
|
+
init_src12();
|
|
13376
14284
|
init_bootstrap_runtime();
|
|
13377
14285
|
init_dashboard_assets();
|
|
13378
14286
|
init_deployment_drain();
|
|
@@ -13396,7 +14304,7 @@ process.env.AGENT_SMITH_DASHBOARD_DIST_DIR ??= join(import.meta.dir, "dashboard"
|
|
|
13396
14304
|
process.env.AGENT_SMITH_USAGE_WORKER_PATH ??= join(import.meta.dir, "post-processor.worker.js");
|
|
13397
14305
|
|
|
13398
14306
|
// src/server.ts
|
|
13399
|
-
|
|
14307
|
+
init_src13();
|
|
13400
14308
|
export {
|
|
13401
14309
|
startServer as default
|
|
13402
14310
|
};
|