@certalis/agent-smith 0.2.0 → 0.3.0

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/pool.js CHANGED
@@ -4679,6 +4679,198 @@ var init_builtin_providers = __esm(() => {
4679
4679
  ];
4680
4680
  });
4681
4681
 
4682
+ // ../../packages/config/src/zoned-time.ts
4683
+ function isTimeZone(value) {
4684
+ if (typeof value !== "string" || value.length === 0 || value.length > 64) {
4685
+ return false;
4686
+ }
4687
+ try {
4688
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
4689
+ return true;
4690
+ } catch {
4691
+ return false;
4692
+ }
4693
+ }
4694
+ function localTimeOfDayMs(time) {
4695
+ const [hour = 0, minute = 0] = time.split(":").map(Number);
4696
+ return hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE;
4697
+ }
4698
+ function wallClockFormat(timeZone) {
4699
+ let format = wallClockFormats.get(timeZone);
4700
+ if (!format) {
4701
+ format = new Intl.DateTimeFormat("en-US", {
4702
+ timeZone,
4703
+ hourCycle: "h23",
4704
+ year: "numeric",
4705
+ month: "numeric",
4706
+ day: "numeric",
4707
+ hour: "numeric",
4708
+ minute: "numeric",
4709
+ second: "numeric"
4710
+ });
4711
+ wallClockFormats.set(timeZone, format);
4712
+ }
4713
+ return format;
4714
+ }
4715
+ function wallClock(at, timeZone) {
4716
+ const parts = wallClockFormat(timeZone).formatToParts(at);
4717
+ const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
4718
+ return {
4719
+ year: part("year"),
4720
+ month: part("month"),
4721
+ day: part("day"),
4722
+ hour: part("hour") % 24,
4723
+ minute: part("minute"),
4724
+ second: part("second")
4725
+ };
4726
+ }
4727
+ function zoneOffsetMs(at, timeZone) {
4728
+ const wall = wallClock(at, timeZone);
4729
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
4730
+ }
4731
+ function zonedInstant(wall, timeZone) {
4732
+ return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
4733
+ }
4734
+ var LOCAL_TIME, wallClockFormats;
4735
+ var init_zoned_time = __esm(() => {
4736
+ init_src2();
4737
+ LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
4738
+ wallClockFormats = new Map;
4739
+ });
4740
+
4741
+ // ../../packages/config/src/night-pacing.ts
4742
+ function localHours(value) {
4743
+ if (!isRecord(value) || Object.keys(value).length !== 2 || typeof value.start !== "string" || typeof value.end !== "string" || !LOCAL_TIME.test(value.start) || !LOCAL_TIME.test(value.end) || value.start === value.end) {
4744
+ return;
4745
+ }
4746
+ return { start: value.start, end: value.end };
4747
+ }
4748
+ function isWorkingDays(value) {
4749
+ return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length && value.every((day) => typeof day === "string" && WEEKDAYS.includes(day));
4750
+ }
4751
+ function sanitizeNightPacing(value) {
4752
+ if (!isRecord(value) || Object.keys(value).some((key) => !NIGHT_PACING_FIELDS.has(key))) {
4753
+ return;
4754
+ }
4755
+ const result = {};
4756
+ if (value.time_zone !== undefined) {
4757
+ if (!isTimeZone(value.time_zone))
4758
+ return;
4759
+ result.time_zone = value.time_zone;
4760
+ }
4761
+ if (value.working_days !== undefined) {
4762
+ if (!isWorkingDays(value.working_days))
4763
+ return;
4764
+ result.working_days = [...value.working_days];
4765
+ }
4766
+ if (value.working_hours !== undefined) {
4767
+ const hours = localHours(value.working_hours);
4768
+ if (!hours || hours.start > hours.end)
4769
+ return;
4770
+ result.working_hours = hours;
4771
+ }
4772
+ if (value.night_hours !== undefined) {
4773
+ const hours = localHours(value.night_hours);
4774
+ if (!hours)
4775
+ return;
4776
+ result.night_hours = hours;
4777
+ }
4778
+ if (value.margin_working_days !== undefined) {
4779
+ if (!isFiniteNumber(value.margin_working_days) || value.margin_working_days < 0 || value.margin_working_days > 7) {
4780
+ return;
4781
+ }
4782
+ result.margin_working_days = value.margin_working_days;
4783
+ }
4784
+ if (value.use_up_before !== undefined) {
4785
+ if (typeof value.use_up_before !== "string" || !LOCAL_TIME.test(value.use_up_before)) {
4786
+ return;
4787
+ }
4788
+ result.use_up_before = value.use_up_before;
4789
+ }
4790
+ return result;
4791
+ }
4792
+ function nightPacingSettings(file) {
4793
+ return {
4794
+ timeZone: file.time_zone ?? NIGHT_PACING_DEFAULTS.timeZone,
4795
+ workingDays: [...file.working_days ?? NIGHT_PACING_DEFAULTS.workingDays],
4796
+ workingHours: {
4797
+ ...file.working_hours ?? NIGHT_PACING_DEFAULTS.workingHours
4798
+ },
4799
+ nightHours: { ...file.night_hours ?? NIGHT_PACING_DEFAULTS.nightHours },
4800
+ marginWorkingDays: file.margin_working_days ?? NIGHT_PACING_DEFAULTS.marginWorkingDays,
4801
+ useUpBefore: file.use_up_before ?? NIGHT_PACING_DEFAULTS.useUpBefore
4802
+ };
4803
+ }
4804
+ function localDay(at, timeZone) {
4805
+ const wall = wallClock(at, timeZone);
4806
+ return {
4807
+ day: Date.UTC(wall.year, wall.month - 1, wall.day),
4808
+ timeOfDay: wall.hour * TIME_CONSTANTS.HOUR + wall.minute * TIME_CONSTANTS.MINUTE + wall.second * 1000
4809
+ };
4810
+ }
4811
+ function nightEndAt(pacing, now) {
4812
+ const { day, timeOfDay } = localDay(now, pacing.timeZone);
4813
+ const start = localTimeOfDayMs(pacing.nightHours.start);
4814
+ const end = localTimeOfDayMs(pacing.nightHours.end);
4815
+ const wraps = start > end;
4816
+ const night = wraps ? timeOfDay >= start || timeOfDay < end : timeOfDay >= start && timeOfDay < end;
4817
+ if (!night)
4818
+ return null;
4819
+ const endDay = wraps && timeOfDay >= start ? day + TIME_CONSTANTS.DAY : day;
4820
+ return zonedInstant(endDay + end, pacing.timeZone);
4821
+ }
4822
+ function workingMsBetween(pacing, from, to) {
4823
+ const start = localTimeOfDayMs(pacing.workingHours.start);
4824
+ const end = localTimeOfDayMs(pacing.workingHours.end);
4825
+ let total = 0;
4826
+ for (let day = localDay(from, pacing.timeZone).day - TIME_CONSTANTS.DAY;zonedInstant(day + start, pacing.timeZone) < to; day += TIME_CONSTANTS.DAY) {
4827
+ if (!pacing.workingDays.includes(WEEKDAYS[new Date(day).getUTCDay()] ?? ""))
4828
+ continue;
4829
+ const opens = zonedInstant(day + start, pacing.timeZone);
4830
+ const closes = zonedInstant(day + end, pacing.timeZone);
4831
+ total += Math.max(0, Math.min(closes, to) - Math.max(opens, from));
4832
+ }
4833
+ return total;
4834
+ }
4835
+ function expiresBeforeUseUpTime(pacing, resetAt2, now) {
4836
+ const endAt = nightEndAt(pacing, now);
4837
+ if (endAt === null || resetAt2 <= now)
4838
+ return false;
4839
+ return resetAt2 <= zonedInstant(localDay(endAt, pacing.timeZone).day + localTimeOfDayMs(pacing.useUpBefore), pacing.timeZone);
4840
+ }
4841
+ function nightWeeklyTarget(pacing, resetAt2, now) {
4842
+ if (expiresBeforeUseUpTime(pacing, resetAt2, now))
4843
+ return 1;
4844
+ const windowStart = resetAt2 - WEEKLY_WINDOW_MS;
4845
+ const workingDayMs = localTimeOfDayMs(pacing.workingHours.end) - localTimeOfDayMs(pacing.workingHours.start);
4846
+ const elapsed = workingMsBetween(pacing, windowStart, Math.min(now, resetAt2));
4847
+ return (elapsed - pacing.marginWorkingDays * workingDayMs) / workingMsBetween(pacing, windowStart, resetAt2);
4848
+ }
4849
+ var WEEKDAYS, WEEKLY_WINDOW_MS, NIGHT_PACING_DEFAULTS, NIGHT_PACING_FIELDS;
4850
+ var init_night_pacing = __esm(() => {
4851
+ init_src2();
4852
+ init_src();
4853
+ init_zoned_time();
4854
+ WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
4855
+ WEEKLY_WINDOW_MS = 7 * TIME_CONSTANTS.DAY;
4856
+ NIGHT_PACING_DEFAULTS = {
4857
+ timeZone: "Europe/Paris",
4858
+ workingDays: ["mon", "tue", "wed", "thu", "fri"],
4859
+ workingHours: { start: "07:00", end: "21:00" },
4860
+ nightHours: { start: "21:00", end: "07:00" },
4861
+ marginWorkingDays: 1,
4862
+ useUpBefore: "10:00"
4863
+ };
4864
+ NIGHT_PACING_FIELDS = new Set([
4865
+ "time_zone",
4866
+ "working_days",
4867
+ "working_hours",
4868
+ "night_hours",
4869
+ "margin_working_days",
4870
+ "use_up_before"
4871
+ ]);
4872
+ });
4873
+
4682
4874
  // ../../packages/config/src/paths-common.ts
