@certalis/agent-smith 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pool.js CHANGED
@@ -238,9 +238,11 @@ var init_errors = __esm(() => {
238
238
  };
239
239
  ServiceUnavailableError = class ServiceUnavailableError extends AppError {
240
240
  service;
241
- constructor(message, service) {
241
+ retryAfterSeconds;
242
+ constructor(message, service, retryAfterSeconds) {
242
243
  super(message, "SERVICE_UNAVAILABLE", 503, { service });
243
244
  this.service = service;
245
+ this.retryAfterSeconds = retryAfterSeconds;
244
246
  }
245
247
  };
246
248
  });
@@ -1105,7 +1107,8 @@ function errorResponse(error) {
1105
1107
  }
1106
1108
  if (error instanceof Error && "statusCode" in error && typeof error.statusCode === "number") {
1107
1109
  const details = "context" in error && error.context !== undefined ? { details: error.context } : {};
1108
- return jsonResponse({ error: error.message, ...details }, error.statusCode);
1110
+ 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;
1111
+ return jsonResponse({ error: error.message, ...details }, error.statusCode, retryAfter);
1109
1112
  }
1110
1113
  const message = error instanceof Error ? error.message : "Internal server error";
1111
1114
  const status = 500;
@@ -1931,7 +1934,7 @@ function utilization(value) {
1931
1934
  const raw = number(value.used_percentage ?? value.usedPercentage ?? value.percent ?? value.utilization);
1932
1935
  if (raw === null)
1933
1936
  return null;
1934
- return raw > 1 ? raw / 100 : raw;
1937
+ return raw / 100;
1935
1938
  }
