@certalis/agent-smith 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -93,8 +93,10 @@ Render. HTTPS needs no VPN: use the shipped standalone launcher or let an existi
93
93
  only inference to the pool's private socket. Each device has its own revocable
94
94
  key; provider tokens and the single database stay on the server.
95
95
 
96
- Device keys allow independent revocation and cannot read management data.
97
- This does not add per-client fairness or budgets.
96
+ Device keys allow independent revocation and cannot read management data. A
97
+ server-side policy may give a registered device name a lower weekly seat ceiling
98
+ than the default; this filters account eligibility only and does not create a
99
+ per-client budget or usage meter.
98
100
 
99
101
  Seat owners join through the server's optional `/pool-enroll` page, not its
100
102
  proxy homepage. Allow individual addresses or an exact domain (`*@example.test`)
package/dist/bin.js CHANGED
@@ -1660,6 +1660,12 @@ 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
+ }
1663
1669
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1664
1670
  result.admission_cap = Math.floor(value.admission_cap);
1665
1671
  }
@@ -1701,7 +1707,7 @@ function clientRouting(client) {
1701
1707
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1702
1708
  };
1703
1709
  }
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;
1710
+ 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
1711
  var init_src4 = __esm(() => {
1706
1712
  init_src2();
1707
1713
  init_src3();
@@ -1727,6 +1733,7 @@ var init_src4 = __esm(() => {
1727
1733
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1728
1734
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1729
1735
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1736
+ CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1730
1737
  TEAM_ROUTING_DEFAULTS = {
1731
1738
  enabled: false,
1732
1739
  distributionEnabled: true,
@@ -1735,6 +1742,7 @@ var init_src4 = __esm(() => {
1735
1742
  maxUsage: 0.9,
1736
1743
  weeklyMaxUsage: 0.95,
1737
1744
  weeklyMaxUsageByEmail: {},
1745
+ callerWeeklyMaxUsage: {},
1738
1746
  admissionCap: 5,
1739
1747
  admissionQueueLimit: 25,
1740
1748
  admissionWaitMs: 30000,
@@ -1897,6 +1905,7 @@ var init_src4 = __esm(() => {
1897
1905
  maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1898
1906
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1899
1907
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1908
+ callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1900
1909
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1901
1910
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1902
1911
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -1966,6 +1975,7 @@ var init_src4 = __esm(() => {
1966
1975
  "max_usage",
1967
1976
  "weekly_max_usage",
1968
1977
  "weekly_max_usage_by_email",
1978
+ "caller_weekly_max_usage",
1969
1979
  "admission_cap",
1970
1980
  "admission_queue_limit",
1971
1981
  "admission_wait_ms",
@@ -1991,6 +2001,11 @@ var init_src4 = __esm(() => {
1991
2001
  ...oldValue.weekly_max_usage_by_email
1992
2002
  };
1993
2003
  }
2004
+ if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2005
+ sanitized.caller_weekly_max_usage = {
2006
+ ...oldValue.caller_weekly_max_usage
2007
+ };
2008
+ }
1994
2009
  this.persistStrictly("team_routing", sanitized);
1995
2010
  }
1996
2011
  allowAccountUuid(accountUuid) {
@@ -7422,6 +7437,14 @@ var init_analytics = __esm(() => {
7422
7437
  });
7423
7438
 
7424
7439
  // ../../packages/api/src/handlers/config.ts
7440
+ function publicTeamRouting(config) {
7441
+ const {
7442
+ callerWeeklyMaxUsage: _callerWeeklyMaxUsage,
7443
+ weeklyMaxUsageByEmail: _weeklyMaxUsageByEmail,
7444
+ ...routing
7445
+ } = config.getTeamRouting();
7446
+ return routing;
7447
+ }
7425
7448
  function createConfigHandlers(config) {
7426
7449
  return {
7427
7450
  getConfig: () => {
@@ -7462,10 +7485,7 @@ function createConfigHandlers(config) {
7462
7485
  getStrategies: () => {
7463
7486
  return jsonResponse(LB_STRATEGIES);
7464
7487
  },
7465
- getTeamRouting: () => {
7466
- const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
7467
- return jsonResponse(routing);
7468
- },
7488
+ getTeamRouting: () => jsonResponse(publicTeamRouting(config)),
7469
7489
  setTeamRouting: async (req) => {
7470
7490
  try {
7471
7491
  const body = await parseJsonObject(req);
@@ -7473,7 +7493,7 @@ function createConfigHandlers(config) {
7473
7493
  return jsonResponse({
7474
7494
  success: true,
7475
7495
  message: "Team routing settings updated",
7476
- data: config.getTeamRouting()
7496
+ data: publicTeamRouting(config)
7477
7497
  });
7478
7498
  } catch (error) {
7479
7499
  if (error instanceof ValidationError || error instanceof Error) {
@@ -9287,22 +9307,23 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
9287
9307
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
9288
9308
  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
9309
  }
9290
- function pooledMaxUsage(provider, account2, bucket, ctx) {
9310
+ function pooledMaxUsage(provider, account2, bucket, ctx, callerId) {
9291
9311
  const teamRouting = ctx.runtime.teamRouting;
9292
9312
  if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
9293
9313
  return;
9294
9314
  if (!provider.isWeeklyBucket(bucket))
9295
9315
  return teamRouting.maxUsage;
9296
9316
  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);
9317
+ const accountOverride = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9318
+ const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
9319
+ return Math.min(teamRouting.weeklyMaxUsage, accountOverride ?? Number.POSITIVE_INFINITY, callerOverride ?? Number.POSITIVE_INFINITY);
9299
9320
  }
9300
- function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
9321
+ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
9301
9322
  const quota2 = account2.quota_state;
9302
9323
  if (!quota2)
9303
9324
  return true;
9304
9325
  for (const [name, window2] of Object.entries(quota2.windows)) {
9305
- if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx))) {
9326
+ if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, callerId))) {
9306
9327
  return false;
9307
9328
  }
9308
9329
  }
@@ -9323,23 +9344,23 @@ function cooldownEnd(account2, now) {
9323
9344
  function isServableSeat(provider, account2, model, ctx, now) {
9324
9345
  return isFleetSeat(account2, ctx) && cooldownEnd(account2, now) === null && isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9325
9346
  }
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);
9347
+ function blockingResets(provider, account2, model, ctx, now, callerId) {
9348
+ 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
9349
  }
9329
- function servableAt(provider, account2, model, ctx, now) {
9350
+ function servableAt(provider, account2, model, ctx, now, callerId) {
9330
9351
  const cooldown = cooldownEnd(account2, now);
9331
- if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
9352
+ if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId)) {
9332
9353
  return cooldown;
9333
9354
  }
9334
- const resets = blockingResets(provider, account2, model, ctx, now);
9355
+ const resets = blockingResets(provider, account2, model, ctx, now, callerId);
9335
9356
  return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
9336
9357
  }
9337
- function soonestServableAt(provider, fleet, seats, model, ctx, now) {
9338
- if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
9358
+ function soonestServableAt(provider, fleet, seats, model, ctx, now, callerId) {
9359
+ if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now, callerId).length > 0)) {
9339
9360
  return null;
9340
9361
  }
9341
9362
  const times = seats.flatMap((account2) => {
9342
- const at = servableAt(provider, account2, model, ctx, now);
9363
+ const at = servableAt(provider, account2, model, ctx, now, callerId);
9343
9364
  return at === null ? [] : [at];
9344
9365
  });
9345
9366
  return times.length > 0 ? Math.min(...times) : null;
@@ -9362,21 +9383,22 @@ function getPoolStatus(provider, model, ctx) {
9362
9383
  admissionWaitMs: config?.admissionWaitMs ?? 0
9363
9384
  };
9364
9385
  }
9365
- function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
9386
+ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
9366
9387
  const fleet = fleetAccounts(ctx.providerName, ctx);
9367
- return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
9388
+ return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now(), callerId);
9368
9389
  }
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));
9390
+ function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now(), callerId) {
9391
+ return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9371
9392
  }
9372
- function selectRevalidationProbe(accounts, ctx, now, model) {
9393
+ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
9373
9394
  const probes = ctx.quotaProbeAt;
9374
9395
  const lastProbeAt = probes?.get(ctx.providerName);
9375
9396
  if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
9376
9397
  return [];
9377
9398
  }
9378
9399
  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);
9400
+ const routing = ctx.runtime.teamRouting;
9401
+ return routing?.enabled !== true || !isAllowlisted(account2, routing) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId);
9380
9402
  }).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