4683
4875
  import { homedir } from "os";
4684
4876
  import { join as join4 } from "path";
@@ -4949,17 +5141,6 @@ var init_rewrite_file = __esm(() => {
4949
5141
  function isLocalTimes(value) {
4950
5142
  return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
4951
5143
  }
4952
- function isTimeZone(value) {
4953
- if (typeof value !== "string" || value.length === 0 || value.length > 64) {
4954
- return false;
4955
- }
4956
- try {
4957
- new Intl.DateTimeFormat("en-US", { timeZone: value });
4958
- return true;
4959
- } catch {
4960
- return false;
4961
- }
4962
- }
4963
5144
  function sanitizeWindowWarmup(value) {
4964
5145
  if (!isRecord(value))
4965
5146
  return;
@@ -4996,42 +5177,6 @@ function windowWarmupFileConfig(config) {
4996
5177
  ...config.model && { model: config.model }
4997
5178
  };
4998
5179
  }
4999
- function wallClockFormat(timeZone) {
5000
- let format = wallClockFormats.get(timeZone);
5001
- if (!format) {
5002
- format = new Intl.DateTimeFormat("en-US", {
5003
- timeZone,
5004
- hourCycle: "h23",
5005
- year: "numeric",
5006
- month: "numeric",
5007
- day: "numeric",
5008
- hour: "numeric",
5009
- minute: "numeric",
5010
- second: "numeric"
5011
- });
5012
- wallClockFormats.set(timeZone, format);
5013
- }
5014
- return format;
5015
- }
5016
- function wallClock(at, timeZone) {
5017
- const parts = wallClockFormat(timeZone).formatToParts(at);
5018
- const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
5019
- return {
5020
- year: part("year"),
5021
- month: part("month"),
5022
- day: part("day"),
5023
- hour: part("hour") % 24,
5024
- minute: part("minute"),
5025
- second: part("second")
5026
- };
5027
- }
5028
- function zoneOffsetMs(at, timeZone) {
5029
- const wall = wallClock(at, timeZone);
5030
- return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
5031
- }
5032
- function zonedInstant(wall, timeZone) {
5033
- return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
5034
- }
5035
5180
  function nextWindowWarmupAt(routing, after) {
5036
5181
  const warmup = routing.windowWarmup;
5037
5182
  if (!routing.enabled || !warmup.enabled)
@@ -5043,19 +5188,16 @@ function nextWindowWarmupAt(routing, after) {
5043
5188
  if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
5044
5189
  continue;
5045
5190
  }
5046
- const instants = warmup.times.map((time) => {
5047
- const [hour = 0, minute = 0] = time.split(":").map(Number);
5048
- return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
5049
- }).filter((at) => at > after);
5191
+ const instants = warmup.times.map((time) => zonedInstant(day + localTimeOfDayMs(time), warmup.timeZone)).filter((at) => at > after);
5050
5192
  if (instants.length > 0)
5051
5193
  return Math.min(...instants);
5052
5194
  }
5053
5195
  return null;
5054
5196
  }
5055
- var WINDOW_WARMUP_DEFAULTS, LOCAL_TIME, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0, wallClockFormats;
5197
+ var WINDOW_WARMUP_DEFAULTS, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0;
5056
5198
  var init_window_warmup = __esm(() => {
5057
- init_src2();
5058
5199
  init_src();
5200
+ init_zoned_time();
5059
5201
  WINDOW_WARMUP_DEFAULTS = {
5060
5202
  enabled: false,
5061
5203
  times: ["06:00"],
@@ -5063,9 +5205,7 @@ var init_window_warmup = __esm(() => {
5063
5205
  weekdaysOnly: true,
5064
5206
  model: null
5065
5207
  };
5066
- LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
5067
5208
  MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
5068
- wallClockFormats = new Map;
5069
5209
  });
5070
5210
 
5071
5211
  // ../../packages/config/src/index.ts
@@ -5331,6 +5471,29 @@ function wireForStrategy(strategy3) {
5331
5471
  function isNonNegativeFiniteNumber(value) {
5332
5472
  return isFiniteNumber(value) && value >= 0;
5333
5473
  }
5474
+ function sanitizeCapsByEmail(value, maximum) {
5475
+ if (!isRecord(value))
5476
+ return;
5477
+ const entries = Object.entries(value);
5478
+ const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
5479
+ const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
5480
+ if (!isValid)
5481
+ return;
5482
+ return Object.fromEntries(normalized);
5483
+ }
5484
+ function isDeviceList(value) {
5485
+ return Array.isArray(value) && value.length > 0 && value.length <= MAX_CALLERS && value.every((device) => typeof device === "string" && CALLER_ID_PATTERN.test(device)) && new Set(value).size === value.length;
5486
+ }
5487
+ function sanitizeOwnerDevicesByEmail(value) {
5488
+ if (!isRecord(value))
5489
+ return;
5490
+ const entries = Object.entries(value);
5491
+ const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
5492
+ const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
5493
+ if (!isValid)
5494
+ return;
5495
+ return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
5496
+ }
5334
5497
  function sanitizeTeamRouting(value) {
5335
5498
  if (!isRecord(value))
5336
5499
  return;
@@ -5352,19 +5515,21 @@ function sanitizeTeamRouting(value) {
5352
5515
  if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
5353
5516
  result.weekly_max_usage = value.weekly_max_usage;
5354
5517
  }
5355
- if (isRecord(value.weekly_max_usage_by_email)) {
5356
- const entries = Object.entries(value.weekly_max_usage_by_email);
5357
- const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
5358
- if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 1) && new Set(normalized.map(([email]) => email)).size === entries.length) {
5359
- result.weekly_max_usage_by_email = Object.fromEntries(normalized);
5360
- }
5361
- }
5518
+ const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
5519
+ if (maxUsageByEmail)
5520
+ result.max_usage_by_email = maxUsageByEmail;
5521
+ const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
5522
+ if (weeklyMaxUsageByEmail)
5523
+ result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
5362
5524
  if (isRecord(value.caller_weekly_max_usage)) {
5363
5525
  const entries = Object.entries(value.caller_weekly_max_usage);
5364
5526
  if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
5365
5527
  result.caller_weekly_max_usage = Object.fromEntries(entries);
5366
5528
  }
5367
5529
  }
5530
+ const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
5531
+ if (ownerDevicesByEmail)
5532
+ result.owner_devices_by_email = ownerDevicesByEmail;
5368
5533
  if (isRecord(value.caller_provider_fallback)) {
5369
5534
  const entries = Object.entries(value.caller_provider_fallback);
5370
5535
  if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
@@ -5415,9 +5580,11 @@ function sanitizeProviderPool(value) {
5415
5580
  "distribution_enabled",
5416
5581
  "prefer_expiring_quota",
5417
5582
  "max_usage",
5583
+ "max_usage_by_email",
5418
5584
  "weekly_max_usage",
5419
5585
  "weekly_max_usage_by_email",
5420
5586
  "caller_weekly_max_usage",
5587
+ "owner_devices_by_email",
5421
5588
  "quota_probe_seconds",
5422
5589
  "window_warmup"
5423
5590
  ]) {
@@ -5439,8 +5606,17 @@ function sanitizeProviderPool(value) {
5439
5606
  }
5440
5607
  if (typeof value.block_when_all_full === "boolean")
5441
5608
  pool.block_when_all_full = value.block_when_all_full;
5609
+ const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
5610
+ if (nightPacing)
5611
+ pool.caller_night_pacing = nightPacing;
5442
5612
  return pool;
5443
5613
  }
5614
+ function sanitizeCallerNightPacing(value) {
5615
+ if (!isRecord(value))
5616
+ return;
5617
+ const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
5618
+ return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
5619
+ }
5444
5620
  function sanitizeRouting(value) {
5445
5621
  if (!isRecord(value))
5446
5622
  return;
@@ -5510,9 +5686,11 @@ var init_src8 = __esm(() => {
5510
5686
  init_src4();
5511
5687
  init_src();
5512
5688
  init_builtin_providers();
5689
+ init_night_pacing();
5513
5690
  init_paths();
5514
5691
  init_rewrite_file();
5515
5692
  init_window_warmup();
5693
+ init_night_pacing();
5516
5694
  init_paths();
5517
5695
  init_paths_common();
5518
5696
  init_rewrite_config();
@@ -5538,9 +5716,12 @@ var init_src8 = __esm(() => {
5538
5716
  preferExpiringQuota: false,
5539
5717
  allowlistedAccountUuids: [],
5540
5718
  maxUsage: 0.9,
5719
+ maxUsageByEmail: {},
5541
5720
  weeklyMaxUsage: 0.95,
5542
5721
  weeklyMaxUsageByEmail: {},
5543
5722
  callerWeeklyMaxUsage: {},
5723
+ callerNightPacing: {},
5724
+ ownerDevicesByEmail: {},
5544
5725
  admissionCap: 5,
5545
5726
  admissionQueueLimit: 25,
5546
5727
  admissionWaitMs: 30000,
@@ -5714,9 +5895,12 @@ var init_src8 = __esm(() => {
5714
5895
  preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
5715
5896
  allowlistedAccountUuids: [...pool?.members ?? []],
5716
5897
  maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
5898
+ maxUsageByEmail: { ...pool?.max_usage_by_email },
5717
5899
  weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
5718
5900
  weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
5719
5901
  callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
5902
+ callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
5903
+ ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
5720
5904
  admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
5721
5905
  admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
5722
5906
  admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
@@ -5793,9 +5977,12 @@ var init_src8 = __esm(() => {
5793
5977
  "distribution_enabled",
5794
5978
  "prefer_expiring_quota",
5795
5979
  "max_usage",
5980
+ "max_usage_by_email",
5796
5981
  "weekly_max_usage",
5797
5982
  "weekly_max_usage_by_email",
5798
5983
  "caller_weekly_max_usage",
5984
+ "caller_night_pacing",
5985
+ "owner_devices_by_email",
5799
5986
  "admission",
5800
5987
  "quota_probe_seconds",
5801
5988
  "window_warmup",
@@ -6386,7 +6573,8 @@ function ensureRequestLinkageColumns(db) {
6386
6573
  ["ttft_ms", "INTEGER"],
6387
6574
  ["proxy_overhead_ms", "INTEGER"],
6388
6575
  ["upstream_ttfb_ms", "INTEGER"],
6389
- ["streaming_duration_ms", "INTEGER"]
6576
+ ["streaming_duration_ms", "INTEGER"],
6577
+ ["caller", "TEXT"]
6390
6578
  ];
6391
6579
  for (const [columnName, columnType] of requestColumns) {
6392
6580
  if (!hasColumn(columns, columnName)) {
@@ -6804,7 +6992,8 @@ function ensureSchema(db) {
6804
6992
  ttft_ms INTEGER,
6805
6993
  proxy_overhead_ms INTEGER,
6806
6994
  upstream_ttfb_ms INTEGER,
6807
- streaming_duration_ms INTEGER
6995
+ streaming_duration_ms INTEGER,
6996
+ caller TEXT
6808
6997
  )
6809
6998
  `);
6810
6999
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
@@ -7258,6 +7447,30 @@ var init_analytics_repository = __esm(() => {
7258
7447
  totalTokens: row.total_tokens ?? 0,
7259
7448
  totalCostUsd: row.total_cost_usd ?? 0
7260
7449
  }));
7450
+ const callerBreakdown = this.query(`
7451
+ SELECT
7452
+ r.caller as caller,
7453
+ COUNT(*) as requests,
7454
+ SUM(COALESCE(r.input_tokens, 0)) as input_tokens,
7455
+ SUM(COALESCE(r.cache_read_input_tokens, 0)) as cache_read_input_tokens,
7456
+ SUM(COALESCE(r.cache_creation_input_tokens, 0)) as cache_creation_input_tokens,
7457
+ SUM(COALESCE(r.output_tokens, 0)) as output_tokens,
7458
+ SUM(COALESCE(r.cost_usd, 0)) as total_cost_usd
7459
+ FROM requests r
7460
+ WHERE ${whereClause}
7461
+ GROUP BY r.caller
7462
+ ORDER BY total_cost_usd DESC, requests DESC
7463
+ `, queryParams).map((row) => ({
7464
+ caller: row.caller,
7465
+ requests: row.requests,
7466
+ tokenBreakdown: {
7467
+ inputTokens: row.input_tokens ?? 0,
7468
+ cacheReadInputTokens: row.cache_read_input_tokens ?? 0,
7469
+ cacheCreationInputTokens: row.cache_creation_input_tokens ?? 0,
7470
+ outputTokens: row.output_tokens ?? 0
7471
+ },
7472
+ totalCostUsd: row.total_cost_usd ?? 0
7473
+ }));
7261
7474
  const modelPerformance = this.query(`
7262
7475
  WITH model_stats AS (
7263
7476
  SELECT
@@ -7354,6 +7567,7 @@ var init_analytics_repository = __esm(() => {
7354
7567
  successRate: account2.success_rate ?? 0
7355
7568
  })),
7356
7569
  providerBreakdown,
7570
+ callerBreakdown,
7357
7571
  costByModel,
7358
7572
  modelPerformance
7359
7573
  };
@@ -7748,7 +7962,8 @@ var init_request_repository = __esm(() => {
7748
7962
  response_id = ?,
7749
7963
  previous_response_id = ?,
7750
7964
  response_chain_id = ?,
7751
- client_session_id = ?
7965
+ client_session_id = ?,
7966
+ caller = ?
7752
7967
  WHERE id = ?
7753
7968
  `, [
7754
7969
  data.method,
@@ -7780,6 +7995,7 @@ var init_request_repository = __esm(() => {
7780
7995
  linkage.previousResponseId,
7781
7996
  responseChainId,
7782
7997
  linkage.clientSessionId,
7998
+ data.caller ?? null,
7783
7999
  data.id
7784
8000
  ]);
7785
8001
  if (payloadJson !== undefined) {
@@ -8042,6 +8258,13 @@ var init_request_repository = __esm(() => {
8042
8258
  `, [limit]);
8043
8259
  return errors2.map((e) => e.error_message);
8044
8260
  }
8261
+ sumAccountCostSince(accountId, since) {
8262
+ return this.get(`
8263
+ SELECT SUM(cost_usd) AS cost
8264
+ FROM requests
8265
+ WHERE account_used = ? AND timestamp >= ?
8266
+ `, [accountId, since])?.cost ?? 0;
8267
+ }
8045
8268
  getRequestsByAccount(since) {
8046
8269
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
8047
8270
  const params = since ? [since] : [];
@@ -8385,9 +8608,13 @@ class DatabaseOperations {
8385
8608
  timestamp: options?.timestamp,
8386
8609
  payload: options?.payload,
8387
8610
  storePayload: options?.storePayload,
8388
- timings: options?.timings
8611
+ timings: options?.timings,
8612
+ caller: options?.callerId ?? null
8389
8613
  });
8390
8614
  }
8615
+ getAccountCostSince(accountId, since) {
8616
+ return this.requests.sumAccountCostSince(accountId, since);
8617
+ }
8391
8618
  updateRequestUsage(requestId, usage) {
8392
8619
  this.requests.updateUsage(requestId, usage);
8393
8620
  }
@@ -8691,8 +8918,11 @@ var init_analytics = __esm(() => {
8691
8918
  // ../../packages/api/src/handlers/config.ts
8692
8919
  function publicProviderPool(config, name) {
8693
8920
  const {
8921
+ maxUsageByEmail: _fiveHour,
8694
8922
  weeklyMaxUsageByEmail: _weekly,
8695
8923
  callerWeeklyMaxUsage: _caller,
8924
+ callerNightPacing: _nightPacing,
8925
+ ownerDevicesByEmail: _owners,
8696
8926
  ...pool
8697
8927
  } = config.getTeamRouting(name);
8698
8928
  return pool;
@@ -10554,9 +10784,12 @@ class TeamAdmission {
10554
10784
  preferExpiringQuota: false,
10555
10785
  allowlistedAccountUuids: [],
10556
10786
  maxUsage: 0.9,
10787
+ maxUsageByEmail: {},
10557
10788
  weeklyMaxUsage: 0.95,
10558
10789
  weeklyMaxUsageByEmail: {},
10559
10790
  callerWeeklyMaxUsage: {},
10791
+ callerNightPacing: {},
10792
+ ownerDevicesByEmail: {},
10560
10793
  admissionCap: 1,
10561
10794
  admissionQueueLimit: 0,
10562
10795
  admissionWaitMs: 0,
@@ -10978,13 +11211,17 @@ function pinKey(request3, provider) {
10978
11211
  function isAllowlisted(account2, config) {
10979
11212
  return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
10980
11213
  }
11214
+ function soonestToUseUp(accounts, useUpResetAt) {
11215
+ const soonest = Math.min(...accounts.map(useUpResetAt));
11216
+ return soonest === Number.POSITIVE_INFINITY ? accounts : accounts.filter((account2) => useUpResetAt(account2) === soonest);
11217
+ }
10981
11218
 
10982
11219
  class TeamRouter {
10983
11220
  inFlight = new Map;
10984
11221
  pins = new Map;
10985
11222
  pinLookups = new WeakMap;
10986
11223
  cleanedLookups = new WeakSet;
10987
- order(accounts, request3, config, provider, store, now = Date.now()) {
11224
+ order(accounts, request3, config, provider, store, now = Date.now(), useUpResetAt = () => Number.POSITIVE_INFINITY) {
10988
11225
  if (!config.enabled || !request3)
10989
11226
  return accounts;
10990
11227
  this.removeExpiredPinsOnce(request3, now, store);
@@ -11003,7 +11240,7 @@ class TeamRouter {
11003
11240
  }
11004
11241
  if (!config.distributionEnabled || !key)
11005
11242
  return eligible;
11006
- const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
11243
+ const selected = this.leastUsedPriorityAccount(soonestToUseUp(eligible, useUpResetAt), compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
11007
11244
  this.touchPin(key, selected.id, now, store);
11008
11245
  return [
11009
11246
  selected,
@@ -11091,37 +11328,144 @@ var init_seat_router = __esm(() => {
11091
11328
  PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
11092
11329
  });
11093
11330
 
11331
+ // ../../packages/pool/src/night-pacing.ts
11332
+ function callerNightPacing(pool, callerId) {
11333
+ return callerId && pool.enabled && Object.hasOwn(pool.callerNightPacing, callerId) ? pool.callerNightPacing[callerId] ?? null : null;
11334
+ }
11335
+ function pacedNight(pool, account2, now, callerId) {
11336
+ const pacing = callerNightPacing(pool, callerId);
11337
+ if (!pacing || !isAllowlisted(account2, pool))
11338
+ return null;
11339
+ const endAt = nightEndAt(pacing, now);
11340
+ return endAt === null ? null : { pacing, endAt };
11341
+ }
11342
+ function startsWindowIntoMorning(provider, account2, night, now) {
11343
+ return now >= night.endAt - FIVE_HOUR_WINDOW_MS && !Object.entries(account2.quota_state?.windows ?? {}).some(([bucket, window2]) => provider.isFiveHourBucket(bucket) && window2.resetAt !== null && window2.resetAt > now && window2.resetAt <= night.endAt);
11344
+ }
11345
+ function weeklyWindows(provider, account2, model, now) {
11346
+ return Object.entries(account2.quota_state?.windows ?? {}).flatMap(([bucket, window2]) => {
11347
+ if (window2.resetAt === null || !provider.isWeeklyBucket(bucket) || !(provider.quotaBucketsFor(model)?.includes(bucket) ?? true)) {
11348
+ return [];
11349
+ }
11350
+ const rolled = window2.resetAt <= now;
11351
+ const resetAt2 = rolled ? window2.resetAt + (Math.floor((now - window2.resetAt) / WEEKLY_WINDOW_MS) + 1) * WEEKLY_WINDOW_MS : window2.resetAt;
11352
+ return [
11353
+ {
11354
+ bucket,
11355
+ resetAt: resetAt2,
11356
+ used: rolled ? 0 : window2.status === "rejected" ? 1 : window2.utilization ?? 0
11357
+ }
11358
+ ];
11359
+ });
11360
+ }
11361
+ function nightWeeklyWindows(provider, account2, model, pacing, now) {
11362
+ return weeklyWindows(provider, account2, model, now).map((window2) => ({
11363
+ ...window2,
11364
+ target: nightWeeklyTarget(pacing, window2.resetAt, now)
11365
+ }));
11366
+ }
11367
+ function useUpResetAt(provider, account2, model, pool, now, callerId) {
11368
+ const night = pacedNight(pool, account2, now, callerId);
11369
+ if (!night)
11370
+ return Number.POSITIVE_INFINITY;
11371
+ return Math.min(...weeklyWindows(provider, account2, model, now).flatMap(({ resetAt: resetAt2 }) => expiresBeforeUseUpTime(night.pacing, resetAt2, now) ? [resetAt2] : []), Number.POSITIVE_INFINITY);
11372
+ }
11373
+ function nightPacingBlock(provider, account2, model, pool, now, callerId) {
11374
+ const night = pacedNight(pool, account2, now, callerId);
11375
+ if (!night)
11376
+ return null;
11377
+ if (startsWindowIntoMorning(provider, account2, night, now)) {
11378
+ return { category: "five-hour-limit", retryAt: night.endAt };
11379
+ }
11380
+ return nightWeeklyWindows(provider, account2, model, night.pacing, now).some((window2) => window2.used >= Math.max(0, window2.target)) ? { category: "weekly-limit", retryAt: night.endAt } : null;
11381
+ }
11382
+ function median(values) {
11383
+ if (values.length === 0)
11384
+ return 0;
11385
+ const sorted = [...values].sort((left, right) => left - right);
11386
+ const upper = sorted[Math.floor(sorted.length / 2)] ?? 0;
11387
+ const lower = sorted[Math.ceil(sorted.length / 2) - 1] ?? 0;
11388
+ return (lower + upper) / 2;
11389
+ }
11390
+ function seatsNightCostEq(provider, seats, model, pacing, now, costSince, weeklyCap) {
11391
+ const endAt = nightEndAt(pacing, now);
11392
+ const headrooms = seats.flatMap((account2) => {
11393
+ if (endAt !== null && startsWindowIntoMorning(provider, account2, { pacing, endAt }, now)) {
11394
+ return [];
11395
+ }
11396
+ const [binding] = nightWeeklyWindows(provider, account2, model, pacing, now).map((window2) => ({
11397
+ ...window2,
11398
+ ceiling: Math.min(window2.target, weeklyCap(account2, window2.bucket))
11399
+ })).sort((left, right) => left.ceiling - left.used - (right.ceiling - right.used));
11400
+ if (!binding)
11401
+ return [];
11402
+ const usedPoints = binding.used * 100;
11403
+ return [
11404
+ {
11405
+ points: Math.max(0, binding.ceiling - binding.used) * 100,
11406
+ costPerPoint: usedPoints >= MIN_OWN_RATE_POINTS ? costSince(account2.id, binding.resetAt - WEEKLY_WINDOW_MS) / usedPoints : null
11407
+ }
11408
+ ];
11409
+ });
11410
+ const fallbackRate = median(headrooms.flatMap(({ costPerPoint }) => costPerPoint === null ? [] : [costPerPoint]));
11411
+ return headrooms.reduce((sum, { points, costPerPoint }) => sum + points * (costPerPoint ?? fallbackRate), 0);
11412
+ }
11413
+ var FIVE_HOUR_WINDOW_MS, MIN_OWN_RATE_POINTS = 5;
11414
+ var init_night_pacing2 = __esm(() => {
11415
+ init_src8();
11416
+ init_seat_router();
11417
+ FIVE_HOUR_WINDOW_MS = 5 * 60 * 60000;
11418
+ });
11419
+
11094
11420
  // ../../packages/pool/src/handlers/account-selector.ts
11095
- function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
11421
+ function quotaCeiling(account2, bucket, fleetThreshold, maxUsage) {
11096
11422
  const accountThreshold = account2.switch_threshold === null || account2.switch_threshold === undefined ? undefined : quotaThresholdFor(account2, bucket, fleetThreshold);
11097
- const threshold = maxUsage?.overridesFleetThreshold === true ? Math.min(maxUsage.limit, accountThreshold ?? Number.POSITIVE_INFINITY) : Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage?.limit ?? Number.POSITIVE_INFINITY);
11423
+ return maxUsage?.overridesFleetThreshold === true ? Math.min(maxUsage.limit, accountThreshold ?? Number.POSITIVE_INFINITY) : Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage?.limit ?? Number.POSITIVE_INFINITY);
11424
+ }
11425
+ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
11426
+ const threshold = quotaCeiling(account2, bucket, fleetThreshold, maxUsage);
11098
11427
  return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
11099
11428
  }
11100
- function pooledMaxUsage(provider, account2, bucket, ctx, callerId) {
11429
+ function capForAccountEmail(capsByEmail, account2, ctx) {
11430
+ if (Object.keys(capsByEmail).length === 0)
11431
+ return;
11432
+ const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
11433
+ return email ? capsByEmail[email] : undefined;
11434
+ }
11435
+ function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
11101
11436
  const teamRouting = ctx.runtime.pool;
11102
11437
  if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
11103
11438
  return;
11104
11439
  if (!provider.isWeeklyBucket(bucket)) {
11105
- return { limit: teamRouting.maxUsage, overridesFleetThreshold: false };
11440
+ const accountCap = capForAccountEmail(teamRouting.maxUsageByEmail, account2, ctx);
11441
+ return {
11442
+ limit: Math.min(teamRouting.maxUsage, accountCap ?? Number.POSITIVE_INFINITY),
11443
+ overridesFleetThreshold: false
11444
+ };
11106
11445
  }
11107
- const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
11108
- const accountOverride = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
11109
- const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
11446
+ const accountOverride = capForAccountEmail(teamRouting.weeklyMaxUsageByEmail, account2, ctx);
11447
+ const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) && !pacedNight(teamRouting, account2, now, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
11110
11448
  return {
11111
11449
  limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
11112
11450
  overridesFleetThreshold: accountOverride !== undefined
11113
11451
  };
11114
11452
  }
11115
- function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
11116
- const quota2 = account2.quota_state;
11117
- if (!quota2)
11453
+ function servesCaller(account2, ctx, callerId) {
11454
+ const ownerDevices = ctx.runtime.pool?.ownerDevicesByEmail;
11455
+ if (!ownerDevices || Object.keys(ownerDevices).length === 0)
11456
+ return true;
11457
+ const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
11458
+ if (!email || !Object.hasOwn(ownerDevices, email))
11118
11459
  return true;
11119
- for (const [name, window2] of Object.entries(quota2.windows)) {
11120
- if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, callerId))) {
11460
+ return callerId !== undefined && !!ownerDevices[email]?.includes(callerId);
11461
+ }
11462
+ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
11463
+ for (const [name, window2] of Object.entries(account2.quota_state?.windows ?? {})) {
11464
+ if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, now, callerId))) {
11121
11465
  return false;
11122
11466
  }
11123
11467
  }
11124
- return true;
11468
+ return nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId) === null;
11125
11469
  }
11126
11470
  function fleetAccounts(provider, ctx) {
11127
11471
  return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
@@ -11145,19 +11489,23 @@ function callerPoolAccounts(provider, ctx, orderedFallback) {
11145
11489
  return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx) || orderedFallback && !account2.paused && account2.auth_method === "api_key");
11146
11490
  }
11147
11491
  function blockingResets(provider, account2, model, ctx, now, callerId) {
11148
- 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);
11492
+ const nightEnd = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId)?.retryAt;
11493
+ 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, now, callerId))).map(([, window2]) => window2.resetAt).concat(nightEnd === undefined ? [] : [nightEnd]);
11149
11494
  }
11150
11495
  function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
11151
- 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)));
11496
+ const night = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId);
11497
+ 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, now, callerId)));
11152
11498
  if (blocking.length === 0)