1936
1939
  function resetAt(value) {
1937
1940
  const raw = value.resets_at ?? value.reset_at ?? value.resetAt;
@@ -8110,6 +8113,18 @@ class APIRouter {
8110
8113
  this.registerHandlers();
8111
8114
  }
8112
8115
  registerHandlers() {
8116
+ if (this.context.deploymentDrain) {
8117
+ const control = this.context.deploymentDrain;
8118
+ for (const [method, action] of [
8119
+ ["GET", "status"],
8120
+ ["POST", "start"],
8121
+ ["DELETE", "resume"]
8122
+ ]) {
8123
+ this.staticHandlers.set(`${method}:/api/drain`, () => Response.json(control(action), {
8124
+ headers: { "cache-control": "no-store" }
8125
+ }));
8126
+ }
8127
+ }
8113
8128
  if (this.enrollment) {
8114
8129
  this.staticHandlers.set("POST:/api/enrollment-invitations", this.enrollment.issue);
8115
8130
  this.staticHandlers.set("POST:/api/enrollment-emails", this.enrollment.emails);
@@ -8144,6 +8159,9 @@ class APIRouter {
8144
8159
  this.staticHandlers.set("GET:/api/stats", () => statsHandler());
8145
8160
  this.staticHandlers.set("GET:/api/status", () => fleetStatusHandler());
8146
8161
  this.staticHandlers.set("GET:/api/pool-status", (_req, url) => {
8162
+ if (this.context.deploymentDrain?.("status").draining) {
8163
+ return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
8164
+ }
8147
8165
  const provider = url.searchParams.get("provider") ?? "";
8148
8166
  const model = url.searchParams.get("model") ?? undefined;
8149
8167
  if (!isAccountProvider(provider) || !getProviders().includes(provider) || model !== undefined && (model.trim().length === 0 || model.length > 200)) {
@@ -8466,6 +8484,118 @@ var init_team_router = __esm(() => {
8466
8484
  PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
8467
8485
  });
8468
8486
 
8487
+ // ../../packages/proxy/src/constants.ts
8488
+ var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
8489
+ var init_constants2 = __esm(() => {
8490
+ TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
8491
+ });
8492
+
8493
+ // ../../packages/proxy/src/handlers/proxy-types.ts
8494
+ function createResolvedProxyContext(ctx, provider, upstreamPath) {
8495
+ return {
8496
+ ...ctx,
8497
+ provider,
8498
+ providerName: provider.name,
8499
+ upstreamPath
8500
+ };
8501
+ }
8502
+ function resolveProxyContext(url, ctx) {
8503
+ const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
8504
+ if (!resolvedProvider) {
8505
+ return null;
8506
+ }
8507
+ return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
8508
+ }
8509
+ var ERROR_MESSAGES, TIMING;
8510
+ var init_proxy_types = __esm(() => {
8511
+ ERROR_MESSAGES = {
8512
+ NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
8513
+ PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
8514
+ REFRESH_NOT_FOUND: "Refresh promise not found for account",
8515
+ ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
8516
+ TOKEN_REFRESH_FAILED: "Failed to refresh access token",
8517
+ PROXY_REQUEST_FAILED: "Failed to proxy request with account"
8518
+ };
8519
+ TIMING = {
8520
+ WORKER_SHUTDOWN_DELAY: 5000
8521
+ };
8522
+ });
8523
+
8524
+ // ../../packages/proxy/src/handlers/token-manager.ts
8525
+ function refreshBackoffUntil(accountId, now = Date.now()) {
8526
+ const failure = refreshFailures.get(accountId);
8527
+ return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
8528
+ }
8529
+ function quarantineAccount(account2, ctx, reason) {
8530
+ account2.paused = true;
8531
+ account2.error_reason = reason;
8532
+ ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
8533
+ }
8534
+ function recordRefreshFailure(account2, ctx, error) {
8535
+ const refreshError = new TokenRefreshError(account2.id, error);
8536
+ refreshFailures.set(account2.id, { at: Date.now(), error: refreshError });
8537
+ const status = error?.status;
8538
+ if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
8539
+ quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
8540
+ }
8541
+ log18.error(`Token refresh failed for account ${account2.name}`, error);
8542
+ return refreshError;
8543
+ }
8544
+ async function refreshAccessTokenSafe(account2, ctx) {
8545
+ const lastFailure = refreshFailures.get(account2.id);
8546
+ if (lastFailure && refreshBackoffUntil(account2.id) !== null) {
8547
+ log18.warn(`Account ${account2.name} is in refresh backoff period`);
8548
+ throw lastFailure.error;
8549
+ }
8550
+ if (!ctx.refreshInFlight.has(account2.id)) {
8551
+ if (!ctx.provider.refreshToken) {
8552
+ throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
8553
+ }
8554
+ const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
8555
+ ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
8556
+ account2.access_token = result.accessToken;
8557
+ account2.expires_at = result.expiresAt;
8558
+ if (result.refreshToken) {
8559
+ account2.refresh_token = result.refreshToken;
8560
+ }
8561
+ account2.last_used = Date.now();
8562
+ refreshFailures.delete(account2.id);
8563
+ log18.info(`Successfully refreshed token for account: ${account2.name}`);
8564
+ return result.accessToken;
8565
+ }).catch((error) => {
8566
+ throw recordRefreshFailure(account2, ctx, error);
8567
+ }).finally(() => {
8568
+ ctx.refreshInFlight.delete(account2.id);
8569
+ });
8570
+ ctx.refreshInFlight.set(account2.id, refreshPromise);
8571
+ }
8572
+ const promise = ctx.refreshInFlight.get(account2.id);
8573
+ if (!promise) {
8574
+ throw new TokenRefreshError(account2.id, new Error(ERROR_MESSAGES.REFRESH_NOT_FOUND));
8575
+ }
8576
+ return promise;
8577
+ }
8578
+ async function getValidAccessToken(account2, ctx) {
8579
+ if (!account2.refresh_token && account2.api_key) {
8580
+ return "";
8581
+ }
8582
+ if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
8583
+ return account2.access_token;
8584
+ }
8585
+ const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
8586
+ log18.info(`Token ${reason} for account: ${account2.name}`);
8587
+ return await refreshAccessTokenSafe(account2, ctx);
8588
+ }
8589
+ var log18, refreshFailures;
8590
+ var init_token_manager = __esm(() => {
8591
+ init_src2();
8592
+ init_src4();
8593
+ init_constants2();
8594
+ init_proxy_types();
8595
+ log18 = new Logger("TokenManager");
8596
+ refreshFailures = new Map;
8597
+ });
8598
+
8469
8599
  // ../../packages/proxy/src/handlers/account-selector.ts
8470
8600
  function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
8471
8601
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
@@ -8491,7 +8621,9 @@ function fleetAccounts(provider, ctx) {
8491
8621
  return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
8492
8622
  }
8493
8623
  function cooldownEnd(account2, now) {
8494
- return account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8624
+ const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8625
+ const refreshEnd = refreshBackoffUntil(account2.id, now);
8626
+ return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
8495
8627
  }
8496
8628
  function blockingResets(provider, account2, model, ctx, now) {
8497
8629
  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(account2, ctx))).map(([, window2]) => window2.resetAt);
@@ -8554,8 +8686,8 @@ function selectRevalidationProbe(accounts, ctx, now) {
8554
8686
  return [probe];
8555
8687
  }
8556
8688
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
8557
- const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
8558
8689
  const now = Date.now();
8690
+ const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2.id, now) === null);
8559
8691
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8560
8692
  const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
