@certalis/agent-smith 0.3.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 +284 -87
- package/dist/client-launcher.js +214 -9
- package/dist/edge.js +15 -3
- package/dist/https.js +17 -4
- package/dist/pool.js +213 -86
- package/dist/post-processor.worker.js +88 -42
- package/dist/server.js +213 -86
- package/package.json +2 -1
package/dist/server.js
CHANGED
|
@@ -5221,6 +5221,13 @@ import {
|
|
|
5221
5221
|
writeFileSync as writeFileSync2
|
|
5222
5222
|
} from "fs";
|
|
5223
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
|
+
}
|
|
5224
5231
|
function runtimeForProvider(runtime, provider) {
|
|
5225
5232
|
return {
|
|
5226
5233
|
...runtime,
|
|
@@ -5522,8 +5529,9 @@ function sanitizeTeamRouting(value) {
|
|
|
5522
5529
|
if (weeklyMaxUsageByEmail)
|
|
5523
5530
|
result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
|
|
5524
5531
|
if (isRecord(value.caller_weekly_max_usage)) {
|
|
5525
|
-
const
|
|
5526
|
-
|
|
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)))) {
|
|
5527
5535
|
result.caller_weekly_max_usage = Object.fromEntries(entries);
|
|
5528
5536
|
}
|
|
5529
5537
|
}
|
|
@@ -5680,7 +5688,7 @@ function clientRouting(client2) {
|
|
|
5680
5688
|
...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
|
|
5681
5689
|
};
|
|
5682
5690
|
}
|
|
5683
|
-
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;
|
|
5684
5692
|
var init_src8 = __esm(() => {
|
|
5685
5693
|
init_src2();
|
|
5686
5694
|
init_src4();
|
|
@@ -6204,10 +6212,11 @@ function addPerformanceIndexes(db) {
|
|
|
6204
6212
|
`);
|
|
6205
6213
|
log7.info("Added index: idx_accounts_paused");
|
|
6206
6214
|
db.run(`
|
|
6207
|
-
CREATE INDEX IF NOT EXISTS
|
|
6208
|
-
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)
|
|
6209
6217
|
`);
|
|
6210
|
-
|
|
6218
|
+
db.run("DROP INDEX IF EXISTS idx_requests_account_timestamp");
|
|
6219
|
+
log7.info("Added index: idx_requests_account_timestamp_cost");
|
|
6211
6220
|
db.run(`
|
|
6212
6221
|
CREATE INDEX IF NOT EXISTS idx_requests_cost_model
|
|
6213
6222
|
ON requests(cost_usd, model, timestamp DESC)
|
|
@@ -6598,6 +6607,13 @@ function ensureAccountExtensionColumns(db) {
|
|
|
6598
6607
|
}
|
|
6599
6608
|
}
|
|
6600
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
|
+
}
|
|
6601
6617
|
function backfillRequestLinkageColumns(db) {
|
|
6602
6618
|
const missingCount = db.query(`
|
|
6603
6619
|
SELECT COUNT(*) AS count
|
|
@@ -7021,7 +7037,7 @@ function runMigrations(db) {
|
|
|
7021
7037
|
migrateRequestsTable(db, requestsInfo);
|
|
7022
7038
|
}
|
|
7023
7039
|
ensureRequestLinkageColumns(db);
|
|
7024
|
-
|
|
7040
|
+
backfillRequestLinkageColumnsOnce(db);
|
|
7025
7041
|
db.run("DROP TABLE IF EXISTS agent_preferences");
|
|
7026
7042
|
db.run("DROP TABLE IF EXISTS oauth_sessions");
|
|
7027
7043
|
db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
|
|
@@ -7037,7 +7053,7 @@ function runMigrations(db) {
|
|
|
7037
7053
|
db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
|
|
7038
7054
|
addPerformanceIndexes(db);
|
|
7039
7055
|
}
|
|
7040
|
-
var log9;
|
|
7056
|
+
var log9, LINKAGE_BACKFILLED_VERSION = 1;
|
|
7041
7057
|
var init_migrations = __esm(() => {
|
|
7042
7058
|
init_src4();
|
|
7043
7059
|
init_src();
|
|
@@ -7884,7 +7900,7 @@ function requestLinkageFromPayload(payload) {
|
|
|
7884
7900
|
clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
|
|
7885
7901
|
};
|
|
7886
7902
|
}
|
|
7887
|
-
var log10, RequestRepository;
|
|
7903
|
+
var log10, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
|
|
7888
7904
|
var init_request_repository = __esm(() => {
|
|
7889
7905
|
init_src4();
|
|
7890
7906
|
init_src();
|
|
@@ -8259,11 +8275,10 @@ var init_request_repository = __esm(() => {
|
|
|
8259
8275
|
return errors2.map((e) => e.error_message);
|
|
8260
8276
|
}
|
|
8261
8277
|
sumAccountCostSince(accountId, since) {
|
|
8262
|
-
return this.get(
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8266
|
-
`, [accountId, since])?.cost ?? 0;
|
|
8278
|
+
return this.get(ACCOUNT_COST_SINCE_SQL, [
|
|
8279
|
+
accountId,
|
|
8280
|
+
since
|
|
8281
|
+
])?.cost ?? 0;
|
|
8267
8282
|
}
|
|
8268
8283
|
getRequestsByAccount(since) {
|
|
8269
8284
|
const whereClause = since ? "WHERE r.timestamp > ?" : "";
|
|
@@ -8287,23 +8302,26 @@ var init_request_repository = __esm(() => {
|
|
|
8287
8302
|
successRate: row.success_rate
|
|
8288
8303
|
}));
|
|
8289
8304
|
}
|
|
8290
|
-
deleteOlderThan(cutoffTs) {
|
|
8291
|
-
return this.runWithChanges(`DELETE FROM requests WHERE
|
|
8292
|
-
|
|
8293
|
-
|
|
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]);
|
|
8294
8309
|
}
|
|
8295
8310
|
clear() {
|
|
8296
8311
|
return this.runWithChanges(`DELETE FROM requests`);
|
|
8297
8312
|
}
|
|
8298
|
-
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
|
|
8302
|
-
|
|
8303
|
-
|
|
8304
|
-
|
|
8305
|
-
|
|
8306
|
-
|
|
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]);
|
|
8307
8325
|
}
|
|
8308
8326
|
};
|
|
8309
8327
|
});
|
|
@@ -8432,6 +8450,7 @@ var init_strategy_repository = __esm(() => {
|
|
|
8432
8450
|
import { Database } from "bun:sqlite";
|
|
8433
8451
|
import { mkdirSync as mkdirSync3, statfsSync } from "fs";
|
|
8434
8452
|
import { dirname as dirname3 } from "path";
|
|
8453
|
+
import { setImmediate as yieldToEventLoop } from "timers/promises";
|
|
8435
8454
|
function freeDiskBytes(directory) {
|
|
8436
8455
|
const { bavail, bsize } = statfsSync(directory);
|
|
8437
8456
|
return bavail * bsize;
|
|
@@ -8451,7 +8470,7 @@ class DatabaseOperations {
|
|
|
8451
8470
|
conversationProviderPreferences;
|
|
8452
8471
|
strategy;
|
|
8453
8472
|
stats;
|
|
8454
|
-
constructor(dbPath) {
|
|
8473
|
+
constructor(dbPath, { migrate = true } = {}) {
|
|
8455
8474
|
const resolvedPath = dbPath ?? resolveDbPath();
|
|
8456
8475
|
this.dbPath = resolvedPath;
|
|
8457
8476
|
const dir = dirname3(resolvedPath);
|
|
@@ -8461,8 +8480,11 @@ class DatabaseOperations {
|
|
|
8461
8480
|
this.db.exec("PRAGMA journal_mode = WAL");
|
|
8462
8481
|
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
8463
8482
|
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
8464
|
-
|
|
8465
|
-
|
|
8483
|
+
this.db.exec(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);
|
|
8484
|
+
if (migrate) {
|
|
8485
|
+
ensureSchema(this.db);
|
|
8486
|
+
runMigrations(this.db);
|
|
8487
|
+
}
|
|
8466
8488
|
this.accounts = new AccountRepository(this.db);
|
|
8467
8489
|
this.analytics = new AnalyticsRepository(this.db);
|
|
8468
8490
|
this.requests = new RequestRepository(this.db);
|
|
@@ -8678,18 +8700,40 @@ class DatabaseOperations {
|
|
|
8678
8700
|
getAnalytics(options) {
|
|
8679
8701
|
return this.analytics.getAnalytics(options);
|
|
8680
8702
|
}
|
|
8681
|
-
cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
|
|
8682
|
-
const
|
|
8683
|
-
const
|
|
8684
|
-
|
|
8685
|
-
|
|
8686
|
-
|
|
8687
|
-
|
|
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;
|
|
8688
8736
|
}
|
|
8689
|
-
const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
|
|
8690
|
-
const removedOrphans = this.requests.deleteOrphanedPayloads();
|
|
8691
|
-
const removedPayloads = removedPayloadsByAge + removedOrphans;
|
|
8692
|
-
return { removedRequests, removedPayloads };
|
|
8693
8737
|
}
|
|
8694
8738
|
close() {
|
|
8695
8739
|
if (this.closed) {
|
|
@@ -8728,6 +8772,7 @@ class DatabaseOperations {
|
|
|
8728
8772
|
return this.stats;
|
|
8729
8773
|
}
|
|
8730
8774
|
}
|
|
8775
|
+
var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
|
|
8731
8776
|
var init_database_operations = __esm(() => {
|
|
8732
8777
|
init_migrations();
|
|
8733
8778
|
init_paths2();
|
|
@@ -8740,6 +8785,7 @@ var init_database_operations = __esm(() => {
|
|
|
8740
8785
|
init_request_repository();
|
|
8741
8786
|
init_stats_repository();
|
|
8742
8787
|
init_strategy_repository();
|
|
8788
|
+
WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
8743
8789
|
});
|
|
8744
8790
|
|
|
8745
8791
|
// ../../packages/database/src/factory.ts
|
|
@@ -9889,13 +9935,13 @@ var init_logs_history = __esm(() => {
|
|
|
9889
9935
|
|
|
9890
9936
|
// ../../packages/api/src/handlers/maintenance.ts
|
|
9891
9937
|
function createCleanupHandler(dbOps, config) {
|
|
9892
|
-
return () => {
|
|
9938
|
+
return async () => {
|
|
9893
9939
|
try {
|
|
9894
9940
|
const payloadDays = config.getDataRetentionDays();
|
|
9895
9941
|
const requestDays = config.getRequestRetentionDays();
|
|
9896
9942
|
const payloadMs = payloadDays * 24 * 60 * 60 * 1000;
|
|
9897
9943
|
const requestMs = requestDays * 24 * 60 * 60 * 1000;
|
|
9898
|
-
const { removedRequests, removedPayloads } = dbOps.
|
|
9944
|
+
const { removedRequests, removedPayloads } = await dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs);
|
|
9899
9945
|
const cutoffIso = new Date(Date.now() - Math.min(payloadMs, requestMs)).toISOString();
|
|
9900
9946
|
const cleanupData = {
|
|
9901
9947
|
removedRequests,
|
|
@@ -10414,7 +10460,7 @@ class APIRouter {
|
|
|
10414
10460
|
error: `A registered device key is required in ${DEVICE_KEY_HEADER}`
|
|
10415
10461
|
}, { status: 401 });
|
|
10416
10462
|
}
|
|
10417
|
-
const status = await getCallerPoolStatus(pool, model, callerId);
|
|
10463
|
+
const status = await getCallerPoolStatus(pool, model, callerId, url.searchParams.get("nightBudget") === "1");
|
|
10418
10464
|
if (!status) {
|
|
10419
10465
|
return Response.json({ error: "No provider in this pool serves the model" }, { status: 400 });
|
|
10420
10466
|
}
|
|
@@ -11444,7 +11490,7 @@ function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
|
|
|
11444
11490
|
};
|
|
11445
11491
|
}
|
|
11446
11492
|
const accountOverride = capForAccountEmail(teamRouting.weeklyMaxUsageByEmail, account2, ctx);
|
|
11447
|
-
const callerOverride = callerId &&
|
|
11493
|
+
const callerOverride = callerId && !pacedNight(teamRouting, account2, now, callerId) ? callerWeeklyCap(teamRouting.callerWeeklyMaxUsage, callerId) : undefined;
|
|
11448
11494
|
return {
|
|
11449
11495
|
limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
|
|
11450
11496
|
overridesFleetThreshold: accountOverride !== undefined
|
|
@@ -11547,7 +11593,7 @@ function getPoolStatus(provider, model, ctx) {
|
|
|
11547
11593
|
admissionWaitMs: config?.admissionWaitMs ?? 0
|
|
11548
11594
|
};
|
|
11549
11595
|
}
|
|
11550
|
-
function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts) {
|
|
11596
|
+
function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts, readNightBudget) {
|
|
11551
11597
|
const strategy3 = ctx.providerRegistry.getProvider(provider);
|
|
11552
11598
|
if (!strategy3)
|
|
11553
11599
|
throw new Error(`Unknown provider '${provider}'`);
|
|
@@ -11555,7 +11601,7 @@ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts)
|
|
|
11555
11601
|
const now = Date.now();
|
|
11556
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));
|
|
11557
11603
|
const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
|
|
11558
|
-
const nightBudget = callerNightBudget(strategy3, accounts, model, callerId, ctx, now);
|
|
11604
|
+
const nightBudget = readNightBudget ? callerNightBudget(strategy3, accounts, model, callerId, ctx, now) : null;
|
|
11559
11605
|
return {
|
|
11560
11606
|
poolEnabled: config.enabled,
|
|
11561
11607
|
servableSeats,
|
|
@@ -11987,7 +12033,7 @@ class ProviderSupply {
|
|
|
11987
12033
|
admissionWaitMs: context2.runtime.pool.admissionWaitMs
|
|
11988
12034
|
};
|
|
11989
12035
|
if (route.scope.kind === "pool-route" && route.callerId) {
|
|
11990
|
-
return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts);
|
|
12036
|
+
return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts, route.readNightBudget === true);
|
|
11991
12037
|
}
|
|
11992
12038
|
return getPoolStatus(this.name, mapped, context2);
|
|
11993
12039
|
}
|
|
@@ -12889,7 +12935,9 @@ async function getCallerPoolStatus(input) {
|
|
|
12889
12935
|
retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
|
|
12890
12936
|
holdSeconds: input.holdSeconds,
|
|
12891
12937
|
admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
|
|
12892
|
-
|
|
12938
|
+
...input.route.readNightBudget && {
|
|
12939
|
+
nightBudget: callerNightBudget2(statuses, Date.now())
|
|
12940
|
+
}
|
|
12893
12941
|
};
|
|
12894
12942
|
}
|
|
12895
12943
|
function toCents(value) {
|
|
@@ -14718,6 +14766,18 @@ var init_router_bridge = __esm(() => {
|
|
|
14718
14766
|
// ../../packages/proxy/src/usage-worker.ts
|
|
14719
14767
|
import { isAbsolute, resolve as resolve2 } from "path";
|
|
14720
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
|
+
}
|
|
14721
14781
|
function noop() {}
|
|
14722
14782
|
function createDefaultLogger() {
|
|
14723
14783
|
return {
|
|
@@ -14771,6 +14831,7 @@ class UsageWorkerController {
|
|
|
14771
14831
|
readyTimeoutMs;
|
|
14772
14832
|
ackTimeoutMs;
|
|
14773
14833
|
shutdownDelayMs;
|
|
14834
|
+
maxHeldBytes;
|
|
14774
14835
|
logger;
|
|
14775
14836
|
worker = null;
|
|
14776
14837
|
ready = false;
|
|
@@ -14780,6 +14841,9 @@ class UsageWorkerController {
|
|
|
14780
14841
|
shutdownTimer = null;
|
|
14781
14842
|
queuedMessages = [];
|
|
14782
14843
|
pendingAcks = new Map;
|
|
14844
|
+
heldBytes = 0;
|
|
14845
|
+
droppedRequestIds = new Set;
|
|
14846
|
+
droppedRequests = 0;
|
|
14783
14847
|
shutdownPromise = null;
|
|
14784
14848
|
resolveShutdown = null;
|
|
14785
14849
|
rejectShutdown = null;
|
|
@@ -14790,6 +14854,7 @@ class UsageWorkerController {
|
|
|
14790
14854
|
this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
|
|
14791
14855
|
this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
|
|
14792
14856
|
this.shutdownDelayMs = options.shutdownDelayMs ?? DEFAULT_SHUTDOWN_DELAY_MS;
|
|
14857
|
+
this.maxHeldBytes = options.maxHeldBytes ?? DEFAULT_MAX_HELD_BYTES;
|
|
14793
14858
|
this.logger = options.logger ?? createDefaultLogger();
|
|
14794
14859
|
this.startWorker();
|
|
14795
14860
|
}
|
|
@@ -14798,16 +14863,65 @@ class UsageWorkerController {
|
|
|
14798
14863
|
this.logger.warn("Dropping usage worker message because the worker is shutting down");
|
|
14799
14864
|
return;
|
|
14800
14865
|
}
|
|
14866
|
+
if (!this.admit(message)) {
|
|
14867
|
+
return;
|
|
14868
|
+
}
|
|
14801
14869
|
const decoratedMessage = {
|
|
14802
14870
|
...message,
|
|
14803
14871
|
messageId: crypto.randomUUID()
|
|
14804
14872
|
};
|
|
14805
14873
|
if (!this.ready || !this.worker) {
|
|
14806
|
-
this.
|
|
14874
|
+
this.queue(decoratedMessage);
|
|
14807
14875
|
return;
|
|
14808
14876
|
}
|
|
14809
14877
|
this.sendMessage(decoratedMessage);
|
|
14810
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
|
+
}
|
|
14811
14925
|
isShuttingDown() {
|
|
14812
14926
|
return this.shuttingDown;
|
|
14813
14927
|
}
|
|
@@ -14828,7 +14942,7 @@ class UsageWorkerController {
|
|
|
14828
14942
|
this.ready = false;
|
|
14829
14943
|
this.clearReadyTimer();
|
|
14830
14944
|
this.clearPendingAcks();
|
|
14831
|
-
this.
|
|
14945
|
+
this.forgetQueuedMessages();
|
|
14832
14946
|
const worker = this.worker;
|
|
14833
14947
|
if (!worker) {
|
|
14834
14948
|
this.shuttingDown = false;
|
|
@@ -14864,7 +14978,7 @@ class UsageWorkerController {
|
|
|
14864
14978
|
this.ready = false;
|
|
14865
14979
|
this.clearReadyTimer();
|
|
14866
14980
|
this.clearPendingAcks();
|
|
14867
|
-
this.
|
|
14981
|
+
this.forgetQueuedMessages();
|
|
14868
14982
|
if (this.shutdownTimer) {
|
|
14869
14983
|
clearTimeout(this.shutdownTimer);
|
|
14870
14984
|
this.shutdownTimer = null;
|
|
@@ -14935,10 +15049,9 @@ class UsageWorkerController {
|
|
|
14935
15049
|
this.readyTimer = null;
|
|
14936
15050
|
}
|
|
14937
15051
|
clearPendingAcks() {
|
|
14938
|
-
for (const
|
|
14939
|
-
|
|
15052
|
+
for (const messageId of Array.from(this.pendingAcks.keys())) {
|
|
15053
|
+
this.forgetPendingAck(messageId);
|
|
14940
15054
|
}
|
|
14941
|
-
this.pendingAcks.clear();
|
|
14942
15055
|
}
|
|
14943
15056
|
handleWorkerMessage(message) {
|
|
14944
15057
|
if (isShutdownCompleteMessage(message)) {
|
|
@@ -14961,12 +15074,7 @@ class UsageWorkerController {
|
|
|
14961
15074
|
return;
|
|
14962
15075
|
}
|
|
14963
15076
|
if (isAckMessage(message)) {
|
|
14964
|
-
|
|
14965
|
-
if (!pendingAck) {
|
|
14966
|
-
return;
|
|
14967
|
-
}
|
|
14968
|
-
clearTimeout(pendingAck.timer);
|
|
14969
|
-
this.pendingAcks.delete(message.messageId);
|
|
15077
|
+
this.forgetPendingAck(message.messageId);
|
|
14970
15078
|
return;
|
|
14971
15079
|
}
|
|
14972
15080
|
this.onWorkerMessage?.(message);
|
|
@@ -14975,14 +15083,15 @@ class UsageWorkerController {
|
|
|
14975
15083
|
if (!this.worker || !this.ready || this.queuedMessages.length === 0) {
|
|
14976
15084
|
return;
|
|
14977
15085
|
}
|
|
14978
|
-
const queuedMessages = this.queuedMessages.
|
|
15086
|
+
const queuedMessages = this.queuedMessages.slice();
|
|
15087
|
+
this.forgetQueuedMessages();
|
|
14979
15088
|
for (const message of queuedMessages) {
|
|
14980
15089
|
this.sendMessage(message);
|
|
14981
15090
|
}
|
|
14982
15091
|
}
|
|
14983
15092
|
sendMessage(message) {
|
|
14984
15093
|
if (!this.worker) {
|
|
14985
|
-
this.
|
|
15094
|
+
this.queue(message);
|
|
14986
15095
|
return;
|
|
14987
15096
|
}
|
|
14988
15097
|
try {
|
|
@@ -14996,11 +15105,10 @@ class UsageWorkerController {
|
|
|
14996
15105
|
return;
|
|
14997
15106
|
}
|
|
14998
15107
|
const timer = setTimeout(() => {
|
|
14999
|
-
|
|
15000
|
-
if (!pendingAck) {
|
|
15108
|
+
if (!this.pendingAcks.has(message.messageId)) {
|
|
15001
15109
|
return;
|
|
15002
15110
|
}
|
|
15003
|
-
this.
|
|
15111
|
+
this.forgetPendingAck(message.messageId);
|
|
15004
15112
|
this.logger.warn("Usage worker became unresponsive while waiting for an acknowledgement; restarting it");
|
|
15005
15113
|
this.restartWorker();
|
|
15006
15114
|
}, this.ackTimeoutMs);
|
|
@@ -15009,6 +15117,7 @@ class UsageWorkerController {
|
|
|
15009
15117
|
message,
|
|
15010
15118
|
timer
|
|
15011
15119
|
});
|
|
15120
|
+
this.heldBytes += heldBytesOf(message);
|
|
15012
15121
|
}
|
|
15013
15122
|
restartWorker() {
|
|
15014
15123
|
if (this.shuttingDown) {
|
|
@@ -15062,12 +15171,13 @@ class UsageWorkerController {
|
|
|
15062
15171
|
resolveShutdown?.();
|
|
15063
15172
|
}
|
|
15064
15173
|
}
|
|
15065
|
-
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;
|
|
15066
15175
|
var init_usage_worker = __esm(() => {
|
|
15067
15176
|
init_src2();
|
|
15068
15177
|
init_src();
|
|
15069
15178
|
DEFAULT_READY_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_READY_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
|
|
15070
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;
|
|
15071
15181
|
});
|
|
15072
15182
|
|
|
15073
15183
|
// ../../packages/proxy/src/proxy.ts
|
|
@@ -15581,7 +15691,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
15581
15691
|
admissionWaitMs: status.admissionWaitMs
|
|
15582
15692
|
};
|
|
15583
15693
|
},
|
|
15584
|
-
getCallerPoolStatus: async (pool, model, callerId) => {
|
|
15694
|
+
getCallerPoolStatus: async (pool, model, callerId, readNightBudget) => {
|
|
15585
15695
|
const members = providerRegistry.poolCapacityMembers(pool, model);
|
|
15586
15696
|
const url = new URL(`http://localhost/v1/pool/${pool}/`);
|
|
15587
15697
|
const providers2 = members.map(({ provider }) => {
|
|
@@ -15591,7 +15701,10 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
15591
15701
|
return supply;
|
|
15592
15702
|
});
|
|
15593
15703
|
return getCallerPoolStatus({
|
|
15594
|
-
route:
|
|
15704
|
+
route: {
|
|
15705
|
+
...createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
|
|
15706
|
+
readNightBudget
|
|
15707
|
+
},
|
|
15595
15708
|
providers: providers2,
|
|
15596
15709
|
orderedFallback: hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
|
|
15597
15710
|
apiKeyAccounts: runtimeConfig2.routing.apiKeyAccounts === "everyone" || hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
|
|
@@ -15909,35 +16022,49 @@ var init_fetch_handler = __esm(() => {
|
|
|
15909
16022
|
});
|
|
15910
16023
|
|
|
15911
16024
|
// ../../packages/runtime-server/src/retention-maintenance.ts
|
|
15912
|
-
function
|
|
15913
|
-
|
|
15914
|
-
|
|
15915
|
-
|
|
15916
|
-
|
|
15917
|
-
|
|
15918
|
-
|
|
15919
|
-
|
|
15920
|
-
|
|
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})`);
|
|
15921
16036
|
}
|
|
15922
16037
|
function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
|
|
15923
16038
|
const log27 = new Logger("RetentionMaintenance");
|
|
15924
|
-
|
|
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
|
+
}
|
|
15925
16045
|
try {
|
|
15926
16046
|
const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
|
|
15927
16047
|
log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
|
|
15928
16048
|
} catch (err) {
|
|
15929
16049
|
log27.error(`Database compaction error: ${err}`);
|
|
15930
16050
|
}
|
|
16051
|
+
const stopped = new AbortController;
|
|
16052
|
+
let running;
|
|
15931
16053
|
const timer = setInterval(() => {
|
|
15932
|
-
|
|
15933
|
-
|
|
15934
|
-
|
|
15935
|
-
|
|
15936
|
-
|
|
15937
|
-
}
|
|
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
|
+
});
|
|
15938
16062
|
}, intervalMs);
|
|
15939
16063
|
timer.unref?.();
|
|
15940
|
-
return () =>
|
|
16064
|
+
return () => {
|
|
16065
|
+
clearInterval(timer);
|
|
16066
|
+
stopped.abort();
|
|
16067
|
+
};
|
|
15941
16068
|
}
|
|
15942
16069
|
var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
|
|
15943
16070
|
var init_retention_maintenance = __esm(() => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@certalis/agent-smith",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "PROOF OF CONCEPT for ideation only: an experimental local proxy and provider pool for Claude Code and Codex",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Certalis",
|
|
@@ -40,6 +40,7 @@
|
|
|
40
40
|
"@agent-smith/config": "workspace:*",
|
|
41
41
|
"@agent-smith/core": "workspace:*",
|
|
42
42
|
"@agent-smith/database": "workspace:*",
|
|
43
|
+
"@agent-smith/http": "workspace:*",
|
|
43
44
|
"@agent-smith/logger": "workspace:*",
|
|
44
45
|
"@agent-smith/oauth-flow": "workspace:*",
|
|
45
46
|
"@agent-smith/providers": "workspace:*",
|