11153
- return null;
11499
+ return night;
11154
11500
  const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
11155
11501
  const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
11156
11502
  const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
11157
11503
  return rightReset - leftReset;
11158
11504
  })[0];
11159
11505
  const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
11160
- return window2.resetAt === null ? { category } : { category, retryAt: window2.resetAt };
11506
+ if (window2.resetAt === null)
11507
+ return { category };
11508
+ return night?.retryAt !== undefined && night.retryAt > window2.resetAt ? night : { category, retryAt: window2.resetAt };
11161
11509
  }
11162
11510
  function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
11163
11511
  const now = Date.now();
@@ -11205,13 +11553,24 @@ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts)
11205
11553
  throw new Error(`Unknown provider '${provider}'`);
11206
11554
  const config = ctx.runtime.pool;
11207
11555
  const now = Date.now();
11208
- const accounts = config.enabled ? callerPoolAccounts(provider, ctx, apiKeyAccounts) : ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (apiKeyAccounts || account2.auth_method !== "api_key"));
11556
+ const accounts = (config.enabled ? callerPoolAccounts(provider, ctx, apiKeyAccounts) : ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (apiKeyAccounts || account2.auth_method !== "api_key"))).filter((account2) => servesCaller(account2, ctx, callerId));
11209
11557
  const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