8561
8693
  const prioritized = [...candidates].sort((left, right) => {
@@ -8573,6 +8705,7 @@ var init_account_selector = __esm(() => {
8573
8705
  init_src();
8574
8706
  init_seat_usage();
8575
8707
  init_team_router();
8708
+ init_token_manager();
8576
8709
  });
8577
8710
 
8578
8711
  // ../../packages/proxy/src/handlers/request-handler.ts
@@ -8664,101 +8797,6 @@ var init_request_handler = __esm(() => {
8664
8797
  DEFAULT_MAX_BODY_BYTES = 64 * 1024 * 1024;
8665
8798
  });
8666
8799
 
8667
- // ../../packages/proxy/src/constants.ts
8668
- var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
8669
- var init_constants2 = __esm(() => {
8670
- TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
8671
- });
8672
-
8673
- // ../../packages/proxy/src/handlers/proxy-types.ts
8674
- function createResolvedProxyContext(ctx, provider, upstreamPath) {
8675
- return {
8676
- ...ctx,
8677
- provider,
8678
- providerName: provider.name,
8679
- upstreamPath
8680
- };
8681
- }
8682
- function resolveProxyContext(url, ctx) {
8683
- const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
8684
- if (!resolvedProvider) {
8685
- return null;
8686
- }
8687
- return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
8688
- }
8689
- var ERROR_MESSAGES, TIMING;
8690
- var init_proxy_types = __esm(() => {
8691
- ERROR_MESSAGES = {
8692
- NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
8693
- PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
8694
- REFRESH_NOT_FOUND: "Refresh promise not found for account",
8695
- ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
8696
- TOKEN_REFRESH_FAILED: "Failed to refresh access token",
8697
- PROXY_REQUEST_FAILED: "Failed to proxy request with account"
8698
- };
8699
- TIMING = {
8700
- WORKER_SHUTDOWN_DELAY: 5000
8701
- };
8702
- });
8703
-
8704
- // ../../packages/proxy/src/handlers/token-manager.ts
8705
- async function refreshAccessTokenSafe(account2, ctx) {
8706
- const lastFailure = refreshFailures.get(account2.id);
8707
- if (lastFailure && Date.now() - lastFailure < TOKEN_REFRESH_BACKOFF_MS) {
8708
- log18.warn(`Account ${account2.name} is in refresh backoff period`);
8709
- throw new ServiceUnavailableError(`Token refresh for account ${account2.name} is in backoff period after recent failure`);
8710
- }
8711
- if (!ctx.refreshInFlight.has(account2.id)) {
8712
- if (!ctx.provider.refreshToken) {
8713
- throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
8714
- }
8715
- const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
8716
- ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
8717
- account2.access_token = result.accessToken;
8718
- account2.expires_at = result.expiresAt;
8719
- if (result.refreshToken) {
8720
- account2.refresh_token = result.refreshToken;
8721
- }
8722
- account2.last_used = Date.now();
8723
- refreshFailures.delete(account2.id);
8724
- log18.info(`Successfully refreshed token for account: ${account2.name}`);
8725
- return result.accessToken;
8726
- }).catch((error) => {
8727
- refreshFailures.set(account2.id, Date.now());
8728
- log18.error(`Token refresh failed for account ${account2.name}`, error);
8729
- throw new TokenRefreshError(account2.id, error);
8730
- }).finally(() => {
8731
- ctx.refreshInFlight.delete(account2.id);
8732
- });
8733
- ctx.refreshInFlight.set(account2.id, refreshPromise);
8734
- }
8735
- const promise = ctx.refreshInFlight.get(account2.id);
8736
- if (!promise) {
8737
- throw new ServiceUnavailableError(`${ERROR_MESSAGES.REFRESH_NOT_FOUND} ${account2.id}`);
8738
- }
8739
- return promise;
8740
- }
8741
- async function getValidAccessToken(account2, ctx) {
8742
- if (!account2.refresh_token && account2.api_key) {
8743
- return "";
8744
- }
8745
- if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
8746
- return account2.access_token;
8747
- }
8748
- const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
8749
- log18.info(`Token ${reason} for account: ${account2.name}`);
8750
- return await refreshAccessTokenSafe(account2, ctx);
8751
- }
8752
- var log18, refreshFailures;
8753
- var init_token_manager = __esm(() => {
8754
- init_src2();
8755
- init_src4();
8756
- init_constants2();
8757
- init_proxy_types();
8758
- log18 = new Logger("TokenManager");
8759
- refreshFailures = new Map;
8760
- });
8761
-
8762
8800
  // ../../packages/proxy/src/outside-spend.ts
