@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.
@@ -1249,6 +1249,198 @@ var init_builtin_providers = __esm(() => {
1249
1249
  ];
1250
1250
  });
1251
1251
 
1252
+ // ../../packages/config/src/zoned-time.ts
1253
+ function isTimeZone(value) {
1254
+ if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1255
+ return false;
1256
+ }
1257
+ try {
1258
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
1259
+ return true;
1260
+ } catch {
1261
+ return false;
1262
+ }
1263
+ }
1264
+ function localTimeOfDayMs(time) {
1265
+ const [hour = 0, minute = 0] = time.split(":").map(Number);
1266
+ return hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE;
1267
+ }
1268
+ function wallClockFormat(timeZone) {
1269
+ let format = wallClockFormats.get(timeZone);
1270
+ if (!format) {
1271
+ format = new Intl.DateTimeFormat("en-US", {
1272
+ timeZone,
1273
+ hourCycle: "h23",
1274
+ year: "numeric",
1275
+ month: "numeric",
1276
+ day: "numeric",
1277
+ hour: "numeric",
1278
+ minute: "numeric",
1279
+ second: "numeric"
1280
+ });
1281
+ wallClockFormats.set(timeZone, format);
1282
+ }
1283
+ return format;
1284
+ }
1285
+ function wallClock(at, timeZone) {
1286
+ const parts = wallClockFormat(timeZone).formatToParts(at);
1287
+ const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1288
+ return {
1289
+ year: part("year"),
1290
+ month: part("month"),
1291
+ day: part("day"),
1292
+ hour: part("hour") % 24,
1293
+ minute: part("minute"),
1294
+ second: part("second")
1295
+ };
1296
+ }
1297
+ function zoneOffsetMs(at, timeZone) {
1298
+ const wall = wallClock(at, timeZone);
1299
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1300
+ }
1301
+ function zonedInstant(wall, timeZone) {
1302
+ return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1303
+ }
1304
+ var LOCAL_TIME, wallClockFormats;
1305
+ var init_zoned_time = __esm(() => {
1306
+ init_src2();
1307
+ LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1308
+ wallClockFormats = new Map;
1309
+ });
1310
+
1311
+ // ../../packages/config/src/night-pacing.ts
1312
+ function localHours(value) {
1313
+ 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) {
1314
+ return;
1315
+ }
1316
+ return { start: value.start, end: value.end };
1317
+ }
1318
+ function isWorkingDays(value) {
1319
+ return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length && value.every((day) => typeof day === "string" && WEEKDAYS.includes(day));
1320
+ }
1321
+ function sanitizeNightPacing(value) {
1322
+ if (!isRecord(value) || Object.keys(value).some((key) => !NIGHT_PACING_FIELDS.has(key))) {
1323
+ return;
1324
+ }
1325
+ const result = {};
1326
+ if (value.time_zone !== undefined) {
1327
+ if (!isTimeZone(value.time_zone))
1328
+ return;
1329
+ result.time_zone = value.time_zone;
1330
+ }
1331
+ if (value.working_days !== undefined) {
1332
+ if (!isWorkingDays(value.working_days))
1333
+ return;
1334
+ result.working_days = [...value.working_days];
1335
+ }
1336
+ if (value.working_hours !== undefined) {
1337
+ const hours = localHours(value.working_hours);
1338
+ if (!hours || hours.start > hours.end)
1339
+ return;
1340
+ result.working_hours = hours;
1341
+ }
1342
+ if (value.night_hours !== undefined) {
1343
+ const hours = localHours(value.night_hours);
1344
+ if (!hours)
1345
+ return;
1346
+ result.night_hours = hours;
1347
+ }
1348
+ if (value.margin_working_days !== undefined) {
1349
+ if (!isFiniteNumber(value.margin_working_days) || value.margin_working_days < 0 || value.margin_working_days > 7) {
1350
+ return;
1351
+ }
1352
+ result.margin_working_days = value.margin_working_days;
1353
+ }
1354
+ if (value.use_up_before !== undefined) {
1355
+ if (typeof value.use_up_before !== "string" || !LOCAL_TIME.test(value.use_up_before)) {
1356
+ return;
1357
+ }
1358
+ result.use_up_before = value.use_up_before;
1359
+ }
1360
+ return result;
1361
+ }
1362
+ function nightPacingSettings(file) {
1363
+ return {
1364
+ timeZone: file.time_zone ?? NIGHT_PACING_DEFAULTS.timeZone,
1365
+ workingDays: [...file.working_days ?? NIGHT_PACING_DEFAULTS.workingDays],
1366
+ workingHours: {
1367
+ ...file.working_hours ?? NIGHT_PACING_DEFAULTS.workingHours
1368
+ },
1369
+ nightHours: { ...file.night_hours ?? NIGHT_PACING_DEFAULTS.nightHours },
1370
+ marginWorkingDays: file.margin_working_days ?? NIGHT_PACING_DEFAULTS.marginWorkingDays,
1371
+ useUpBefore: file.use_up_before ?? NIGHT_PACING_DEFAULTS.useUpBefore
1372
+ };
1373
+ }
1374
+ function localDay(at, timeZone) {
1375
+ const wall = wallClock(at, timeZone);
1376
+ return {
1377
+ day: Date.UTC(wall.year, wall.month - 1, wall.day),
1378
+ timeOfDay: wall.hour * TIME_CONSTANTS.HOUR + wall.minute * TIME_CONSTANTS.MINUTE + wall.second * 1000
1379
+ };
1380
+ }
1381
+ function nightEndAt(pacing, now) {
1382
+ const { day, timeOfDay } = localDay(now, pacing.timeZone);
1383
+ const start = localTimeOfDayMs(pacing.nightHours.start);
1384
+ const end = localTimeOfDayMs(pacing.nightHours.end);
1385
+ const wraps = start > end;
1386
+ const night = wraps ? timeOfDay >= start || timeOfDay < end : timeOfDay >= start && timeOfDay < end;
1387
+ if (!night)
1388
+ return null;
1389
+ const endDay = wraps && timeOfDay >= start ? day + TIME_CONSTANTS.DAY : day;
1390
+ return zonedInstant(endDay + end, pacing.timeZone);
1391
+ }
1392
+ function workingMsBetween(pacing, from, to) {
1393
+ const start = localTimeOfDayMs(pacing.workingHours.start);
1394
+ const end = localTimeOfDayMs(pacing.workingHours.end);
1395
+ let total = 0;
1396
+ for (let day = localDay(from, pacing.timeZone).day - TIME_CONSTANTS.DAY;zonedInstant(day + start, pacing.timeZone) < to; day += TIME_CONSTANTS.DAY) {
1397
+ if (!pacing.workingDays.includes(WEEKDAYS[new Date(day).getUTCDay()] ?? ""))
1398
+ continue;
1399
+ const opens = zonedInstant(day + start, pacing.timeZone);
1400
+ const closes = zonedInstant(day + end, pacing.timeZone);
1401
+ total += Math.max(0, Math.min(closes, to) - Math.max(opens, from));
1402
+ }
1403
+ return total;
1404
+ }
1405
+ function expiresBeforeUseUpTime(pacing, resetAt, now) {
1406
+ const endAt = nightEndAt(pacing, now);
1407
+ if (endAt === null || resetAt <= now)
1408
+ return false;
1409
+ return resetAt <= zonedInstant(localDay(endAt, pacing.timeZone).day + localTimeOfDayMs(pacing.useUpBefore), pacing.timeZone);
1410
+ }
1411
+ function nightWeeklyTarget(pacing, resetAt, now) {
1412
+ if (expiresBeforeUseUpTime(pacing, resetAt, now))
1413
+ return 1;
1414
+ const windowStart = resetAt - WEEKLY_WINDOW_MS;
1415
+ const workingDayMs = localTimeOfDayMs(pacing.workingHours.end) - localTimeOfDayMs(pacing.workingHours.start);
1416
+ const elapsed = workingMsBetween(pacing, windowStart, Math.min(now, resetAt));
1417
+ return (elapsed - pacing.marginWorkingDays * workingDayMs) / workingMsBetween(pacing, windowStart, resetAt);
1418
+ }
1419
+ var WEEKDAYS, WEEKLY_WINDOW_MS, NIGHT_PACING_DEFAULTS, NIGHT_PACING_FIELDS;
1420
+ var init_night_pacing = __esm(() => {
1421
+ init_src2();
1422
+ init_src();
1423
+ init_zoned_time();
1424
+ WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
1425
+ WEEKLY_WINDOW_MS = 7 * TIME_CONSTANTS.DAY;
1426
+ NIGHT_PACING_DEFAULTS = {
1427
+ timeZone: "Europe/Paris",
1428
+ workingDays: ["mon", "tue", "wed", "thu", "fri"],
1429
+ workingHours: { start: "07:00", end: "21:00" },
1430
+ nightHours: { start: "21:00", end: "07:00" },
1431
+ marginWorkingDays: 1,
1432
+ useUpBefore: "10:00"
1433
+ };
1434
+ NIGHT_PACING_FIELDS = new Set([
1435
+ "time_zone",
1436
+ "working_days",
1437
+ "working_hours",
1438
+ "night_hours",
1439
+ "margin_working_days",
1440
+ "use_up_before"
1441
+ ]);
1442
+ });
1443
+
1252
1444
  // ../../packages/config/src/paths-common.ts