11558
+ const nightBudget = callerNightBudget(strategy3, accounts, model, callerId, ctx, now);
11210
11559
  return {
11211
11560
  poolEnabled: config.enabled,
11212
11561
  servableSeats,
11213
11562
  retryAt: servableSeats === 0 ? soonestServableAt(strategy3, accounts, accounts, model, ctx, now, callerId) : null,
11214
- admissionWaitMs: config.admissionWaitMs
11563
+ admissionWaitMs: config.admissionWaitMs,
11564
+ ...nightBudget && { nightBudget }
11565
+ };
11566
+ }
11567
+ function callerNightBudget(provider, accounts, model, callerId, ctx, now) {
11568
+ const pacing = callerNightPacing(ctx.runtime.pool, callerId);
11569
+ if (!pacing)
11570
+ return null;
11571
+ return {
11572
+ night: nightEndAt(pacing, now) !== null,
11573
+ seatsCostEq: seatsNightCostEq(provider, accounts.filter((account2) => isFleetSeat(account2, ctx)), model, pacing, now, (accountId, since) => ctx.dbOps.getAccountCostSince(accountId, since), (account2, bucket) => quotaCeiling(account2, bucket, ctx.runtime.quotaThreshold, pooledMaxUsage(provider, account2, bucket, ctx, now)))
11215
11574
  };
11216
11575
  }