8763
8801
  class OutsideSpendTracker {
8764
8802
  now;
@@ -8968,7 +9006,12 @@ class TeamAdmission {
8968
9006
  holdSeconds: 0,
8969
9007
  quotaProbeSeconds: 0
8970
9008
  });
8971
- account2.switchedAt = this.now();
9009
+ if (account2.active > 0 || account2.queue.length > 0)
9010
+ return;
9011
+ const now = this.now();
9012
+ if (account2.switchedAt === undefined || now - account2.switchedAt >= RAMP_WINDOW_MS) {
9013
+ account2.switchedAt = now;
9014
+ }
8972
9015
  this.scheduleRamp(accountId, account2);
8973
9016
  }
8974
9017
  advance() {
@@ -9660,17 +9703,6 @@ var init_stream_failure = __esm(() => {
9660
9703
  });
9661
9704
 
9662
9705
  // ../../packages/proxy/src/handlers/proxy-operations.ts
9663
- function shouldQuarantineAfterRefreshFailure(error) {
9664
- if (!(error instanceof TokenRefreshError))
9665
- return false;
9666
- const status = error.originalError?.status;
9667
- return typeof status === "number" && status >= 400 && status < 500;
9668
- }
9669
- function quarantineAccount(account2, ctx, reason) {
9670
- account2.paused = true;
9671
- account2.error_reason = reason;
9672
- ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
9673
- }
9674
9706
  function createUpstreamSender(input) {
9675
9707
  const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
9676
9708
  return async (token) => {
@@ -9703,10 +9735,7 @@ async function sendAuthorizedRequest(input, send) {
9703
9735
  try {
9704
9736
  accessToken = await refreshAccessTokenSafe(input.account, input.ctx);
9705
9737
  upstream = await send(accessToken);
9706
- } catch (error) {
9707
- if (shouldQuarantineAfterRefreshFailure(error)) {
9708
- quarantineAccount(input.account, input.ctx, "OAuth refresh was rejected by the upstream");
9709
- }
9738
+ } catch {
9710
9739
  return { kind: "failed" };
9711
9740
  }
9712
9741
  return upstream.response.status === 401 ? { kind: "authentication-failure" } : upstream;
@@ -9822,6 +9851,15 @@ var init_proxy_operations = __esm(() => {
9822
9851
  });
9823
9852
 
9824
9853
  // ../../packages/proxy/src/handlers/proxy-attempts.ts
9854
+ function admissionRetrySeconds(req) {
9855
+ if (req.signal.aborted)
9856
+ return;
9857
+ const count = req.headers.get("x-stainless-retry-count") ?? "0";
9858
+ if (!/^\d+$/.test(count))
9859
+ return 1;
9860
+ const ordinal = Number(count);
9861
+ return ordinal === 0 ? 1 : ordinal === 1 ? 10 : 30;
9862
+ }
9825
9863
  function createBodyStream(body) {
9826
9864
  if (!body)
9827
9865
  return;
@@ -9881,7 +9919,7 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9881
9919
  permit = request2.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request2.ctx.runtime.teamRouting, request2.req.signal) : undefined;
9882
9920
  } catch (error) {
9883
9921
  if (error instanceof TeamAdmissionError) {
9884
- throw new ServiceUnavailableError(error.message, request2.ctx.providerName);
9922
+ throw new ServiceUnavailableError(error.message, request2.ctx.providerName, admissionRetrySeconds(request2.req));
9885
9923
  }
9886
9924
  throw error;
9887
9925
  }
@@ -11852,7 +11890,7 @@ function exposureFailure(req, url, server, config) {
11852
11890
  if (!isSameOriginManagementRequest(req, url)) {
11853
11891
  return jsonError(403, "Cross-origin management requests are not allowed");
11854
11892
  }
11855
- if (MUTATING_METHODS.has(req.method)) {
11893
+ if (url.pathname === "/api/drain" || MUTATING_METHODS.has(req.method)) {
11856
11894
  if (role !== "admin") {
11857
11895
  return jsonError(401, "An admin key is required for management writes");
11858
11896
  }
@@ -11909,7 +11947,7 @@ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig
11909
11947
  }
11910
11948
  });
11911
11949
  }
11912
- function bootstrapRuntime(port, serverLog) {
11950
+ function bootstrapRuntime(port, serverLog, deploymentDrain) {
11913
11951
  container.registerInstance(SERVICE_KEYS.Config, new Config);
11914
11952
  container.registerInstance(SERVICE_KEYS.Logger, serverLog);
11915
11953
  const config = container.resolve(SERVICE_KEYS.Config);
@@ -11928,6 +11966,7 @@ function bootstrapRuntime(port, serverLog) {
11928
11966
  container.registerInstance(SERVICE_KEYS.PricingLogger, pricingLogger);
11929
11967
  setPricingLogger(pricingLogger);
11930
11968
  const apiRouter = new APIRouter({
11969
+ deploymentDrain,
11931
11970
  enrollmentOrigin: process.env.AGENT_SMITH_ENROLLMENT_ORIGIN,
11932
11971
  config,
11933
11972
  dbOps,
@@ -12088,6 +12127,48 @@ var init_dashboard_assets = __esm(() => {
12088
12127
  init_src2();
12089
12128
  });
12090
12129
 
12130
+ // ../../packages/runtime-server/src/deployment-drain.ts
12131
+ class DeploymentDrain {
12132
+ activity;
12133
+ now;
12134
+ expiresAt = null;
12135
+ stopping = false;
12136
+ log = new Logger("DeploymentDrain");
12137
+ constructor(activity, now = () => Date.now()) {
12138
+ this.activity = activity;
12139
+ this.now = now;
12140
+ }
12141
+ isDraining = () => {
12142
+ if (this.expiresAt !== null && this.now() >= this.expiresAt) {
12143
+ this.expiresAt = null;
12144
+ this.log.info("Deployment pause expired; accepting new inference");
12145
+ }
12146
+ return this.stopping || this.expiresAt !== null;
12147
+ };
12148
+ control = (action) => {
12149
+ if (action === "start" && !this.stopping) {
12150
+ if (!this.isDraining())
12151
+ this.log.info("Deployment pause started");
12152
+ this.expiresAt = this.now() + 120000;
12153
+ } else if (action === "resume" && !this.stopping) {
12154
+ this.expiresAt = null;
12155
+ this.log.info("Deployment pause cancelled; accepting new inference");
12156
+ }
12157
+ return {
12158
+ draining: this.isDraining(),
12159
+ expiresAt: this.expiresAt,
12160
+ ...this.activity()
12161
+ };
12162
+ };
12163
+ shutdown() {
12164
+ this.stopping = true;
12165
+ this.expiresAt = null;
12166
+ }
12167
+ }
12168
+ var init_deployment_drain = __esm(() => {
12169
+ init_src4();
12170
+ });
12171
+
12091
12172
  // ../../packages/runtime-server/src/oauth-token.ts
12092
12173
  async function forwardOAuthTokenRequest(req, body) {
12093
12174
  const headers3 = new Headers(req.headers);
@@ -12136,7 +12217,8 @@ function createServerFetchHandler({
12136
12217
  handleProxyRequest = handleProxy,
12137
12218
  handleWebSocketUpgrade = handleWebSocketUpgradeRequest,
12138
12219
  handleOAuthTokenRequest = forwardOAuthTokenRequest,
12139
- serveDashboardAsset = serveDashboardRoute
12220
+ serveDashboardAsset = serveDashboardRoute,
12221
+ isDeploymentDraining = () => false
12140
12222
  }) {
12141
12223
  return async (req, server) => {
12142
12224
  const url = new URL(req.url);
@@ -12164,6 +12246,9 @@ function createServerFetchHandler({
12164
12246
  }
12165
12247
  const isProviderRoute = url.pathname === "/v1" || url.pathname.startsWith("/v1/") || url.pathname.startsWith("/tc-acct/");
12166
12248
  if (isProviderRoute) {
12249
+ if (isDeploymentDraining()) {
12250
+ return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
12251
+ }
12167
12252
  if (server) {
12168
12253
  const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
12169
12254
  if (websocketResponse) {
@@ -12278,17 +12363,38 @@ async function stopServerRuntime() {
12278
12363
  const errors2 = [];
12279
12364
  const activeServer = serverInstance;
12280
12365
  const activeUnixServer = unixServerInstance;
12281
- serverInstance = null;
12282
- unixServerInstance = null;
12366
+ deploymentDrain?.shutdown();
12367
+ const listeners = [activeUnixServer, activeServer].filter((listener) => listener !== null);
12368
+ const shutdownDeadline = Date.now() + 25000;
12283
12369
  try {
12284
- await activeUnixServer?.stop(true);
12285
- } catch (error) {
12286
- errors2.push(toError("Failed to stop Unix server", error));
12287
- }
12288
- try {
12289
- await activeServer?.stop(true);
12290
- } catch (error) {
12291
- errors2.push(toError("Failed to stop Bun server", error));
12370
+ await new Promise((resolve3) => {
12371
+ let timer;
12372
+ const finish = () => {
12373
+ clearInterval(timer);
12374
+ resolve3();
12375
+ };
12376
+ const check = () => {
12377
+ const pending = listeners.some((listener) => listener.pendingRequests > 0 || listener.pendingWebSockets > 0);
12378
+ if (!pending)
12379
+ finish();
12380
+ else if (Date.now() >= shutdownDeadline) {
12381
+ lifecycleLog.warn("Shutdown grace expired; closing remaining connections");
12382
+ finish();
12383
+ }
12384
+ };
12385
+ checkShutdownDrain = check;
12386
+ timer = setInterval(check, 50);
12387
+ check();
12388
+ });
12389
+ const stopped = await Promise.allSettled(listeners.map((listener) => listener.stop(true)));
12390
+ for (const result of stopped) {
12391
+ if (result.status === "rejected")
12392
+ errors2.push(toError("Failed to stop listener", result.reason));
12393
+ }
12394
+ } finally {
12395
+ checkShutdownDrain = undefined;
12396
+ serverInstance = null;
12397
+ unixServerInstance = null;
12292
12398
  }
12293
12399
  stopRetentionMaintenance();
12294
12400
  try {
@@ -12336,6 +12442,11 @@ function startServer(options) {
12336
12442
  if (withDashboard) {
12337
12443
  loadDashboardAssets();
12338
12444
  }
12445
+ const drain = new DeploymentDrain(() => ({
12446
+ activeRequests: Math.max(0, (serverInstance?.pendingRequests ?? 0) + (unixServerInstance?.pendingRequests ?? 0) - 1),
12447
+ activeWebSockets: (serverInstance?.pendingWebSockets ?? 0) + (unixServerInstance?.pendingWebSockets ?? 0)
12448
+ }));
12449
+ deploymentDrain = drain;
12339
12450
  const {
12340
12451
  config,
12341
12452
  dbOps,
@@ -12345,13 +12456,14 @@ function startServer(options) {
12345
12456
  proxyContext,
12346
12457
  providerRegistry,
12347
12458
  runtimeConfig: runtimeConfig2
12348
- } = bootstrapRuntime(port, serverLog);
12459
+ } = bootstrapRuntime(port, serverLog, drain.control);
12349
12460
  stopRetentionJob = runStartupMaintenance(config, dbOps);
12350
12461
  const fetchHandler = createServerFetchHandler({
12351
12462
  apiRouter,
12352
12463
  exposureConfig,
12353
12464
  proxyContext,
12354
- withDashboard
12465
+ withDashboard,
12466
+ isDeploymentDraining: drain.isDraining
12355
12467
  });
12356
12468
  try {
12357
12469
  if (options?.additionalUnixSocket) {
@@ -12390,6 +12502,7 @@ function startServer(options) {
12390
12502
  advanceRoutingClock: () => {
12391
12503
  proxyContext.teamAdmission?.advance();
12392
12504
  proxyContext.quotaHold?.advance();
12505
+ checkShutdownDrain?.();
12393
12506
  }
12394
12507
  };
12395
12508
  }
@@ -12404,7 +12517,7 @@ async function handleGracefulShutdown(signal) {
12404
12517
  process.exit(1);
12405
12518
  }
12406
12519
  }
12407
- var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null;
12520
+ var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null, deploymentDrain, checkShutdownDrain;
12408
12521
  var init_src11 = __esm(() => {
12409
12522
  init_src9();
12410
12523
  init_src2();
@@ -12413,6 +12526,7 @@ var init_src11 = __esm(() => {
12413
12526
  init_src10();
12414
12527
  init_bootstrap_runtime();
12415
12528
  init_dashboard_assets();
12529
+ init_deployment_drain();
12416
12530
  init_fetch_handler();
12417
12531
  init_startup_banner();
12418
12532
  init_startup_maintenance();
@@ -238,9 +238,11 @@ var init_errors = __esm(() => {
238
238
  };
239
239
  ServiceUnavailableError = class ServiceUnavailableError extends AppError {
240
240
  service;
241
- constructor(message, service) {
241
+ retryAfterSeconds;
242
+ constructor(message, service, retryAfterSeconds) {
242
243
  super(message, "SERVICE_UNAVAILABLE", 503, { service });
243
244
  this.service = service;
245
+ this.retryAfterSeconds = retryAfterSeconds;
244
246
  }
245
247
  };
246
248
  });