@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/dist/bin.js CHANGED
@@ -1627,7 +1627,7 @@ function sanitizeProviderPools(value) {
1627
1627
  return pools;
1628
1628
  }
1629
1629
  function wireForStrategy(strategy3) {
1630
- return strategy3 === "anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1630
+ return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1631
1631
  }
1632
1632
  function isNonNegativeFiniteNumber(value) {
1633
1633
  return isFiniteNumber(value) && value >= 0;
@@ -1660,6 +1660,18 @@ function sanitizeTeamRouting(value) {
1660
1660
  result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1661
1661
  }
1662
1662
  }
1663
+ if (isRecord(value.caller_weekly_max_usage)) {
1664
+ const entries = Object.entries(value.caller_weekly_max_usage);
1665
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
1666
+ result.caller_weekly_max_usage = Object.fromEntries(entries);
1667
+ }
1668
+ }
1669
+ if (isRecord(value.caller_provider_fallback)) {
1670
+ const entries = Object.entries(value.caller_provider_fallback);
1671
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
1672
+ result.caller_provider_fallback = Object.fromEntries(entries);
1673
+ }
1674
+ }
1663
1675
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1664
1676
  result.admission_cap = Math.floor(value.admission_cap);
1665
1677
  }
@@ -1701,7 +1713,7 @@ function clientRouting(client) {
1701
1713
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1702
1714
  };
1703
1715
  }