11217
11576
  function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
@@ -11239,19 +11598,23 @@ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
11239
11598
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
11240
11599
  const now = Date.now();
11241
11600
  const callerId = teamRequest?.callerId;
11242
- const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
11601
+ const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null && servesCaller(account2, ctx, callerId));
11243
11602
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
11244
11603
  const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.pool.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
11245
- const prioritized = [...candidates].sort((left, right) => {
11246
- const priority = (left.priority ?? 0) - (right.priority ?? 0);
11247
- return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
11248
- });
11604
+ const useUpResets = new Map(candidates.map((account2) => [
11605
+ account2.id,
11606
+ useUpResetAt(ctx.provider, account2, meta.model, ctx.runtime.pool, now, callerId)
11607
+ ]));
11608
+ const useUpAt = (account2) => useUpResets.get(account2.id) ?? Number.POSITIVE_INFINITY;
11609
+ const prioritized = [...candidates].sort((left, right) => useUpAt(left) - useUpAt(right) || (left.priority ?? 0) - (right.priority ?? 0) || soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
11249
11610
  const ordered = ctx.strategy.select(prioritized, meta);
11250
- return (options.applyTeamRouting === false ? undefined : ctx.teamRouter?.order(ordered, teamRequest, ctx.runtime.pool, ctx.provider, ctx.dbOps)) ?? ordered;
11611
+ return (options.applyTeamRouting === false ? undefined : ctx.teamRouter?.order(ordered, teamRequest, ctx.runtime.pool, ctx.provider, ctx.dbOps, now, useUpAt)) ?? ordered;
11251
11612
  }
