@certalis/agent-smith 0.2.0 → 0.3.2
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 +5 -3
- package/dist/bin.js +786 -191
- package/dist/client-launcher.js +463 -71
- package/dist/dashboard/chunk-wzenqdk1.js.map +1 -1
- package/dist/edge.js +15 -3
- package/dist/https.js +17 -4
- package/dist/pool.js +697 -184
- package/dist/post-processor.worker.js +378 -104
- package/dist/server.js +697 -184
- package/package.json +2 -1
package/dist/server.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,
|
|
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
|
|
@@ -5081,6 +5221,13 @@ import {
|
|
|
5081
5221
|
writeFileSync as writeFileSync2
|
|
5082
5222
|
} from "fs";
|
|
5083
5223
|
import { dirname as dirname2 } from "path";
|
|
5224
|
+
function callerWeeklyCap(caps, callerId) {
|
|
5225
|
+
if (!Object.hasOwn(caps, callerId))
|
|
5226
|
+
return;
|
|
5227
|
+
const cap = caps[callerId];
|
|
5228
|
+
const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
|
|
5229
|
+
return typeof shared === "number" ? shared : undefined;
|
|
5230
|
+
}
|
|
5084
5231
|
function runtimeForProvider(runtime, provider) {
|
|
5085
5232
|
return {
|
|
5086
5233
|
...runtime,
|
|
@@ -5331,6 +5478,29 @@ function wireForStrategy(strategy3) {
|
|
|
5331
5478
|
function isNonNegativeFiniteNumber(value) {
|
|
5332
5479
|
return isFiniteNumber(value) && value >= 0;
|
|
5333
5480
|
}
|
|
5481
|
+
function sanitizeCapsByEmail(value, maximum) {
|
|
5482
|
+
if (!isRecord(value))
|
|
5483
|
+
return;
|
|
5484
|
+
const entries = Object.entries(value);
|
|
5485
|
+
const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
|
|
5486
|
+
const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
|
|
5487
|
+
if (!isValid)
|
|
5488
|
+
return;
|
|
5489
|
+
return Object.fromEntries(normalized);
|
|
5490
|
+
}
|
|
5491
|
+
function isDeviceList(value) {
|
|
5492
|
+
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;
|
|
5493
|
+
}
|
|
5494
|
+
function sanitizeOwnerDevicesByEmail(value) {
|
|
5495
|
+
if (!isRecord(value))
|
|
5496
|
+
return;
|
|
5497
|
+
const entries = Object.entries(value);
|
|
5498
|
+
const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
|
|
5499
|
+
const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
|
|
5500
|
+
if (!isValid)
|
|
5501
|
+
return;
|
|
5502
|
+
return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
|
|
5503
|
+
}
|
|
5334
5504
|
function sanitizeTeamRouting(value) {
|
|
5335
5505
|
if (!isRecord(value))
|
|
5336
5506
|
return;
|
|
@@ -5352,19 +5522,22 @@ function sanitizeTeamRouting(value) {
|
|
|
5352
5522
|
if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
|
|
5353
5523
|
result.weekly_max_usage = value.weekly_max_usage;
|
|
5354
5524
|
}
|
|
5355
|
-
|
|
5356
|
-
|
|
5357
|
-
|
|
5358
|
-
|
|
5359
|
-
|
|
5360
|
-
|
|
5361
|
-
}
|
|
5525
|
+
const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
|
|
5526
|
+
if (maxUsageByEmail)
|
|
5527
|
+
result.max_usage_by_email = maxUsageByEmail;
|
|
5528
|
+
const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
|
|
5529
|
+
if (weeklyMaxUsageByEmail)
|
|
5530
|
+
result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
|
|
5362
5531
|
if (isRecord(value.caller_weekly_max_usage)) {
|
|
5363
|
-
const
|
|
5364
|
-
|
|
5532
|
+
const caps = value.caller_weekly_max_usage;
|
|
5533
|
+
const entries = Object.entries(caps);
|
|
5534
|
+
if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
|
|
5365
5535
|
result.caller_weekly_max_usage = Object.fromEntries(entries);
|
|
5366
5536
|
}
|
|
5367
5537
|
}
|
|
5538
|
+
const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
|
|
5539
|
+
if (ownerDevicesByEmail)
|
|
5540
|
+
result.owner_devices_by_email = ownerDevicesByEmail;
|
|
5368
5541
|
if (isRecord(value.caller_provider_fallback)) {
|
|
5369
5542
|
const entries = Object.entries(value.caller_provider_fallback);
|
|
5370
5543
|
if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
|
|
@@ -5415,9 +5588,11 @@ function sanitizeProviderPool(value) {
|
|
|
5415
5588
|
"distribution_enabled",
|
|
5416
5589
|
"prefer_expiring_quota",
|
|
5417
5590
|
"max_usage",
|
|
5591
|
+
"max_usage_by_email",
|
|
5418
5592
|
"weekly_max_usage",
|
|
5419
5593
|
"weekly_max_usage_by_email",
|
|
5420
5594
|
"caller_weekly_max_usage",
|
|
5595
|
+
"owner_devices_by_email",
|
|
5421
5596
|
"quota_probe_seconds",
|
|
5422
5597
|
"window_warmup"
|
|
5423
5598
|
]) {
|
|
@@ -5439,8 +5614,17 @@ function sanitizeProviderPool(value) {
|
|
|
5439
5614
|
}
|
|
5440
5615
|
if (typeof value.block_when_all_full === "boolean")
|
|
5441
5616
|
pool.block_when_all_full = value.block_when_all_full;
|
|
5617
|
+
const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
|
|
5618
|
+
if (nightPacing)
|
|
5619
|
+
pool.caller_night_pacing = nightPacing;
|
|
5442
5620
|
return pool;
|
|
5443
5621
|
}
|
|
5622
|
+
function sanitizeCallerNightPacing(value) {
|
|
5623
|
+
if (!isRecord(value))
|
|
5624
|
+
return;
|
|
5625
|
+
const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
|
|
5626
|
+
return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
|
|
5627
|
+
}
|
|
5444
5628
|
function sanitizeRouting(value) {
|
|
5445
5629
|
if (!isRecord(value))
|
|
5446
5630
|
return;
|
|
@@ -5504,15 +5688,17 @@ function clientRouting(client2) {
|
|
|
5504
5688
|
...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
|
|
5505
5689
|
};
|
|
5506
5690
|
}
|
|
5507
|
-
var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
5691
|
+
var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, isCallerWeeklyCap = (cap) => isFiniteNumber(cap) && cap > 0 && cap <= 0.95, sharesACallerCap = (caps, cap) => typeof cap === "string" && Object.hasOwn(caps, cap) && isCallerWeeklyCap(caps[cap]), POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
5508
5692
|
var init_src8 = __esm(() => {
|
|
5509
5693
|
init_src2();
|
|
5510
5694
|
init_src4();
|
|
5511
5695
|
init_src();
|
|
5512
5696
|
init_builtin_providers();
|
|
5697
|
+
init_night_pacing();
|
|
5513
5698
|
init_paths();
|
|
5514
5699
|
init_rewrite_file();
|
|
5515
5700
|
init_window_warmup();
|
|
5701
|
+
init_night_pacing();
|
|
5516
5702
|
init_paths();
|
|
5517
5703
|
init_paths_common();
|
|
5518
5704
|
init_rewrite_config();
|
|
@@ -5538,9 +5724,12 @@ var init_src8 = __esm(() => {
|
|
|
5538
5724
|
preferExpiringQuota: false,
|
|
5539
5725
|
allowlistedAccountUuids: [],
|
|
5540
5726
|
maxUsage: 0.9,
|
|
5727
|
+
maxUsageByEmail: {},
|
|
5541
5728
|
weeklyMaxUsage: 0.95,
|
|
5542
5729
|
weeklyMaxUsageByEmail: {},
|
|
5543
5730
|
callerWeeklyMaxUsage: {},
|
|
5731
|
+
callerNightPacing: {},
|
|
5732
|
+
ownerDevicesByEmail: {},
|
|
5544
5733
|
admissionCap: 5,
|
|
5545
5734
|
admissionQueueLimit: 25,
|
|
5546
5735
|
admissionWaitMs: 30000,
|
|
@@ -5714,9 +5903,12 @@ var init_src8 = __esm(() => {
|
|
|
5714
5903
|
preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
|
|
5715
5904
|
allowlistedAccountUuids: [...pool?.members ?? []],
|
|
5716
5905
|
maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
|
|
5906
|
+
maxUsageByEmail: { ...pool?.max_usage_by_email },
|
|
5717
5907
|
weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
|
|
5718
5908
|
weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
|
|
5719
5909
|
callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
|
|
5910
|
+
callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
|
|
5911
|
+
ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
|
|
5720
5912
|
admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
|
|
5721
5913
|
admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
|
|
5722
5914
|
admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
|
|
@@ -5793,9 +5985,12 @@ var init_src8 = __esm(() => {
|
|
|
5793
5985
|
"distribution_enabled",
|
|
5794
5986
|
"prefer_expiring_quota",
|
|
5795
5987
|
"max_usage",
|
|
5988
|
+
"max_usage_by_email",
|
|
5796
5989
|
"weekly_max_usage",
|
|
5797
5990
|
"weekly_max_usage_by_email",
|
|
5798
5991
|
"caller_weekly_max_usage",
|
|
5992
|
+
"caller_night_pacing",
|
|
5993
|
+
"owner_devices_by_email",
|
|
5799
5994
|
"admission",
|
|
5800
5995
|
"quota_probe_seconds",
|
|
5801
5996
|
"window_warmup",
|
|
@@ -6017,10 +6212,11 @@ function addPerformanceIndexes(db) {
|
|
|
6017
6212
|
`);
|
|
6018
6213
|
log7.info("Added index: idx_accounts_paused");
|
|
6019
6214
|
db.run(`
|
|
6020
|
-
CREATE INDEX IF NOT EXISTS
|
|
6021
|
-
ON requests(account_used, timestamp DESC)
|
|
6215
|
+
CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp_cost
|
|
6216
|
+
ON requests(account_used, timestamp DESC, cost_usd)
|
|
6022
6217
|
`);
|
|
6023
|
-
|
|
6218
|
+
db.run("DROP INDEX IF EXISTS idx_requests_account_timestamp");
|
|
6219
|
+
log7.info("Added index: idx_requests_account_timestamp_cost");
|
|
6024
6220
|
db.run(`
|
|
6025
6221
|
CREATE INDEX IF NOT EXISTS idx_requests_cost_model
|
|
6026
6222
|
ON requests(cost_usd, model, timestamp DESC)
|
|
@@ -6386,7 +6582,8 @@ function ensureRequestLinkageColumns(db) {
|
|
|
6386
6582
|
["ttft_ms", "INTEGER"],
|
|
6387
6583
|
["proxy_overhead_ms", "INTEGER"],
|
|
6388
6584
|
["upstream_ttfb_ms", "INTEGER"],
|
|
6389
|
-
["streaming_duration_ms", "INTEGER"]
|
|
6585
|
+
["streaming_duration_ms", "INTEGER"],
|
|
6586
|
+
["caller", "TEXT"]
|
|
6390
6587
|
];
|
|
6391
6588
|
for (const [columnName, columnType] of requestColumns) {
|
|
6392
6589
|
if (!hasColumn(columns, columnName)) {
|
|
@@ -6410,6 +6607,13 @@ function ensureAccountExtensionColumns(db) {
|
|
|
6410
6607
|
}
|
|
6411
6608
|
}
|
|
6412
6609
|
}
|
|
6610
|
+
function backfillRequestLinkageColumnsOnce(db) {
|
|
6611
|
+
const { user_version } = db.query("PRAGMA user_version").get();
|
|
6612
|
+
if (user_version >= LINKAGE_BACKFILLED_VERSION)
|
|
6613
|
+
return;
|
|
6614
|
+
backfillRequestLinkageColumns(db);
|
|
6615
|
+
db.run(`PRAGMA user_version = ${LINKAGE_BACKFILLED_VERSION}`);
|
|
6616
|
+
}
|
|
6413
6617
|
function backfillRequestLinkageColumns(db) {
|
|
6414
6618
|
const missingCount = db.query(`
|
|
6415
6619
|
SELECT COUNT(*) AS count
|
|
@@ -6804,7 +7008,8 @@ function ensureSchema(db) {
|
|
|
6804
7008
|
ttft_ms INTEGER,
|
|
6805
7009
|
proxy_overhead_ms INTEGER,
|
|
6806
7010
|
upstream_ttfb_ms INTEGER,
|
|
6807
|
-
streaming_duration_ms INTEGER
|
|
7011
|
+
streaming_duration_ms INTEGER,
|
|
7012
|
+
caller TEXT
|
|
6808
7013
|
)
|
|
6809
7014
|
`);
|
|
6810
7015
|
db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
|
|
@@ -6832,7 +7037,7 @@ function runMigrations(db) {
|
|
|
6832
7037
|
migrateRequestsTable(db, requestsInfo);
|
|
6833
7038
|
}
|
|
6834
7039
|
ensureRequestLinkageColumns(db);
|
|
6835
|
-
|
|
7040
|
+
backfillRequestLinkageColumnsOnce(db);
|
|
6836
7041
|
db.run("DROP TABLE IF EXISTS agent_preferences");
|
|
6837
7042
|
db.run("DROP TABLE IF EXISTS oauth_sessions");
|
|
6838
7043
|
db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
|
|
@@ -6848,7 +7053,7 @@ function runMigrations(db) {
|
|
|
6848
7053
|
db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
|
|
6849
7054
|
addPerformanceIndexes(db);
|
|
6850
7055
|
}
|
|
6851
|
-
var log9;
|
|
7056
|
+
var log9, LINKAGE_BACKFILLED_VERSION = 1;
|
|
6852
7057
|
var init_migrations = __esm(() => {
|
|
6853
7058
|
init_src4();
|
|
6854
7059
|
init_src();
|
|
@@ -7258,6 +7463,30 @@ var init_analytics_repository = __esm(() => {
|
|
|
7258
7463
|
totalTokens: row.total_tokens ?? 0,
|
|
7259
7464
|
totalCostUsd: row.total_cost_usd ?? 0
|
|
7260
7465
|
}));
|
|
7466
|
+
const callerBreakdown = this.query(`
|
|
7467
|
+
SELECT
|
|
7468
|
+
r.caller as caller,
|
|
7469
|
+
COUNT(*) as requests,
|
|
7470
|
+
SUM(COALESCE(r.input_tokens, 0)) as input_tokens,
|
|
7471
|
+
SUM(COALESCE(r.cache_read_input_tokens, 0)) as cache_read_input_tokens,
|
|
7472
|
+
SUM(COALESCE(r.cache_creation_input_tokens, 0)) as cache_creation_input_tokens,
|
|
7473
|
+
SUM(COALESCE(r.output_tokens, 0)) as output_tokens,
|
|
7474
|
+
SUM(COALESCE(r.cost_usd, 0)) as total_cost_usd
|
|
7475
|
+
FROM requests r
|
|
7476
|
+
WHERE ${whereClause}
|
|
7477
|
+
GROUP BY r.caller
|
|
7478
|
+
ORDER BY total_cost_usd DESC, requests DESC
|
|
7479
|
+
`, queryParams).map((row) => ({
|
|
7480
|
+
caller: row.caller,
|
|
7481
|
+
requests: row.requests,
|
|
7482
|
+
tokenBreakdown: {
|
|
7483
|
+
inputTokens: row.input_tokens ?? 0,
|
|
7484
|
+
cacheReadInputTokens: row.cache_read_input_tokens ?? 0,
|
|
7485
|
+
cacheCreationInputTokens: row.cache_creation_input_tokens ?? 0,
|
|
7486
|
+
outputTokens: row.output_tokens ?? 0
|
|
7487
|
+
},
|
|
7488
|
+
totalCostUsd: row.total_cost_usd ?? 0
|
|
7489
|
+
}));
|
|
7261
7490
|
const modelPerformance = this.query(`
|
|
7262
7491
|
WITH model_stats AS (
|
|
7263
7492
|
SELECT
|
|
@@ -7354,6 +7583,7 @@ var init_analytics_repository = __esm(() => {
|
|
|
7354
7583
|
successRate: account2.success_rate ?? 0
|
|
7355
7584
|
})),
|
|
7356
7585
|
providerBreakdown,
|
|
7586
|
+
callerBreakdown,
|
|
7357
7587
|
costByModel,
|
|
7358
7588
|
modelPerformance
|
|
7359
7589
|
};
|
|
@@ -7670,7 +7900,7 @@ function requestLinkageFromPayload(payload) {
|
|
|
7670
7900
|
clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
|
|
7671
7901
|
};
|
|
7672
7902
|
}
|
|
7673
|
-
var log10, RequestRepository;
|
|
7903
|
+
var log10, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
|
|
7674
7904
|
var init_request_repository = __esm(() => {
|
|
7675
7905
|
init_src4();
|
|
7676
7906
|
init_src();
|
|
@@ -7748,7 +7978,8 @@ var init_request_repository = __esm(() => {
|
|
|
7748
7978
|
response_id = ?,
|
|
7749
7979
|
previous_response_id = ?,
|
|
7750
7980
|
response_chain_id = ?,
|
|
7751
|
-
client_session_id =
|
|
7981
|
+
client_session_id = ?,
|
|
7982
|
+
caller = ?
|
|
7752
7983
|
WHERE id = ?
|
|
7753
7984
|
`, [
|
|
7754
7985
|
data.method,
|
|
@@ -7780,6 +8011,7 @@ var init_request_repository = __esm(() => {
|
|
|
7780
8011
|
linkage.previousResponseId,
|
|
7781
8012
|
responseChainId,
|
|
7782
8013
|
linkage.clientSessionId,
|
|
8014
|
+
data.caller ?? null,
|
|
7783
8015
|
data.id
|
|
7784
8016
|
]);
|
|
7785
8017
|
if (payloadJson !== undefined) {
|
|
@@ -8042,6 +8274,12 @@ var init_request_repository = __esm(() => {
|
|
|
8042
8274
|
`, [limit]);
|
|
8043
8275
|
return errors2.map((e) => e.error_message);
|
|
8044
8276
|
}
|
|
8277
|
+
sumAccountCostSince(accountId, since) {
|
|
8278
|
+
return this.get(ACCOUNT_COST_SINCE_SQL, [
|
|
8279
|
+
accountId,
|
|
8280
|
+
since
|
|
8281
|
+
])?.cost ?? 0;
|
|
8282
|
+
}
|
|
8045
8283
|
getRequestsByAccount(since) {
|
|
8046
8284
|
const whereClause = since ? "WHERE r.timestamp > ?" : "";
|
|
8047
8285
|
const params = since ? [since] : [];
|
|
@@ -8064,23 +8302,26 @@ var init_request_repository = __esm(() => {
|
|
|
8064
8302
|
successRate: row.success_rate
|
|
8065
8303
|
}));
|
|
8066
8304
|
}
|
|
8067
|
-
deleteOlderThan(cutoffTs) {
|
|
8068
|
-
return this.runWithChanges(`DELETE FROM requests WHERE
|
|
8069
|
-
|
|
8070
|
-
|
|
8305
|
+
deleteOlderThan(cutoffTs, limit) {
|
|
8306
|
+
return this.runWithChanges(`DELETE FROM requests WHERE rowid IN (
|
|
8307
|
+
SELECT rowid FROM requests WHERE timestamp < ? LIMIT ?
|
|
8308
|
+
)`, [cutoffTs, limit]);
|
|
8071
8309
|
}
|
|
8072
8310
|
clear() {
|
|
8073
8311
|
return this.runWithChanges(`DELETE FROM requests`);
|
|
8074
8312
|
}
|
|
8075
|
-
|
|
8076
|
-
|
|
8077
|
-
|
|
8078
|
-
|
|
8079
|
-
|
|
8080
|
-
|
|
8081
|
-
|
|
8082
|
-
|
|
8083
|
-
|
|
8313
|
+
deleteOldestExpiredPayloads(cutoffTs, limit) {
|
|
8314
|
+
const oldest = this.query(`SELECT rp.rowid AS rowid, r.timestamp AS timestamp
|
|
8315
|
+
FROM request_payloads rp
|
|
8316
|
+
LEFT JOIN requests r ON r.id = rp.id
|
|
8317
|
+
ORDER BY rp.rowid
|
|
8318
|
+
LIMIT ?`, [limit]);
|
|
8319
|
+
const firstLive = oldest.findIndex(({ timestamp }) => timestamp !== null && timestamp >= cutoffTs);
|
|
8320
|
+
const expiredCount = firstLive === -1 ? oldest.length : firstLive;
|
|
8321
|
+
const lastExpired = oldest[expiredCount - 1];
|
|
8322
|
+
if (!lastExpired)
|
|
8323
|
+
return 0;
|
|
8324
|
+
return this.runWithChanges(`DELETE FROM request_payloads WHERE rowid <= ?`, [lastExpired.rowid]);
|
|
8084
8325
|
}
|
|
8085
8326
|
};
|
|
8086
8327
|
});
|
|
@@ -8209,6 +8450,7 @@ var init_strategy_repository = __esm(() => {
|
|
|
8209
8450
|
import { Database } from "bun:sqlite";
|
|
8210
8451
|
import { mkdirSync as mkdirSync3, statfsSync } from "fs";
|
|
8211
8452
|
import { dirname as dirname3 } from "path";
|
|
8453
|
+
import { setImmediate as yieldToEventLoop } from "timers/promises";
|
|
8212
8454
|
function freeDiskBytes(directory) {
|
|
8213
8455
|
const { bavail, bsize } = statfsSync(directory);
|
|
8214
8456
|
return bavail * bsize;
|
|
@@ -8228,7 +8470,7 @@ class DatabaseOperations {
|
|
|
8228
8470
|
conversationProviderPreferences;
|
|
8229
8471
|
strategy;
|
|
8230
8472
|
stats;
|
|
8231
|
-
constructor(dbPath) {
|
|
8473
|
+
constructor(dbPath, { migrate = true } = {}) {
|
|
8232
8474
|
const resolvedPath = dbPath ?? resolveDbPath();
|
|
8233
8475
|
this.dbPath = resolvedPath;
|
|
8234
8476
|
const dir = dirname3(resolvedPath);
|
|
@@ -8238,8 +8480,11 @@ class DatabaseOperations {
|
|
|
8238
8480
|
this.db.exec("PRAGMA journal_mode = WAL");
|
|
8239
8481
|
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
8240
8482
|
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
8241
|
-
|
|
8242
|
-
|
|
8483
|
+
this.db.exec(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);
|
|
8484
|
+
if (migrate) {
|
|
8485
|
+
ensureSchema(this.db);
|
|
8486
|
+
runMigrations(this.db);
|
|
8487
|
+
}
|
|
8243
8488
|
this.accounts = new AccountRepository(this.db);
|
|
8244
8489
|
this.analytics = new AnalyticsRepository(this.db);
|
|
8245
8490
|
this.requests = new RequestRepository(this.db);
|
|
@@ -8385,9 +8630,13 @@ class DatabaseOperations {
|
|
|
8385
8630
|
timestamp: options?.timestamp,
|
|
8386
8631
|
payload: options?.payload,
|
|
8387
8632
|
storePayload: options?.storePayload,
|
|
8388
|
-
timings: options?.timings
|
|
8633
|
+
timings: options?.timings,
|
|
8634
|
+
caller: options?.callerId ?? null
|
|
8389
8635
|
});
|
|
8390
8636
|
}
|
|
8637
|
+
getAccountCostSince(accountId, since) {
|
|
8638
|
+
return this.requests.sumAccountCostSince(accountId, since);
|
|
8639
|
+
}
|
|
8391
8640
|
updateRequestUsage(requestId, usage) {
|
|
8392
8641
|
this.requests.updateUsage(requestId, usage);
|
|
8393
8642
|
}
|
|
@@ -8451,18 +8700,40 @@ class DatabaseOperations {
|
|
|
8451
8700
|
getAnalytics(options) {
|
|
8452
8701
|
return this.analytics.getAnalytics(options);
|
|
8453
8702
|
}
|
|
8454
|
-
cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
|
|
8455
|
-
const
|
|
8456
|
-
const
|
|
8457
|
-
|
|
8458
|
-
|
|
8459
|
-
|
|
8460
|
-
|
|
8703
|
+
cleanupOldRequests(payloadRetentionMs, requestRetentionMs, batchRows = CLEANUP_BATCH_ROWS) {
|
|
8704
|
+
const total = { removedRequests: 0, removedPayloads: 0 };
|
|
8705
|
+
for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
|
|
8706
|
+
total.removedRequests += batch.removedRequests;
|
|
8707
|
+
total.removedPayloads += batch.removedPayloads;
|
|
8708
|
+
}
|
|
8709
|
+
return total;
|
|
8710
|
+
}
|
|
8711
|
+
async cleanupOldRequestsInBatches(payloadRetentionMs, requestRetentionMs, {
|
|
8712
|
+
batchRows = CLEANUP_BATCH_ROWS,
|
|
8713
|
+
signal
|
|
8714
|
+
} = {}) {
|
|
8715
|
+
const total = { removedRequests: 0, removedPayloads: 0 };
|
|
8716
|
+
for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
|
|
8717
|
+
total.removedRequests += batch.removedRequests;
|
|
8718
|
+
total.removedPayloads += batch.removedPayloads;
|
|
8719
|
+
await yieldToEventLoop();
|
|
8720
|
+
if (signal?.aborted)
|
|
8721
|
+
break;
|
|
8722
|
+
}
|
|
8723
|
+
return total;
|
|
8724
|
+
}
|
|
8725
|
+
*cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows) {
|
|
8726
|
+
for (;; ) {
|
|
8727
|
+
const now = Date.now();
|
|
8728
|
+
let removedRequests = 0;
|
|
8729
|
+
if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
|
|
8730
|
+
removedRequests = this.requests.deleteOlderThan(now - requestRetentionMs, batchRows);
|
|
8731
|
+
}
|
|
8732
|
+
const removedPayloads = this.requests.deleteOldestExpiredPayloads(now - payloadRetentionMs, batchRows);
|
|
8733
|
+
yield { removedRequests, removedPayloads };
|
|
8734
|
+
if (removedRequests < batchRows && removedPayloads < batchRows)
|
|
8735
|
+
return;
|
|
8461
8736
|
}
|
|
8462
|
-
const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
|
|
8463
|
-
const removedOrphans = this.requests.deleteOrphanedPayloads();
|
|
8464
|
-
const removedPayloads = removedPayloadsByAge + removedOrphans;
|
|
8465
|
-
return { removedRequests, removedPayloads };
|
|
8466
8737
|
}
|
|
8467
8738
|
close() {
|
|
8468
8739
|
if (this.closed) {
|
|
@@ -8501,6 +8772,7 @@ class DatabaseOperations {
|
|
|
8501
8772
|
return this.stats;
|
|
8502
8773
|
}
|
|
8503
8774
|
}
|
|
8775
|
+
var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
|
|
8504
8776
|
var init_database_operations = __esm(() => {
|
|
8505
8777
|
init_migrations();
|
|
8506
8778
|
init_paths2();
|
|
@@ -8513,6 +8785,7 @@ var init_database_operations = __esm(() => {
|
|
|
8513
8785
|
init_request_repository();
|
|
8514
8786
|
init_stats_repository();
|
|
8515
8787
|
init_strategy_repository();
|
|
8788
|
+
WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
8516
8789
|
});
|
|
8517
8790
|
|
|
8518
8791
|
// ../../packages/database/src/factory.ts
|
|
@@ -8691,8 +8964,11 @@ var init_analytics = __esm(() => {
|
|
|
8691
8964
|
// ../../packages/api/src/handlers/config.ts
|
|
8692
8965
|
function publicProviderPool(config, name) {
|
|
8693
8966
|
const {
|
|
8967
|
+
maxUsageByEmail: _fiveHour,
|
|
8694
8968
|
weeklyMaxUsageByEmail: _weekly,
|
|
8695
8969
|
callerWeeklyMaxUsage: _caller,
|
|
8970
|
+
callerNightPacing: _nightPacing,
|
|
8971
|
+
ownerDevicesByEmail: _owners,
|
|
8696
8972
|
...pool
|
|
8697
8973
|
} = config.getTeamRouting(name);
|
|
8698
8974
|
return pool;
|
|
@@ -9659,13 +9935,13 @@ var init_logs_history = __esm(() => {
|
|
|
9659
9935
|
|
|
9660
9936
|
// ../../packages/api/src/handlers/maintenance.ts
|
|
9661
9937
|
function createCleanupHandler(dbOps, config) {
|
|
9662
|
-
return () => {
|
|
9938
|
+
return async () => {
|
|
9663
9939
|
try {
|
|
9664
9940
|
const payloadDays = config.getDataRetentionDays();
|
|
9665
9941
|
const requestDays = config.getRequestRetentionDays();
|
|
9666
9942
|
const payloadMs = payloadDays * 24 * 60 * 60 * 1000;
|
|
9667
9943
|
const requestMs = requestDays * 24 * 60 * 60 * 1000;
|
|
9668
|
-
const { removedRequests, removedPayloads } = dbOps.
|
|
9944
|
+
const { removedRequests, removedPayloads } = await dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs);
|
|
9669
9945
|
const cutoffIso = new Date(Date.now() - Math.min(payloadMs, requestMs)).toISOString();
|
|
9670
9946
|
const cleanupData = {
|
|
9671
9947
|
removedRequests,
|
|
@@ -10184,7 +10460,7 @@ class APIRouter {
|
|
|
10184
10460
|
error: `A registered device key is required in ${DEVICE_KEY_HEADER}`
|
|
10185
10461
|
}, { status: 401 });
|
|
10186
10462
|
}
|
|
10187
|
-
const status = await getCallerPoolStatus(pool, model, callerId);
|
|
10463
|
+
const status = await getCallerPoolStatus(pool, model, callerId, url.searchParams.get("nightBudget") === "1");
|
|
10188
10464
|
if (!status) {
|
|
10189
10465
|
return Response.json({ error: "No provider in this pool serves the model" }, { status: 400 });
|
|
10190
10466
|
}
|
|
@@ -10554,9 +10830,12 @@ class TeamAdmission {
|
|
|
10554
10830
|
preferExpiringQuota: false,
|
|
10555
10831
|
allowlistedAccountUuids: [],
|
|
10556
10832
|
maxUsage: 0.9,
|
|
10833
|
+
maxUsageByEmail: {},
|
|
10557
10834
|
weeklyMaxUsage: 0.95,
|
|
10558
10835
|
weeklyMaxUsageByEmail: {},
|
|
10559
10836
|
callerWeeklyMaxUsage: {},
|
|
10837
|
+
callerNightPacing: {},
|
|
10838
|
+
ownerDevicesByEmail: {},
|
|
10560
10839
|
admissionCap: 1,
|
|
10561
10840
|
admissionQueueLimit: 0,
|
|
10562
10841
|
admissionWaitMs: 0,
|
|
@@ -10978,13 +11257,17 @@ function pinKey(request3, provider) {
|
|
|
10978
11257
|
function isAllowlisted(account2, config) {
|
|
10979
11258
|
return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
|
|
10980
11259
|
}
|
|
11260
|
+
function soonestToUseUp(accounts, useUpResetAt) {
|
|
11261
|
+
const soonest = Math.min(...accounts.map(useUpResetAt));
|
|
11262
|
+
return soonest === Number.POSITIVE_INFINITY ? accounts : accounts.filter((account2) => useUpResetAt(account2) === soonest);
|
|
11263
|
+
}
|
|
10981
11264
|
|
|
10982
11265
|
class TeamRouter {
|
|
10983
11266
|
inFlight = new Map;
|
|
10984
11267
|
pins = new Map;
|
|
10985
11268
|
pinLookups = new WeakMap;
|
|
10986
11269
|
cleanedLookups = new WeakSet;
|
|
10987
|
-
order(accounts, request3, config, provider, store, now = Date.now()) {
|
|
11270
|
+
order(accounts, request3, config, provider, store, now = Date.now(), useUpResetAt = () => Number.POSITIVE_INFINITY) {
|
|
10988
11271
|
if (!config.enabled || !request3)
|
|
10989
11272
|
return accounts;
|
|
10990
11273
|
this.removeExpiredPinsOnce(request3, now, store);
|
|
@@ -11003,7 +11286,7 @@ class TeamRouter {
|
|
|
11003
11286
|
}
|
|
11004
11287
|
if (!config.distributionEnabled || !key)
|
|
11005
11288
|
return eligible;
|
|
11006
|
-
const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
|
|
11289
|
+
const selected = this.leastUsedPriorityAccount(soonestToUseUp(eligible, useUpResetAt), compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
|
|
11007
11290
|
this.touchPin(key, selected.id, now, store);
|
|
11008
11291
|
return [
|
|
11009
11292
|
selected,
|
|
@@ -11091,37 +11374,144 @@ var init_seat_router = __esm(() => {
|
|
|
11091
11374
|
PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
11092
11375
|
});
|
|
11093
11376
|
|
|
11377
|
+
// ../../packages/pool/src/night-pacing.ts
|
|
11378
|
+
function callerNightPacing(pool, callerId) {
|
|
11379
|
+
return callerId && pool.enabled && Object.hasOwn(pool.callerNightPacing, callerId) ? pool.callerNightPacing[callerId] ?? null : null;
|
|
11380
|
+
}
|
|
11381
|
+
function pacedNight(pool, account2, now, callerId) {
|
|
11382
|
+
const pacing = callerNightPacing(pool, callerId);
|
|
11383
|
+
if (!pacing || !isAllowlisted(account2, pool))
|
|
11384
|
+
return null;
|
|
11385
|
+
const endAt = nightEndAt(pacing, now);
|
|
11386
|
+
return endAt === null ? null : { pacing, endAt };
|
|
11387
|
+
}
|
|
11388
|
+
function startsWindowIntoMorning(provider, account2, night, now) {
|
|
11389
|
+
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);
|
|
11390
|
+
}
|
|
11391
|
+
function weeklyWindows(provider, account2, model, now) {
|
|
11392
|
+
return Object.entries(account2.quota_state?.windows ?? {}).flatMap(([bucket, window2]) => {
|
|
11393
|
+
if (window2.resetAt === null || !provider.isWeeklyBucket(bucket) || !(provider.quotaBucketsFor(model)?.includes(bucket) ?? true)) {
|
|
11394
|
+
return [];
|
|
11395
|
+
}
|
|
11396
|
+
const rolled = window2.resetAt <= now;
|
|
11397
|
+
const resetAt2 = rolled ? window2.resetAt + (Math.floor((now - window2.resetAt) / WEEKLY_WINDOW_MS) + 1) * WEEKLY_WINDOW_MS : window2.resetAt;
|
|
11398
|
+
return [
|
|
11399
|
+
{
|
|
11400
|
+
bucket,
|
|
11401
|
+
resetAt: resetAt2,
|
|
11402
|
+
used: rolled ? 0 : window2.status === "rejected" ? 1 : window2.utilization ?? 0
|
|
11403
|
+
}
|
|
11404
|
+
];
|
|
11405
|
+
});
|
|
11406
|
+
}
|
|
11407
|
+
function nightWeeklyWindows(provider, account2, model, pacing, now) {
|
|
11408
|
+
return weeklyWindows(provider, account2, model, now).map((window2) => ({
|
|
11409
|
+
...window2,
|
|
11410
|
+
target: nightWeeklyTarget(pacing, window2.resetAt, now)
|
|
11411
|
+
}));
|
|
11412
|
+
}
|
|
11413
|
+
function useUpResetAt(provider, account2, model, pool, now, callerId) {
|
|
11414
|
+
const night = pacedNight(pool, account2, now, callerId);
|
|
11415
|
+
if (!night)
|
|
11416
|
+
return Number.POSITIVE_INFINITY;
|
|
11417
|
+
return Math.min(...weeklyWindows(provider, account2, model, now).flatMap(({ resetAt: resetAt2 }) => expiresBeforeUseUpTime(night.pacing, resetAt2, now) ? [resetAt2] : []), Number.POSITIVE_INFINITY);
|
|
11418
|
+
}
|
|
11419
|
+
function nightPacingBlock(provider, account2, model, pool, now, callerId) {
|
|
11420
|
+
const night = pacedNight(pool, account2, now, callerId);
|
|
11421
|
+
if (!night)
|
|
11422
|
+
return null;
|
|
11423
|
+
if (startsWindowIntoMorning(provider, account2, night, now)) {
|
|
11424
|
+
return { category: "five-hour-limit", retryAt: night.endAt };
|
|
11425
|
+
}
|
|
11426
|
+
return nightWeeklyWindows(provider, account2, model, night.pacing, now).some((window2) => window2.used >= Math.max(0, window2.target)) ? { category: "weekly-limit", retryAt: night.endAt } : null;
|
|
11427
|
+
}
|
|
11428
|
+
function median(values) {
|
|
11429
|
+
if (values.length === 0)
|
|
11430
|
+
return 0;
|
|
11431
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
11432
|
+
const upper = sorted[Math.floor(sorted.length / 2)] ?? 0;
|
|
11433
|
+
const lower = sorted[Math.ceil(sorted.length / 2) - 1] ?? 0;
|
|
11434
|
+
return (lower + upper) / 2;
|
|
11435
|
+
}
|
|
11436
|
+
function seatsNightCostEq(provider, seats, model, pacing, now, costSince, weeklyCap) {
|
|
11437
|
+
const endAt = nightEndAt(pacing, now);
|
|
11438
|
+
const headrooms = seats.flatMap((account2) => {
|
|
11439
|
+
if (endAt !== null && startsWindowIntoMorning(provider, account2, { pacing, endAt }, now)) {
|
|
11440
|
+
return [];
|
|
11441
|
+
}
|
|
11442
|
+
const [binding] = nightWeeklyWindows(provider, account2, model, pacing, now).map((window2) => ({
|
|
11443
|
+
...window2,
|
|
11444
|
+
ceiling: Math.min(window2.target, weeklyCap(account2, window2.bucket))
|
|
11445
|
+
})).sort((left, right) => left.ceiling - left.used - (right.ceiling - right.used));
|
|
11446
|
+
if (!binding)
|
|
11447
|
+
return [];
|
|
11448
|
+
const usedPoints = binding.used * 100;
|
|
11449
|
+
return [
|
|
11450
|
+
{
|
|
11451
|
+
points: Math.max(0, binding.ceiling - binding.used) * 100,
|
|
11452
|
+
costPerPoint: usedPoints >= MIN_OWN_RATE_POINTS ? costSince(account2.id, binding.resetAt - WEEKLY_WINDOW_MS) / usedPoints : null
|
|
11453
|
+
}
|
|
11454
|
+
];
|
|
11455
|
+
});
|
|
11456
|
+
const fallbackRate = median(headrooms.flatMap(({ costPerPoint }) => costPerPoint === null ? [] : [costPerPoint]));
|
|
11457
|
+
return headrooms.reduce((sum, { points, costPerPoint }) => sum + points * (costPerPoint ?? fallbackRate), 0);
|
|
11458
|
+
}
|
|
11459
|
+
var FIVE_HOUR_WINDOW_MS, MIN_OWN_RATE_POINTS = 5;
|
|
11460
|
+
var init_night_pacing2 = __esm(() => {
|
|
11461
|
+
init_src8();
|
|
11462
|
+
init_seat_router();
|
|
11463
|
+
FIVE_HOUR_WINDOW_MS = 5 * 60 * 60000;
|
|
11464
|
+
});
|
|
11465
|
+
|
|
11094
11466
|
// ../../packages/pool/src/handlers/account-selector.ts
|
|
11095
|
-
function
|
|
11467
|
+
function quotaCeiling(account2, bucket, fleetThreshold, maxUsage) {
|
|
11096
11468
|
const accountThreshold = account2.switch_threshold === null || account2.switch_threshold === undefined ? undefined : quotaThresholdFor(account2, bucket, fleetThreshold);
|
|
11097
|
-
|
|
11469
|
+
return maxUsage?.overridesFleetThreshold === true ? Math.min(maxUsage.limit, accountThreshold ?? Number.POSITIVE_INFINITY) : Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage?.limit ?? Number.POSITIVE_INFINITY);
|
|
11470
|
+
}
|
|
11471
|
+
function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
|
|
11472
|
+
const threshold = quotaCeiling(account2, bucket, fleetThreshold, maxUsage);
|
|
11098
11473
|
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
11474
|
}
|
|
11100
|
-
function
|
|
11475
|
+
function capForAccountEmail(capsByEmail, account2, ctx) {
|
|
11476
|
+
if (Object.keys(capsByEmail).length === 0)
|
|
11477
|
+
return;
|
|
11478
|
+
const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
|
|
11479
|
+
return email ? capsByEmail[email] : undefined;
|
|
11480
|
+
}
|
|
11481
|
+
function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
|
|
11101
11482
|
const teamRouting = ctx.runtime.pool;
|
|
11102
11483
|
if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
|
|
11103
11484
|
return;
|
|
11104
11485
|
if (!provider.isWeeklyBucket(bucket)) {
|
|
11105
|
-
|
|
11486
|
+
const accountCap = capForAccountEmail(teamRouting.maxUsageByEmail, account2, ctx);
|
|
11487
|
+
return {
|
|
11488
|
+
limit: Math.min(teamRouting.maxUsage, accountCap ?? Number.POSITIVE_INFINITY),
|
|
11489
|
+
overridesFleetThreshold: false
|
|
11490
|
+
};
|
|
11106
11491
|
}
|
|
11107
|
-
const
|
|
11108
|
-
const
|
|
11109
|
-
const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
|
|
11492
|
+
const accountOverride = capForAccountEmail(teamRouting.weeklyMaxUsageByEmail, account2, ctx);
|
|
11493
|
+
const callerOverride = callerId && !pacedNight(teamRouting, account2, now, callerId) ? callerWeeklyCap(teamRouting.callerWeeklyMaxUsage, callerId) : undefined;
|
|
11110
11494
|
return {
|
|
11111
11495
|
limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
|
|
11112
11496
|
overridesFleetThreshold: accountOverride !== undefined
|
|
11113
11497
|
};
|
|
11114
11498
|
}
|
|
11115
|
-
function
|
|
11116
|
-
const
|
|
11117
|
-
if (!
|
|
11499
|
+
function servesCaller(account2, ctx, callerId) {
|
|
11500
|
+
const ownerDevices = ctx.runtime.pool?.ownerDevicesByEmail;
|
|
11501
|
+
if (!ownerDevices || Object.keys(ownerDevices).length === 0)
|
|
11502
|
+
return true;
|
|
11503
|
+
const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
|
|
11504
|
+
if (!email || !Object.hasOwn(ownerDevices, email))
|
|
11118
11505
|
return true;
|
|
11119
|
-
|
|
11120
|
-
|
|
11506
|
+
return callerId !== undefined && !!ownerDevices[email]?.includes(callerId);
|
|
11507
|
+
}
|
|
11508
|
+
function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
|
|
11509
|
+
for (const [name, window2] of Object.entries(account2.quota_state?.windows ?? {})) {
|
|
11510
|
+
if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, now, callerId))) {
|
|
11121
11511
|
return false;
|
|
11122
11512
|
}
|
|
11123
11513
|
}
|
|
11124
|
-
return
|
|
11514
|
+
return nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId) === null;
|
|
11125
11515
|
}
|
|
11126
11516
|
function fleetAccounts(provider, ctx) {
|
|
11127
11517
|
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
|
|
@@ -11145,19 +11535,23 @@ function callerPoolAccounts(provider, ctx, orderedFallback) {
|
|
|
11145
11535
|
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx) || orderedFallback && !account2.paused && account2.auth_method === "api_key");
|
|
11146
11536
|
}
|
|
11147
11537
|
function blockingResets(provider, account2, model, ctx, now, callerId) {
|
|
11148
|
-
|
|
11538
|
+
const nightEnd = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId)?.retryAt;
|
|
11539
|
+
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
11540
|
}
|
|
11150
11541
|
function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
|
|
11151
|
-
const
|
|
11542
|
+
const night = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId);
|
|
11543
|
+
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
11544
|
if (blocking.length === 0)
|
|
11153
|
-
return
|
|
11545
|
+
return night;
|
|
11154
11546
|
const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
|
|
11155
11547
|
const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
|
|
11156
11548
|
const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
|
|
11157
11549
|
return rightReset - leftReset;
|
|
11158
11550
|
})[0];
|
|
11159
11551
|
const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
|
|
11160
|
-
|
|
11552
|
+
if (window2.resetAt === null)
|
|
11553
|
+
return { category };
|
|
11554
|
+
return night?.retryAt !== undefined && night.retryAt > window2.resetAt ? night : { category, retryAt: window2.resetAt };
|
|
11161
11555
|
}
|
|
11162
11556
|
function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
|
|
11163
11557
|
const now = Date.now();
|
|
@@ -11199,19 +11593,30 @@ function getPoolStatus(provider, model, ctx) {
|
|
|
11199
11593
|
admissionWaitMs: config?.admissionWaitMs ?? 0
|
|
11200
11594
|
};
|
|
11201
11595
|
}
|
|
11202
|
-
function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts) {
|
|
11596
|
+
function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts, readNightBudget) {
|
|
11203
11597
|
const strategy3 = ctx.providerRegistry.getProvider(provider);
|
|
11204
11598
|
if (!strategy3)
|
|
11205
11599
|
throw new Error(`Unknown provider '${provider}'`);
|
|
11206
11600
|
const config = ctx.runtime.pool;
|
|
11207
11601
|
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"));
|
|
11602
|
+
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
11603
|
const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
|
|
11604
|
+
const nightBudget = readNightBudget ? callerNightBudget(strategy3, accounts, model, callerId, ctx, now) : null;
|
|
11210
11605
|
return {
|
|
11211
11606
|
poolEnabled: config.enabled,
|
|
11212
11607
|
servableSeats,
|
|
11213
11608
|
retryAt: servableSeats === 0 ? soonestServableAt(strategy3, accounts, accounts, model, ctx, now, callerId) : null,
|
|
11214
|
-
admissionWaitMs: config.admissionWaitMs
|
|
11609
|
+
admissionWaitMs: config.admissionWaitMs,
|
|
11610
|
+
...nightBudget && { nightBudget }
|
|
11611
|
+
};
|
|
11612
|
+
}
|
|
11613
|
+
function callerNightBudget(provider, accounts, model, callerId, ctx, now) {
|
|
11614
|
+
const pacing = callerNightPacing(ctx.runtime.pool, callerId);
|
|
11615
|
+
if (!pacing)
|
|
11616
|
+
return null;
|
|
11617
|
+
return {
|
|
11618
|
+
night: nightEndAt(pacing, now) !== null,
|
|
11619
|
+
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
11620
|
};
|
|
11216
11621
|
}
|
|
11217
11622
|
function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
|
|
@@ -11239,19 +11644,23 @@ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
|
|
|
11239
11644
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
11240
11645
|
const now = Date.now();
|
|
11241
11646
|
const callerId = teamRequest?.callerId;
|
|
11242
|
-
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
|
|
11647
|
+
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null && servesCaller(account2, ctx, callerId));
|
|
11243
11648
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
|
|
11244
11649
|
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.pool.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
|
|
11245
|
-
const
|
|
11246
|
-
|
|
11247
|
-
|
|
11248
|
-
|
|
11650
|
+
const useUpResets = new Map(candidates.map((account2) => [
|
|
11651
|
+
account2.id,
|
|
11652
|
+
useUpResetAt(ctx.provider, account2, meta.model, ctx.runtime.pool, now, callerId)
|
|
11653
|
+
]));
|
|
11654
|
+
const useUpAt = (account2) => useUpResets.get(account2.id) ?? Number.POSITIVE_INFINITY;
|
|
11655
|
+
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
11656
|
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;
|
|
11657
|
+
return (options.applyTeamRouting === false ? undefined : ctx.teamRouter?.order(ordered, teamRequest, ctx.runtime.pool, ctx.provider, ctx.dbOps, now, useUpAt)) ?? ordered;
|
|
11251
11658
|
}
|
|
11252
11659
|
var QUOTA_PROBE_INTERVAL_MS = 60000;
|
|
11253
11660
|
var init_account_selector = __esm(() => {
|
|
11661
|
+
init_src8();
|
|
11254
11662
|
init_src();
|
|
11663
|
+
init_night_pacing2();
|
|
11255
11664
|
init_seat_router();
|
|
11256
11665
|
init_seat_usage();
|
|
11257
11666
|
init_token_manager();
|
|
@@ -11501,7 +11910,7 @@ class ProviderSupply {
|
|
|
11501
11910
|
return threadAccount;
|
|
11502
11911
|
};
|
|
11503
11912
|
const seatsFor = (fleet) => {
|
|
11504
|
-
const eligible = ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet;
|
|
11913
|
+
const eligible = (ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet).filter((account2) => servesCaller(account2, ctx, route.callerId));
|
|
11505
11914
|
const id = getThreadAccount();
|
|
11506
11915
|
return id ? eligible.filter((account2) => account2.id === id) : eligible;
|
|
11507
11916
|
};
|
|
@@ -11588,7 +11997,7 @@ class ProviderSupply {
|
|
|
11588
11997
|
const teamEnabled = ctx.runtime.pool.enabled;
|
|
11589
11998
|
const pooled = account2.auth_method !== "api_key" && (!teamEnabled || isAllowlisted(account2, ctx.runtime.pool) && (!route.seatHint || account2.name === route.seatHint));
|
|
11590
11999
|
const keyReached = route.apiKeyAccounts && account2.auth_method === "api_key";
|
|
11591
|
-
return (pooled || keyReached) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
|
|
12000
|
+
return (pooled || keyReached) && servesCaller(account2, ctx, route.callerId) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
|
|
11592
12001
|
});
|
|
11593
12002
|
if (hasAvailableAccount)
|
|
11594
12003
|
return {
|
|
@@ -11624,7 +12033,7 @@ class ProviderSupply {
|
|
|
11624
12033
|
admissionWaitMs: context2.runtime.pool.admissionWaitMs
|
|
11625
12034
|
};
|
|
11626
12035
|
if (route.scope.kind === "pool-route" && route.callerId) {
|
|
11627
|
-
return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts);
|
|
12036
|
+
return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts, route.readNightBudget === true);
|
|
11628
12037
|
}
|
|
11629
12038
|
return getPoolStatus(this.name, mapped, context2);
|
|
11630
12039
|
}
|
|
@@ -12525,7 +12934,26 @@ async function getCallerPoolStatus(input) {
|
|
|
12525
12934
|
eligibleAccounts,
|
|
12526
12935
|
retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
|
|
12527
12936
|
holdSeconds: input.holdSeconds,
|
|
12528
|
-
admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0
|
|
12937
|
+
admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
|
|
12938
|
+
...input.route.readNightBudget && {
|
|
12939
|
+
nightBudget: callerNightBudget2(statuses, Date.now())
|
|
12940
|
+
}
|
|
12941
|
+
};
|
|
12942
|
+
}
|
|
12943
|
+
function toCents(value) {
|
|
12944
|
+
return Math.round(value * 100) / 100;
|
|
12945
|
+
}
|
|
12946
|
+
function callerNightBudget2(statuses, now) {
|
|
12947
|
+
const budgets = statuses.flatMap((status) => status.nightBudget ? [status.nightBudget] : []);
|
|
12948
|
+
if (budgets.length === 0)
|
|
12949
|
+
return null;
|
|
12950
|
+
const seatsCostEq = toCents(budgets.reduce((sum, budget) => sum + budget.seatsCostEq, 0));
|
|
12951
|
+
return {
|
|
12952
|
+
costEq: seatsCostEq,
|
|
12953
|
+
creditsCostEq: 0,
|
|
12954
|
+
seatsCostEq,
|
|
12955
|
+
night: budgets.some((budget) => budget.night),
|
|
12956
|
+
computedAtMs: now
|
|
12529
12957
|
};
|
|
12530
12958
|
}
|
|
12531
12959
|
var init_router2 = () => {};
|
|
@@ -12596,12 +13024,13 @@ function normalizeMaxBodyBytes(maxBodyBytes) {
|
|
|
12596
13024
|
function bodyTooLargeError(maxBodyBytes) {
|
|
12597
13025
|
return new HttpError(413, `Request body too large (maximum ${maxBodyBytes} bytes)`);
|
|
12598
13026
|
}
|
|
12599
|
-
function createRequestMetadata(req, url) {
|
|
13027
|
+
function createRequestMetadata(req, url, callerId) {
|
|
12600
13028
|
return {
|
|
12601
13029
|
id: crypto2.randomUUID(),
|
|
12602
13030
|
method: isHttpMethod(req.method) ? req.method : "GET",
|
|
12603
13031
|
path: url.pathname,
|
|
12604
|
-
timestamp: Date.now()
|
|
13032
|
+
timestamp: Date.now(),
|
|
13033
|
+
...callerId !== undefined && { callerId }
|
|
12605
13034
|
};
|
|
12606
13035
|
}
|
|
12607
13036
|
function readRequestModel(body) {
|
|
@@ -12696,7 +13125,8 @@ async function forwardToClient(options, ctx) {
|
|
|
12696
13125
|
responseHeadersReceivedAt,
|
|
12697
13126
|
retryAttempt,
|
|
12698
13127
|
failoverAttempts,
|
|
12699
|
-
preExtractedModel
|
|
13128
|
+
preExtractedModel,
|
|
13129
|
+
callerId
|
|
12700
13130
|
} = options;
|
|
12701
13131
|
const responseProcessed = ctx.provider.processResponse ? await ctx.provider.processResponse(responseRaw, account2, {
|
|
12702
13132
|
messageId: `msg_${requestId.replaceAll("-", "")}`,
|
|
@@ -12725,7 +13155,8 @@ async function forwardToClient(options, ctx) {
|
|
|
12725
13155
|
providerName: ctx.providerName,
|
|
12726
13156
|
retryAttempt,
|
|
12727
13157
|
failoverAttempts,
|
|
12728
|
-
storePayload: ctx.runtime.storeRequestPayloads
|
|
13158
|
+
storePayload: ctx.runtime.storeRequestPayloads,
|
|
13159
|
+
callerId
|
|
12729
13160
|
};
|
|
12730
13161
|
ctx.usageWorker.postMessage(startMessage);
|
|
12731
13162
|
requestEvents.emit("event", {
|
|
@@ -13302,7 +13733,8 @@ function createForwarder(input, upstream, state) {
|
|
|
13302
13733
|
responseHeadersReceivedAt: upstream.responseHeadersReceivedAt,
|
|
13303
13734
|
retryAttempt: 0,
|
|
13304
13735
|
failoverAttempts: input.failoverAttempts,
|
|
13305
|
-
preExtractedModel: input.mappedModel ?? input.requestMeta.model
|
|
13736
|
+
preExtractedModel: input.mappedModel ?? input.requestMeta.model,
|
|
13737
|
+
callerId: input.requestMeta.callerId
|
|
13306
13738
|
}, input.ctx);
|
|
13307
13739
|
}
|
|
13308
13740
|
function discardUpstreamResponse(state) {
|
|
@@ -13785,7 +14217,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
|
|
|
13785
14217
|
providerName: session.providerName,
|
|
13786
14218
|
retryAttempt: 0,
|
|
13787
14219
|
failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
|
|
13788
|
-
storePayload: session.requestContext.runtime.storeRequestPayloads
|
|
14220
|
+
storePayload: session.requestContext.runtime.storeRequestPayloads,
|
|
14221
|
+
callerId: session.callerId
|
|
13789
14222
|
};
|
|
13790
14223
|
session.activeTurn = {
|
|
13791
14224
|
requestId,
|
|
@@ -14051,7 +14484,7 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
|
|
|
14051
14484
|
status: 400
|
|
14052
14485
|
});
|
|
14053
14486
|
}
|
|
14054
|
-
const requestMeta = createRequestMetadata(req, url);
|
|
14487
|
+
const requestMeta = createRequestMetadata(req, url, callerId);
|
|
14055
14488
|
const teamRequest = {
|
|
14056
14489
|
body: null,
|
|
14057
14490
|
contentType: null,
|
|
@@ -14105,7 +14538,8 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
|
|
|
14105
14538
|
activeTurn: null,
|
|
14106
14539
|
connectedAccount: null,
|
|
14107
14540
|
pendingRequestBody: null,
|
|
14108
|
-
pendingRequestTimestamp: null
|
|
14541
|
+
pendingRequestTimestamp: null,
|
|
14542
|
+
callerId
|
|
14109
14543
|
};
|
|
14110
14544
|
websocketSessions.set(sessionId, session);
|
|
14111
14545
|
const upgraded = server.upgrade(req, {
|
|
@@ -14332,6 +14766,18 @@ var init_router_bridge = __esm(() => {
|
|
|
14332
14766
|
// ../../packages/proxy/src/usage-worker.ts
|
|
14333
14767
|
import { isAbsolute, resolve as resolve2 } from "path";
|
|
14334
14768
|
import { pathToFileURL } from "url";
|
|
14769
|
+
function heldBytesOf(message) {
|
|
14770
|
+
switch (message.type) {
|
|
14771
|
+
case "start":
|
|
14772
|
+
return MESSAGE_OVERHEAD_BYTES + (message.requestBody?.length ?? 0);
|
|
14773
|
+
case "chunk":
|
|
14774
|
+
return MESSAGE_OVERHEAD_BYTES + message.data.byteLength;
|
|
14775
|
+
case "end":
|
|
14776
|
+
return MESSAGE_OVERHEAD_BYTES + (message.responseBody?.length ?? 0);
|
|
14777
|
+
default:
|
|
14778
|
+
return MESSAGE_OVERHEAD_BYTES;
|
|
14779
|
+
}
|
|
14780
|
+
}
|
|
14335
14781
|
function noop() {}
|
|
14336
14782
|
function createDefaultLogger() {
|
|
14337
14783
|
return {
|
|
@@ -14385,6 +14831,7 @@ class UsageWorkerController {
|
|
|
14385
14831
|
readyTimeoutMs;
|
|
14386
14832
|
ackTimeoutMs;
|
|
14387
14833
|
shutdownDelayMs;
|
|
14834
|
+
maxHeldBytes;
|
|
14388
14835
|
logger;
|
|
14389
14836
|
worker = null;
|
|
14390
14837
|
ready = false;
|
|
@@ -14394,6 +14841,9 @@ class UsageWorkerController {
|
|
|
14394
14841
|
shutdownTimer = null;
|
|
14395
14842
|
queuedMessages = [];
|
|
14396
14843
|
pendingAcks = new Map;
|
|
14844
|
+
heldBytes = 0;
|
|
14845
|
+
droppedRequestIds = new Set;
|
|
14846
|
+
droppedRequests = 0;
|
|
14397
14847
|
shutdownPromise = null;
|
|
14398
14848
|
resolveShutdown = null;
|
|
14399
14849
|
rejectShutdown = null;
|
|
@@ -14404,6 +14854,7 @@ class UsageWorkerController {
|
|
|
14404
14854
|
this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
|
|
14405
14855
|
this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
|
|
14406
14856
|
this.shutdownDelayMs = options.shutdownDelayMs ?? DEFAULT_SHUTDOWN_DELAY_MS;
|
|
14857
|
+
this.maxHeldBytes = options.maxHeldBytes ?? DEFAULT_MAX_HELD_BYTES;
|
|
14407
14858
|
this.logger = options.logger ?? createDefaultLogger();
|
|
14408
14859
|
this.startWorker();
|
|
14409
14860
|
}
|
|
@@ -14412,16 +14863,65 @@ class UsageWorkerController {
|
|
|
14412
14863
|
this.logger.warn("Dropping usage worker message because the worker is shutting down");
|
|
14413
14864
|
return;
|
|
14414
14865
|
}
|
|
14866
|
+
if (!this.admit(message)) {
|
|
14867
|
+
return;
|
|
14868
|
+
}
|
|
14415
14869
|
const decoratedMessage = {
|
|
14416
14870
|
...message,
|
|
14417
14871
|
messageId: crypto.randomUUID()
|
|
14418
14872
|
};
|
|
14419
14873
|
if (!this.ready || !this.worker) {
|
|
14420
|
-
this.
|
|
14874
|
+
this.queue(decoratedMessage);
|
|
14421
14875
|
return;
|
|
14422
14876
|
}
|
|
14423
14877
|
this.sendMessage(decoratedMessage);
|
|
14424
14878
|
}
|
|
14879
|
+
admit(message) {
|
|
14880
|
+
if (message.type === "shutdown") {
|
|
14881
|
+
return true;
|
|
14882
|
+
}
|
|
14883
|
+
if (this.droppedRequestIds.has(message.requestId)) {
|
|
14884
|
+
if (message.type === "end") {
|
|
14885
|
+
this.droppedRequestIds.delete(message.requestId);
|
|
14886
|
+
}
|
|
14887
|
+
return false;
|
|
14888
|
+
}
|
|
14889
|
+
if (message.type !== "start") {
|
|
14890
|
+
return true;
|
|
14891
|
+
}
|
|
14892
|
+
if (this.heldBytes + heldBytesOf(message) > this.maxHeldBytes) {
|
|
14893
|
+
if (this.droppedRequests === 0) {
|
|
14894
|
+
this.logger.warn(`Usage worker messages hold ${this.heldBytes} bytes, over the ${this.maxHeldBytes}-byte cap; dropping new requests' usage until the worker catches up`);
|
|
14895
|
+
}
|
|
14896
|
+
this.droppedRequests += 1;
|
|
14897
|
+
this.droppedRequestIds.add(message.requestId);
|
|
14898
|
+
return false;
|
|
14899
|
+
}
|
|
14900
|
+
if (this.droppedRequests > 0) {
|
|
14901
|
+
this.logger.warn(`Dropped the usage of ${this.droppedRequests} requests while usage worker messages were over their byte cap`);
|
|
14902
|
+
this.droppedRequests = 0;
|
|
14903
|
+
}
|
|
14904
|
+
return true;
|
|
14905
|
+
}
|
|
14906
|
+
queue(message) {
|
|
14907
|
+
this.queuedMessages.push(message);
|
|
14908
|
+
this.heldBytes += heldBytesOf(message);
|
|
14909
|
+
}
|
|
14910
|
+
forgetQueuedMessages() {
|
|
14911
|
+
for (const message of this.queuedMessages) {
|
|
14912
|
+
this.heldBytes -= heldBytesOf(message);
|
|
14913
|
+
}
|
|
14914
|
+
this.queuedMessages.length = 0;
|
|
14915
|
+
}
|
|
14916
|
+
forgetPendingAck(messageId) {
|
|
14917
|
+
const pending = this.pendingAcks.get(messageId);
|
|
14918
|
+
if (!pending) {
|
|
14919
|
+
return;
|
|
14920
|
+
}
|
|
14921
|
+
clearTimeout(pending.timer);
|
|
14922
|
+
this.heldBytes -= heldBytesOf(pending.message);
|
|
14923
|
+
this.pendingAcks.delete(messageId);
|
|
14924
|
+
}
|
|
14425
14925
|
isShuttingDown() {
|
|
14426
14926
|
return this.shuttingDown;
|
|
14427
14927
|
}
|
|
@@ -14442,7 +14942,7 @@ class UsageWorkerController {
|
|
|
14442
14942
|
this.ready = false;
|
|
14443
14943
|
this.clearReadyTimer();
|
|
14444
14944
|
this.clearPendingAcks();
|
|
14445
|
-
this.
|
|
14945
|
+
this.forgetQueuedMessages();
|
|
14446
14946
|
const worker = this.worker;
|
|
14447
14947
|
if (!worker) {
|
|
14448
14948
|
this.shuttingDown = false;
|
|
@@ -14478,7 +14978,7 @@ class UsageWorkerController {
|
|
|
14478
14978
|
this.ready = false;
|
|
14479
14979
|
this.clearReadyTimer();
|
|
14480
14980
|
this.clearPendingAcks();
|
|
14481
|
-
this.
|
|
14981
|
+
this.forgetQueuedMessages();
|
|
14482
14982
|
if (this.shutdownTimer) {
|
|
14483
14983
|
clearTimeout(this.shutdownTimer);
|
|
14484
14984
|
this.shutdownTimer = null;
|
|
@@ -14549,10 +15049,9 @@ class UsageWorkerController {
|
|
|
14549
15049
|
this.readyTimer = null;
|
|
14550
15050
|
}
|
|
14551
15051
|
clearPendingAcks() {
|
|
14552
|
-
for (const
|
|
14553
|
-
|
|
15052
|
+
for (const messageId of Array.from(this.pendingAcks.keys())) {
|
|
15053
|
+
this.forgetPendingAck(messageId);
|
|
14554
15054
|
}
|
|
14555
|
-
this.pendingAcks.clear();
|
|
14556
15055
|
}
|
|
14557
15056
|
handleWorkerMessage(message) {
|
|
14558
15057
|
if (isShutdownCompleteMessage(message)) {
|
|
@@ -14575,12 +15074,7 @@ class UsageWorkerController {
|
|
|
14575
15074
|
return;
|
|
14576
15075
|
}
|
|
14577
15076
|
if (isAckMessage(message)) {
|
|
14578
|
-
|
|
14579
|
-
if (!pendingAck) {
|
|
14580
|
-
return;
|
|
14581
|
-
}
|
|
14582
|
-
clearTimeout(pendingAck.timer);
|
|
14583
|
-
this.pendingAcks.delete(message.messageId);
|
|
15077
|
+
this.forgetPendingAck(message.messageId);
|
|
14584
15078
|
return;
|
|
14585
15079
|
}
|
|
14586
15080
|
this.onWorkerMessage?.(message);
|
|
@@ -14589,14 +15083,15 @@ class UsageWorkerController {
|
|
|
14589
15083
|
if (!this.worker || !this.ready || this.queuedMessages.length === 0) {
|
|
14590
15084
|
return;
|
|
14591
15085
|
}
|
|
14592
|
-
const queuedMessages = this.queuedMessages.
|
|
15086
|
+
const queuedMessages = this.queuedMessages.slice();
|
|
15087
|
+
this.forgetQueuedMessages();
|
|
14593
15088
|
for (const message of queuedMessages) {
|
|
14594
15089
|
this.sendMessage(message);
|
|
14595
15090
|
}
|
|
14596
15091
|
}
|
|
14597
15092
|
sendMessage(message) {
|
|
14598
15093
|
if (!this.worker) {
|
|
14599
|
-
this.
|
|
15094
|
+
this.queue(message);
|
|
14600
15095
|
return;
|
|
14601
15096
|
}
|
|
14602
15097
|
try {
|
|
@@ -14610,11 +15105,10 @@ class UsageWorkerController {
|
|
|
14610
15105
|
return;
|
|
14611
15106
|
}
|
|
14612
15107
|
const timer = setTimeout(() => {
|
|
14613
|
-
|
|
14614
|
-
if (!pendingAck) {
|
|
15108
|
+
if (!this.pendingAcks.has(message.messageId)) {
|
|
14615
15109
|
return;
|
|
14616
15110
|
}
|
|
14617
|
-
this.
|
|
15111
|
+
this.forgetPendingAck(message.messageId);
|
|
14618
15112
|
this.logger.warn("Usage worker became unresponsive while waiting for an acknowledgement; restarting it");
|
|
14619
15113
|
this.restartWorker();
|
|
14620
15114
|
}, this.ackTimeoutMs);
|
|
@@ -14623,6 +15117,7 @@ class UsageWorkerController {
|
|
|
14623
15117
|
message,
|
|
14624
15118
|
timer
|
|
14625
15119
|
});
|
|
15120
|
+
this.heldBytes += heldBytesOf(message);
|
|
14626
15121
|
}
|
|
14627
15122
|
restartWorker() {
|
|
14628
15123
|
if (this.shuttingDown) {
|
|
@@ -14676,12 +15171,13 @@ class UsageWorkerController {
|
|
|
14676
15171
|
resolveShutdown?.();
|
|
14677
15172
|
}
|
|
14678
15173
|
}
|
|
14679
|
-
var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100;
|
|
15174
|
+
var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100, DEFAULT_MAX_HELD_BYTES, MESSAGE_OVERHEAD_BYTES = 1024;
|
|
14680
15175
|
var init_usage_worker = __esm(() => {
|
|
14681
15176
|
init_src2();
|
|
14682
15177
|
init_src();
|
|
14683
15178
|
DEFAULT_READY_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_READY_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
|
|
14684
15179
|
DEFAULT_ACK_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_ACK_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
|
|
15180
|
+
DEFAULT_MAX_HELD_BYTES = Number(process.env.AGENT_SMITH_USAGE_WORKER_MAX_HELD_MB || 256) * 1024 * 1024;
|
|
14685
15181
|
});
|
|
14686
15182
|
|
|
14687
15183
|
// ../../packages/proxy/src/proxy.ts
|
|
@@ -14762,7 +15258,7 @@ async function handleProxy(req, url, ctx, callerId) {
|
|
|
14762
15258
|
if (!upstreamUrl.pathname.startsWith("/v1/pool/")) {
|
|
14763
15259
|
return new Response("Not Found", { status: 404 });
|
|
14764
15260
|
}
|
|
14765
|
-
const requestMeta2 = createRequestMetadata(req, upstreamUrl);
|
|
15261
|
+
const requestMeta2 = createRequestMetadata(req, upstreamUrl, callerId);
|
|
14766
15262
|
const { buffer: buffer2 } = await prepareRequestBody(req, ctx.runtime.maxBodyBytes);
|
|
14767
15263
|
const body2 = buffer2 ?? null;
|
|
14768
15264
|
requestMeta2.model = readRequestModel(body2);
|
|
@@ -14774,7 +15270,7 @@ async function handleProxy(req, url, ctx, callerId) {
|
|
|
14774
15270
|
}
|
|
14775
15271
|
return await routePoolRequest(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
|
|
14776
15272
|
}
|
|
14777
|
-
const requestMeta = createRequestMetadata(req, upstreamUrl);
|
|
15273
|
+
const requestMeta = createRequestMetadata(req, upstreamUrl, callerId);
|
|
14778
15274
|
const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
|
|
14779
15275
|
const body = buffer ?? null;
|
|
14780
15276
|
requestMeta.model = readRequestModel(body);
|
|
@@ -15195,7 +15691,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
15195
15691
|
admissionWaitMs: status.admissionWaitMs
|
|
15196
15692
|
};
|
|
15197
15693
|
},
|
|
15198
|
-
getCallerPoolStatus: async (pool, model, callerId) => {
|
|
15694
|
+
getCallerPoolStatus: async (pool, model, callerId, readNightBudget) => {
|
|
15199
15695
|
const members = providerRegistry.poolCapacityMembers(pool, model);
|
|
15200
15696
|
const url = new URL(`http://localhost/v1/pool/${pool}/`);
|
|
15201
15697
|
const providers2 = members.map(({ provider }) => {
|
|
@@ -15205,7 +15701,10 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
15205
15701
|
return supply;
|
|
15206
15702
|
});
|
|
15207
15703
|
return getCallerPoolStatus({
|
|
15208
|
-
route:
|
|
15704
|
+
route: {
|
|
15705
|
+
...createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
|
|
15706
|
+
readNightBudget
|
|
15707
|
+
},
|
|
15209
15708
|
providers: providers2,
|
|
15210
15709
|
orderedFallback: hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
|
|
15211
15710
|
apiKeyAccounts: runtimeConfig2.routing.apiKeyAccounts === "everyone" || hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
|
|
@@ -15523,35 +16022,49 @@ var init_fetch_handler = __esm(() => {
|
|
|
15523
16022
|
});
|
|
15524
16023
|
|
|
15525
16024
|
// ../../packages/runtime-server/src/retention-maintenance.ts
|
|
15526
|
-
function
|
|
15527
|
-
|
|
15528
|
-
|
|
15529
|
-
|
|
15530
|
-
|
|
15531
|
-
|
|
15532
|
-
|
|
15533
|
-
|
|
15534
|
-
|
|
16025
|
+
function retentionWindows(config) {
|
|
16026
|
+
const payloadDays = config.getDataRetentionDays();
|
|
16027
|
+
const requestDays = config.getRequestRetentionDays();
|
|
16028
|
+
return {
|
|
16029
|
+
payloadMs: payloadDays * DAY_MS2,
|
|
16030
|
+
requestMs: requestDays * DAY_MS2,
|
|
16031
|
+
description: `payload=${payloadDays}d, requests=${requestDays}d`
|
|
16032
|
+
};
|
|
16033
|
+
}
|
|
16034
|
+
function logRemoved(log27, label, { removedRequests, removedPayloads }, description) {
|
|
16035
|
+
log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (${description})`);
|
|
15535
16036
|
}
|
|
15536
16037
|
function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
|
|
15537
16038
|
const log27 = new Logger("RetentionMaintenance");
|
|
15538
|
-
|
|
16039
|
+
try {
|
|
16040
|
+
const { payloadMs, requestMs, description } = retentionWindows(config);
|
|
16041
|
+
logRemoved(log27, "Startup", dbOps.cleanupOldRequests(payloadMs, requestMs), description);
|
|
16042
|
+
} catch (err) {
|
|
16043
|
+
log27.error(`Startup cleanup error: ${err}`);
|
|
16044
|
+
}
|
|
15539
16045
|
try {
|
|
15540
16046
|
const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
|
|
15541
16047
|
log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
|
|
15542
16048
|
} catch (err) {
|
|
15543
16049
|
log27.error(`Database compaction error: ${err}`);
|
|
15544
16050
|
}
|
|
16051
|
+
const stopped = new AbortController;
|
|
16052
|
+
let running;
|
|
15545
16053
|
const timer = setInterval(() => {
|
|
15546
|
-
|
|
15547
|
-
|
|
15548
|
-
|
|
15549
|
-
|
|
15550
|
-
|
|
15551
|
-
}
|
|
16054
|
+
if (running)
|
|
16055
|
+
return;
|
|
16056
|
+
const { payloadMs, requestMs, description } = retentionWindows(config);
|
|
16057
|
+
running = dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs, {
|
|
16058
|
+
signal: stopped.signal
|
|
16059
|
+
}).then((removed) => logRemoved(log27, "Periodic", removed, description), (err) => log27.error(`Periodic cleanup error: ${err}`)).finally(() => {
|
|
16060
|
+
running = undefined;
|
|
16061
|
+
});
|
|
15552
16062
|
}, intervalMs);
|
|
15553
16063
|
timer.unref?.();
|
|
15554
|
-
return () =>
|
|
16064
|
+
return () => {
|
|
16065
|
+
clearInterval(timer);
|
|
16066
|
+
stopped.abort();
|
|
16067
|
+
};
|
|
15555
16068
|
}
|
|
15556
16069
|
var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
|
|
15557
16070
|
var init_retention_maintenance = __esm(() => {
|