1704
- var log2, 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;
1716
+ var log2, 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;
1705
1717
  var init_src4 = __esm(() => {
1706
1718
  init_src2();
1707
1719
  init_src3();
@@ -1714,6 +1726,7 @@ var init_src4 = __esm(() => {
1714
1726
  log2 = new Logger("Config");
1715
1727
  PROVIDER_STRATEGIES = [
1716
1728
  "anthropic-api",
1729
+ "model-studio-anthropic-api",
1717
1730
  "openai-api",
1718
1731
  "claude-code",
1719
1732
  "codex"
@@ -1727,6 +1740,7 @@ var init_src4 = __esm(() => {
1727
1740
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1728
1741
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1729
1742
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1743
+ CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1730
1744
  TEAM_ROUTING_DEFAULTS = {
1731
1745
  enabled: false,
1732
1746
  distributionEnabled: true,
@@ -1735,6 +1749,8 @@ var init_src4 = __esm(() => {
1735
1749
  maxUsage: 0.9,
1736
1750
  weeklyMaxUsage: 0.95,
1737
1751
  weeklyMaxUsageByEmail: {},
1752
+ callerWeeklyMaxUsage: {},
1753
+ callerProviderFallback: {},
1738
1754
  admissionCap: 5,
1739
1755
  admissionQueueLimit: 25,
1740
1756
  admissionWaitMs: 30000,
@@ -1897,6 +1913,8 @@ var init_src4 = __esm(() => {
1897
1913
  maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1898
1914
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1899
1915
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1916
+ callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1917
+ callerProviderFallback: { ...file?.caller_provider_fallback },
1900
1918
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1901
1919
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1902
1920
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -1966,6 +1984,8 @@ var init_src4 = __esm(() => {
1966
1984
  "max_usage",
1967
1985
  "weekly_max_usage",
1968
1986
  "weekly_max_usage_by_email",
1987
+ "caller_weekly_max_usage",
1988
+ "caller_provider_fallback",
1969
1989
  "admission_cap",
1970
1990
  "admission_queue_limit",
1971
1991
  "admission_wait_ms",
@@ -1991,6 +2011,16 @@ var init_src4 = __esm(() => {
1991
2011
  ...oldValue.weekly_max_usage_by_email
1992
2012
  };
1993
2013
  }
2014
+ if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2015
+ sanitized.caller_weekly_max_usage = {
2016
+ ...oldValue.caller_weekly_max_usage
2017
+ };
2018
+ }
2019
+ if (!("caller_provider_fallback" in value) && oldValue?.caller_provider_fallback) {
2020
+ sanitized.caller_provider_fallback = {
2021
+ ...oldValue.caller_provider_fallback
2022
+ };
2023
+ }
1994
2024
  this.persistStrictly("team_routing", sanitized);
1995
2025
  }
1996
2026
  allowAccountUuid(accountUuid) {
@@ -2869,6 +2899,30 @@ function ensureConversationPinsTable(db) {
2869
2899
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_account ON conversation_pins(account_id)`);
2870
2900
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_last_seen ON conversation_pins(last_seen_at)`);
2871
2901
  }
2902
+ function ensureConversationProviderPreferencesTable(db) {
2903
+ db.run(`
2904
+ CREATE TABLE IF NOT EXISTS conversation_provider_preferences (
2905
+ pin_key TEXT PRIMARY KEY,
2906
+ provider TEXT NOT NULL,
2907
+ promotion_declined INTEGER NOT NULL DEFAULT 0,
2908
+ last_seen_at INTEGER NOT NULL
2909
+ )
2910
+ `);
2911
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_preferences_last_seen ON conversation_provider_preferences(last_seen_at)`);
2912
+ }
2913
+ function ensureConversationProviderBlocksTable(db) {
2914
+ db.run(`
2915
+ CREATE TABLE IF NOT EXISTS conversation_provider_blocks (
2916
+ pin_key TEXT NOT NULL,
2917
+ provider TEXT NOT NULL,
2918
+ category TEXT NOT NULL DEFAULT 'unknown',
2919
+ retry_at INTEGER,
2920
+ last_seen_at INTEGER NOT NULL,
2921
+ PRIMARY KEY (pin_key, provider)
2922
+ )
2923
+ `);
2924
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_blocks_last_seen ON conversation_provider_blocks(last_seen_at)`);
2925
+ }
2872
2926
  function remediateDuplicateAccountNames(db) {
2873
2927
  const accounts = db.query(`
2874
2928
  SELECT id, name, created_at
@@ -2994,6 +3048,8 @@ function ensureSchema(db) {
2994
3048
  `);
2995
3049
  ensureAuthSessionsTable(db);
2996
3050
  ensureConversationPinsTable(db);
3051
+ ensureConversationProviderPreferencesTable(db);
3052
+ ensureConversationProviderBlocksTable(db);
2997
3053
  }
2998
3054
  function runMigrations(db) {
2999
3055
  ensureSchema(db);
@@ -3013,6 +3069,8 @@ function runMigrations(db) {
3013
3069
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
3014
3070
  ensureAuthSessionsTable(db);
3015
3071
  ensureConversationPinsTable(db);
3072
+ ensureConversationProviderPreferencesTable(db);
3073
+ ensureConversationProviderBlocksTable(db);
3016
3074
  ensureAccountsNameUniqueness(db);
3017
3075
  db.run(`CREATE TABLE IF NOT EXISTS enrollment_contacts (
3018
3076
  account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
@@ -3708,6 +3766,85 @@ var init_conversation_pin_repository = __esm(() => {
3708
3766
  };
3709
3767
  });
3710
3768
 
3769
+ // ../../packages/database/src/repositories/conversation-provider-block.repository.ts
3770
+ var ConversationProviderBlockRepository;
3771
+ var init_conversation_provider_block_repository = __esm(() => {
3772
+ ConversationProviderBlockRepository = class ConversationProviderBlockRepository extends BaseRepository {
3773
+ find(pinKey, provider) {
3774
+ const row = this.get(`SELECT category, retry_at, last_seen_at FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
3775
+ return row ? {
3776
+ category: row.category,
3777
+ lastSeenAt: row.last_seen_at,
3778
+ retryAt: row.retry_at ?? undefined
3779
+ } : null;
3780
+ }
3781
+ upsert(pinKey, provider, category, retryAt, lastSeenAt) {
3782
+ this.run(`
3783
+ INSERT INTO conversation_provider_blocks (
3784
+ pin_key, provider, category, retry_at, last_seen_at
3785
+ )
3786
+ VALUES (?, ?, ?, ?, ?)
3787
+ ON CONFLICT(pin_key, provider) DO UPDATE SET
3788
+ category = excluded.category,
3789
+ retry_at = excluded.retry_at,
3790
+ last_seen_at = excluded.last_seen_at
3791
+ `, [pinKey, provider, category, retryAt ?? null, lastSeenAt]);
3792
+ }
3793
+ delete(pinKey, provider) {
3794
+ this.run(`DELETE FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
3795
+ }
3796
+ deleteExpired(before) {
3797
+ this.run(`DELETE FROM conversation_provider_blocks WHERE last_seen_at < ?`, [before]);
3798
+ }
3799
+ deleteForAccount(accountId) {
3800
+ this.run(`
3801
+ DELETE FROM conversation_provider_blocks
3802
+ WHERE pin_key IN (
3803
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
3804
+ )
3805
+ `, [accountId]);
3806
+ }
3807
+ };
3808
+ });
3809
+
3810
+ // ../../packages/database/src/repositories/conversation-provider-preference.repository.ts
3811
+ var ConversationProviderPreferenceRepository;
3812
+ var init_conversation_provider_preference_repository = __esm(() => {
3813
+ ConversationProviderPreferenceRepository = class ConversationProviderPreferenceRepository extends BaseRepository {
3814
+ find(pinKey) {
3815
+ const row = this.get(`SELECT provider, promotion_declined, last_seen_at FROM conversation_provider_preferences WHERE pin_key = ?`, [pinKey]);
3816
+ return row ? {
3817
+ provider: row.provider,
3818
+ promotionDeclined: row.promotion_declined === 1,
3819
+ lastSeenAt: row.last_seen_at
3820
+ } : null;
3821
+ }
3822
+ upsert(pinKey, provider, promotionDeclined, lastSeenAt) {
3823
+ this.run(`
3824
+ INSERT INTO conversation_provider_preferences (
3825
+ pin_key, provider, promotion_declined, last_seen_at
3826
+ )
3827
+ VALUES (?, ?, ?, ?)
3828
+ ON CONFLICT(pin_key) DO UPDATE SET
3829
+ provider = excluded.provider,
3830
+ promotion_declined = excluded.promotion_declined,
3831
+ last_seen_at = excluded.last_seen_at
3832
+ `, [pinKey, provider, promotionDeclined ? 1 : 0, lastSeenAt]);
3833
+ }
3834
+ deleteExpired(before) {
3835
+ this.run(`DELETE FROM conversation_provider_preferences WHERE last_seen_at < ?`, [before]);
3836
+ }
3837
+ deleteForAccount(accountId) {
3838
+ this.run(`
3839
+ DELETE FROM conversation_provider_preferences
3840
+ WHERE pin_key IN (
3841
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
3842
+ )
3843
+ `, [accountId]);
3844
+ }
3845
+ };
3846
+ });
3847
+
3711
3848
  // ../../packages/database/src/models/request-row.ts
3712
3849
  function toRequest(row) {
3713
3850
  return {
@@ -4318,6 +4455,8 @@ class DatabaseOperations {
4318
4455
  requests;
4319
4456
  authSessions;
4320
4457
  conversationPins;
4458
+ conversationProviderBlocks;
4459
+ conversationProviderPreferences;
4321
4460
  strategy;
4322
4461
  stats;
4323
4462
  constructor(dbPath) {
@@ -4337,6 +4476,8 @@ class DatabaseOperations {
4337
4476
  this.requests = new RequestRepository(this.db);
4338
4477
  this.authSessions = new AuthSessionRepository(this.db);
4339
4478
  this.conversationPins = new ConversationPinRepository(this.db);
4479
+ this.conversationProviderBlocks = new ConversationProviderBlockRepository(this.db);
4480
+ this.conversationProviderPreferences = new ConversationProviderPreferenceRepository(this.db);
4340
4481
  this.strategy = new StrategyRepository(this.db);
4341
4482
  this.stats = new StatsRepository(this.db);
4342
4483
  }
@@ -4380,6 +4521,8 @@ class DatabaseOperations {
4380
4521
  return this.accounts.update(accountId, data);
4381
4522
  }
4382
4523
  deleteAccount(accountId) {
4524
+ this.conversationProviderBlocks.deleteForAccount(accountId);
4525
+ this.conversationProviderPreferences.deleteForAccount(accountId);
4383
4526
  this.conversationPins.deleteForAccount(accountId);
4384
4527
  return this.accounts.delete(accountId);
4385
4528
  }
@@ -4394,6 +4537,23 @@ class DatabaseOperations {
4394
4537
  }
4395
4538
  deleteExpiredConversationPins(before) {
4396
4539
  this.conversationPins.deleteExpired(before);
4540
+ this.conversationProviderBlocks.deleteExpired(before);
4541
+ this.conversationProviderPreferences.deleteExpired(before);
4542
+ }
4543
+ getConversationProviderPreference(pinKey) {
4544
+ return this.conversationProviderPreferences.find(pinKey);
4545
+ }
4546
+ upsertConversationProviderPreference(pinKey, provider, promotionDeclined, lastSeenAt) {
4547
+ this.conversationProviderPreferences.upsert(pinKey, provider, promotionDeclined, lastSeenAt);
4548
+ }
4549
+ getConversationProviderBlock(pinKey, provider) {
4550
+ return this.conversationProviderBlocks.find(pinKey, provider);
4551
+ }
4552
+ upsertConversationProviderBlock(pinKey, provider, category, retryAt, lastSeenAt) {
4553
+ this.conversationProviderBlocks.upsert(pinKey, provider, category, retryAt, lastSeenAt);
4554
+ }
4555
+ deleteConversationProviderBlock(pinKey, provider) {
4556
+ this.conversationProviderBlocks.delete(pinKey, provider);
4397
4557
  }
4398
4558
  countAccounts() {
4399
4559
  return this.accounts.count();
@@ -4579,6 +4739,8 @@ var init_database_operations = __esm(() => {
4579
4739
  init_analytics_repository();
4580
4740
  init_auth_session_repository();
4581
4741
  init_conversation_pin_repository();
4742
+ init_conversation_provider_block_repository();
4743
+ init_conversation_provider_preference_repository();
4582
4744
  init_request_repository();
4583
4745
  init_stats_repository();
4584
4746
  init_strategy_repository();
@@ -6182,6 +6344,112 @@ var init_provider4 = __esm(() => {
6182
6344
  };
6183
6345
  });
6184
6346
 
6347
+ // ../../packages/providers/src/connectors/model-studio-capacity.ts
6348
+ function retryAtFromHeader(response, now = Date.now()) {
6349
+ const retryAfter = response.headers.get("retry-after");
6350
+ if (!retryAfter)
6351
+ return;
6352
+ const seconds = Number(retryAfter);
6353
+ if (Number.isFinite(seconds))
6354
+ return now + Math.max(0, seconds) * 1000;
6355
+ const date2 = Date.parse(retryAfter);
6356
+ return Number.isNaN(date2) ? undefined : Math.max(now, date2);
6357
+ }
6358
+ async function readSmallJsonBody(response) {
6359
+ const contentLength = Number(response.headers.get("content-length"));
6360
+ if (Number.isFinite(contentLength) && contentLength > MAX_BLOCK_BODY_BYTES) {
6361
+ return null;
6362
+ }
6363
+ const contentType = response.headers.get("content-type") ?? "";
6364
+ if (!contentType.toLowerCase().includes("application/json"))
6365
+ return null;
6366
+ const reader = response.clone().body?.getReader();
6367
+ if (!reader)
6368
+ return null;
6369
+ const chunks = [];
6370
+ let length = 0;
6371
+ try {
6372
+ while (true) {
6373
+ const { done, value } = await reader.read();
6374
+ if (done)
6375
+ break;
6376
+ length += value.byteLength;
6377
+ if (length > MAX_BLOCK_BODY_BYTES) {
6378
+ await reader.cancel();
6379
+ return null;
6380
+ }
6381
+ chunks.push(value);
6382
+ }
6383
+ } catch {
6384
+ return null;
6385
+ }
6386
+ const bytes = new Uint8Array(length);
6387
+ let offset = 0;
6388
+ for (const chunk of chunks) {
6389
+ bytes.set(chunk, offset);
6390
+ offset += chunk.byteLength;
6391
+ }
6392
+ try {
6393
+ return JSON.parse(new TextDecoder().decode(bytes));
6394
+ } catch {
6395
+ return null;
6396
+ }
6397
+ }
6398
+ function errorCode(payload) {
6399
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
6400
+ return;
6401
+ }
6402
+ const record2 = payload;
6403
+ if (typeof record2.code === "string")
6404
+ return record2.code;
6405
+ const error = record2.error;
6406
+ if (typeof error !== "object" || error === null || Array.isArray(error)) {
6407
+ return;
6408
+ }
6409
+ return typeof error.code === "string" ? error.code : undefined;
6410
+ }
6411
+ async function classifyModelStudioCapacityBlock(response, now = Date.now()) {
6412
+ if (response.status !== 429 && response.status !== 503)
6413
+ return null;
6414
+ const code = errorCode(await readSmallJsonBody(response));
6415
+ const category = code ? MODEL_STUDIO_BLOCK_CATEGORIES[code] : undefined;
6416
+ if (!category) {
6417
+ return response.status === 429 ? { category: "unknown" } : null;
6418
+ }
6419
+ const retryAt = retryAtFromHeader(response, now);
6420
+ return retryAt === undefined ? { category } : { category, retryAt };
6421
+ }
6422
+ var MAX_BLOCK_BODY_BYTES, MODEL_STUDIO_BLOCK_CATEGORIES;
6423
+ var init_model_studio_capacity = __esm(() => {
6424
+ MAX_BLOCK_BODY_BYTES = 64 * 1024;
6425
+ MODEL_STUDIO_BLOCK_CATEGORIES = {
6426
+ "Throttling.RateQuota": "request-rate",
6427
+ "Throttling.AllocationQuota": "token-allocation",
6428
+ "Throttling.BurstRate": "burst",
6429
+ "Throttling.ResourceExhausted": "dynamic-throughput",
6430
+ "Throttling.ServiceOverloaded": "dynamic-throughput",
6431
+ ServiceUnavailable: "temporary-capacity"
6432
+ };
6433
+ });
6434
+
6435
+ // ../../packages/providers/src/providers/model-studio/provider.ts
6436
+ var ModelStudioAnthropicProvider;
6437
+ var init_provider5 = __esm(() => {
6438
+ init_model_studio_capacity();
6439
+ init_provider();
6440
+ ModelStudioAnthropicProvider = class ModelStudioAnthropicProvider extends AnthropicProvider {
6441
+ async getCapacityBlock(response) {
6442
+ return await classifyModelStudioCapacityBlock(response);
6443
+ }
6444
+ parseRateLimit(response) {
6445
+ if (response.status !== 429)
6446
+ return super.parseRateLimit(response);
6447
+ const resetTime = retryAtFromHeader(response);
6448
+ return resetTime === undefined ? { isRateLimited: true } : { isRateLimited: true, resetTime };
6449
+ }
6450
+ };
6451
+ });
6452
+
6185
6453
  // ../../packages/providers/src/registry.ts
6186
6454
  function supportsOAuth(provider) {
6187
6455
  return "supportsOAuth" in provider && typeof provider.supportsOAuth === "function" && "getOAuthProvider" in provider && typeof provider.getOAuthProvider === "function";
@@ -6299,6 +6567,8 @@ function createProvider(definition) {
6299
6567
  switch (definition.strategy) {
6300
6568
  case "anthropic-api":
6301
6569
  return new AnthropicProvider;
6570
+ case "model-studio-anthropic-api":
6571
+ return new ModelStudioAnthropicProvider;
6302
6572
  case "openai-api":
6303
6573
  return new OpenAIProvider;
6304
6574
  case "claude-code":
@@ -6326,6 +6596,7 @@ var init_configured_registry = __esm(() => {
6326
6596
  init_provider();
6327
6597
  init_provider2();
6328
6598
  init_provider4();
6599
+ init_provider5();
6329
6600
  init_provider3();
6330
6601
  init_registry();
6331
6602
  });
@@ -6373,6 +6644,11 @@ var init_codex = __esm(() => {
6373
6644
  init_provider4();
6374
6645
  });
6375
6646
 
6647
+ // ../../packages/providers/src/providers/model-studio/index.ts
6648
+ var init_model_studio = __esm(() => {
6649
+ init_provider5();
6650
+ });
6651
+
6376
6652
  // ../../packages/providers/src/providers/openai/index.ts
6377
6653
  var init_openai = __esm(() => {
6378
6654
  init_oauth2();
@@ -6384,6 +6660,7 @@ var init_providers = __esm(() => {
6384
6660
  init_anthropic();
6385
6661
  init_claude_code();
6386
6662
  init_codex();
6663
+ init_model_studio();
6387
6664
  init_openai();
6388
6665
  });
6389
6666
  // ../../packages/providers/src/index.ts
@@ -7422,6 +7699,15 @@ var init_analytics = __esm(() => {
7422
7699
  });
7423
7700
 
7424
7701
  // ../../packages/api/src/handlers/config.ts
7702
+ function publicTeamRouting(config) {
7703
+ const {
7704
+ callerProviderFallback: _callerProviderFallback,
7705
+ callerWeeklyMaxUsage: _callerWeeklyMaxUsage,
7706
+ weeklyMaxUsageByEmail: _weeklyMaxUsageByEmail,
7707
+ ...routing
7708
+ } = config.getTeamRouting();
7709
+ return routing;
7710
+ }
7425
7711
  function createConfigHandlers(config) {
7426
7712
  return {
7427
7713
  getConfig: () => {
@@ -7462,10 +7748,7 @@ function createConfigHandlers(config) {
7462
7748
  getStrategies: () => {
7463
7749
  return jsonResponse(LB_STRATEGIES);
7464
7750
  },
7465
- getTeamRouting: () => {
7466
- const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
7467
- return jsonResponse(routing);
7468
- },
7751
+ getTeamRouting: () => jsonResponse(publicTeamRouting(config)),
7469
7752
  setTeamRouting: async (req) => {
7470
7753
  try {
7471
7754
  const body = await parseJsonObject(req);
@@ -7473,7 +7756,7 @@ function createConfigHandlers(config) {
7473
7756
  return jsonResponse({
7474
7757
  success: true,
7475
7758
  message: "Team routing settings updated",
7476
- data: config.getTeamRouting()
7759
+ data: publicTeamRouting(config)
7477
7760
  });
7478
7761
  } catch (error) {
7479
7762
  if (error instanceof ValidationError || error instanceof Error) {
@@ -9045,6 +9328,11 @@ function pinKey(request3, provider) {
9045
9328
  digest
9046
9329
  ].join("\x00")).digest("hex");
9047
9330
  }
9331
+ function providerConversationKey(request3) {
9332
+ if (!request3.sessionId)
9333
+ return null;
9334
+ return createHash2("sha256").update([request3.pinScope ?? request3.provider, request3.sessionId].join("\x00")).digest("hex");
9335
+ }
9048
9336
  function isAllowlisted(account2, config) {
9049
9337
  return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
9050
9338
  }
@@ -9091,9 +9379,20 @@ class TeamRouter {
9091
9379
  return;
9092
9380
  }
9093
9381
  this.removeExpiredPins(now, store);
9094
- const key = pinKey(request3, provider);
9382
+ const key = this.getConversationPinKey(request3, config, provider);
9095
9383
  return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
9096
9384
  }
9385
+ getConversationPinKey(request3, _config, provider) {
9386
+ if (!request3?.sessionId || request3.manualAccountName) {
9387
+ return;
9388
+ }
9389
+ return pinKey(request3, provider) ?? undefined;
9390
+ }
9391
+ getConversationProviderKey(request3, _config) {
9392
+ if (!request3?.sessionId || request3.manualAccountName)
9393
+ return;
9394
+ return providerConversationKey(request3) ?? undefined;
9395
+ }
9097
9396
  begin(accountId) {
9098
9397
  this.inFlight.set(accountId, (this.inFlight.get(accountId) ?? 0) + 1);
9099
9398
  }
@@ -9287,22 +9586,23 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
9287
9586
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
9288
9587
  return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
9289
9588
  }
9290
- function pooledMaxUsage(provider, account2, bucket, ctx) {
9589
+ function pooledMaxUsage(provider, account2, bucket, ctx, callerId) {
9291
9590
  const teamRouting = ctx.runtime.teamRouting;
9292
9591
  if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
9293
9592
  return;
9294
9593
  if (!provider.isWeeklyBucket(bucket))
9295
9594
  return teamRouting.maxUsage;
9296
9595
  const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
9297
- const override = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9298
- return Math.min(teamRouting.weeklyMaxUsage, override ?? teamRouting.weeklyMaxUsage);
9596
+ const accountOverride = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9597
+ const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
9598
+ return Math.min(teamRouting.weeklyMaxUsage, accountOverride ?? Number.POSITIVE_INFINITY, callerOverride ?? Number.POSITIVE_INFINITY);
9299
9599
  }
9300
- function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
9600
+ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
9301
9601
  const quota2 = account2.quota_state;
9302
9602
  if (!quota2)
9303
9603
  return true;
9304
9604
  for (const [name, window2] of Object.entries(quota2.windows)) {
9305
- if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx))) {
9605
+ if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, callerId))) {
9306
9606
  return false;
9307
9607
  }
9308
9608
  }
@@ -9323,23 +9623,42 @@ function cooldownEnd(account2, now) {
9323
9623
  function isServableSeat(provider, account2, model, ctx, now) {
9324
9624
  return isFleetSeat(account2, ctx) && cooldownEnd(account2, now) === null && isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9325
9625
  }
9326
- function blockingResets(provider, account2, model, ctx, now) {
9327
- 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);
9626
+ function blockingResets(provider, account2, model, ctx, now, callerId) {
9627
+ 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);
9328
9628
  }
9329
- function servableAt(provider, account2, model, ctx, now) {
9629
+ function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
9630
+ 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)));
9631
+ if (blocking.length === 0)
9632
+ return null;
9633
+ const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
9634
+ const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
9635
+ const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
9636
+ return rightReset - leftReset;
9637
+ })[0];
9638
+ const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
9639
+ return window2.resetAt === null ? { category } : { category, retryAt: window2.resetAt };
9640
+ }
9641
+ function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
9642
+ const now = Date.now();
9643
+ const blocks = seatsFor(fleetAccounts(ctx.providerName, ctx)).map((account2) => quotaBlockForAccount(ctx.provider, account2, meta.model, ctx, now, callerId)).filter((block) => block !== null);
9644
+ if (blocks.length === 0)
9645
+ return null;
9646
+ return [...blocks].sort((left, right) => (left.retryAt ?? Number.POSITIVE_INFINITY) - (right.retryAt ?? Number.POSITIVE_INFINITY))[0];
9647
+ }
9648
+ function servableAt(provider, account2, model, ctx, now, callerId) {
9330
9649
  const cooldown = cooldownEnd(account2, now);
9331
- if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
9650
+ if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId)) {
9332
9651
  return cooldown;
9333
9652
  }
9334
- const resets = blockingResets(provider, account2, model, ctx, now);
9653
+ const resets = blockingResets(provider, account2, model, ctx, now, callerId);
9335
9654
  return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
9336
9655
  }
9337
- function soonestServableAt(provider, fleet, seats, model, ctx, now) {
9338
- if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
9656
+ function soonestServableAt(provider, fleet, seats, model, ctx, now, callerId) {
9657
+ if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now, callerId).length > 0)) {
9339
9658
  return null;
9340
9659
  }
9341
9660
  const times = seats.flatMap((account2) => {
9342
- const at = servableAt(provider, account2, model, ctx, now);
9661
+ const at = servableAt(provider, account2, model, ctx, now, callerId);
9343
9662
  return at === null ? [] : [at];
9344
9663
  });
9345
9664
  return times.length > 0 ? Math.min(...times) : null;
@@ -9362,21 +9681,22 @@ function getPoolStatus(provider, model, ctx) {
9362
9681
  admissionWaitMs: config?.admissionWaitMs ?? 0
9363
9682
  };
9364
9683
  }
9365
- function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
9684
+ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
9366
9685
  const fleet = fleetAccounts(ctx.providerName, ctx);
9367
- return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
9686
+ return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now(), callerId);
9368
9687
  }
9369
- function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
9370
- return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
9688
+ function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now(), callerId) {
9689
+ return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9371
9690
  }
9372
- function selectRevalidationProbe(accounts, ctx, now, model) {
9691
+ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
9373
9692
  const probes = ctx.quotaProbeAt;
9374
9693
  const lastProbeAt = probes?.get(ctx.providerName);
9375
9694
  if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
9376
9695
  return [];
9377
9696
  }
9378
9697
  const [probe] = accounts.filter((account2) => {
9379
- return ctx.runtime.teamRouting?.enabled !== true || !isAllowlisted(account2, ctx.runtime.teamRouting) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9698
+ const routing = ctx.runtime.teamRouting;
9699
+ return routing?.enabled !== true || !isAllowlisted(account2, routing) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId);
9380
9700
  }).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
9381
9701
  if (!probe)
9382
9702
  return [];
@@ -9385,9 +9705,10 @@ function selectRevalidationProbe(accounts, ctx, now, model) {
9385
9705
  }
9386
9706
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
9387
9707
  const now = Date.now();
9708
+ const callerId = teamRequest?.callerId;
9388
9709
  const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
9389
- const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
9390
- const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model);
9710
+ const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9711
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
9391
9712
  const prioritized = [...candidates].sort((left, right) => {
9392
9713
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
9393
9714
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9701,6 +10022,8 @@ class TeamAdmission {
9701
10022
  maxUsage: 0.9,
9702
10023
  weeklyMaxUsage: 0.95,
9703
10024
  weeklyMaxUsageByEmail: {},
10025
+ callerWeeklyMaxUsage: {},
10026
+ callerProviderFallback: {},
9704
10027
  admissionCap: 1,
9705
10028
  admissionQueueLimit: 0,
9706
10029
  admissionWaitMs: 0,
@@ -9808,6 +10131,206 @@ var init_team_admission = __esm(() => {
9808
10131
  };
9809
10132
  });
9810
10133
 
10134
+ // ../../packages/routing/src/conversation-provider-routing.ts
10135
+ class ConversationProviderRouting {
10136
+ store;
10137
+ constructor(store) {
10138
+ this.store = store;
10139
+ }
10140
+ getPreference(conversationKey) {
10141
+ return this.store.getPreference(conversationKey);
10142
+ }
10143
+ getBlock(conversationKey, provider) {
10144
+ return this.store.getBlock(conversationKey, provider);
10145
+ }
10146
+ selectProvider(conversationKey, provider, now) {
10147
+ this.store.upsertPreference(conversationKey, {
10148
+ lastSeenAt: now,
10149
+ promotionDeclined: false,
10150
+ provider
10151
+ });
10152
+ }
10153
+ declinePromotion(conversationKey, now) {
10154
+ const preference = this.store.getPreference(conversationKey);
10155
+ if (!preference)
10156
+ return;
10157
+ this.store.upsertPreference(conversationKey, {
10158
+ ...preference,
10159
+ lastSeenAt: now,
10160
+ promotionDeclined: true
10161
+ });
10162
+ }
10163
+ recordBlock(conversationKey, provider, block, now) {
10164
+ this.store.upsertBlock(conversationKey, provider, {
10165
+ ...block,
10166
+ lastSeenAt: now
10167
+ });
10168
+ }
10169
+ clearBlock(conversationKey, provider) {
10170
+ this.store.deleteBlock(conversationKey, provider);
10171
+ }
10172
+ canOfferProvider(conversationKey, provider, now) {
10173
+ const block = this.store.getBlock(conversationKey, provider);
10174
+ return block === null || block.retryAt !== undefined && block.retryAt <= now;
10175
+ }
10176
+ }
10177
+
10178
+ // ../../packages/routing/src/provider-choice.ts
10179
+ function encodeCapacityDetails(problem) {
10180
+ return Buffer.from(JSON.stringify({
10181
+ kind: problem.kind,
10182
+ blockedProvider: problem.blockedProvider,
10183
+ category: problem.category,
10184
+ choices: problem.choices,
10185
+ wait: problem.retryAt === undefined ? null : { retryAt: problem.retryAt }
10186
+ })).toString("base64url");
10187
+ }
10188
+ function interactiveProviderChoiceRequested(headers3) {
10189
+ return headers3.get(INTERACTIVE_PROVIDER_CHOICE_HEADER) === "v1";
10190
+ }
10191
+ function manualProviderChoiceRequested(headers3) {
10192
+ return headers3.get(PROVIDER_CHOICE_MENU_HEADER) === "v1";
10193
+ }
10194
+ function providerWaitRequested(headers3) {
10195
+ return headers3.get(PROVIDER_WAIT_HEADER) === "v1";
10196
+ }
10197
+ function capacityChoices(candidates, blockedProvider, eligibleProviders) {
10198
+ return candidates.filter((candidate) => candidate.provider !== blockedProvider && eligibleProviders.has(candidate.provider));
10199
+ }
10200
+ function readProviderChoice(headers3, choices) {
10201
+ const selected = headers3.get(PROVIDER_CHOICE_HEADER);
10202
+ return selected && choices.some((choice) => choice.provider === selected) ? selected : null;
10203
+ }
10204
+ function providerPromotionDeclined(headers3) {
10205
+ return headers3.get(PROVIDER_PROMOTION_DECLINED_HEADER) === "v1";
10206
+ }
10207
+ function stripProviderChoiceHeaders(headers3) {
10208
+ const forwarded = new Headers(headers3);
10209
+ forwarded.delete(INTERACTIVE_PROVIDER_CHOICE_HEADER);
10210
+ forwarded.delete(PROVIDER_CHOICE_HEADER);
10211
+ forwarded.delete(PROVIDER_CHOICE_MENU_HEADER);
10212
+ forwarded.delete(PROVIDER_WAIT_HEADER);
10213
+ forwarded.delete(PROVIDER_PROMOTION_DECLINED_HEADER);
10214
+ return forwarded;
10215
+ }
10216
+ function withServedProviderHeaders(response, choice) {
10217
+ const headers3 = new Headers(response.headers);
10218
+ headers3.set(SERVED_PROVIDER_HEADER, choice.provider);
10219
+ headers3.set(SERVED_MODEL_HEADER, choice.model);
10220
+ return new Response(response.body, {
10221
+ status: response.status,
10222
+ statusText: response.statusText,
10223
+ headers: headers3
10224
+ });
10225
+ }
10226
+ function withProviderPromotionDetails(response, choices) {
10227
+ if (choices.length === 0)
10228
+ return response;
10229
+ const headers3 = new Headers(response.headers);
10230
+ headers3.set(PROVIDER_PROMOTION_DETAILS_HEADER, Buffer.from(JSON.stringify({ choices })).toString("base64url"));
10231
+ return new Response(response.body, {
10232
+ status: response.status,
10233
+ statusText: response.statusText,
10234
+ headers: headers3
10235
+ });
10236
+ }
10237
+ function createProviderCapacityProblem({
10238
+ blockedProvider,
10239
+ category,
10240
+ choices,
10241
+ retryAt
10242
+ }) {
10243
+ const retryAfter = retryAt === undefined ? undefined : String(Math.max(1, Math.ceil((retryAt - Date.now()) / 1000)));
10244
+ return Response.json({
10245
+ type: "urn:agent-smith:provider-capacity:v1",
10246
+ title: "Current provider cannot serve this turn",
10247
+ status: 429,
10248
+ blockedProvider,
10249
+ category,
10250
+ choices,
10251
+ wait: retryAt === undefined ? null : { retryAt }
10252
+ }, {
10253
+ status: 429,
10254
+ headers: {
10255
+ "cache-control": "no-store",
10256
+ "content-type": "application/problem+json",
10257
+ "x-should-retry": "false",
10258
+ ...retryAfter ? { "retry-after": retryAfter } : {},
10259
+ [PROVIDER_CAPACITY_HEADER]: "v1",
10260
+ [PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
10261
+ kind: "capacity",
10262
+ blockedProvider,
10263
+ category,
10264
+ choices,
10265
+ retryAt
10266
+ })
10267
+ }
10268
+ });
10269
+ }
10270
+ function createProviderChoiceProblem({
10271
+ activeProvider,
10272
+ choices
10273
+ }) {
10274
+ return Response.json({
10275
+ type: "urn:agent-smith:provider-choice:v1",
10276
+ title: "Choose provider for this conversation",
10277
+ status: 409,
10278
+ activeProvider,
10279
+ choices,
10280
+ wait: null
10281
+ }, {
10282
+ status: 409,
10283
+ headers: {
10284
+ "cache-control": "no-store",
10285
+ "content-type": "application/problem+json",
10286
+ "x-should-retry": "false",
10287
+ [PROVIDER_CAPACITY_HEADER]: "v1",
10288
+ [PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
10289
+ kind: "manual",
10290
+ blockedProvider: activeProvider,
10291
+ category: "unknown",
10292
+ choices
10293
+ })
10294
+ }
10295
+ });
10296
+ }
10297
+ 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";
10298
+
10299
+ // ../../packages/routing/src/provider-selection.ts
10300
+ function preferProviders(providers2, providerName, pinnedProvider, preferredProvider) {
10301
+ const pinFirst = pinnedProvider ? [
10302
+ ...providers2.filter((provider) => providerName(provider) === pinnedProvider),
10303
+ ...providers2.filter((provider) => providerName(provider) !== pinnedProvider)
10304
+ ] : [...providers2];
10305
+ if (!preferredProvider)
10306
+ return pinFirst;
10307
+ return [
10308
+ ...pinFirst.filter((provider) => providerName(provider) === preferredProvider),
10309
+ ...pinFirst.filter((provider) => providerName(provider) !== preferredProvider)
10310
+ ];
10311
+ }
10312
+ function selectPoolProviders(providers2, providerName, selection) {
10313
+ if (selection.requestedProvider) {
10314
+ return providers2.filter((provider) => providerName(provider) === selection.requestedProvider);
10315
+ }
10316
+ const preferred = preferProviders(providers2, providerName, selection.pinnedProvider, selection.preferredProvider);
10317
+ if (selection.orderedFallback) {
10318
+ const currentProvider = selection.pinnedProvider ?? selection.preferredProvider;
10319
+ const currentIndex = currentProvider ? providers2.findIndex((provider) => providerName(provider) === currentProvider) : -1;
10320
+ return currentIndex < 0 ? [...providers2] : providers2.slice(currentIndex);
10321
+ }
10322
+ return preferred.slice(0, 1);
10323
+ }
10324
+ function higherRankedProviderChoices(choices, selectedProvider, eligibleProviders, canOffer) {
10325
+ const selectedIndex = choices.findIndex((choice) => choice.provider === selectedProvider);
10326
+ if (selectedIndex <= 0)
10327
+ return [];
10328
+ return choices.slice(0, selectedIndex).filter((choice) => eligibleProviders.has(choice.provider) && canOffer(choice.provider));
10329
+ }
10330
+
10331
+ // ../../packages/routing/src/index.ts
10332
+ var init_src10 = () => {};
10333
+
9811
10334
  // ../../packages/proxy/src/response-handler.ts
9812
10335
  function isExpectedResponse(path, response) {
9813
10336
  if (path.startsWith("/.well-known/") && response.status === 404) {
@@ -10411,7 +10934,7 @@ function createUpstreamSender(input) {
10411
10934
  const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
10412
10935
  return async (token) => {
10413
10936
  const requestAccount = token === input.account.access_token ? input.account : { ...input.account, access_token: token };
10414
- const headers3 = input.ctx.provider.prepareHeaders(input.req.headers, requestAccount);
10937
+ const headers3 = input.ctx.provider.prepareHeaders(stripProviderChoiceHeaders(input.req.headers), requestAccount);
10415
10938
  const upstreamRequestStartedAt = Date.now();
10416
10939
  const response = await makeProxyRequest(targetUrl, input.req.method, headers3, () => input.createBodyStream(input.requestBody), !!input.req.body, input.req.signal);
10417
10940
  return {
@@ -10478,6 +11001,28 @@ async function classifyUpstreamResponse(input, upstream) {
10478
11001
  }
10479
11002
  let response = state.response;
10480
11003
  const forward = createForwarder(input, upstream, state);
11004
+ const interactive = interactiveProviderChoiceRequested(input.req.headers);
11005
+ const capacityBlock = await input.ctx.provider.getCapacityBlock?.(response);
11006
+ if (capacityBlock) {
11007
+ const quotaRejected2 = await isQuotaRejection(response, input.ctx.provider);
11008
+ processProxyResponse(response, input.account, input.ctx, quotaRejected2);
11009
+ const perMinuteRetryAfterMs2 = getPerMinuteRetryAfterMs(response, quotaRejected2);
11010
+ if (interactive && (capacityBlock.category === "request-rate" || capacityBlock.category === "burst")) {
11011
+ if (perMinuteRetryAfterMs2 !== undefined) {
11012
+ return {
11013
+ forward,
11014
+ kind: "per-minute-rate-limit",
11015
+ retryAfterMs: perMinuteRetryAfterMs2
11016
+ };
11017
+ }
11018
+ }
11019
+ return {
11020
+ block: capacityBlock,
11021
+ discard: discardUpstreamResponse(state),
11022
+ forward,
11023
+ kind: "provider-capacity-block"
11024
+ };
11025
+ }
10481
11026
  if (isRequestScopedRateLimit(response, input.ctx.provider)) {
10482
11027
  return { forward, kind: "request-scoped-rate-limit" };
10483
11028
  }
@@ -10543,6 +11088,7 @@ var API_KEY_AUTH_COOLDOWN_MS, ORGANIZATION_QUARANTINE_MS, log20;
10543
11088
  var init_proxy_operations = __esm(() => {
10544
11089
  init_src2();
10545
11090
  init_src3();
11091
+ init_src10();
10546
11092
  init_response_handler();
10547
11093
  init_message_thread();
10548
11094
  init_request_handler();
@@ -10782,6 +11328,9 @@ async function proxySelectedAccounts(request3, accounts) {
10782
11328
  if (attempt.kind === "authentication-failure") {
10783
11329
  return new Response("Bad Gateway", { status: 502 });
10784
11330
  }
11331
+ if (attempt.kind === "provider-capacity-block") {
11332
+ return await attempt.forward();
11333
+ }
10785
11334
  if (attempt.kind === "per-minute-rate-limit") {
10786
11335
  return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
10787
11336
  }
@@ -10812,7 +11361,7 @@ var init_proxy_attempts = __esm(() => {
10812
11361
  });
10813
11362
 
10814
11363
  // ../../packages/proxy/src/handlers/proxy-request.ts
10815
- function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions) {
11364
+ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions, callerId) {
10816
11365
  const thread = parseMessageThreadRequest(body, ctx.upstreamPath, req.headers.get("content-type"), ctx.provider.getClientSessionId?.(req.headers) ?? null);
10817
11366
  const sessionId = ctx.provider.getClientSessionId?.(req.headers) ?? null;
10818
11367
  const teamRequest = teamRequestOverride ?? {
@@ -10821,7 +11370,8 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
10821
11370
  manualAccountName,
10822
11371
  model: meta.model,
10823
11372
  provider: ctx.providerName,
10824
- sessionId
11373
+ sessionId,
11374
+ callerId
10825
11375
  };
10826
11376
  const request3 = {
10827
11377
  body,
@@ -10847,7 +11397,11 @@ function selectRequestAccounts(request3, selectionOptions) {
10847
11397
  }
10848
11398
  function getRequestRetryAt(request3) {
10849
11399
  const { ctx, teamRequest } = request3;
10850
- return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
11400
+ return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
11401
+ }
11402
+ function getRequestQuotaCapacityBlock(request3) {
11403
+ const { ctx, teamRequest } = request3;
11404
+ return getQuotaCapacityBlock(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
10851
11405
  }
10852
11406
  var init_proxy_request = __esm(() => {
10853
11407
  init_account_selector();
@@ -10867,31 +11421,139 @@ var init_handlers = __esm(() => {
10867
11421
  init_token_manager();
10868
11422
  });
10869
11423
 
10870
- // ../../packages/proxy/src/provider-pool.ts
10871
- function poolTeamRequest(req, body, pool, requestedModel, manualAccountName) {
10872
- return {
10873
- body,
10874
- contentType: req.headers.get("content-type"),
10875
- manualAccountName,
10876
- model: requestedModel,
10877
- pinBucket: requestedModel,
10878
- pinScope: `pool:${pool.wire}`,
10879
- provider: `pool:${pool.wire}`,
10880
- sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
10881
- };
11424
+ // ../../packages/capacity/src/index.ts
11425
+ function isProviderBlockCategory(value) {
11426
+ return typeof value === "string" && PROVIDER_BLOCK_CATEGORIES.includes(value);
10882
11427
  }
11428
+ var PROVIDER_BLOCK_CATEGORIES;
11429
+ var init_src11 = __esm(() => {
11430
+ PROVIDER_BLOCK_CATEGORIES = [
11431
+ "five-hour-limit",
11432
+ "weekly-limit",
11433
+ "request-rate",
11434
+ "token-allocation",
11435
+ "burst",
11436
+ "dynamic-throughput",
11437
+ "temporary-capacity",
11438
+ "unknown"
11439
+ ];
11440
+ });
11441
+
11442
+ // ../../packages/proxy/src/pool/conversation-provider-routing-store.ts
11443
+ class PoolConversationProviderRoutingStore {
11444
+ dbOps;
11445
+ constructor(dbOps) {
11446
+ this.dbOps = dbOps;
11447
+ }
11448
+ getPreference(conversationKey) {
11449
+ return this.dbOps.getConversationProviderPreference(conversationKey);
11450
+ }
11451
+ upsertPreference(conversationKey, preference) {
11452
+ this.dbOps.upsertConversationProviderPreference(conversationKey, preference.provider, preference.promotionDeclined, preference.lastSeenAt);
11453
+ }
11454
+ getBlock(conversationKey, provider) {
11455
+ const block = this.dbOps.getConversationProviderBlock(conversationKey, provider);
11456
+ if (!block)
11457
+ return null;
11458
+ return {
11459
+ ...block,
11460
+ category: isProviderBlockCategory(block.category) ? block.category : "unknown"
11461
+ };
11462
+ }
11463
+ upsertBlock(conversationKey, provider, block) {
11464
+ this.dbOps.upsertConversationProviderBlock(conversationKey, provider, block.category, block.retryAt, block.lastSeenAt);
11465
+ }
11466
+ deleteBlock(conversationKey, provider) {
11467
+ this.dbOps.deleteConversationProviderBlock(conversationKey, provider);
11468
+ }
11469
+ }
11470
+ var init_conversation_provider_routing_store = __esm(() => {
11471
+ init_src11();
11472
+ });
11473
+
11474
+ // ../../packages/proxy/src/pool/interactive-provider-pool.ts
11475
+ function configuredPoolChoices(pool, fallbackModel) {
11476
+ return pool.providers.map((candidate) => ({
11477
+ model: candidate.model ?? fallbackModel ?? "",
11478
+ provider: candidate.provider.name
11479
+ }));
11480
+ }
11481
+ function eligiblePoolProviders({
11482
+ body,
11483
+ ctx,
11484
+ manualAccountName,
11485
+ meta,
11486
+ pool,
11487
+ req,
11488
+ teamRequest,
11489
+ url
11490
+ }) {
11491
+ const eligibleProviders = new Set;
11492
+ for (const candidate of pool.providers) {
11493
+ const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
11494
+ const prepared = prepareProxyRequest(req, url, candidateContext, { ...meta, model: candidate.model }, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
11495
+ if (prepared.request.thread || prepared.accounts.length === 0)
11496
+ continue;
11497
+ const accounts = candidateContext.teamRouter ? candidateContext.teamRouter.eligibleAccounts(prepared.accounts, teamRequest, candidateContext.runtime.teamRouting) : prepared.accounts;
11498
+ if (accounts.length > 0)
11499
+ eligibleProviders.add(candidate.provider.name);
11500
+ }
11501
+ return eligibleProviders;
11502
+ }
11503
+ function eligiblePoolChoices(input, blockedProvider) {
11504
+ return capacityChoices(configuredPoolChoices(input.pool, input.meta.model), blockedProvider, eligiblePoolProviders(input));
11505
+ }
11506
+ function createManualProviderChoiceResponse(input, pinnedAccount, preferredProvider) {
11507
+ const ordered = preferProviders(input.pool.providers, (candidate) => candidate.provider.name, pinnedAccount?.provider, preferredProvider);
11508
+ const activeProvider = ordered[0]?.provider.name ?? input.pool.providers[0]?.provider.name ?? "";
11509
+ const eligible = eligiblePoolProviders(input);
11510
+ return createProviderChoiceProblem({
11511
+ activeProvider,
11512
+ choices: configuredPoolChoices(input.pool, input.meta.model).filter((choice) => eligible.has(choice.provider))
11513
+ });
11514
+ }
11515
+ async function waitOrReturnProviderCapacity({
11516
+ candidates,
11517
+ conversationKey,
11518
+ input,
11519
+ providerWaited,
11520
+ retry,
11521
+ routing
11522
+ }) {
11523
+ if (!providerWaitRequested(input.req.headers) || providerWaited || !candidates[0]) {
11524
+ return null;
11525
+ }
11526
+ const provider = candidates[0].provider.name;
11527
+ const blocked = conversationKey ? routing.getBlock(conversationKey, provider) : null;
11528
+ const retryAt = blocked?.retryAt;
11529
+ const holdMs = input.ctx.runtime.teamRouting.holdSeconds * 1000;
11530
+ if (input.ctx.quotaHold && retryAt !== undefined && retryAt > Date.now() && holdMs > 0 && retryAt - Date.now() <= holdMs) {
11531
+ await input.ctx.quotaHold.waitUntil(retryAt, input.req.signal);
11532
+ return await retry();
11533
+ }
11534
+ if (retryAt === undefined || retryAt > Date.now()) {
11535
+ return createProviderCapacityProblem({
11536
+ blockedProvider: provider,
11537
+ category: blocked?.category ?? "unknown",
11538
+ choices: eligiblePoolChoices(input, provider),
11539
+ ...retryAt !== undefined && { retryAt }
11540
+ });
11541
+ }
11542
+ return null;
11543
+ }
11544
+ var init_interactive_provider_pool = __esm(() => {
11545
+ init_src10();
11546
+ init_handlers();
11547
+ init_proxy_request();
11548
+ });
11549
+
11550
+ // ../../packages/proxy/src/pool/provider-pool-attempts.ts
10883
11551
  function preferPinnedAccount(accounts, pinnedId) {
10884
11552
  if (!pinnedId)
10885
11553
  return accounts;
10886
11554
  const pinned = accounts.find((account2) => account2.id === pinnedId);
10887
11555
  return pinned ? [pinned, ...accounts.filter((account2) => account2.id !== pinned.id)] : accounts;
10888
11556
  }
10889
- function preferPinnedProvider(pool, pinnedAccount) {
10890
- if (!pinnedAccount)
10891
- return pool.providers;
10892
- const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
10893
- return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
10894
- }
10895
11557
  async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10896
11558
  for (let index = 0;index < accounts.length; index += 1) {
10897
11559
  const account2 = accounts[index];
@@ -10905,6 +11567,15 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10905
11567
  response: new Response("Bad Gateway", { status: 502 })
10906
11568
  };
10907
11569
  }
11570
+ if (attempt.kind === "provider-capacity-block") {
11571
+ await attempt.discard?.();
11572
+ if (accounts[index + 1])
11573
+ continue;
11574
+ if (allowNextProvider) {
11575
+ return { block: attempt.block, kind: "next-provider" };
11576
+ }
11577
+ return { block: attempt.block, kind: "capacity-block" };
11578
+ }
10908
11579
  if (attempt.kind === "per-minute-rate-limit") {
10909
11580
  return {
10910
11581
  kind: "response",
@@ -10961,77 +11632,303 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10961
11632
  response: new Response("Bad Gateway", { status: 502 })
10962
11633
  };
10963
11634
  }
10964
- async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName) {
10965
- const firstCandidate = pool.providers[0];
10966
- if (!firstCandidate) {
10967
- return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
11635
+ function resolvePoolCandidateResult({
11636
+ candidate,
11637
+ candidateContext,
11638
+ conversationKey,
11639
+ interactive,
11640
+ interactiveInput,
11641
+ providerPreference,
11642
+ requestedChoice,
11643
+ result,
11644
+ routing
11645
+ }) {
11646
+ if (result.kind === "capacity-block") {
11647
+ if (conversationKey) {
11648
+ routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
11649
+ }
11650
+ return createProviderCapacityProblem({
11651
+ blockedProvider: candidate.provider.name,
11652
+ category: result.block.category,
11653
+ choices: eligiblePoolChoices(interactiveInput, candidate.provider.name),
11654
+ ...result.block.retryAt !== undefined && {
11655
+ retryAt: result.block.retryAt
11656
+ }
11657
+ });
10968
11658
  }
10969
- const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName);
10970
- const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10971
- const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10972
- const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
11659
+ if (result.kind !== "response")
11660
+ return null;
11661
+ if (result.account) {
11662
+ if (conversationKey) {
11663
+ routing.clearBlock(conversationKey, candidate.provider.name);
11664
+ }
11665
+ if (conversationKey && requestedChoice) {
11666
+ routing.selectProvider(conversationKey, candidate.provider.name, Date.now());
11667
+ }
11668
+ candidateContext.teamRouter?.rebind(interactiveInput.teamRequest, result.account.id, candidateContext.runtime.teamRouting, candidateContext.provider, candidateContext.dbOps);
11669
+ }
11670
+ if (!interactive)
11671
+ return result.response;
11672
+ const served = withServedProviderHeaders(result.response, {
11673
+ model: candidate.model ?? interactiveInput.meta.model ?? "",
11674
+ provider: candidate.provider.name
11675
+ });
11676
+ if (!conversationKey || !providerPreference || providerPreference.promotionDeclined || requestedChoice || providerPreference.provider !== candidate.provider.name) {
11677
+ return served;
11678
+ }
11679
+ return withProviderPromotionDetails(served, higherRankedProviderChoices(configuredPoolChoices(interactiveInput.pool, interactiveInput.meta.model), candidate.provider.name, eligiblePoolProviders(interactiveInput), (provider) => routing.canOfferProvider(conversationKey, provider, Date.now())));
11680
+ }
11681
+ function preparePoolCandidate(input, candidate, pinnedId, orderedFallback) {
11682
+ const context2 = createResolvedProxyContext(input.ctx, candidate.provider, input.pool.upstreamPath);
11683
+ 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 });
11684
+ const pooledAccounts = context2.teamRouter ? context2.teamRouter.eligibleAccounts(prepared.accounts, input.teamRequest, context2.runtime.teamRouting) : prepared.accounts;
11685
+ const eligibleAccounts = orderedFallback ? prepared.accounts.filter((account2) => account2.auth_method === "api_key" || pooledAccounts.includes(account2)) : pooledAccounts;
11686
+ return {
11687
+ accounts: preferPinnedAccount(eligibleAccounts, pinnedId),
11688
+ context: context2,
11689
+ request: prepared.request
11690
+ };
11691
+ }
11692
+ async function proxyPoolCandidates({
11693
+ candidates,
11694
+ conversationKey,
11695
+ interactive,
11696
+ interactiveInput,
11697
+ orderedFallback,
11698
+ pinnedId,
11699
+ providerPreference,
11700
+ requestedChoice,
11701
+ routing
11702
+ }) {
10973
11703
  let soonestRetry = null;
10974
11704
  let soonestFleetReset = null;
10975
11705
  let everyCandidateFull = true;
11706
+ let firstCapacityBlock = null;
10976
11707
  let emittedIngress = false;
10977
11708
  const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
10978
11709
  const recordUnserved = (request3) => {
11710
+ firstCapacityBlock ??= getRequestQuotaCapacityBlock(request3);
10979
11711
  everyCandidateFull &&= isEveryAccountQuotaBlocked(request3.meta, request3.ctx);
10980
11712
  soonestRetry = earliest(soonestRetry, getRequestRetryAt(request3));
10981
11713
  soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request3.meta, request3.ctx));
10982
11714
  };
10983
- const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
10984
11715
  for (const [candidateIndex, candidate] of candidates.entries()) {
10985
- const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
10986
- const candidateMeta = { ...meta, model: candidate.model };
10987
- const prepared = prepareProxyRequest(req, url, candidateContext, candidateMeta, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
10988
- let accounts = prepared.accounts;
10989
- if (candidateContext.teamRouter) {
10990
- accounts = candidateContext.teamRouter.eligibleAccounts(accounts, teamRequest, candidateContext.runtime.teamRouting);
10991
- }
10992
- accounts = preferPinnedAccount(accounts, pinnedId);
11716
+ const { accounts, context: context2, request: request3 } = preparePoolCandidate(interactiveInput, candidate, pinnedId, orderedFallback);
10993
11717
  if (accounts.length === 0) {
10994
- recordUnserved(prepared.request);
11718
+ recordUnserved(request3);
10995
11719
  continue;
10996
11720
  }
10997
11721
  if (!emittedIngress) {
10998
11722
  requestEvents.emit("event", {
10999
11723
  type: "ingress",
11000
- id: meta.id,
11001
- timestamp: meta.timestamp,
11002
- method: meta.method,
11003
- path: meta.path
11724
+ id: interactiveInput.meta.id,
11725
+ timestamp: interactiveInput.meta.timestamp,
11726
+ method: interactiveInput.meta.method,
11727
+ path: interactiveInput.meta.path
11004
11728
  });
11005
11729
  emittedIngress = true;
11006
11730
  }
11007
11731
  log22.info(`Selected ${accounts.length} accounts: ${accounts.map((account2) => account2.name).join(", ")}`);
11008
- const result = await proxyPoolCandidate(prepared.request, accounts, candidateIndex === 0);
11009
- if (result.kind === "response") {
11010
- if (result.account) {
11011
- candidateContext.teamRouter?.rebind(teamRequest, result.account.id, candidateContext.runtime.teamRouting, candidateContext.provider, candidateContext.dbOps);
11732
+ const result = await proxyPoolCandidate(request3, accounts, candidateIndex < candidates.length - 1);
11733
+ if (result.kind === "next-provider" && result.block) {
11734
+ firstCapacityBlock ??= result.block;
11735
+ if (conversationKey) {
11736
+ routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
11012
11737
  }
11013
- return result.response;
11014
11738
  }
11015
- recordUnserved(prepared.request);
11016
- }
11017
- if (everyCandidateFull && soonestFleetReset !== null) {
11018
- ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, soonestFleetReset, { blocked: true, holdSeconds: 0 });
11739
+ const response = resolvePoolCandidateResult({
11740
+ candidate,
11741
+ candidateContext: context2,
11742
+ conversationKey,
11743
+ interactive,
11744
+ interactiveInput,
11745
+ providerPreference,
11746
+ requestedChoice,
11747
+ result,
11748
+ routing
11749
+ });
11750
+ if (response)
11751
+ return { kind: "response", response };
11752
+ recordUnserved(request3);
11019
11753
  }
11020
- if (soonestRetry !== null)
11021
- return quotaExhaustionResponse(soonestRetry);
11022
- log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11023
- throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
11754
+ return {
11755
+ everyCandidateFull,
11756
+ kind: "unserved",
11757
+ firstCapacityBlock,
11758
+ soonestFleetReset,
11759
+ soonestRetry
11760
+ };
11024
11761
  }
11025
11762
  var log22;
11026
- var init_provider_pool = __esm(() => {
11763
+ var init_provider_pool_attempts = __esm(() => {
11027
11764
  init_src2();
11028
11765
  init_src3();
11766
+ init_src10();
11029
11767
  init_handlers();
11030
11768
  init_proxy_attempts();
11031
11769
  init_proxy_request();
11770
+ init_interactive_provider_pool();
11032
11771
  log22 = new Logger("Proxy");
11033
11772
  });
11034
11773
 
11774
+ // ../../packages/proxy/src/provider-pool.ts
11775
+ function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
11776
+ return {
11777
+ body,
11778
+ callerId,
11779
+ contentType: req.headers.get("content-type"),
11780
+ manualAccountName,
11781
+ model: requestedModel,
11782
+ pinBucket: requestedModel,
11783
+ pinScope: `pool:${pool.wire}`,
11784
+ provider: `pool:${pool.wire}`,
11785
+ sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
11786
+ };
11787
+ }
11788
+ function hasOrderedCallerFallback(ctx, callerId) {
11789
+ const routing = ctx.runtime.teamRouting;
11790
+ return routing.enabled && callerId !== undefined && Object.hasOwn(routing.callerProviderFallback, callerId) && routing.callerProviderFallback[callerId] === "ordered";
11791
+ }
11792
+ function prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
11793
+ const firstCandidate = pool.providers[0];
11794
+ if (!firstCandidate) {
11795
+ return {
11796
+ kind: "response",
11797
+ response: new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 })
11798
+ };
11799
+ }
11800
+ const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
11801
+ const interactiveInput = {
11802
+ body,
11803
+ ctx,
11804
+ manualAccountName,
11805
+ meta,
11806
+ pool,
11807
+ req,
11808
+ teamRequest,
11809
+ url
11810
+ };
11811
+ const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
11812
+ const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
11813
+ const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
11814
+ const conversationKey = firstContext.teamRouter?.getConversationProviderKey(teamRequest, firstContext.runtime.teamRouting);
11815
+ const routing = new ConversationProviderRouting(new PoolConversationProviderRoutingStore(ctx.dbOps));
11816
+ let providerPreference = conversationKey ? routing.getPreference(conversationKey) : null;
11817
+ const interactive = interactiveProviderChoiceRequested(req.headers);
11818
+ if (interactive && conversationKey && providerPreference && providerPromotionDeclined(req.headers)) {
11819
+ routing.declinePromotion(conversationKey, Date.now());
11820
+ providerPreference = routing.getPreference(conversationKey);
11821
+ }
11822
+ const requestedChoice = interactive ? req.headers.get("x-agent-smith-provider-choice") : null;
11823
+ const configuredChoices = configuredPoolChoices(pool, meta.model);
11824
+ if (requestedChoice && !readProviderChoice(req.headers, configuredChoices)) {
11825
+ return {
11826
+ kind: "response",
11827
+ response: new Response("Selected provider is not available for this request", { status: 409 })
11828
+ };
11829
+ }
11830
+ if (interactive && manualProviderChoiceRequested(req.headers)) {
11831
+ return {
11832
+ kind: "response",
11833
+ response: createManualProviderChoiceResponse(interactiveInput, pinnedAccount, providerPreference?.provider)
11834
+ };
11835
+ }
11836
+ const orderedFallback = !interactive && hasOrderedCallerFallback(ctx, callerId);
11837
+ return {
11838
+ candidates: selectPoolProviders(pool.providers, (candidate) => candidate.provider.name, {
11839
+ orderedFallback,
11840
+ pinnedProvider: pinnedAccount?.provider,
11841
+ preferredProvider: providerPreference?.provider,
11842
+ requestedProvider: requestedChoice
11843
+ }),
11844
+ conversationKey,
11845
+ interactive,
11846
+ interactiveInput,
11847
+ kind: "selection",
11848
+ orderedFallback,
11849
+ pinnedId,
11850
+ providerPreference,
11851
+ requestedChoice,
11852
+ routing
11853
+ };
11854
+ }
11855
+ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, providerWaited = false) {
11856
+ const selection = prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId);
11857
+ if (selection.kind === "response")
11858
+ return selection.response;
11859
+ const {
11860
+ candidates,
11861
+ conversationKey,
11862
+ interactive,
11863
+ interactiveInput,
11864
+ orderedFallback,
11865
+ pinnedId,
11866
+ providerPreference,
11867
+ requestedChoice,
11868
+ routing
11869
+ } = selection;
11870
+ if (interactive) {
11871
+ const waitResponse = await waitOrReturnProviderCapacity({
11872
+ candidates,
11873
+ conversationKey,
11874
+ input: interactiveInput,
11875
+ providerWaited,
11876
+ retry: () => proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, true),
11877
+ routing
11878
+ });
11879
+ if (waitResponse)
11880
+ return waitResponse;
11881
+ }
11882
+ const candidateAttempt = await proxyPoolCandidates({
11883
+ candidates,
11884
+ conversationKey,
11885
+ interactive,
11886
+ interactiveInput,
11887
+ orderedFallback,
11888
+ pinnedId,
11889
+ providerPreference,
11890
+ requestedChoice,
11891
+ routing
11892
+ });
11893
+ if (candidateAttempt.kind === "response")
11894
+ return candidateAttempt.response;
11895
+ if (candidateAttempt.everyCandidateFull && candidateAttempt.soonestFleetReset !== null) {
11896
+ ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, candidateAttempt.soonestFleetReset, { blocked: true, holdSeconds: 0 });
11897
+ }
11898
+ if (interactive) {
11899
+ const blockedProvider = candidates[0]?.provider.name;
11900
+ if (blockedProvider) {
11901
+ const block = candidateAttempt.firstCapacityBlock;
11902
+ const retryAt = block?.retryAt ?? candidateAttempt.soonestRetry;
11903
+ return createProviderCapacityProblem({
11904
+ blockedProvider,
11905
+ category: block?.category ?? "unknown",
11906
+ choices: eligiblePoolChoices(interactiveInput, blockedProvider),
11907
+ ...retryAt !== null && retryAt !== undefined && {
11908
+ retryAt
11909
+ }
11910
+ });
11911
+ }
11912
+ }
11913
+ if (candidateAttempt.soonestRetry !== null) {
11914
+ return quotaExhaustionResponse(candidateAttempt.soonestRetry);
11915
+ }
11916
+ log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11917
+ throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
11918
+ }
11919
+ var log23;
11920
+ var init_provider_pool = __esm(() => {
11921
+ init_src2();
11922
+ init_src3();
11923
+ init_src10();
11924
+ init_handlers();
11925
+ init_proxy_attempts();
11926
+ init_conversation_provider_routing_store();
11927
+ init_interactive_provider_pool();
11928
+ init_provider_pool_attempts();
11929
+ log23 = new Logger("Proxy");
11930
+ });
11931
+
11035
11932
  // ../../packages/proxy/src/seat-alerts.ts
11036
11933
  function alertWhenFleetFull(meta, ctx, holdSeconds) {
11037
11934
  const resetAt2 = getSoonestQuotaReset(meta, ctx);
@@ -11054,10 +11951,10 @@ class SeatAlerts {
11054
11951
  this.config = config;
11055
11952
  this.send = send;
11056
11953
  if (config.email && !(config.emailFrom && config.resendApiKey)) {
11057
- log23.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
11954
+ log24.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
11058
11955
  }
11059
11956
  if (!config.slackBotToken !== !config.slackChannel) {
11060
- log23.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
11957
+ log24.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
11061
11958
  }
11062
11959
  }
11063
11960
  extraUsageSpent(account2, provider) {
@@ -11080,7 +11977,7 @@ class SeatAlerts {
11080
11977
  });
11081
11978
  }
11082
11979
  notify(alert) {
11083
- log23.warn(alert.text);
11980
+ log24.warn(alert.text);
11084
11981
  for (const delivery of this.deliveries(alert)) {
11085
11982
  trackProxyBackgroundTask(this.deliver(delivery));
11086
11983
  }
@@ -11135,7 +12032,7 @@ class SeatAlerts {
11135
12032
  signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
11136
12033
  });
11137
12034
  if (!response.ok) {
11138
- log23.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
12035
+ log24.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
11139
12036
  return;
11140
12037
  }
11141
12038
  if (!delivery.repliesOk)
@@ -11143,19 +12040,19 @@ class SeatAlerts {
11143
12040
  const reply2 = await response.json();
11144
12041
  if (reply2.ok !== true) {
11145
12042
  const code = typeof reply2.error === "string" && SLACK_ERROR_CODE.test(reply2.error) ? reply2.error : "no reason given";
11146
- log23.warn(`${delivery.channel} alert was refused (${code})`);
12043
+ log24.warn(`${delivery.channel} alert was refused (${code})`);
11147
12044
  }
11148
12045
  } catch (error) {
11149
- log23.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
12046
+ log24.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
11150
12047
  }
11151
12048
  }
11152
12049
  }
11153
- var log23, RESEND_EMAILS_URL = "https://api.resend.com/emails", SLACK_POST_MESSAGE_URL = "https://slack.com/api/chat.postMessage", SEND_TIMEOUT_MS = 1e4, SLACK_ERROR_CODE;
12050
+ 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;
11154
12051
  var init_seat_alerts = __esm(() => {
11155
12052
  init_src3();
11156
12053
  init_background_tasks();
11157
12054
  init_account_selector();
11158
- log23 = new Logger("SeatAlerts");
12055
+ log24 = new Logger("SeatAlerts");
11159
12056
  SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
11160
12057
  });
11161
12058
 
@@ -11540,7 +12437,7 @@ function getUsageWorker() {
11540
12437
  }
11541
12438
  if (!usageWorkerInstance) {
11542
12439
  usageWorkerInstance = new UsageWorkerController({
11543
- logger: log24,
12440
+ logger: log25,
11544
12441
  shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
11545
12442
  onWorkerMessage: (data) => {
11546
12443
  if (data.type === "summary" && isRequestSummary(data.summary)) {
@@ -11579,7 +12476,7 @@ async function terminateUsageWorker() {
11579
12476
  }
11580
12477
  }
11581
12478
  }
11582
- async function handleProxy(req, url, ctx) {
12479
+ async function handleProxy(req, url, ctx, callerId) {
11583
12480
  const manualPin = manualPinFromUrl(url);
11584
12481
  if (manualPin === "invalid")
11585
12482
  return new Response("Not Found", { status: 404 });
@@ -11602,13 +12499,13 @@ async function handleProxy(req, url, ctx) {
11602
12499
  if (pool.providers.length === 0) {
11603
12500
  return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
11604
12501
  }
11605
- return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName);
12502
+ return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
11606
12503
  }
11607
12504
  const requestMeta = createRequestMetadata(req, upstreamUrl);
11608
12505
  const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
11609
12506
  const body = buffer ?? null;
11610
12507
  requestMeta.model = readRequestModel(body);
11611
- const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
12508
+ const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName, undefined, undefined, undefined, callerId);
11612
12509
  let accounts = initiallySelectedAccounts;
11613
12510
  if (accounts.length === 0) {
11614
12511
  const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
@@ -11627,7 +12524,7 @@ async function handleProxy(req, url, ctx) {
11627
12524
  return quotaExhaustionResponse(retryAt);
11628
12525
  }
11629
12526
  if (accounts.length === 0) {
11630
- log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
12527
+ log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11631
12528
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
11632
12529
  }
11633
12530
  }
@@ -11638,11 +12535,11 @@ async function handleProxy(req, url, ctx) {
11638
12535
  method: requestMeta.method,
11639
12536
  path: requestMeta.path
11640
12537
  });
11641
- log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
11642
- log24.info(`Request: ${req.method} ${url.pathname}`);
12538
+ log25.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
12539
+ log25.info(`Request: ${req.method} ${url.pathname}`);
11643
12540
  return await proxySelectedAccounts(request3, accounts);
11644
12541
  }
11645
- var log24, usageWorkerInstance = null;
12542
+ var log25, usageWorkerInstance = null;
11646
12543
  var init_proxy = __esm(() => {
11647
12544
  init_src2();
11648
12545
  init_src3();
@@ -11651,7 +12548,7 @@ var init_proxy = __esm(() => {
11651
12548
  init_provider_pool();
11652
12549
  init_seat_alerts();
11653
12550
  init_usage_worker();
11654
- log24 = new Logger("Proxy");
12551
+ log25 = new Logger("Proxy");
11655
12552
  });
11656
12553
 
11657
12554
  // ../../packages/proxy/src/quota-hold.ts
@@ -12003,7 +12900,7 @@ function endActiveTurn(session, success, error) {
12003
12900
  if (!activeTurn) {
12004
12901
  return;
12005
12902
  }
12006
- log25.debug("Ending tracked websocket turn", {
12903
+ log26.debug("Ending tracked websocket turn", {
12007
12904
  requestId: activeTurn.requestId,
12008
12905
  provider: session.providerName,
12009
12906
  path: session.path,
@@ -12057,7 +12954,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
12057
12954
  timestamp,
12058
12955
  model: getEventModel(parsed)
12059
12956
  };
12060
- log25.debug("Starting tracked websocket turn", {
12957
+ log26.debug("Starting tracked websocket turn", {
12061
12958
  requestId,
12062
12959
  provider: session.providerName,
12063
12960
  path: session.path,
@@ -12087,7 +12984,7 @@ function handleTrackedUpstreamText(session, data) {
12087
12984
  if (!messageType) {
12088
12985
  return;
12089
12986
  }
12090
- log25.debug("Processing tracked websocket message", {
12987
+ log26.debug("Processing tracked websocket message", {
12091
12988
  provider: session.providerName,
12092
12989
  path: session.path,
12093
12990
  messageType,
@@ -12128,7 +13025,7 @@ function capturePendingRequestBody(session, message) {
12128
13025
  }
12129
13026
  session.pendingRequestBody = Buffer.from(message).toString("base64");
12130
13027
  session.pendingRequestTimestamp = Date.now();
12131
- log25.debug("Captured websocket request body for next tracked turn", {
13028
+ log26.debug("Captured websocket request body for next tracked turn", {
12132
13029
  provider: session.providerName,
12133
13030
  path: session.path,
12134
13031
  size: message.length
@@ -12201,7 +13098,7 @@ async function connectToNextUpstream(ws) {
12201
13098
  plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
12202
13099
  } catch (error) {
12203
13100
  session.connecting = false;
12204
- log25.warn("Skipping websocket account during upstream connection", {
13101
+ log26.warn("Skipping websocket account during upstream connection", {
12205
13102
  account: account2.name,
12206
13103
  error: error instanceof Error ? error.message : String(error)
12207
13104
  });
@@ -12260,7 +13157,7 @@ async function connectToNextUpstream(ws) {
12260
13157
  }
12261
13158
  });
12262
13159
  upstream.addEventListener("error", () => {
12263
- log25.warn("Upstream websocket error", {
13160
+ log26.warn("Upstream websocket error", {
12264
13161
  account: plan.account.name,
12265
13162
  provider: session.providerName,
12266
13163
  path: session.path
@@ -12269,7 +13166,7 @@ async function connectToNextUpstream(ws) {
12269
13166
  } catch (error) {
12270
13167
  session.connecting = false;
12271
13168
  clearConnectTimeout(session);
12272
- log25.warn("Failed to create upstream websocket", {
13169
+ log26.warn("Failed to create upstream websocket", {
12273
13170
  account: plan.account.name,
12274
13171
  error: error instanceof Error ? error.message : String(error)
12275
13172
  });
@@ -12289,7 +13186,7 @@ function isWebSocketUpgradeRequest(req) {
12289
13186
  }
12290
13187
  return connection.toLowerCase().split(",").some((value) => value.trim() === "upgrade");
12291
13188
  }
12292
- function handleWebSocketUpgradeRequest(req, url, ctx, server) {
13189
+ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12293
13190
  if (!isWebSocketUpgradeRequest(req)) {
12294
13191
  return;
12295
13192
  }
@@ -12306,6 +13203,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12306
13203
  const teamRequest = {
12307
13204
  body: null,
12308
13205
  contentType: null,
13206
+ callerId,
12309
13207
  model: requestMeta.model,
12310
13208
  provider: requestContext.providerName,
12311
13209
  sessionId: requestContext.provider.getClientSessionId?.(req.headers) ?? null
@@ -12313,7 +13211,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12313
13211
  const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
12314
13212
  if (accounts.length === 0) {
12315
13213
  alertWhenFleetFull(requestMeta, requestContext, 0);
12316
- log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
13214
+ log26.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
12317
13215
  return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
12318
13216
  }
12319
13217
  const protocols = getProtocols(req.headers);
@@ -12351,7 +13249,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12351
13249
  }
12352
13250
  return;
12353
13251
  }
12354
- var log25, CONNECT_TIMEOUT_MS = 5000, PENDING_MESSAGE_LIMIT = 128, CLOSE_CODE_NORMAL = 1000, CLOSE_CODE_INTERNAL_ERROR = 1011, CLOSE_CODE_TRY_AGAIN_LATER = 1013, websocketSessions, textEncoder, websocketProxyHandler;
13252
+ 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;
12355
13253
  var init_websocket_proxy = __esm(() => {
12356
13254
  init_src2();
12357
13255
  init_src6();
@@ -12362,7 +13260,7 @@ var init_websocket_proxy = __esm(() => {
12362
13260
  init_token_manager();
12363
13261
  init_openai_usage();
12364
13262
  init_seat_alerts();
12365
- log25 = new Logger("WebSocketProxy");
13263
+ log26 = new Logger("WebSocketProxy");
12366
13264
  websocketSessions = new Map;
12367
13265
  textEncoder = new TextEncoder;
12368
13266
  websocketProxyHandler = {
@@ -12476,16 +13374,16 @@ class WindowWarmup {
12476
13374
  try {
12477
13375
  const accessToken = await this.readToken(account2);
12478
13376
  if (!accessToken) {
12479
- log26.warn(`Window warm-up skipped ${account2.name}: no access token`);
13377
+ log27.warn(`Window warm-up skipped ${account2.name}: no access token`);
12480
13378
  return;
12481
13379
  }
12482
13380
  const quota2 = await this.startWindow(provider, account2, accessToken, model);
12483
- log26.info(`Window warm-up started ${account2.name}'s five-hour window`);
13381
+ log27.info(`Window warm-up started ${account2.name}'s five-hour window`);
12484
13382
  if (quota2) {
12485
13383
  recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
12486
13384
  }
12487
13385
  } catch (error) {
12488
- log26.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
13386
+ log27.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
12489
13387
  }
12490
13388
  }
12491
13389
  async startWindow(provider, account2, accessToken, model) {
@@ -12497,18 +13395,18 @@ class WindowWarmup {
12497
13395
  }
12498
13396
  }
12499
13397
  }
12500
- var log26;
13398
+ var log27;
12501
13399
  var init_window_warmup2 = __esm(() => {
12502
13400
  init_src4();
12503
13401
  init_src3();
12504
13402
  init_src();
12505
13403
  init_account_selector();
12506
13404
  init_quota_probe();
12507
- log26 = new Logger("WindowWarmup");
13405
+ log27 = new Logger("WindowWarmup");
12508
13406
  });
12509
13407
 
12510
13408
  // ../../packages/proxy/src/index.ts
12511
- var init_src10 = __esm(() => {
13409
+ var init_src12 = __esm(() => {
12512
13410
  init_background_tasks();
12513
13411
  init_account_selector();
12514
13412
  init_request_handler();
@@ -12534,30 +13432,33 @@ import {
12534
13432
  readFileSync as readFileSync2
12535
13433
  } from "fs";
12536
13434
  import { isAbsolute as isAbsolute2 } from "path";
12537
- function deviceKeyMatches(key, path) {
13435
+ function deviceKeyName(key, path) {
12538
13436
  if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
12539
- return false;
13437
+ return;
12540
13438
  let fd;
12541
13439
  try {
12542
13440
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
12543
13441
  const stat = fstatSync(fd);
12544
13442
  if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
12545
- return false;
13443
+ return;
12546
13444
  const registry = JSON.parse(readFileSync2(fd, "utf8"));
12547
13445
  if (!registry || typeof registry !== "object" || Array.isArray(registry))
12548
- return false;
13446
+ return;
12549
13447
  const entries = Object.entries(registry);
12550
13448
  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)))
12551
- return false;
13449
+ return;
12552
13450
  const digest = createHash3("sha256").update(key).digest();
12553
- return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
13451
+ return entries.find(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")))?.[0];
12554
13452
  } catch {
12555
- return false;
13453
+ return;
12556
13454
  } finally {
12557
13455
  if (fd !== undefined)
12558
13456
  closeSync(fd);
12559
13457
  }
12560
13458
  }
13459
+ function deviceKeyMatches(key, path) {
13460
+ return deviceKeyName(key, path) !== undefined;
13461
+ }
12561
13462
  var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
12562
13463
  var init_device_keys = __esm(() => {
12563
13464
  MAX_REGISTRY_BYTES = 32 * 1024;
@@ -12651,6 +13552,12 @@ function keyRole(req, url, config) {
12651
13552
  }
12652
13553
  return null;
12653
13554
  }
13555
+ function callerIdForRequest(req, url, config) {
13556
+ if (keyRole(req, url, config) !== "device")
13557
+ return;
13558
+ const apiKey = req.headers.get("x-api-key");
13559
+ return deviceKeyName(apiKey, config.clientKeysFile) ?? (isResponsesInferenceRoute(url.pathname) ? deviceKeyName(bearerToken(req), config.clientKeysFile) : undefined);
13560
+ }
12654
13561
  function hostnameFromHostHeader(host) {
12655
13562
  try {
12656
13563
  const hostname = new URL(`http://${host}`).hostname.toLowerCase();
@@ -12740,10 +13647,10 @@ function createRuntimeConfig(config, port) {
12740
13647
  teamRouting: config.getTeamRouting()
12741
13648
  };
12742
13649
  }
12743
- function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
13650
+ function wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
12744
13651
  config.on("change", (change) => {
12745
13652
  if (change.key === "lb_strategy") {
12746
- log27.info("Strategy configuration changed");
13653
+ log28.info("Strategy configuration changed");
12747
13654
  const newStrategyName = config.getStrategy();
12748
13655
  if (newStrategyName === "session") {
12749
13656
  const strategy3 = new SessionStrategy;
@@ -12758,7 +13665,7 @@ function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig
12758
13665
  runtimeConfig2.teamRouting = config.getTeamRouting();
12759
13666
  quotaProbe.reschedule();
12760
13667
  windowWarmup.reschedule();
12761
- log27.info("Team routing configuration changed");
13668
+ log28.info("Team routing configuration changed");
12762
13669
  }
12763
13670
  });
12764
13671
  }
@@ -12793,7 +13700,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12793
13700
  sessionDurationMs: runtimeConfig2.sessionDurationMs
12794
13701
  });
12795
13702
  const dbOps = DatabaseFactory.getInstance();
12796
- const log27 = container.resolve(SERVICE_KEYS.Logger);
13703
+ const log28 = container.resolve(SERVICE_KEYS.Logger);
12797
13704
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
12798
13705
  const asyncWriter = new AsyncDbWriter;
12799
13706
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -12858,11 +13765,11 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12858
13765
  usageWorker: getUsageWorker()
12859
13766
  };
12860
13767
  const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
12861
- wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
13768
+ wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
12862
13769
  return {
12863
13770
  config,
12864
13771
  dbOps,
12865
- log: log27,
13772
+ log: log28,
12866
13773
  asyncWriter,
12867
13774
  apiRouter,
12868
13775
  exposureConfig,
@@ -12871,12 +13778,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12871
13778
  runtimeConfig: runtimeConfig2
12872
13779
  };
12873
13780
  }
12874
- function logInitialAccountStatus(log27, dbOps) {
13781
+ function logInitialAccountStatus(log28, dbOps) {
12875
13782
  const accounts = dbOps.getAllAccounts();
12876
13783
  const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
12877
- log27.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
13784
+ log28.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
12878
13785
  if (activeAccounts.length === 0) {
12879
- log27.warn("No active accounts available - requests will be refused with a 503 until an account is added");
13786
+ log28.warn("No active accounts available - requests will be refused with a 503 until an account is added");
12880
13787
  }
12881
13788
  }
12882
13789
  var init_bootstrap_runtime = __esm(() => {
@@ -12886,7 +13793,7 @@ var init_bootstrap_runtime = __esm(() => {
12886
13793
  init_src5();
12887
13794
  init_src3();
12888
13795
  init_src7();
12889
- init_src10();
13796
+ init_src12();
12890
13797
  init_exposure();
12891
13798
  });
12892
13799
 
@@ -13067,6 +13974,7 @@ function createServerFetchHandler({
13067
13974
  if (rejected) {
13068
13975
  return rejected;
13069
13976
  }
13977
+ const callerId = callerIdForRequest(req, url, exposureConfig);
13070
13978
  const apiResponse = await apiRouter.handleRequest(url, req);
13071
13979
  if (apiResponse) {
13072
13980
  return apiResponse;
@@ -13085,7 +13993,7 @@ function createServerFetchHandler({
13085
13993
  return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
13086
13994
  }
13087
13995
  if (server) {
13088
- const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
13996
+ const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server, callerId);
13089
13997
  if (websocketResponse) {
13090
13998
  return websocketResponse;
13091
13999
  }
@@ -13094,7 +14002,7 @@ function createServerFetchHandler({
13094
14002
  }
13095
14003
  }
13096
14004
  try {
13097
- return await handleProxyRequest(req, url, proxyContext);
14005
+ return await handleProxyRequest(req, url, proxyContext, callerId);
13098
14006
  } catch (error) {
13099
14007
  return errorResponse(error);
13100
14008
  }
@@ -13111,38 +14019,38 @@ function createServerFetchHandler({
13111
14019
  var init_fetch_handler = __esm(() => {
13112
14020
  init_src2();
13113
14021
  init_src6();
13114
- init_src10();
14022
+ init_src12();
13115
14023
  init_dashboard_assets();
13116
14024
  init_exposure();
13117
14025
  init_oauth_token();
13118
14026
  });
13119
14027
 
13120
14028
  // ../../packages/runtime-server/src/retention-maintenance.ts
13121
- function removeExpiredRequests(config, dbOps, log27, label) {
14029
+ function removeExpiredRequests(config, dbOps, log28, label) {
13122
14030
  try {
13123
14031
  const payloadDays = config.getDataRetentionDays();
13124
14032
  const requestDays = config.getRequestRetentionDays();
13125
14033
  const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
13126
- log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
14034
+ log28.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
13127
14035
  } catch (err) {
13128
- log27.error(`${label} cleanup error: ${err}`);
14036
+ log28.error(`${label} cleanup error: ${err}`);
13129
14037
  }
13130
14038
  }
13131
14039
  function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
13132
- const log27 = new Logger("RetentionMaintenance");
13133
- removeExpiredRequests(config, dbOps, log27, "Startup");
14040
+ const log28 = new Logger("RetentionMaintenance");
14041
+ removeExpiredRequests(config, dbOps, log28, "Startup");
13134
14042
  try {
13135
14043
  const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
13136
- log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
14044
+ log28.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
13137
14045
  } catch (err) {
13138
- log27.error(`Database compaction error: ${err}`);
14046
+ log28.error(`Database compaction error: ${err}`);
13139
14047
  }
13140
14048
  const timer = setInterval(() => {
13141
- removeExpiredRequests(config, dbOps, log27, "Periodic");
14049
+ removeExpiredRequests(config, dbOps, log28, "Periodic");
13142
14050
  try {
13143
14051
  dbOps.checkpointWal();
13144
14052
  } catch (err) {
13145
- log27.error(`WAL checkpoint error: ${err}`);
14053
+ log28.error(`WAL checkpoint error: ${err}`);
13146
14054
  }
13147
14055
  }, intervalMs);
13148
14056
  timer.unref?.();
@@ -13300,7 +14208,7 @@ function startServer(options) {
13300
14208
  const {
13301
14209
  config,
13302
14210
  dbOps,
13303
- log: log27,
14211
+ log: log28,
13304
14212
  apiRouter,
13305
14213
  exposureConfig,
13306
14214
  proxyContext,
@@ -13345,7 +14253,7 @@ function startServer(options) {
13345
14253
  strategy: config.getStrategy(),
13346
14254
  providers: providerRegistry.listProviders()
13347
14255
  }));
13348
- logInitialAccountStatus(log27, dbOps);
14256
+ logInitialAccountStatus(log28, dbOps);
13349
14257
  return {
13350
14258
  port: activePort,
13351
14259
  stop: () => stopServerRuntime(),
@@ -13368,12 +14276,12 @@ async function handleGracefulShutdown(signal) {
13368
14276
  }
13369
14277
  }
13370
14278
  var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null, deploymentDrain, checkShutdownDrain;
13371
- var init_src11 = __esm(() => {
14279
+ var init_src13 = __esm(() => {
13372
14280
  init_src9();
13373
14281
  init_src2();
13374
14282
  init_src5();
13375
14283
  init_src3();
13376
- init_src10();
14284
+ init_src12();
13377
14285
  init_bootstrap_runtime();
13378
14286
  init_dashboard_assets();
13379
14287
  init_deployment_drain();
@@ -14502,7 +15410,7 @@ var init_themes = __esm(() => {
14502
15410
  THEME_FAMILIES = [...new Set(THEME_REGISTRY.map((t) => t.family))];
14503
15411
  });
14504
15412
  // ../../packages/ui/src/index.ts
14505
- var init_src12 = __esm(() => {
15413
+ var init_src14 = __esm(() => {
14506
15414
  init_account_display();
14507
15415
  init_analytics_display();
14508
15416
  init_TokenUsageDisplay();
@@ -14638,7 +15546,7 @@ var init_account2 = __esm(() => {
14638
15546
  init_src8();
14639
15547
  init_src7();
14640
15548
  init_src();
14641
- init_src12();
15549
+ init_src14();
14642
15550
  init_std_adapter();
14643
15551
  init_browser();
14644
15552
  });
@@ -14688,6 +15596,8 @@ function teamRoutingFileConfig(routing) {
14688
15596
  max_usage: routing.maxUsage,
14689
15597
  weekly_max_usage: routing.weeklyMaxUsage,
14690
15598
  weekly_max_usage_by_email: routing.weeklyMaxUsageByEmail,
15599
+ caller_weekly_max_usage: routing.callerWeeklyMaxUsage,
15600
+ caller_provider_fallback: routing.callerProviderFallback,
14691
15601
  admission_cap: routing.admissionCap,
14692
15602
  admission_queue_limit: routing.admissionQueueLimit,
14693
15603
  admission_wait_ms: routing.admissionWaitMs,
@@ -14887,7 +15797,7 @@ var init_accounts2 = __esm(() => {
14887
15797
  init_src8();
14888
15798
  init_src7();
14889
15799
  init_src();
14890
- init_src12();
15800
+ init_src14();
14891
15801
  init_cli();
14892
15802
  init_cli();
14893
15803
  init_local_pool();
@@ -15009,9 +15919,11 @@ import {
15009
15919
  accessSync,
15010
15920
  chmodSync as chmodSync2,
15011
15921
  constants as constants3,
15922
+ copyFileSync,
15012
15923
  existsSync as existsSync3,
15013
15924
  mkdirSync as mkdirSync4,
15014
15925
  readFileSync as readFileSync4,
15926
+ rmSync as rmSync2,
15015
15927
  statSync as statSync3,
15016
15928
  unlinkSync as unlinkSync2,
15017
15929
  writeFileSync as writeFileSync2
@@ -15067,7 +15979,37 @@ function claudeProxyCredential(keepClaudeLogin) {
15067
15979
  export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_HEADERS
15068
15980
  }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
15069
15981
  }
15070
- function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin) {
15982
+ function claudeCompanionSourceDir() {
15983
+ const bundled = join8(import.meta.dir, "claude-companion");
15984
+ if (existsSync3(join8(bundled, ".claude-plugin", "plugin.json"))) {
15985
+ return bundled;
15986
+ }
15987
+ const source = join8(import.meta.dir, "..", "claude-companion");
15988
+ if (existsSync3(join8(source, ".claude-plugin", "plugin.json"))) {
15989
+ return source;
15990
+ }
15991
+ throw new Error("Agent-smith Claude companion files are missing");
15992
+ }
15993
+ function installClaudeCompanion(binDir) {
15994
+ const sourceDir = claudeCompanionSourceDir();
15995
+ const targetDir = join8(binDir, CLAUDE_COMPANION_DIRNAME);
15996
+ rmSync2(targetDir, { force: true, recursive: true });
15997
+ for (const relativePath of CLAUDE_COMPANION_FILES) {
15998
+ const target = join8(targetDir, relativePath);
15999
+ mkdirSync4(dirname4(target), { recursive: true, mode: 448 });
16000
+ copyFileSync(join8(sourceDir, relativePath), target, constants3.COPYFILE_FICLONE);
16001
+ chmodSync2(target, 384);
16002
+ }
16003
+ for (const directory of [
16004
+ targetDir,
16005
+ join8(targetDir, ".claude-plugin"),
16006
+ join8(targetDir, "hooks")
16007
+ ]) {
16008
+ chmodSync2(directory, 448);
16009
+ }
16010
+ return targetDir;
16011
+ }
16012
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin, companionDir) {
15071
16013
  return `#!/bin/sh
15072
16014
  # Generated by agent-smith. This file delegates to the real Claude Code binary.
15073
16015
  unset AGENT_SMITH_ADMIN_KEY
@@ -15077,7 +16019,7 @@ ${proxyKeySetup(proxyKeyFile)}
15077
16019
  ${claudeProxyCredential(keepClaudeLogin)}
15078
16020
  unset AGENT_SMITH_PROXY_KEY
15079
16021
  export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
15080
- exec ${shellQuote(claudePath)} "$@"
16022
+ exec ${shellQuote(claudePath)} --plugin-dir ${shellQuote(companionDir)} "$@"
15081
16023
  `;
15082
16024
  }
15083
16025
  function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
@@ -15114,9 +16056,10 @@ async function installClientWrappers(options) {
15114
16056
  if (target === join8(options.binDir, tool))
15115
16057
  throw new Error("A client launcher cannot call itself");
15116
16058
  const wrapper = join8(options.binDir, tool);
16059
+ const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
15117
16060
  writeFileSync2(wrapper, `#!/bin/sh
15118
16061
  ${CONFIG_CLIENT_MARKER}
15119
- exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(shellQuote).join(" ")} "$@"
16062
+ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
15120
16063
  `, { encoding: "utf8", mode: 448 });
15121
16064
  chmodSync2(wrapper, 448);
15122
16065
  }
@@ -15129,7 +16072,8 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(
15129
16072
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
15130
16073
  if (options.claudePath) {
15131
16074
  const claude = join8(options.binDir, "claude");
15132
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true), {
16075
+ const companionDir = installClaudeCompanion(options.binDir);
16076
+ writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
15133
16077
  encoding: "utf8",
15134
16078
  mode: 448
15135
16079
  });
@@ -15219,7 +16163,7 @@ function configClientWrappersInstalled(paths2 = {}) {
15219
16163
  const files = ["claude", "codex"].map((name) => join8(binDir, name)).filter(existsSync3);
15220
16164
  return installedRoutingStatus(paths2).enabled && files.length > 0 && files.every((path) => readFileSync4(path, "utf8").includes(CONFIG_CLIENT_MARKER));
15221
16165
  }
15222
- async function launchConfiguredClient(configPath, tool, target, args) {
16166
+ async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
15223
16167
  if (tool !== "claude" && tool !== "codex")
15224
16168
  throw new Error("Unknown Agent Smith client");
15225
16169
  const client2 = readClientRouting(configPath);
@@ -15233,7 +16177,7 @@ async function launchConfiguredClient(configPath, tool, target, args) {
15233
16177
  const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
15234
16178
  const wires = Object.keys(new Config(configPath).getProviderPools());
15235
16179
  const base = proxyBaseUrl(8080, client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
15236
- const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true) : codexWrapper(target, base, keyFile);
16180
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
15237
16181
  command = ["/bin/sh", "-c", script, "--", ...args];
15238
16182
  }
15239
16183
  const child = Bun.spawn(command, {
@@ -15309,6 +16253,10 @@ function disableLocalClientRouting(paths2 = {}) {
15309
16253
  if (existsSync3(wrapper))
15310
16254
  unlinkSync2(wrapper);
15311
16255
  }
16256
+ rmSync2(join8(binDir, CLAUDE_COMPANION_DIRNAME), {
16257
+ force: true,
16258
+ recursive: true
16259
+ });
15312
16260
  if (existsSync3(statePath))
15313
16261
  unlinkSync2(statePath);
15314
16262
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
@@ -15335,9 +16283,15 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
15335
16283
  ${ROUTING_END}
15336
16284
  `;
15337
16285
  }
15338
- var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
16286
+ var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
15339
16287
  var init_local_routing = __esm(() => {
15340
16288
  init_src4();
16289
+ CLAUDE_COMPANION_FILES = [
16290
+ ".claude-plugin/plugin.json",
16291
+ "hooks/hooks.json",
16292
+ "hooks/provider-choice.js",
16293
+ "hooks/register.js"
16294
+ ];
15341
16295
  });
15342
16296
 
15343
16297
  // src/core/logs.ts
@@ -15769,7 +16723,7 @@ import {
15769
16723
  mkdirSync as mkdirSync5,
15770
16724
  readFileSync as readFileSync5,
15771
16725
  realpathSync,
15772
- rmSync as rmSync2,
16726
+ rmSync as rmSync3,
15773
16727
  writeFileSync as writeFileSync3
15774
16728
  } from "fs";
15775
16729
  import { homedir as homedir3 } from "os";
@@ -15883,7 +16837,7 @@ function uninstall(deps) {
15883
16837
  deps.log("No Agent Smith menu bar plugin is installed.");
15884
16838
  return;
15885
16839
  }
15886
- rmSync2(path);
16840
+ rmSync3(path);
15887
16841
  deps.log(`Removed ${path}.`);
15888
16842
  }
15889
16843
  async function runMenubarCommand(argv, overrides = {}) {
@@ -15984,7 +16938,7 @@ function getAvailableThemes() {
15984
16938
  }
15985
16939
  var CONFIG_DIR, CONFIG_FILE, currentThemeId, currentColors, C, NAV_ITEMS, SCREEN_TITLES;
15986
16940
  var init_theme = __esm(() => {
15987
- init_src12();
16941
+ init_src14();
15988
16942
  CONFIG_DIR = join10(homedir4(), ".config", "agent-smith");
15989
16943
  CONFIG_FILE = join10(CONFIG_DIR, "theme.json");
15990
16944
  currentThemeId = loadPersistedThemeId();
@@ -17690,7 +18644,7 @@ function AnalyticsScreen({ refreshKey }) {
17690
18644
  var TIME_RANGES3, VIEW_MODES;
17691
18645
  var init_AnalyticsScreen = __esm(() => {
17692
18646
  init_src2();
17693
- init_src12();
18647
+ init_src14();
17694
18648
  init_core();
17695
18649
  init_theme();
17696
18650
  init_BarChart();
@@ -17722,13 +18676,13 @@ function reducer(state, action) {
17722
18676
  function LogsScreen({ refreshKey }) {
17723
18677
  const [state, dispatch] = useReducer(reducer, undefined, createLogFeedInitialState);
17724
18678
  const logKeyCounts = new Map;
17725
- const keyedLogs = state.logs.map((log27) => {
17726
- const baseKey = `${log27.ts}-${log27.level ?? ""}-${log27.msg}`;
18679
+ const keyedLogs = state.logs.map((log28) => {
18680
+ const baseKey = `${log28.ts}-${log28.level ?? ""}-${log28.msg}`;
17727
18681
  const count = (logKeyCounts.get(baseKey) ?? 0) + 1;
17728
18682
  logKeyCounts.set(baseKey, count);
17729
18683
  return {
17730
18684
  key: count === 1 ? baseKey : `${baseKey}-${count}`,
17731
- log: log27
18685
+ log: log28
17732
18686
  };
17733
18687
  });
17734
18688
  useKeyboard3((key) => {
@@ -17752,8 +18706,8 @@ function LogsScreen({ refreshKey }) {
17752
18706
  }, [refreshKey]);
17753
18707
  useEffect3(() => {
17754
18708
  if (!state.paused && !state.loading) {
17755
- const unsubscribe = streamLogs((log27) => {
17756
- dispatch({ type: "new_entry", log: log27 });
18709
+ const unsubscribe = streamLogs((log28) => {
18710
+ dispatch({ type: "new_entry", log: log28 });
17757
18711
  });
17758
18712
  return () => {
17759
18713
  unsubscribe();
@@ -17806,15 +18760,15 @@ function LogsScreen({ refreshKey }) {
17806
18760
  children: "No logs yet..."
17807
18761
  }) : /* @__PURE__ */ jsx7("box", {
17808
18762
  flexDirection: "column",
17809
- children: keyedLogs.map(({ key, log: log27 }) => {
17810
- const sev = getLogSeverityMeta(log27.level);
18763
+ children: keyedLogs.map(({ key, log: log28 }) => {
18764
+ const sev = getLogSeverityMeta(log28.level);
17811
18765
  return /* @__PURE__ */ jsxs7("text", {
17812
18766
  fg: sev.termColor,
17813
18767
  children: [
17814
18768
  "[",
17815
18769
  sev.label,
17816
18770
  "] ",
17817
- log27.msg
18771
+ log28.msg
17818
18772
  ]
17819
18773
  }, key);
17820
18774
  })
@@ -17825,7 +18779,7 @@ function LogsScreen({ refreshKey }) {
17825
18779
  }
17826
18780
  var MAX_LOGS = 200;
17827
18781
  var init_LogsScreen = __esm(() => {
17828
- init_src12();
18782
+ init_src14();
17829
18783
  init_core();
17830
18784
  init_theme();
17831
18785
  });
@@ -18261,7 +19215,7 @@ function TokenBar({
18261
19215
  }
18262
19216
  var init_OverviewScreen = __esm(() => {
18263
19217
  init_src2();
18264
- init_src12();
19218
+ init_src14();
18265
19219
  init_App();
18266
19220
  init_core();
18267
19221
  init_theme();
@@ -18440,7 +19394,7 @@ function TokenUsageDisplay2({ summary }) {
18440
19394
  });
18441
19395
  }
18442
19396
  var init_TokenUsageDisplay2 = __esm(() => {
18443
- init_src12();
19397
+ init_src14();
18444
19398
  init_theme();
18445
19399
  });
18446
19400
 
@@ -18839,7 +19793,7 @@ function RequestsScreen({ refreshKey }) {
18839
19793
  }
18840
19794
  var init_RequestsScreen = __esm(() => {
18841
19795
  init_src2();
18842
- init_src12();
19796
+ init_src14();
18843
19797
  init_core();
18844
19798
  init_theme();
18845
19799
  init_TokenUsageDisplay2();
@@ -19098,7 +20052,7 @@ function ThemePicker({ onClose }) {
19098
20052
  });
19099
20053
  }
19100
20054
  var init_ThemePicker = __esm(() => {
19101
- init_src12();
20055
+ init_src14();
19102
20056
  init_theme();
19103
20057
  init_TuiPrimitives();
19104
20058
  });
@@ -19495,13 +20449,13 @@ Examples:
19495
20449
  const limit = typeof parsed.logs === "number" ? parsed.logs : 100;
19496
20450
  if (typeof parsed.logs === "number") {
19497
20451
  const history = await getLogHistory(limit);
19498
- for (const log27 of history) {
19499
- console.log(`[${log27.level}] ${log27.msg}`);
20452
+ for (const log28 of history) {
20453
+ console.log(`[${log28.level}] ${log28.msg}`);
19500
20454
  }
19501
20455
  console.log("--- Live logs ---");
19502
20456
  }
19503
- await streamLogs((log27) => {
19504
- console.log(`[${log27.level}] ${log27.msg}`);
20457
+ await streamLogs((log28) => {
20458
+ console.log(`[${log28.level}] ${log28.msg}`);
19505
20459
  });
19506
20460
  return;
19507
20461
  }
@@ -19600,7 +20554,7 @@ var init_main = __esm(() => {
19600
20554
  init_src2();
19601
20555
  init_src5();
19602
20556
  init_src3();
19603
- init_src11();
20557
+ init_src13();
19604
20558
  init_core();
19605
20559
  init_core();
19606
20560
  init_client_command();