11252
11613
  var QUOTA_PROBE_INTERVAL_MS = 60000;
11253
11614
  var init_account_selector = __esm(() => {
11615
+ init_src8();
11254
11616
  init_src();
11617
+ init_night_pacing2();
11255
11618
  init_seat_router();
11256
11619
  init_seat_usage();
11257
11620
  init_token_manager();
@@ -11501,7 +11864,7 @@ class ProviderSupply {
11501
11864
  return threadAccount;
11502
11865
  };
11503
11866
  const seatsFor = (fleet) => {
11504
- const eligible = ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet;
11867
+ const eligible = (ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet).filter((account2) => servesCaller(account2, ctx, route.callerId));
11505
11868
  const id = getThreadAccount();
11506
11869
  return id ? eligible.filter((account2) => account2.id === id) : eligible;
11507
11870
  };
@@ -11588,7 +11951,7 @@ class ProviderSupply {
11588
11951
  const teamEnabled = ctx.runtime.pool.enabled;
11589
11952
  const pooled = account2.auth_method !== "api_key" && (!teamEnabled || isAllowlisted(account2, ctx.runtime.pool) && (!route.seatHint || account2.name === route.seatHint));
11590
11953
  const keyReached = route.apiKeyAccounts && account2.auth_method === "api_key";
11591
- return (pooled || keyReached) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
11954
+ return (pooled || keyReached) && servesCaller(account2, ctx, route.callerId) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
11592
11955
  });
11593
11956
  if (hasAvailableAccount)
11594
11957
  return {
@@ -12525,7 +12888,24 @@ async function getCallerPoolStatus(input) {
12525
12888
  eligibleAccounts,
12526
12889
  retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
12527
12890
  holdSeconds: input.holdSeconds,
12528
- admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0
12891
+ admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
12892
+ nightBudget: callerNightBudget2(statuses, Date.now())
12893
+ };
12894
+ }
12895
+ function toCents(value) {
12896
+ return Math.round(value * 100) / 100;
12897
+ }
12898
+ function callerNightBudget2(statuses, now) {
12899
+ const budgets = statuses.flatMap((status) => status.nightBudget ? [status.nightBudget] : []);
12900
+ if (budgets.length === 0)
12901
+ return null;
12902
+ const seatsCostEq = toCents(budgets.reduce((sum, budget) => sum + budget.seatsCostEq, 0));
12903
+ return {
12904
+ costEq: seatsCostEq,
12905
+ creditsCostEq: 0,
12906
+ seatsCostEq,
12907
+ night: budgets.some((budget) => budget.night),
12908
+ computedAtMs: now
12529
12909
  };
12530
12910
  }
12531
12911
  var init_router2 = () => {};
@@ -12596,12 +12976,13 @@ function normalizeMaxBodyBytes(maxBodyBytes) {
12596
12976
  function bodyTooLargeError(maxBodyBytes) {
12597
12977
  return new HttpError(413, `Request body too large (maximum ${maxBodyBytes} bytes)`);
12598
12978
  }
12599
- function createRequestMetadata(req, url) {
12979
+ function createRequestMetadata(req, url, callerId) {
12600
12980
  return {
12601
12981
  id: crypto2.randomUUID(),
12602
12982
  method: isHttpMethod(req.method) ? req.method : "GET",
12603
12983
  path: url.pathname,
12604
- timestamp: Date.now()
12984
+ timestamp: Date.now(),
12985
+ ...callerId !== undefined && { callerId }
12605
12986
  };
12606
12987
  }
12607
12988
  function readRequestModel(body) {
@@ -12696,7 +13077,8 @@ async function forwardToClient(options, ctx) {
12696
13077
  responseHeadersReceivedAt,
12697
13078
  retryAttempt,
12698
13079
  failoverAttempts,
12699
- preExtractedModel
13080
+ preExtractedModel,
13081
+ callerId
12700
13082
  } = options;
12701
13083
  const responseProcessed = ctx.provider.processResponse ? await ctx.provider.processResponse(responseRaw, account2, {
12702
13084
  messageId: `msg_${requestId.replaceAll("-", "")}`,
@@ -12725,7 +13107,8 @@ async function forwardToClient(options, ctx) {
12725
13107
  providerName: ctx.providerName,
12726
13108
  retryAttempt,
12727
13109
  failoverAttempts,
12728
- storePayload: ctx.runtime.storeRequestPayloads
13110
+ storePayload: ctx.runtime.storeRequestPayloads,
13111
+ callerId
12729
13112
  };
12730
13113
  ctx.usageWorker.postMessage(startMessage);
12731
13114
  requestEvents.emit("event", {
@@ -13302,7 +13685,8 @@ function createForwarder(input, upstream, state) {
13302
13685
  responseHeadersReceivedAt: upstream.responseHeadersReceivedAt,
13303
13686
  retryAttempt: 0,
13304
13687
  failoverAttempts: input.failoverAttempts,
13305
- preExtractedModel: input.mappedModel ?? input.requestMeta.model
13688
+ preExtractedModel: input.mappedModel ?? input.requestMeta.model,
13689
+ callerId: input.requestMeta.callerId
13306
13690
  }, input.ctx);
13307
13691
  }
13308
13692
  function discardUpstreamResponse(state) {
@@ -13785,7 +14169,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
13785
14169
  providerName: session.providerName,
13786
14170
  retryAttempt: 0,
13787
14171
  failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
13788
- storePayload: session.requestContext.runtime.storeRequestPayloads
14172
+ storePayload: session.requestContext.runtime.storeRequestPayloads,
14173
+ callerId: session.callerId
13789
14174
  };
13790
14175
  session.activeTurn = {
13791
14176
  requestId,
@@ -14051,7 +14436,7 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
14051
14436
  status: 400
14052
14437
  });
14053
14438
  }
14054
- const requestMeta = createRequestMetadata(req, url);
14439
+ const requestMeta = createRequestMetadata(req, url, callerId);
14055
14440
  const teamRequest = {
14056
14441
  body: null,
14057
14442
  contentType: null,
@@ -14105,7 +14490,8 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
14105
14490
  activeTurn: null,
14106
14491
  connectedAccount: null,
14107
14492
  pendingRequestBody: null,
14108
- pendingRequestTimestamp: null
14493
+ pendingRequestTimestamp: null,
14494
+ callerId
14109
14495
  };
14110
14496
  websocketSessions.set(sessionId, session);
14111
14497
  const upgraded = server.upgrade(req, {
@@ -14762,7 +15148,7 @@ async function handleProxy(req, url, ctx, callerId) {
14762
15148
  if (!upstreamUrl.pathname.startsWith("/v1/pool/")) {
14763
15149
  return new Response("Not Found", { status: 404 });
14764
15150
  }
14765
- const requestMeta2 = createRequestMetadata(req, upstreamUrl);
15151
+ const requestMeta2 = createRequestMetadata(req, upstreamUrl, callerId);
14766
15152
  const { buffer: buffer2 } = await prepareRequestBody(req, ctx.runtime.maxBodyBytes);
14767
15153
  const body2 = buffer2 ?? null;
14768
15154
  requestMeta2.model = readRequestModel(body2);
@@ -14774,7 +15160,7 @@ async function handleProxy(req, url, ctx, callerId) {
14774
15160
  }
14775
15161
  return await routePoolRequest(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
14776
15162
  }
14777
- const requestMeta = createRequestMetadata(req, upstreamUrl);
15163
+ const requestMeta = createRequestMetadata(req, upstreamUrl, callerId);
14778
15164
  const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
14779
15165
  const body = buffer ?? null;
14780
15166
  requestMeta.model = readRequestModel(body);