9381
9403
  if (!probe)
9382
9404
  return [];
@@ -9385,9 +9407,10 @@ function selectRevalidationProbe(accounts, ctx, now, model) {
9385
9407
  }
9386
9408
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
9387
9409
  const now = Date.now();
9410
+ const callerId = teamRequest?.callerId;
9388
9411
  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);
9412
+ const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9413
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
9391
9414
  const prioritized = [...candidates].sort((left, right) => {
9392
9415
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
9393
9416
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9701,6 +9724,7 @@ class TeamAdmission {
9701
9724
  maxUsage: 0.9,
9702
9725
  weeklyMaxUsage: 0.95,
9703
9726
  weeklyMaxUsageByEmail: {},
9727
+ callerWeeklyMaxUsage: {},
9704
9728
  admissionCap: 1,
9705
9729
  admissionQueueLimit: 0,
9706
9730
  admissionWaitMs: 0,
@@ -10812,7 +10836,7 @@ var init_proxy_attempts = __esm(() => {
10812
10836
  });
10813
10837
 
10814
10838
  // ../../packages/proxy/src/handlers/proxy-request.ts
10815
- function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions) {
10839
+ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions, callerId) {
10816
10840
  const thread = parseMessageThreadRequest(body, ctx.upstreamPath, req.headers.get("content-type"), ctx.provider.getClientSessionId?.(req.headers) ?? null);
10817
10841
  const sessionId = ctx.provider.getClientSessionId?.(req.headers) ?? null;
10818
10842
  const teamRequest = teamRequestOverride ?? {
@@ -10821,7 +10845,8 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
10821
10845
  manualAccountName,
10822
10846
  model: meta.model,
10823
10847
  provider: ctx.providerName,
10824
- sessionId
10848
+ sessionId,
10849
+ callerId
10825
10850
  };
10826
10851
  const request3 = {
10827
10852
  body,
@@ -10847,7 +10872,7 @@ function selectRequestAccounts(request3, selectionOptions) {
10847
10872
  }
10848
10873
  function getRequestRetryAt(request3) {
10849
10874
  const { ctx, teamRequest } = request3;
10850
- return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10875
+ return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
10851
10876
  }
10852
10877
  var init_proxy_request = __esm(() => {
10853
10878
  init_account_selector();
@@ -10868,9 +10893,10 @@ var init_handlers = __esm(() => {
10868
10893
  });
10869
10894
 
10870
10895
  // ../../packages/proxy/src/provider-pool.ts
10871
- function poolTeamRequest(req, body, pool, requestedModel, manualAccountName) {
10896
+ function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
10872
10897
  return {
10873
10898
  body,
10899
+ callerId,
10874
10900
  contentType: req.headers.get("content-type"),
10875
10901
  manualAccountName,
10876
10902
  model: requestedModel,
@@ -10961,12 +10987,12 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10961
10987
  response: new Response("Bad Gateway", { status: 502 })
10962
10988
  };
10963
10989
  }
10964
- async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName) {
10990
+ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
10965
10991
  const firstCandidate = pool.providers[0];
10966
10992
  if (!firstCandidate) {
10967
10993
  return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
10968
10994
  }
10969
- const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName);
10995
+ const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
10970
10996
  const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10971
10997
  const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10972
10998
  const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
@@ -11579,7 +11605,7 @@ async function terminateUsageWorker() {
11579
11605
  }
11580
11606
  }
11581
11607
  }
11582
- async function handleProxy(req, url, ctx) {
11608
+ async function handleProxy(req, url, ctx, callerId) {
11583
11609
  const manualPin = manualPinFromUrl(url);
11584
11610
  if (manualPin === "invalid")
11585
11611
  return new Response("Not Found", { status: 404 });
@@ -11602,13 +11628,13 @@ async function handleProxy(req, url, ctx) {
11602
11628
  if (pool.providers.length === 0) {
11603
11629
  return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
11604
11630
  }
11605
- return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName);
11631
+ return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
11606
11632
  }
11607
11633
  const requestMeta = createRequestMetadata(req, upstreamUrl);
11608
11634
  const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
11609
11635
  const body = buffer ?? null;
11610
11636
  requestMeta.model = readRequestModel(body);
11611
- const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
11637
+ const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName, undefined, undefined, undefined, callerId);
11612
11638
  let accounts = initiallySelectedAccounts;
11613
11639
  if (accounts.length === 0) {
11614
11640
  const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
@@ -12289,7 +12315,7 @@ function isWebSocketUpgradeRequest(req) {
12289
12315
  }
12290
12316
  return connection.toLowerCase().split(",").some((value) => value.trim() === "upgrade");
12291
12317
  }
12292
- function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12318
+ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12293
12319
  if (!isWebSocketUpgradeRequest(req)) {
12294
12320
  return;
12295
12321
  }
@@ -12306,6 +12332,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12306
12332
  const teamRequest = {
12307
12333
  body: null,
12308
12334
  contentType: null,
12335
+ callerId,
12309
12336
  model: requestMeta.model,
12310
12337
  provider: requestContext.providerName,
12311
12338
  sessionId: requestContext.provider.getClientSessionId?.(req.headers) ?? null
@@ -12534,30 +12561,33 @@ import {
12534
12561
  readFileSync as readFileSync2
12535
12562
  } from "fs";
12536
12563
  import { isAbsolute as isAbsolute2 } from "path";
12537
- function deviceKeyMatches(key, path) {
12564
+ function deviceKeyName(key, path) {
12538
12565
  if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
12539
- return false;
12566
+ return;
12540
12567
  let fd;
12541
12568
  try {
12542
12569
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
12543
12570
  const stat = fstatSync(fd);
12544
12571
  if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
12545
- return false;
12572
+ return;
12546
12573
  const registry = JSON.parse(readFileSync2(fd, "utf8"));
12547
12574
  if (!registry || typeof registry !== "object" || Array.isArray(registry))
12548
- return false;
12575
+ return;
12549
12576
  const entries = Object.entries(registry);
12550
12577
  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;
12578
+ return;
12552
12579
  const digest = createHash3("sha256").update(key).digest();
12553
- return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
12580
+ return entries.find(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")))?.[0];
12554
12581
  } catch {
12555
- return false;
12582
+ return;
12556
12583
  } finally {
12557
12584
  if (fd !== undefined)
12558
12585
  closeSync(fd);
12559
12586
  }
12560
12587
  }
12588
+ function deviceKeyMatches(key, path) {
12589
+ return deviceKeyName(key, path) !== undefined;
12590
+ }
12561
12591
  var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
12562
12592
  var init_device_keys = __esm(() => {
12563
12593
  MAX_REGISTRY_BYTES = 32 * 1024;
@@ -12651,6 +12681,12 @@ function keyRole(req, url, config) {
12651
12681
  }
12652
12682
  return null;
12653
12683
  }
12684
+ function callerIdForRequest(req, url, config) {
12685
+ if (keyRole(req, url, config) !== "device")
12686
+ return;
12687
+ const apiKey = req.headers.get("x-api-key");
12688
+ return deviceKeyName(apiKey, config.clientKeysFile) ?? (isResponsesInferenceRoute(url.pathname) ? deviceKeyName(bearerToken(req), config.clientKeysFile) : undefined);
12689
+ }
12654
12690
  function hostnameFromHostHeader(host) {
12655
12691
  try {
12656
12692
  const hostname = new URL(`http://${host}`).hostname.toLowerCase();
@@ -13067,6 +13103,7 @@ function createServerFetchHandler({
13067
13103
  if (rejected) {
13068
13104
  return rejected;
13069
13105
  }
13106
+ const callerId = callerIdForRequest(req, url, exposureConfig);
13070
13107
  const apiResponse = await apiRouter.handleRequest(url, req);
13071
13108
  if (apiResponse) {
13072
13109
  return apiResponse;
@@ -13085,7 +13122,7 @@ function createServerFetchHandler({
13085
13122
  return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
13086
13123
  }
13087
13124
  if (server) {
13088
- const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
13125
+ const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server, callerId);
13089
13126
  if (websocketResponse) {
13090
13127
  return websocketResponse;
13091
13128
  }
@@ -13094,7 +13131,7 @@ function createServerFetchHandler({
13094
13131
  }
13095
13132
  }
13096
13133
  try {
13097
- return await handleProxyRequest(req, url, proxyContext);
13134
+ return await handleProxyRequest(req, url, proxyContext, callerId);
13098
13135
  } catch (error) {
13099
13136
  return errorResponse(error);
13100
13137
  }
@@ -14688,6 +14725,7 @@ function teamRoutingFileConfig(routing) {
14688
14725
  max_usage: routing.maxUsage,
14689
14726
  weekly_max_usage: routing.weeklyMaxUsage,
14690
14727
  weekly_max_usage_by_email: routing.weeklyMaxUsageByEmail,
14728
+ caller_weekly_max_usage: routing.callerWeeklyMaxUsage,
14691
14729
  admission_cap: routing.admissionCap,
14692
14730
  admission_queue_limit: routing.admissionQueueLimit,
14693
14731
  admission_wait_ms: routing.admissionWaitMs,
@@ -1659,6 +1659,12 @@ function sanitizeTeamRouting(value) {
1659
1659
  result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1660
1660
  }
1661
1661
  }
1662
+ if (isRecord(value.caller_weekly_max_usage)) {
1663
+ const entries = Object.entries(value.caller_weekly_max_usage);
1664
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
1665
+ result.caller_weekly_max_usage = Object.fromEntries(entries);
1666
+ }
1667
+ }
1662
1668
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1663
1669
  result.admission_cap = Math.floor(value.admission_cap);
1664
1670
  }
@@ -1700,7 +1706,7 @@ function clientRouting(client) {
1700
1706
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1701
1707
  };
1702
1708
  }
1703
- 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;
1709
+ 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;
1704
1710
  var init_src4 = __esm(() => {
1705
1711
  init_src2();
1706
1712
  init_src3();
@@ -1726,6 +1732,7 @@ var init_src4 = __esm(() => {
1726
1732
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1727
1733
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1728
1734
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1735
+ CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1729
1736
  TEAM_ROUTING_DEFAULTS = {
1730
1737
  enabled: false,
1731
1738
  distributionEnabled: true,
@@ -1734,6 +1741,7 @@ var init_src4 = __esm(() => {
1734
1741
  maxUsage: 0.9,
1735
1742
  weeklyMaxUsage: 0.95,
1736
1743
  weeklyMaxUsageByEmail: {},
1744
+ callerWeeklyMaxUsage: {},
1737
1745
  admissionCap: 5,
1738
1746
  admissionQueueLimit: 25,
1739
1747
  admissionWaitMs: 30000,
@@ -1896,6 +1904,7 @@ var init_src4 = __esm(() => {
1896
1904
  maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1897
1905
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1898
1906
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1907
+ callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1899
1908
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1900
1909
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1901
1910
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -1965,6 +1974,7 @@ var init_src4 = __esm(() => {
1965
1974
  "max_usage",
1966
1975
  "weekly_max_usage",
1967
1976
  "weekly_max_usage_by_email",
1977
+ "caller_weekly_max_usage",
1968
1978
  "admission_cap",
1969
1979
  "admission_queue_limit",
1970
1980
  "admission_wait_ms",
@@ -1990,6 +2000,11 @@ var init_src4 = __esm(() => {
1990
2000
  ...oldValue.weekly_max_usage_by_email
1991
2001
  };
1992
2002
  }
2003
+ if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2004
+ sanitized.caller_weekly_max_usage = {
2005
+ ...oldValue.caller_weekly_max_usage
2006
+ };
2007
+ }
1993
2008
  this.persistStrictly("team_routing", sanitized);
1994
2009
  }
1995
2010
  allowAccountUuid(accountUuid) {
package/dist/pool.js CHANGED
@@ -4376,6 +4376,12 @@ function sanitizeTeamRouting(value) {
4376
4376
  result.weekly_max_usage_by_email = Object.fromEntries(normalized);
4377
4377
  }
4378
4378
  }
4379
+ if (isRecord(value.caller_weekly_max_usage)) {
4380
+ const entries = Object.entries(value.caller_weekly_max_usage);
4381
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
4382
+ result.caller_weekly_max_usage = Object.fromEntries(entries);
4383
+ }
4384
+ }
4379
4385
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
4380
4386
  result.admission_cap = Math.floor(value.admission_cap);
4381
4387
  }
@@ -4417,7 +4423,7 @@ function clientRouting(client2) {
4417
4423
  ...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
4418
4424
  };
4419
4425
  }
4420
- var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
4426
+ var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
4421
4427
  var init_src7 = __esm(() => {
4422
4428
  init_src2();
4423
4429
  init_src4();
@@ -4443,6 +4449,7 @@ var init_src7 = __esm(() => {
4443
4449
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
4444
4450
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
4445
4451
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
4452
+ CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
4446
4453
  TEAM_ROUTING_DEFAULTS = {
4447
4454
  enabled: false,
4448
4455
  distributionEnabled: true,
@@ -4451,6 +4458,7 @@ var init_src7 = __esm(() => {
4451
4458
  maxUsage: 0.9,
4452
4459
  weeklyMaxUsage: 0.95,
4453
4460
  weeklyMaxUsageByEmail: {},
4461
+ callerWeeklyMaxUsage: {},
4454
4462
  admissionCap: 5,
4455
4463
  admissionQueueLimit: 25,
4456
4464
  admissionWaitMs: 30000,
@@ -4613,6 +4621,7 @@ var init_src7 = __esm(() => {
4613
4621
  maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
4614
4622
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
4615
4623
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
4624
+ callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
4616
4625
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
4617
4626
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
4618
4627
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -4682,6 +4691,7 @@ var init_src7 = __esm(() => {
4682
4691
  "max_usage",
4683
4692
  "weekly_max_usage",
4684
4693
  "weekly_max_usage_by_email",
4694
+ "caller_weekly_max_usage",
4685
4695
  "admission_cap",
4686
4696
  "admission_queue_limit",
4687
4697
  "admission_wait_ms",
@@ -4707,6 +4717,11 @@ var init_src7 = __esm(() => {
4707
4717
  ...oldValue.weekly_max_usage_by_email
4708
4718
  };
4709
4719
  }
4720
+ if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
4721
+ sanitized.caller_weekly_max_usage = {
4722
+ ...oldValue.caller_weekly_max_usage
4723
+ };
4724
+ }
4710
4725
  this.persistStrictly("team_routing", sanitized);
4711
4726
  }
4712
4727
  allowAccountUuid(accountUuid) {
@@ -7421,6 +7436,14 @@ var init_analytics = __esm(() => {
7421
7436
  });
7422
7437
 
7423
7438
  // ../../packages/api/src/handlers/config.ts
7439
+ function publicTeamRouting(config) {
7440
+ const {
7441
+ callerWeeklyMaxUsage: _callerWeeklyMaxUsage,
7442
+ weeklyMaxUsageByEmail: _weeklyMaxUsageByEmail,
7443
+ ...routing
7444
+ } = config.getTeamRouting();
7445
+ return routing;
7446
+ }
7424
7447
  function createConfigHandlers(config) {
7425
7448
  return {
7426
7449
  getConfig: () => {
@@ -7461,10 +7484,7 @@ function createConfigHandlers(config) {
7461
7484
  getStrategies: () => {
7462
7485
  return jsonResponse(LB_STRATEGIES);
7463
7486
  },
7464
- getTeamRouting: () => {
7465
- const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
7466
- return jsonResponse(routing);
7467
- },
7487
+ getTeamRouting: () => jsonResponse(publicTeamRouting(config)),
7468
7488
  setTeamRouting: async (req) => {
7469
7489
  try {
7470
7490
  const body = await parseJsonObject(req);
@@ -7472,7 +7492,7 @@ function createConfigHandlers(config) {
7472
7492
  return jsonResponse({
7473
7493
  success: true,
7474
7494
  message: "Team routing settings updated",
7475
- data: config.getTeamRouting()
7495
+ data: publicTeamRouting(config)
7476
7496
  });
7477
7497
  } catch (error) {
7478
7498
  if (error instanceof ValidationError || error instanceof Error) {
@@ -9286,22 +9306,23 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
9286
9306
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
9287
9307
  return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
9288
9308
  }
9289
- function pooledMaxUsage(provider, account2, bucket, ctx) {
9309
+ function pooledMaxUsage(provider, account2, bucket, ctx, callerId) {
9290
9310
  const teamRouting = ctx.runtime.teamRouting;
9291
9311
  if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
9292
9312
  return;
9293
9313
  if (!provider.isWeeklyBucket(bucket))
9294
9314
  return teamRouting.maxUsage;
9295
9315
  const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
9296
- const override = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9297
- return Math.min(teamRouting.weeklyMaxUsage, override ?? teamRouting.weeklyMaxUsage);
9316
+ const accountOverride = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9317
+ const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
9318
+ return Math.min(teamRouting.weeklyMaxUsage, accountOverride ?? Number.POSITIVE_INFINITY, callerOverride ?? Number.POSITIVE_INFINITY);
9298
9319
  }
9299
- function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
9320
+ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
9300
9321
  const quota2 = account2.quota_state;
9301
9322
  if (!quota2)
9302
9323
  return true;
9303
9324
  for (const [name, window2] of Object.entries(quota2.windows)) {
9304
- if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx))) {
9325
+ if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, callerId))) {
9305
9326
  return false;
9306
9327
  }
9307
9328
  }
@@ -9322,23 +9343,23 @@ function cooldownEnd(account2, now) {
9322
9343
  function isServableSeat(provider, account2, model, ctx, now) {
9323
9344
  return isFleetSeat(account2, ctx) && cooldownEnd(account2, now) === null && isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9324
9345
  }
9325
- function blockingResets(provider, account2, model, ctx, now) {
9326
- return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket, ctx))).map(([, window2]) => window2.resetAt);
9346
+ function blockingResets(provider, account2, model, ctx, now, callerId) {
9347
+ return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket, ctx, callerId))).map(([, window2]) => window2.resetAt);
9327
9348
  }
9328
- function servableAt(provider, account2, model, ctx, now) {
9349
+ function servableAt(provider, account2, model, ctx, now, callerId) {
9329
9350
  const cooldown = cooldownEnd(account2, now);
9330
- if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
9351
+ if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId)) {
9331
9352
  return cooldown;
9332
9353
  }
9333
- const resets = blockingResets(provider, account2, model, ctx, now);
9354
+ const resets = blockingResets(provider, account2, model, ctx, now, callerId);
9334
9355
  return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
9335
9356
  }
9336
- function soonestServableAt(provider, fleet, seats, model, ctx, now) {
9337
- if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
9357
+ function soonestServableAt(provider, fleet, seats, model, ctx, now, callerId) {
9358
+ if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now, callerId).length > 0)) {
9338
9359
  return null;
9339
9360
  }
9340
9361
  const times = seats.flatMap((account2) => {
9341
- const at = servableAt(provider, account2, model, ctx, now);
9362
+ const at = servableAt(provider, account2, model, ctx, now, callerId);
9342
9363
  return at === null ? [] : [at];
9343
9364
  });
9344
9365
  return times.length > 0 ? Math.min(...times) : null;
@@ -9361,21 +9382,22 @@ function getPoolStatus(provider, model, ctx) {
9361
9382
  admissionWaitMs: config?.admissionWaitMs ?? 0
9362
9383
  };
9363
9384
  }
9364
- function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
9385
+ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
9365
9386
  const fleet = fleetAccounts(ctx.providerName, ctx);
9366
- return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
9387
+ return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now(), callerId);
9367
9388
  }
9368
- function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
9369
- return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
9389
+ function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now(), callerId) {
9390
+ return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9370
9391
  }
9371
- function selectRevalidationProbe(accounts, ctx, now, model) {
9392
+ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
9372
9393
  const probes = ctx.quotaProbeAt;
9373
9394
  const lastProbeAt = probes?.get(ctx.providerName);
9374
9395
  if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
9375
9396
  return [];
9376
9397
  }
9377
9398
  const [probe] = accounts.filter((account2) => {
9378
- return ctx.runtime.teamRouting?.enabled !== true || !isAllowlisted(account2, ctx.runtime.teamRouting) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9399
+ const routing = ctx.runtime.teamRouting;
9400
+ return routing?.enabled !== true || !isAllowlisted(account2, routing) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId);
9379
9401
  }).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
9380
9402
  if (!probe)
9381
9403
  return [];
@@ -9384,9 +9406,10 @@ function selectRevalidationProbe(accounts, ctx, now, model) {
9384
9406
  }
9385
9407
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
9386
9408
  const now = Date.now();
9409
+ const callerId = teamRequest?.callerId;
9387
9410
  const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
9388
- const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
9389
- const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model);
9411
+ const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9412
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
9390
9413
  const prioritized = [...candidates].sort((left, right) => {
9391
9414
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
9392
9415
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9700,6 +9723,7 @@ class TeamAdmission {
9700
9723
  maxUsage: 0.9,
9701
9724
  weeklyMaxUsage: 0.95,
9702
9725
  weeklyMaxUsageByEmail: {},
9726
+ callerWeeklyMaxUsage: {},
9703
9727
  admissionCap: 1,
9704
9728
  admissionQueueLimit: 0,
9705
9729
  admissionWaitMs: 0,
@@ -10811,7 +10835,7 @@ var init_proxy_attempts = __esm(() => {
10811
10835
  });
10812
10836
 
10813
10837
  // ../../packages/proxy/src/handlers/proxy-request.ts
10814
- function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions) {
10838
+ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions, callerId) {
10815
10839
  const thread = parseMessageThreadRequest(body, ctx.upstreamPath, req.headers.get("content-type"), ctx.provider.getClientSessionId?.(req.headers) ?? null);
10816
10840
  const sessionId = ctx.provider.getClientSessionId?.(req.headers) ?? null;
10817
10841
  const teamRequest = teamRequestOverride ?? {
@@ -10820,7 +10844,8 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
10820
10844
  manualAccountName,
10821
10845
  model: meta.model,
10822
10846
  provider: ctx.providerName,
10823
- sessionId
10847
+ sessionId,
10848
+ callerId
10824
10849
  };
10825
10850
  const request3 = {
10826
10851
  body,
@@ -10846,7 +10871,7 @@ function selectRequestAccounts(request3, selectionOptions) {
10846
10871
  }
10847
10872
  function getRequestRetryAt(request3) {
10848
10873
  const { ctx, teamRequest } = request3;
10849
- return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10874
+ return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
10850
10875
  }
10851
10876
  var init_proxy_request = __esm(() => {
10852
10877
  init_account_selector();
@@ -10867,9 +10892,10 @@ var init_handlers = __esm(() => {
10867
10892
  });
10868
10893
 
10869
10894
  // ../../packages/proxy/src/provider-pool.ts
10870
- function poolTeamRequest(req, body, pool, requestedModel, manualAccountName) {
10895
+ function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
10871
10896
  return {
10872
10897
  body,
10898
+ callerId,
10873
10899
  contentType: req.headers.get("content-type"),
10874
10900
  manualAccountName,
10875
10901
  model: requestedModel,
@@ -10960,12 +10986,12 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10960
10986
  response: new Response("Bad Gateway", { status: 502 })
10961
10987
  };
10962
10988
  }
10963
- async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName) {
10989
+ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
10964
10990
  const firstCandidate = pool.providers[0];
10965
10991
  if (!firstCandidate) {
10966
10992
  return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
10967
10993
  }
10968
- const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName);
10994
+ const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
10969
10995
  const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10970
10996
  const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10971
10997
  const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
@@ -11578,7 +11604,7 @@ async function terminateUsageWorker() {
11578
11604
  }
11579
11605
  }
11580
11606
  }
11581
- async function handleProxy(req, url, ctx) {
11607
+ async function handleProxy(req, url, ctx, callerId) {
11582
11608
  const manualPin = manualPinFromUrl(url);
11583
11609
  if (manualPin === "invalid")
11584
11610
  return new Response("Not Found", { status: 404 });
@@ -11601,13 +11627,13 @@ async function handleProxy(req, url, ctx) {
11601
11627
  if (pool.providers.length === 0) {
11602
11628
  return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
11603
11629
  }
11604
- return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName);
11630
+ return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
11605
11631
  }
11606
11632
  const requestMeta = createRequestMetadata(req, upstreamUrl);
11607
11633
  const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
11608
11634
  const body = buffer ?? null;
11609
11635
  requestMeta.model = readRequestModel(body);
11610
- const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
11636
+ const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName, undefined, undefined, undefined, callerId);
11611
11637
  let accounts = initiallySelectedAccounts;
11612
11638
  if (accounts.length === 0) {
11613
11639
  const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
@@ -12288,7 +12314,7 @@ function isWebSocketUpgradeRequest(req) {
12288
12314
  }
12289
12315
  return connection.toLowerCase().split(",").some((value) => value.trim() === "upgrade");
12290
12316
  }
12291
- function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12317
+ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12292
12318
  if (!isWebSocketUpgradeRequest(req)) {
12293
12319
  return;
12294
12320
  }
@@ -12305,6 +12331,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12305
12331
  const teamRequest = {
12306
12332
  body: null,
12307
12333
  contentType: null,
12334
+ callerId,
12308
12335
  model: requestMeta.model,
12309
12336
  provider: requestContext.providerName,
12310
12337
  sessionId: requestContext.provider.getClientSessionId?.(req.headers) ?? null
@@ -12533,30 +12560,33 @@ import {
12533
12560
  readFileSync as readFileSync2
12534
12561
  } from "fs";
12535
12562
  import { isAbsolute as isAbsolute2 } from "path";
12536
- function deviceKeyMatches(key, path) {
12563
+ function deviceKeyName(key, path) {
12537
12564
  if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
12538
- return false;
12565
+ return;
12539
12566
  let fd;
12540
12567
  try {
12541
12568
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
12542
12569
  const stat = fstatSync(fd);
12543
12570
  if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
12544
- return false;
12571
+ return;
12545
12572
  const registry = JSON.parse(readFileSync2(fd, "utf8"));
12546
12573
  if (!registry || typeof registry !== "object" || Array.isArray(registry))
12547
- return false;
12574
+ return;
12548
12575
  const entries = Object.entries(registry);
12549
12576
  if (entries.length > MAX_DEVICES || entries.some(([name, digest2]) => !/^[-a-zA-Z0-9_]{1,64}$/.test(name) || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/.test(digest2)))
12550
- return false;
12577
+ return;
12551
12578
  const digest = createHash3("sha256").update(key).digest();
12552
- return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
12579
+ return entries.find(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")))?.[0];
12553
12580
  } catch {
12554
- return false;
12581
+ return;
12555
12582
  } finally {
12556
12583
  if (fd !== undefined)
12557
12584
  closeSync(fd);
12558
12585
  }
12559
12586
  }
12587
+ function deviceKeyMatches(key, path) {
12588
+ return deviceKeyName(key, path) !== undefined;
12589
+ }
12560
12590
  var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
12561
12591
  var init_device_keys = __esm(() => {
12562
12592
  MAX_REGISTRY_BYTES = 32 * 1024;
@@ -12650,6 +12680,12 @@ function keyRole(req, url, config) {
12650
12680
  }
12651
12681
  return null;
12652
12682
  }
12683
+ function callerIdForRequest(req, url, config) {
12684
+ if (keyRole(req, url, config) !== "device")
12685
+ return;
12686
+ const apiKey = req.headers.get("x-api-key");
12687
+ return deviceKeyName(apiKey, config.clientKeysFile) ?? (isResponsesInferenceRoute(url.pathname) ? deviceKeyName(bearerToken(req), config.clientKeysFile) : undefined);
12688
+ }
12653
12689
  function hostnameFromHostHeader(host) {
12654
12690
  try {
12655
12691
  const hostname = new URL(`http://${host}`).hostname.toLowerCase();
@@ -13066,6 +13102,7 @@ function createServerFetchHandler({
13066
13102
  if (rejected) {
13067
13103
  return rejected;
13068
13104
  }
13105
+ const callerId = callerIdForRequest(req, url, exposureConfig);
13069
13106
  const apiResponse = await apiRouter.handleRequest(url, req);
13070
13107
  if (apiResponse) {
13071
13108
  return apiResponse;
@@ -13084,7 +13121,7 @@ function createServerFetchHandler({
13084
13121
  return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
13085
13122
  }
13086
13123
  if (server) {
13087
- const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
13124
+ const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server, callerId);
13088
13125
  if (websocketResponse) {
13089
13126
  return websocketResponse;
13090
13127
  }
@@ -13093,7 +13130,7 @@ function createServerFetchHandler({
13093
13130
  }
13094
13131
  }
13095
13132
  try {
13096
- return await handleProxyRequest(req, url, proxyContext);
13133
+ return await handleProxyRequest(req, url, proxyContext, callerId);
13097
13134
  } catch (error) {
13098
13135
  return errorResponse(error);
13099
13136
  }
@@ -1712,6 +1712,12 @@ function sanitizeTeamRouting(value) {
1712
1712
  result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1713
1713
  }
1714
1714
  }
1715
+ if (isRecord(value.caller_weekly_max_usage)) {
1716
+ const entries = Object.entries(value.caller_weekly_max_usage);
1717
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
1718
+ result.caller_weekly_max_usage = Object.fromEntries(entries);
1719
+ }
1720
+ }
1715
1721
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1716
1722
  result.admission_cap = Math.floor(value.admission_cap);
1717
1723
  }
@@ -1753,7 +1759,7 @@ function clientRouting(client) {
1753
1759
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1754
1760
  };
1755
1761
  }
1756
- 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;
1762
+ 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;
1757
1763
  var init_src4 = __esm(() => {
1758
1764
  init_src2();
1759
1765
  init_src3();
@@ -1779,6 +1785,7 @@ var init_src4 = __esm(() => {
1779
1785
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1780
1786
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1781
1787
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1788
+ CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1782
1789
  TEAM_ROUTING_DEFAULTS = {
1783
1790
  enabled: false,
1784
1791
  distributionEnabled: true,
@@ -1787,6 +1794,7 @@ var init_src4 = __esm(() => {
1787
1794
  maxUsage: 0.9,
1788
1795
  weeklyMaxUsage: 0.95,
1789
1796
  weeklyMaxUsageByEmail: {},
1797
+ callerWeeklyMaxUsage: {},
1790
1798
  admissionCap: 5,
1791
1799
  admissionQueueLimit: 25,
1792
1800
  admissionWaitMs: 30000,
@@ -1949,6 +1957,7 @@ var init_src4 = __esm(() => {
1949
1957
  maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1950
1958
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1951
1959
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1960
+ callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1952
1961
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1953
1962
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1954
1963
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -2018,6 +2027,7 @@ var init_src4 = __esm(() => {
2018
2027
  "max_usage",
2019
2028
  "weekly_max_usage",
2020
2029
  "weekly_max_usage_by_email",
2030
+ "caller_weekly_max_usage",
2021
2031
  "admission_cap",
2022
2032
  "admission_queue_limit",
2023
2033
  "admission_wait_ms",
@@ -2043,6 +2053,11 @@ var init_src4 = __esm(() => {
2043
2053
  ...oldValue.weekly_max_usage_by_email
2044
2054
  };
2045
2055
  }
2056
+ if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2057
+ sanitized.caller_weekly_max_usage = {
2058
+ ...oldValue.caller_weekly_max_usage
2059
+ };
2060
+ }
2046
2061
  this.persistStrictly("team_routing", sanitized);
2047
2062
  }
2048
2063
  allowAccountUuid(accountUuid) {
package/dist/server.js CHANGED
@@ -4376,6 +4376,12 @@ function sanitizeTeamRouting(value) {
4376
4376
  result.weekly_max_usage_by_email = Object.fromEntries(normalized);
4377
4377
  }
4378
4378
  }
4379
+ if (isRecord(value.caller_weekly_max_usage)) {
4380
+ const entries = Object.entries(value.caller_weekly_max_usage);
4381
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
4382
+ result.caller_weekly_max_usage = Object.fromEntries(entries);
4383
+ }
4384
+ }
4379
4385
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
4380
4386
  result.admission_cap = Math.floor(value.admission_cap);
4381
4387
  }
@@ -4417,7 +4423,7 @@ function clientRouting(client2) {
4417
4423
  ...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
4418
4424
  };
4419
4425
  }
4420
- var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
4426
+ var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
4421
4427
  var init_src7 = __esm(() => {
4422
4428
  init_src2();
4423
4429
  init_src4();
@@ -4443,6 +4449,7 @@ var init_src7 = __esm(() => {
4443
4449
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
4444
4450
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
4445
4451
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
4452
+ CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
4446
4453
  TEAM_ROUTING_DEFAULTS = {
4447
4454
  enabled: false,
4448
4455
  distributionEnabled: true,
@@ -4451,6 +4458,7 @@ var init_src7 = __esm(() => {
4451
4458
  maxUsage: 0.9,
4452
4459
  weeklyMaxUsage: 0.95,
4453
4460
  weeklyMaxUsageByEmail: {},
4461
+ callerWeeklyMaxUsage: {},
4454
4462
  admissionCap: 5,
4455
4463
  admissionQueueLimit: 25,
4456
4464
  admissionWaitMs: 30000,
@@ -4613,6 +4621,7 @@ var init_src7 = __esm(() => {
4613
4621
  maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
4614
4622
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
4615
4623
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
4624
+ callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
4616
4625
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
4617
4626
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
4618
4627
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -4682,6 +4691,7 @@ var init_src7 = __esm(() => {
4682
4691
  "max_usage",
4683
4692
  "weekly_max_usage",
4684
4693
  "weekly_max_usage_by_email",
4694
+ "caller_weekly_max_usage",
4685
4695
  "admission_cap",
4686
4696
  "admission_queue_limit",
4687
4697
  "admission_wait_ms",
@@ -4707,6 +4717,11 @@ var init_src7 = __esm(() => {
4707
4717
  ...oldValue.weekly_max_usage_by_email
4708
4718
  };
4709
4719
  }
4720
+ if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
4721
+ sanitized.caller_weekly_max_usage = {
4722
+ ...oldValue.caller_weekly_max_usage
4723
+ };
4724
+ }
4710
4725
  this.persistStrictly("team_routing", sanitized);
4711
4726
  }
4712
4727
  allowAccountUuid(accountUuid) {
@@ -7421,6 +7436,14 @@ var init_analytics = __esm(() => {
7421
7436
  });
7422
7437
 
7423
7438
  // ../../packages/api/src/handlers/config.ts
7439
+ function publicTeamRouting(config) {
7440
+ const {
7441
+ callerWeeklyMaxUsage: _callerWeeklyMaxUsage,
7442
+ weeklyMaxUsageByEmail: _weeklyMaxUsageByEmail,
7443
+ ...routing
7444
+ } = config.getTeamRouting();
7445
+ return routing;
7446
+ }
7424
7447
  function createConfigHandlers(config) {
7425
7448
  return {
7426
7449
  getConfig: () => {
@@ -7461,10 +7484,7 @@ function createConfigHandlers(config) {
7461
7484
  getStrategies: () => {
7462
7485
  return jsonResponse(LB_STRATEGIES);
7463
7486
  },
7464
- getTeamRouting: () => {
7465
- const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
7466
- return jsonResponse(routing);
7467
- },
7487
+ getTeamRouting: () => jsonResponse(publicTeamRouting(config)),
7468
7488
  setTeamRouting: async (req) => {
7469
7489
  try {
7470
7490
  const body = await parseJsonObject(req);
@@ -7472,7 +7492,7 @@ function createConfigHandlers(config) {
7472
7492
  return jsonResponse({
7473
7493
  success: true,
7474
7494
  message: "Team routing settings updated",
7475
- data: config.getTeamRouting()
7495
+ data: publicTeamRouting(config)
7476
7496
  });
7477
7497
  } catch (error) {
7478
7498
  if (error instanceof ValidationError || error instanceof Error) {
@@ -9286,22 +9306,23 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
9286
9306
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
9287
9307
  return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
9288
9308
  }
9289
- function pooledMaxUsage(provider, account2, bucket, ctx) {
9309
+ function pooledMaxUsage(provider, account2, bucket, ctx, callerId) {
9290
9310
  const teamRouting = ctx.runtime.teamRouting;
9291
9311
  if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
9292
9312
  return;
9293
9313
  if (!provider.isWeeklyBucket(bucket))
9294
9314
  return teamRouting.maxUsage;
9295
9315
  const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
9296
- const override = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9297
- return Math.min(teamRouting.weeklyMaxUsage, override ?? teamRouting.weeklyMaxUsage);
9316
+ const accountOverride = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9317
+ const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
9318
+ return Math.min(teamRouting.weeklyMaxUsage, accountOverride ?? Number.POSITIVE_INFINITY, callerOverride ?? Number.POSITIVE_INFINITY);
9298
9319
  }
9299
- function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
9320
+ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
9300
9321
  const quota2 = account2.quota_state;
9301
9322
  if (!quota2)
9302
9323
  return true;
9303
9324
  for (const [name, window2] of Object.entries(quota2.windows)) {
9304
- if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx))) {
9325
+ if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, callerId))) {
9305
9326
  return false;
9306
9327
  }
9307
9328
  }
@@ -9322,23 +9343,23 @@ function cooldownEnd(account2, now) {
9322
9343
  function isServableSeat(provider, account2, model, ctx, now) {
9323
9344
  return isFleetSeat(account2, ctx) && cooldownEnd(account2, now) === null && isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9324
9345
  }
9325
- function blockingResets(provider, account2, model, ctx, now) {
9326
- return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket, ctx))).map(([, window2]) => window2.resetAt);
9346
+ function blockingResets(provider, account2, model, ctx, now, callerId) {
9347
+ return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket, ctx, callerId))).map(([, window2]) => window2.resetAt);
9327
9348
  }
9328
- function servableAt(provider, account2, model, ctx, now) {
9349
+ function servableAt(provider, account2, model, ctx, now, callerId) {
9329
9350
  const cooldown = cooldownEnd(account2, now);
9330
- if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
9351
+ if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId)) {
9331
9352
  return cooldown;
9332
9353
  }
9333
- const resets = blockingResets(provider, account2, model, ctx, now);
9354
+ const resets = blockingResets(provider, account2, model, ctx, now, callerId);
9334
9355
  return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
9335
9356
  }
9336
- function soonestServableAt(provider, fleet, seats, model, ctx, now) {
9337
- if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
9357
+ function soonestServableAt(provider, fleet, seats, model, ctx, now, callerId) {
9358
+ if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now, callerId).length > 0)) {
9338
9359
  return null;
9339
9360
  }
9340
9361
  const times = seats.flatMap((account2) => {
9341
- const at = servableAt(provider, account2, model, ctx, now);
9362
+ const at = servableAt(provider, account2, model, ctx, now, callerId);
9342
9363
  return at === null ? [] : [at];
9343
9364
  });
9344
9365
  return times.length > 0 ? Math.min(...times) : null;
@@ -9361,21 +9382,22 @@ function getPoolStatus(provider, model, ctx) {
9361
9382
  admissionWaitMs: config?.admissionWaitMs ?? 0
9362
9383
  };
9363
9384
  }
9364
- function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
9385
+ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
9365
9386
  const fleet = fleetAccounts(ctx.providerName, ctx);
9366
- return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
9387
+ return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now(), callerId);
9367
9388
  }
9368
- function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
9369
- return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
9389
+ function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now(), callerId) {
9390
+ return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9370
9391
  }
9371
- function selectRevalidationProbe(accounts, ctx, now, model) {
9392
+ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
9372
9393
  const probes = ctx.quotaProbeAt;
9373
9394
  const lastProbeAt = probes?.get(ctx.providerName);
9374
9395
  if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
9375
9396
  return [];
9376
9397
  }
9377
9398
  const [probe] = accounts.filter((account2) => {
9378
- return ctx.runtime.teamRouting?.enabled !== true || !isAllowlisted(account2, ctx.runtime.teamRouting) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9399
+ const routing = ctx.runtime.teamRouting;
9400
+ return routing?.enabled !== true || !isAllowlisted(account2, routing) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId);
9379
9401
  }).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
9380
9402
  if (!probe)
9381
9403
  return [];
@@ -9384,9 +9406,10 @@ function selectRevalidationProbe(accounts, ctx, now, model) {
9384
9406
  }
9385
9407
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
9386
9408
  const now = Date.now();
9409
+ const callerId = teamRequest?.callerId;
9387
9410
  const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
9388
- const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
9389
- const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model);
9411
+ const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
9412
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
9390
9413
  const prioritized = [...candidates].sort((left, right) => {
9391
9414
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
9392
9415
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9700,6 +9723,7 @@ class TeamAdmission {
9700
9723
  maxUsage: 0.9,
9701
9724
  weeklyMaxUsage: 0.95,
9702
9725
  weeklyMaxUsageByEmail: {},
9726
+ callerWeeklyMaxUsage: {},
9703
9727
  admissionCap: 1,
9704
9728
  admissionQueueLimit: 0,
9705
9729
  admissionWaitMs: 0,
@@ -10811,7 +10835,7 @@ var init_proxy_attempts = __esm(() => {
10811
10835
  });
10812
10836
 
10813
10837
  // ../../packages/proxy/src/handlers/proxy-request.ts
10814
- function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions) {
10838
+ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamRequestOverride, mappedModel = undefined, selectionOptions, callerId) {
10815
10839
  const thread = parseMessageThreadRequest(body, ctx.upstreamPath, req.headers.get("content-type"), ctx.provider.getClientSessionId?.(req.headers) ?? null);
10816
10840
  const sessionId = ctx.provider.getClientSessionId?.(req.headers) ?? null;
10817
10841
  const teamRequest = teamRequestOverride ?? {
@@ -10820,7 +10844,8 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
10820
10844
  manualAccountName,
10821
10845
  model: meta.model,
10822
10846
  provider: ctx.providerName,
10823
- sessionId
10847
+ sessionId,
10848
+ callerId
10824
10849
  };
10825
10850
  const request3 = {
10826
10851
  body,
@@ -10846,7 +10871,7 @@ function selectRequestAccounts(request3, selectionOptions) {
10846
10871
  }
10847
10872
  function getRequestRetryAt(request3) {
10848
10873
  const { ctx, teamRequest } = request3;
10849
- return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10874
+ return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
10850
10875
  }
10851
10876
  var init_proxy_request = __esm(() => {
10852
10877
  init_account_selector();
@@ -10867,9 +10892,10 @@ var init_handlers = __esm(() => {
10867
10892
  });
10868
10893
 
10869
10894
  // ../../packages/proxy/src/provider-pool.ts
10870
- function poolTeamRequest(req, body, pool, requestedModel, manualAccountName) {
10895
+ function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
10871
10896
  return {
10872
10897
  body,
10898
+ callerId,
10873
10899
  contentType: req.headers.get("content-type"),
10874
10900
  manualAccountName,
10875
10901
  model: requestedModel,
@@ -10960,12 +10986,12 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10960
10986
  response: new Response("Bad Gateway", { status: 502 })
10961
10987
  };
10962
10988
  }
10963
- async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName) {
10989
+ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
10964
10990
  const firstCandidate = pool.providers[0];
10965
10991
  if (!firstCandidate) {
10966
10992
  return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
10967
10993
  }
10968
- const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName);
10994
+ const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
10969
10995
  const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10970
10996
  const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10971
10997
  const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
@@ -11578,7 +11604,7 @@ async function terminateUsageWorker() {
11578
11604
  }
11579
11605
  }
11580
11606
  }
11581
- async function handleProxy(req, url, ctx) {
11607
+ async function handleProxy(req, url, ctx, callerId) {
11582
11608
  const manualPin = manualPinFromUrl(url);
11583
11609
  if (manualPin === "invalid")
11584
11610
  return new Response("Not Found", { status: 404 });
@@ -11601,13 +11627,13 @@ async function handleProxy(req, url, ctx) {
11601
11627
  if (pool.providers.length === 0) {
11602
11628
  return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
11603
11629
  }
11604
- return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName);
11630
+ return await proxyProviderPool(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
11605
11631
  }
11606
11632
  const requestMeta = createRequestMetadata(req, upstreamUrl);
11607
11633
  const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
11608
11634
  const body = buffer ?? null;
11609
11635
  requestMeta.model = readRequestModel(body);
11610
- const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
11636
+ const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName, undefined, undefined, undefined, callerId);
11611
11637
  let accounts = initiallySelectedAccounts;
11612
11638
  if (accounts.length === 0) {
11613
11639
  const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
@@ -12288,7 +12314,7 @@ function isWebSocketUpgradeRequest(req) {
12288
12314
  }
12289
12315
  return connection.toLowerCase().split(",").some((value) => value.trim() === "upgrade");
12290
12316
  }
12291
- function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12317
+ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12292
12318
  if (!isWebSocketUpgradeRequest(req)) {
12293
12319
  return;
12294
12320
  }
@@ -12305,6 +12331,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
12305
12331
  const teamRequest = {
12306
12332
  body: null,
12307
12333
  contentType: null,
12334
+ callerId,
12308
12335
  model: requestMeta.model,
12309
12336
  provider: requestContext.providerName,
12310
12337
  sessionId: requestContext.provider.getClientSessionId?.(req.headers) ?? null
@@ -12533,30 +12560,33 @@ import {
12533
12560
  readFileSync as readFileSync2
12534
12561
  } from "fs";
12535
12562
  import { isAbsolute as isAbsolute2 } from "path";
12536
- function deviceKeyMatches(key, path) {
12563
+ function deviceKeyName(key, path) {
12537
12564
  if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
12538
- return false;
12565
+ return;
12539
12566
  let fd;
12540
12567
  try {
12541
12568
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
12542
12569
  const stat = fstatSync(fd);
12543
12570
  if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
12544
- return false;
12571
+ return;
12545
12572
  const registry = JSON.parse(readFileSync2(fd, "utf8"));
12546
12573
  if (!registry || typeof registry !== "object" || Array.isArray(registry))
12547
- return false;
12574
+ return;
12548
12575
  const entries = Object.entries(registry);
12549
12576
  if (entries.length > MAX_DEVICES || entries.some(([name, digest2]) => !/^[-a-zA-Z0-9_]{1,64}$/.test(name) || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/.test(digest2)))
12550
- return false;
12577
+ return;
12551
12578
  const digest = createHash3("sha256").update(key).digest();
12552
- return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
12579
+ return entries.find(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")))?.[0];
12553
12580
  } catch {
12554
- return false;
12581
+ return;
12555
12582
  } finally {
12556
12583
  if (fd !== undefined)
12557
12584
  closeSync(fd);
12558
12585
  }
12559
12586
  }
12587
+ function deviceKeyMatches(key, path) {
12588
+ return deviceKeyName(key, path) !== undefined;
12589
+ }
12560
12590
  var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
12561
12591
  var init_device_keys = __esm(() => {
12562
12592
  MAX_REGISTRY_BYTES = 32 * 1024;
@@ -12650,6 +12680,12 @@ function keyRole(req, url, config) {
12650
12680
  }
12651
12681
  return null;
12652
12682
  }
12683
+ function callerIdForRequest(req, url, config) {
12684
+ if (keyRole(req, url, config) !== "device")
12685
+ return;
12686
+ const apiKey = req.headers.get("x-api-key");
12687
+ return deviceKeyName(apiKey, config.clientKeysFile) ?? (isResponsesInferenceRoute(url.pathname) ? deviceKeyName(bearerToken(req), config.clientKeysFile) : undefined);
12688
+ }
12653
12689
  function hostnameFromHostHeader(host) {
12654
12690
  try {
12655
12691
  const hostname = new URL(`http://${host}`).hostname.toLowerCase();
@@ -13066,6 +13102,7 @@ function createServerFetchHandler({
13066
13102
  if (rejected) {
13067
13103
  return rejected;
13068
13104
  }
13105
+ const callerId = callerIdForRequest(req, url, exposureConfig);
13069
13106
  const apiResponse = await apiRouter.handleRequest(url, req);
13070
13107
  if (apiResponse) {
13071
13108
  return apiResponse;
@@ -13084,7 +13121,7 @@ function createServerFetchHandler({
13084
13121
  return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
13085
13122
  }
13086
13123
  if (server) {
13087
- const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
13124
+ const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server, callerId);
13088
13125
  if (websocketResponse) {
13089
13126
  return websocketResponse;
13090
13127
  }
@@ -13093,7 +13130,7 @@ function createServerFetchHandler({
13093
13130
  }
13094
13131
  }
13095
13132
  try {
13096
- return await handleProxyRequest(req, url, proxyContext);
13133
+ return await handleProxyRequest(req, url, proxyContext, callerId);
13097
13134
  } catch (error) {
13098
13135
  return errorResponse(error);
13099
13136
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@certalis/agent-smith",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "description": "PROOF OF CONCEPT for ideation only: an experimental local proxy and provider pool for Claude Code and Codex",
5
5
  "license": "MIT",
6
6
  "author": "Certalis",