1253
1445
  import { homedir } from "os";
1254
1446
  import { join as join3 } from "path";
@@ -1519,17 +1711,6 @@ var init_rewrite_file = __esm(() => {
1519
1711
  function isLocalTimes(value) {
1520
1712
  return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
1521
1713
  }
1522
- function isTimeZone(value) {
1523
- if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1524
- return false;
1525
- }
1526
- try {
1527
- new Intl.DateTimeFormat("en-US", { timeZone: value });
1528
- return true;
1529
- } catch {
1530
- return false;
1531
- }
1532
- }
1533
1714
  function sanitizeWindowWarmup(value) {
1534
1715
  if (!isRecord(value))
1535
1716
  return;
@@ -1566,42 +1747,6 @@ function windowWarmupFileConfig(config) {
1566
1747
  ...config.model && { model: config.model }
1567
1748
  };
1568
1749
  }
1569
- function wallClockFormat(timeZone) {
1570
- let format = wallClockFormats.get(timeZone);
1571
- if (!format) {
1572
- format = new Intl.DateTimeFormat("en-US", {
1573
- timeZone,
1574
- hourCycle: "h23",
1575
- year: "numeric",
1576
- month: "numeric",
1577
- day: "numeric",
1578
- hour: "numeric",
1579
- minute: "numeric",
1580
- second: "numeric"
1581
- });
1582
- wallClockFormats.set(timeZone, format);
1583
- }
1584
- return format;
1585
- }
1586
- function wallClock(at, timeZone) {
1587
- const parts = wallClockFormat(timeZone).formatToParts(at);
1588
- const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1589
- return {
1590
- year: part("year"),
1591
- month: part("month"),
1592
- day: part("day"),
1593
- hour: part("hour") % 24,
1594
- minute: part("minute"),
1595
- second: part("second")
1596
- };
1597
- }
1598
- function zoneOffsetMs(at, timeZone) {
1599
- const wall = wallClock(at, timeZone);
1600
- return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1601
- }
1602
- function zonedInstant(wall, timeZone) {
1603
- return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1604
- }
1605
1750
  function nextWindowWarmupAt(routing, after) {
1606
1751
  const warmup = routing.windowWarmup;
1607
1752
  if (!routing.enabled || !warmup.enabled)
@@ -1613,19 +1758,16 @@ function nextWindowWarmupAt(routing, after) {
1613
1758
  if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
1614
1759
  continue;
1615
1760
  }
1616
- const instants = warmup.times.map((time) => {
1617
- const [hour = 0, minute = 0] = time.split(":").map(Number);
1618
- return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
1619
- }).filter((at) => at > after);
1761
+ const instants = warmup.times.map((time) => zonedInstant(day + localTimeOfDayMs(time), warmup.timeZone)).filter((at) => at > after);
1620
1762
  if (instants.length > 0)
1621
1763
  return Math.min(...instants);
1622
1764
  }
1623
1765
  return null;
1624
1766
  }
1625
- var WINDOW_WARMUP_DEFAULTS, LOCAL_TIME, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0, wallClockFormats;
1767
+ var WINDOW_WARMUP_DEFAULTS, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0;
1626
1768
  var init_window_warmup = __esm(() => {
1627
- init_src2();
1628
1769
  init_src();
1770
+ init_zoned_time();
1629
1771
  WINDOW_WARMUP_DEFAULTS = {
1630
1772
  enabled: false,
1631
1773
  times: ["06:00"],
@@ -1633,9 +1775,7 @@ var init_window_warmup = __esm(() => {
1633
1775
  weekdaysOnly: true,
1634
1776
  model: null
1635
1777
  };
1636
- LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1637
1778
  MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
1638
- wallClockFormats = new Map;
1639
1779
  });
1640
1780
 
1641
1781
  // ../../packages/config/src/index.ts
@@ -1651,6 +1791,13 @@ import {
1651
1791
  writeFileSync as writeFileSync2
1652
1792
  } from "fs";
1653
1793
  import { dirname as dirname2 } from "path";
1794
+ function callerWeeklyCap(caps, callerId) {
1795
+ if (!Object.hasOwn(caps, callerId))
1796
+ return;
1797
+ const cap = caps[callerId];
1798
+ const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
1799
+ return typeof shared === "number" ? shared : undefined;
1800
+ }
1654
1801
  function runtimeForProvider(runtime, provider) {
1655
1802
  return {
1656
1803
  ...runtime,
@@ -1901,6 +2048,29 @@ function wireForStrategy(strategy3) {
1901
2048
  function isNonNegativeFiniteNumber(value) {
1902
2049
  return isFiniteNumber(value) && value >= 0;
1903
2050
  }
2051
+ function sanitizeCapsByEmail(value, maximum) {
2052
+ if (!isRecord(value))
2053
+ return;
2054
+ const entries = Object.entries(value);
2055
+ const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
2056
+ const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
2057
+ if (!isValid)
2058
+ return;
2059
+ return Object.fromEntries(normalized);
2060
+ }
2061
+ function isDeviceList(value) {
2062
+ 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;
2063
+ }
2064
+ function sanitizeOwnerDevicesByEmail(value) {
2065
+ if (!isRecord(value))
2066
+ return;
2067
+ const entries = Object.entries(value);
2068
+ const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
2069
+ const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
2070
+ if (!isValid)
2071
+ return;
2072
+ return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
2073
+ }
1904
2074
  function sanitizeTeamRouting(value) {
1905
2075
  if (!isRecord(value))
1906
2076
  return;
@@ -1922,19 +2092,22 @@ function sanitizeTeamRouting(value) {
1922
2092
  if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
1923
2093
  result.weekly_max_usage = value.weekly_max_usage;
1924
2094
  }
1925
- if (isRecord(value.weekly_max_usage_by_email)) {
1926
- const entries = Object.entries(value.weekly_max_usage_by_email);
1927
- const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
1928
- if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 1) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1929
- result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1930
- }
1931
- }
2095
+ const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
2096
+ if (maxUsageByEmail)
2097
+ result.max_usage_by_email = maxUsageByEmail;
2098
+ const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
2099
+ if (weeklyMaxUsageByEmail)
2100
+ result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
1932
2101
  if (isRecord(value.caller_weekly_max_usage)) {
1933
- const entries = Object.entries(value.caller_weekly_max_usage);
1934
- if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
2102
+ const caps = value.caller_weekly_max_usage;
2103
+ const entries = Object.entries(caps);
2104
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
1935
2105
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1936
2106
  }
1937
2107
  }
2108
+ const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
2109
+ if (ownerDevicesByEmail)
2110
+ result.owner_devices_by_email = ownerDevicesByEmail;
1938
2111
  if (isRecord(value.caller_provider_fallback)) {
1939
2112
  const entries = Object.entries(value.caller_provider_fallback);
1940
2113
  if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
@@ -1985,9 +2158,11 @@ function sanitizeProviderPool(value) {
1985
2158
  "distribution_enabled",
1986
2159
  "prefer_expiring_quota",
1987
2160
  "max_usage",
2161
+ "max_usage_by_email",
1988
2162
  "weekly_max_usage",
1989
2163
  "weekly_max_usage_by_email",
1990
2164
  "caller_weekly_max_usage",
2165
+ "owner_devices_by_email",
1991
2166
  "quota_probe_seconds",
1992
2167
  "window_warmup"
1993
2168
  ]) {
@@ -2009,8 +2184,17 @@ function sanitizeProviderPool(value) {
2009
2184
  }
2010
2185
  if (typeof value.block_when_all_full === "boolean")
2011
2186
  pool.block_when_all_full = value.block_when_all_full;
2187
+ const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
2188
+ if (nightPacing)
2189
+ pool.caller_night_pacing = nightPacing;
2012
2190
  return pool;
2013
2191
  }
2192
+ function sanitizeCallerNightPacing(value) {
2193
+ if (!isRecord(value))
2194
+ return;
2195
+ const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
2196
+ return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
2197
+ }
2014
2198
  function sanitizeRouting(value) {
2015
2199
  if (!isRecord(value))
2016
2200
  return;
@@ -2074,15 +2258,17 @@ function clientRouting(client) {
2074
2258
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
2075
2259
  };
2076
2260
  }
2077
- var log2, 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;
2261
+ var log2, 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;
2078
2262
  var init_src4 = __esm(() => {
2079
2263
  init_src2();
2080
2264
  init_src3();
2081
2265
  init_src();
2082
2266
  init_builtin_providers();
2267
+ init_night_pacing();
2083
2268
  init_paths();
2084
2269
  init_rewrite_file();
2085
2270
  init_window_warmup();
2271
+ init_night_pacing();
2086
2272
  init_paths();
2087
2273
  init_paths_common();
2088
2274
  init_rewrite_config();
@@ -2108,9 +2294,12 @@ var init_src4 = __esm(() => {
2108
2294
  preferExpiringQuota: false,
2109
2295
  allowlistedAccountUuids: [],
2110
2296
  maxUsage: 0.9,
2297
+ maxUsageByEmail: {},
2111
2298
  weeklyMaxUsage: 0.95,
2112
2299
  weeklyMaxUsageByEmail: {},
2113
2300
  callerWeeklyMaxUsage: {},
2301
+ callerNightPacing: {},
2302
+ ownerDevicesByEmail: {},
2114
2303
  admissionCap: 5,
2115
2304
  admissionQueueLimit: 25,
2116
2305
  admissionWaitMs: 30000,
@@ -2284,9 +2473,12 @@ var init_src4 = __esm(() => {
2284
2473
  preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
2285
2474
  allowlistedAccountUuids: [...pool?.members ?? []],
2286
2475
  maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
2476
+ maxUsageByEmail: { ...pool?.max_usage_by_email },
2287
2477
  weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
2288
2478
  weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
2289
2479
  callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
2480
+ callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
2481
+ ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
2290
2482
  admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
2291
2483
  admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
2292
2484
  admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
@@ -2363,9 +2555,12 @@ var init_src4 = __esm(() => {
2363
2555
  "distribution_enabled",
2364
2556
  "prefer_expiring_quota",
2365
2557
  "max_usage",
2558
+ "max_usage_by_email",
2366
2559
  "weekly_max_usage",
2367
2560
  "weekly_max_usage_by_email",
2368
2561
  "caller_weekly_max_usage",
2562
+ "caller_night_pacing",
2563
+ "owner_devices_by_email",
2369
2564
  "admission",
2370
2565
  "quota_probe_seconds",
2371
2566
  "window_warmup",
@@ -2547,6 +2742,198 @@ var init_src4 = __esm(() => {
2547
2742
  };
2548
2743
  });
2549
2744
 
2745
+ // ../../packages/http/src/errors.ts
2746
+ var ERROR_TYPES, HttpError, BadRequest = (message, details) => new HttpError(400, message, details), NotFound = (message, details) => new HttpError(404, message, details), InternalServerError = (message, details) => new HttpError(500, message, details), ServiceUnavailable = (message, details) => new HttpError(503, message, details), DEFAULT_ERROR_MESSAGES;
2747
+ var init_errors2 = __esm(() => {
2748
+ ERROR_TYPES = {
2749
+ NETWORK: "network",
2750
+ AUTH: "auth",
2751
+ RATE_LIMIT: "rate-limit",
2752
+ VALIDATION: "validation",
2753
+ SERVER: "server",
2754
+ UNKNOWN: "unknown"
2755
+ };
2756
+ HttpError = class HttpError extends Error {
2757
+ status;
2758
+ details;
2759
+ constructor(status, message, details) {
2760
+ super(message);
2761
+ this.status = status;
2762
+ this.details = details;
2763
+ this.name = "HttpError";
2764
+ }
2765
+ };
2766
+ DEFAULT_ERROR_MESSAGES = {
2767
+ [ERROR_TYPES.NETWORK]: "Network error. Please check your connection and try again.",
2768
+ [ERROR_TYPES.AUTH]: "Authentication failed. Please sign in again.",
2769
+ [ERROR_TYPES.RATE_LIMIT]: "Too many requests. Please try again later.",
2770
+ [ERROR_TYPES.VALIDATION]: "Invalid request. Please check your input.",
2771
+ [ERROR_TYPES.SERVER]: "Server error. Please try again later.",
2772
+ [ERROR_TYPES.UNKNOWN]: "An unexpected error occurred."
2773
+ };
2774
+ });
2775
+
2776
+ // ../../packages/http/src/client.ts
2777
+ var init_client = __esm(() => {
2778
+ init_errors2();
2779
+ });
2780
+
2781
+ // ../../packages/http/src/headers.ts
2782
+ function sanitizeProxyHeaders(original) {
2783
+ const sanitized = new Headers(original);
2784
+ sanitized.delete("content-encoding");
2785
+ sanitized.delete("content-length");
2786
+ sanitized.delete("transfer-encoding");
2787
+ return sanitized;
2788
+ }
2789
+ function sanitizeRequestHeaders(original) {
2790
+ const h = new Headers(original);
2791
+ h.delete("accept-encoding");
2792
+ h.delete("content-encoding");
2793
+ h.delete("content-length");
2794
+ h.delete("transfer-encoding");
2795
+ h.delete("authorization");
2796
+ h.delete("proxy-authorization");
2797
+ h.delete("x-api-key");
2798
+ h.delete(DEVICE_KEY_HEADER);
2799
+ h.delete("api-key");
2800
+ h.delete("cookie");
2801
+ h.delete("set-cookie");
2802
+ return h;
2803
+ }
2804
+ function withSanitizedProxyHeaders(res) {
2805
+ return new Response(res.body, {
2806
+ status: res.status,
2807
+ statusText: res.statusText,
2808
+ headers: sanitizeProxyHeaders(res.headers)
2809
+ });
2810
+ }
2811
+ var DEVICE_KEY_HEADER = "x-agent-smith-device-key";
2812
+
2813
+ // ../../packages/http/src/responses.ts
2814
+ function writeUnhandledError(error) {
2815
+ if (typeof process === "undefined") {
2816
+ return;
2817
+ }
2818
+ const formattedError = error instanceof Error ? error.stack ?? error.message : String(error);
2819
+ process.stderr?.write?.(`Unhandled error: ${formattedError}
2820
+ `);
2821
+ }
2822
+ function jsonResponse(data, status = 200, headers) {
2823
+ return new Response(JSON.stringify(data), {
2824
+ status,
2825
+ headers: {
2826
+ "Content-Type": "application/json",
2827
+ ...headers
2828
+ }
2829
+ });
2830
+ }
2831
+ function errorResponse(error) {
2832
+ if (error instanceof HttpError) {
2833
+ const body = {
2834
+ error: error.message
2835
+ };
2836
+ if (error.details !== undefined) {
2837
+ body.details = error.details;
2838
+ }
2839
+ return jsonResponse(body, error.status);
2840
+ }
2841
+ if (error instanceof Error && "statusCode" in error && typeof error.statusCode === "number") {
2842
+ const details = "context" in error && error.context !== undefined ? { details: error.context } : {};
2843
+ const retryAfter = error.statusCode === 503 && "retryAfterSeconds" in error && typeof error.retryAfterSeconds === "number" && Number.isSafeInteger(error.retryAfterSeconds) && error.retryAfterSeconds > 0 ? { "Retry-After": String(error.retryAfterSeconds) } : undefined;
2844
+ return jsonResponse({ error: error.message, ...details }, error.statusCode, retryAfter);
2845
+ }
2846
+ const message = error instanceof Error ? error.message : "Internal server error";
2847
+ const status = 500;
2848
+ writeUnhandledError(error);
2849
+ return jsonResponse({ error: message }, status);
2850
+ }
2851
+ function sseResponse(stream, headers) {
2852
+ return new Response(stream, {
2853
+ headers: {
2854
+ "Content-Type": "text/event-stream",
2855
+ "Cache-Control": "no-cache",
2856
+ Connection: "keep-alive",
2857
+ ...headers
2858
+ }
2859
+ });
2860
+ }
2861
+ var init_responses = __esm(() => {
2862
+ init_errors2();
2863
+ });
2864
+
2865
+ // ../../packages/http/src/index.ts
2866
+ var init_src5 = __esm(() => {
2867
+ init_client();
2868
+ init_errors2();
2869
+ init_responses();
2870
+ });
2871
+
2872
+ // src/core/client-relay.ts
2873
+ function forwardedHeaders(original) {
2874
+ const headers2 = new Headers(original);
2875
+ for (const name of UNFORWARDED_REQUEST_HEADERS)
2876
+ headers2.delete(name);
2877
+ return headers2;
2878
+ }
2879
+ async function compressedBody(req, headers2) {
2880
+ const body = new Uint8Array(await req.arrayBuffer());
2881
+ if (body.length === 0)
2882
+ return;
2883
+ if (headers2.has("content-encoding"))
2884
+ return body;
2885
+ headers2.set("content-encoding", "gzip");
2886
+ return Bun.gzipSync(body);
2887
+ }
2888
+ function startClientRelay(remoteBaseUrl) {
2889
+ const remote = remoteBaseUrl.replace(/\/+$/, "");
2890
+ const server = Bun.serve({
2891
+ hostname: "127.0.0.1",
2892
+ port: 0,
2893
+ idleTimeout: 0,
2894
+ async fetch(req) {
2895
+ const url = new URL(req.url);
2896
+ const headers2 = forwardedHeaders(req.headers);
2897
+ const body = await compressedBody(req, headers2);
2898
+ try {
2899
+ const upstream = await fetch(`${remote}${url.pathname}${url.search}`, {
2900
+ method: req.method,
2901
+ headers: headers2,
2902
+ body,
2903
+ signal: req.signal,
2904
+ redirect: "manual"
2905
+ });
2906
+ return withSanitizedProxyHeaders(upstream);
2907
+ } catch (error) {
2908
+ const reason = error instanceof Error ? error.message : String(error);
2909
+ return Response.json({
2910
+ type: "error",
2911
+ error: {
2912
+ type: "api_error",
2913
+ message: `Agent Smith relay could not reach the pool: ${reason}`
2914
+ }
2915
+ }, { status: 502 });
2916
+ }
2917
+ }
2918
+ });
2919
+ return {
2920
+ url: `http://127.0.0.1:${server.port}`,
2921
+ stop: () => server.stop(true)
2922
+ };
2923
+ }
2924
+ var UNFORWARDED_REQUEST_HEADERS;
2925
+ var init_client_relay = __esm(() => {
2926
+ init_src5();
2927
+ UNFORWARDED_REQUEST_HEADERS = [
2928
+ "accept-encoding",
2929
+ "connection",
2930
+ "content-length",
2931
+ "host",
2932
+ "keep-alive",
2933
+ "transfer-encoding"
2934
+ ];
2935
+ });
2936
+
2550
2937
  // src/core/local-routing.ts
2551
2938
  import {
2552
2939
  accessSync as accessSync2,
@@ -2799,18 +3186,21 @@ function configClientWrappersInstalled(paths = {}) {
2799
3186
  async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
2800
3187
  if (tool !== "claude" && tool !== "codex")
2801
3188
  throw new Error("Unknown Agent Smith client");
2802
- const client = readClientRouting(configPath);
3189
+ const client2 = readClientRouting(configPath);
2803
3190
  const env = { ...process.env };
2804
3191
  delete env.AGENT_SMITH_ADMIN_KEY;
2805
3192
  delete env.AGENT_SMITH_PROXY_KEY;
2806
3193
  let command = [target, ...args];
2807
- if (client.enabled) {
2808
- if (!client.baseUrl || !client.proxyKeyFile)
3194
+ let relay;
3195
+ if (client2.enabled) {
3196
+ if (!client2.baseUrl || !client2.proxyKeyFile)
2809
3197
  throw new Error("client.base_url and client.proxy_key_file are required");
2810
- const keyFile = validateProxyKeyFile(client.proxyKeyFile);
3198
+ const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
2811
3199
  const wires = Object.keys(new Config(configPath).getProviderPools());
2812
- const base = proxyBaseUrl(8080, client.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
2813
- const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
3200
+ if (client2.baseUrl.startsWith("https://"))
3201
+ relay = startClientRelay(client2.baseUrl);
3202
+ const base = proxyBaseUrl(8080, relay?.url ?? client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
3203
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
2814
3204
  command = ["/bin/sh", "-c", script, "--", ...args];
2815
3205
  }
2816
3206
  const child = Bun.spawn(command, {
@@ -2831,6 +3221,7 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
2831
3221
  } finally {
2832
3222
  for (const [signal, listener] of Object.entries(forward))
2833
3223
  process.off(signal, listener);
3224
+ relay?.stop();
2834
3225
  }
2835
3226
  }
2836
3227
  async function enableLocalClientRouting(options) {
@@ -2919,6 +3310,7 @@ ${ROUTING_END}
2919
3310
  var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
2920
3311
  var init_local_routing = __esm(() => {
2921
3312
  init_src4();
3313
+ init_client_relay();
2922
3314
  CLAUDE_COMPANION_FILES = [
2923
3315
  ".claude-plugin/plugin.json",
2924
3316
  "hooks/hooks.json",