@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/README.md CHANGED
@@ -96,6 +96,11 @@ key; provider tokens and the single database stay on the server.
96
96
  Device keys allow independent revocation and cannot read management data.
97
97
  This does not add per-client fairness or budgets.
98
98
 
99
+ Seat owners join through the server's optional `/pool-enroll` page, not its
100
+ proxy homepage. Enable the existing email-listed sign-in flow with
101
+ `AGENT_SMITH_ENROLLMENT_ORIGIN` as described in the
102
+ [HTTPS deployment guide](docs/https-edge.md#standalone-render-web-service).
103
+
99
104
  Copy [`https-client.json`](examples/config/https-client.json) into your private
100
105
  Agent Smith config. Put the device key in the owner-only file named by
101
106
  `proxy_key_file`, not in the JSON or a shell profile. `base_url` is the endpoint
package/dist/bin.js CHANGED
@@ -239,9 +239,11 @@ var init_errors = __esm(() => {
239
239
  };
240
240
  ServiceUnavailableError = class ServiceUnavailableError extends AppError {
241
241
  service;
242
- constructor(message, service) {
242
+ retryAfterSeconds;
243
+ constructor(message, service, retryAfterSeconds) {
243
244
  super(message, "SERVICE_UNAVAILABLE", 503, { service });
244
245
  this.service = service;
246
+ this.retryAfterSeconds = retryAfterSeconds;
245
247
  }
246
248
  };
247
249
  });
@@ -4505,7 +4507,8 @@ function errorResponse(error) {
4505
4507
  }
4506
4508
  if (error instanceof Error && "statusCode" in error && typeof error.statusCode === "number") {
4507
4509
  const details = "context" in error && error.context !== undefined ? { details: error.context } : {};
4508
- return jsonResponse({ error: error.message, ...details }, error.statusCode);
4510
+ 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;
4511
+ return jsonResponse({ error: error.message, ...details }, error.statusCode, retryAfter);
4509
4512
  }
4510
4513
  const message = error instanceof Error ? error.message : "Internal server error";
4511
4514
  const status = 500;
@@ -5111,7 +5114,7 @@ function utilization(value) {
5111
5114
  const raw = number(value.used_percentage ?? value.usedPercentage ?? value.percent ?? value.utilization);
5112
5115
  if (raw === null)
5113
5116
  return null;
5114
- return raw > 1 ? raw / 100 : raw;
5117
+ return raw / 100;
5115
5118
  }
5116
5119
  function resetAt(value) {
5117
5120
  const raw = value.resets_at ?? value.reset_at ?? value.resetAt;
@@ -8111,6 +8114,18 @@ class APIRouter {
8111
8114
  this.registerHandlers();
8112
8115
  }
8113
8116
  registerHandlers() {
8117
+ if (this.context.deploymentDrain) {
8118
+ const control = this.context.deploymentDrain;
8119
+ for (const [method, action] of [
8120
+ ["GET", "status"],
8121
+ ["POST", "start"],
8122
+ ["DELETE", "resume"]
8123
+ ]) {
8124
+ this.staticHandlers.set(`${method}:/api/drain`, () => Response.json(control(action), {
8125
+ headers: { "cache-control": "no-store" }
8126
+ }));
8127
+ }
8128
+ }
8114
8129
  if (this.enrollment) {
8115
8130
  this.staticHandlers.set("POST:/api/enrollment-invitations", this.enrollment.issue);
8116
8131
  this.staticHandlers.set("POST:/api/enrollment-emails", this.enrollment.emails);
@@ -8145,6 +8160,9 @@ class APIRouter {
8145
8160
  this.staticHandlers.set("GET:/api/stats", () => statsHandler());
8146
8161
  this.staticHandlers.set("GET:/api/status", () => fleetStatusHandler());
8147
8162
  this.staticHandlers.set("GET:/api/pool-status", (_req, url) => {
8163
+ if (this.context.deploymentDrain?.("status").draining) {
8164
+ return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
8165
+ }
8148
8166
  const provider = url.searchParams.get("provider") ?? "";
8149
8167
  const model = url.searchParams.get("model") ?? undefined;
8150
8168
  if (!isAccountProvider(provider) || !getProviders().includes(provider) || model !== undefined && (model.trim().length === 0 || model.length > 200)) {
@@ -8467,6 +8485,118 @@ var init_team_router = __esm(() => {
8467
8485
  PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
8468
8486
  });
8469
8487
 
8488
+ // ../../packages/proxy/src/constants.ts
8489
+ var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
8490
+ var init_constants2 = __esm(() => {
8491
+ TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
8492
+ });
8493
+
8494
+ // ../../packages/proxy/src/handlers/proxy-types.ts
8495
+ function createResolvedProxyContext(ctx, provider, upstreamPath) {
8496
+ return {
8497
+ ...ctx,
8498
+ provider,
8499
+ providerName: provider.name,
8500
+ upstreamPath
8501
+ };
8502
+ }
8503
+ function resolveProxyContext(url, ctx) {
8504
+ const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
8505
+ if (!resolvedProvider) {
8506
+ return null;
8507
+ }
8508
+ return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
8509
+ }
8510
+ var ERROR_MESSAGES, TIMING;
8511
+ var init_proxy_types = __esm(() => {
8512
+ ERROR_MESSAGES = {
8513
+ NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
8514
+ PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
8515
+ REFRESH_NOT_FOUND: "Refresh promise not found for account",
8516
+ ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
8517
+ TOKEN_REFRESH_FAILED: "Failed to refresh access token",
8518
+ PROXY_REQUEST_FAILED: "Failed to proxy request with account"
8519
+ };
8520
+ TIMING = {
8521
+ WORKER_SHUTDOWN_DELAY: 5000
8522
+ };
8523
+ });
8524
+
8525
+ // ../../packages/proxy/src/handlers/token-manager.ts
8526
+ function refreshBackoffUntil(accountId, now = Date.now()) {
8527
+ const failure = refreshFailures.get(accountId);
8528
+ return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
8529
+ }
8530
+ function quarantineAccount(account2, ctx, reason) {
8531
+ account2.paused = true;
8532
+ account2.error_reason = reason;
8533
+ ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
8534
+ }
8535
+ function recordRefreshFailure(account2, ctx, error) {
8536
+ const refreshError = new TokenRefreshError(account2.id, error);
8537
+ refreshFailures.set(account2.id, { at: Date.now(), error: refreshError });
8538
+ const status = error?.status;
8539
+ if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
8540
+ quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
8541
+ }
8542
+ log18.error(`Token refresh failed for account ${account2.name}`, error);
8543
+ return refreshError;
8544
+ }
8545
+ async function refreshAccessTokenSafe(account2, ctx) {
8546
+ const lastFailure = refreshFailures.get(account2.id);
8547
+ if (lastFailure && refreshBackoffUntil(account2.id) !== null) {
8548
+ log18.warn(`Account ${account2.name} is in refresh backoff period`);
8549
+ throw lastFailure.error;
8550
+ }
8551
+ if (!ctx.refreshInFlight.has(account2.id)) {
8552
+ if (!ctx.provider.refreshToken) {
8553
+ throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
8554
+ }
8555
+ const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
8556
+ ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
8557
+ account2.access_token = result.accessToken;
8558
+ account2.expires_at = result.expiresAt;
8559
+ if (result.refreshToken) {
8560
+ account2.refresh_token = result.refreshToken;
8561
+ }
8562
+ account2.last_used = Date.now();
8563
+ refreshFailures.delete(account2.id);
8564
+ log18.info(`Successfully refreshed token for account: ${account2.name}`);
8565
+ return result.accessToken;
8566
+ }).catch((error) => {
8567
+ throw recordRefreshFailure(account2, ctx, error);
8568
+ }).finally(() => {
8569
+ ctx.refreshInFlight.delete(account2.id);
8570
+ });
8571
+ ctx.refreshInFlight.set(account2.id, refreshPromise);
8572
+ }
8573
+ const promise = ctx.refreshInFlight.get(account2.id);
8574
+ if (!promise) {
8575
+ throw new TokenRefreshError(account2.id, new Error(ERROR_MESSAGES.REFRESH_NOT_FOUND));
8576
+ }
8577
+ return promise;
8578
+ }
8579
+ async function getValidAccessToken(account2, ctx) {
8580
+ if (!account2.refresh_token && account2.api_key) {
8581
+ return "";
8582
+ }
8583
+ if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
8584
+ return account2.access_token;
8585
+ }
8586
+ const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
8587
+ log18.info(`Token ${reason} for account: ${account2.name}`);
8588
+ return await refreshAccessTokenSafe(account2, ctx);
8589
+ }
8590
+ var log18, refreshFailures;
8591
+ var init_token_manager = __esm(() => {
8592
+ init_src2();
8593
+ init_src3();
8594
+ init_constants2();
8595
+ init_proxy_types();
8596
+ log18 = new Logger("TokenManager");
8597
+ refreshFailures = new Map;
8598
+ });
8599
+
8470
8600
  // ../../packages/proxy/src/handlers/account-selector.ts
8471
8601
  function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
8472
8602
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
@@ -8492,7 +8622,9 @@ function fleetAccounts(provider, ctx) {
8492
8622
  return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
8493
8623
  }
8494
8624
  function cooldownEnd(account2, now) {
8495
- return account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8625
+ const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8626
+ const refreshEnd = refreshBackoffUntil(account2.id, now);
8627
+ return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
8496
8628
  }
8497
8629
  function blockingResets(provider, account2, model, ctx, now) {
8498
8630
  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);
@@ -8555,8 +8687,8 @@ function selectRevalidationProbe(accounts, ctx, now) {
8555
8687
  return [probe];
8556
8688
  }
8557
8689
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
8558
- const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
8559
8690
  const now = Date.now();
8691
+ const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2.id, now) === null);
8560
8692
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8561
8693
  const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
8562
8694
  const prioritized = [...candidates].sort((left, right) => {
@@ -8574,6 +8706,7 @@ var init_account_selector = __esm(() => {
8574
8706
  init_src();
8575
8707
  init_seat_usage();
8576
8708
  init_team_router();
8709
+ init_token_manager();
8577
8710
  });
8578
8711
 
8579
8712
  // ../../packages/proxy/src/handlers/request-handler.ts
@@ -8665,101 +8798,6 @@ var init_request_handler = __esm(() => {
8665
8798
  DEFAULT_MAX_BODY_BYTES = 64 * 1024 * 1024;
8666
8799
  });
8667
8800
 
8668
- // ../../packages/proxy/src/constants.ts
8669
- var TOKEN_SAFETY_WINDOW_MS, TOKEN_REFRESH_BACKOFF_MS = 60000;
8670
- var init_constants2 = __esm(() => {
8671
- TOKEN_SAFETY_WINDOW_MS = 5 * 60000;
8672
- });
8673
-
8674
- // ../../packages/proxy/src/handlers/proxy-types.ts
8675
- function createResolvedProxyContext(ctx, provider, upstreamPath) {
8676
- return {
8677
- ...ctx,
8678
- provider,
8679
- providerName: provider.name,
8680
- upstreamPath
8681
- };
8682
- }
8683
- function resolveProxyContext(url, ctx) {
8684
- const resolvedProvider = ctx.providerRegistry.resolveProvider(url.pathname);
8685
- if (!resolvedProvider) {
8686
- return null;
8687
- }
8688
- return createResolvedProxyContext(ctx, resolvedProvider.provider, resolvedProvider.upstreamPath);
8689
- }
8690
- var ERROR_MESSAGES, TIMING;
8691
- var init_proxy_types = __esm(() => {
8692
- ERROR_MESSAGES = {
8693
- NO_ELIGIBLE_ACCOUNT: "No eligible account available for this provider",
8694
- PROVIDER_CANNOT_HANDLE: "Provider cannot handle path",
8695
- REFRESH_NOT_FOUND: "Refresh promise not found for account",
8696
- ALL_ACCOUNTS_FAILED: "All accounts failed to proxy the request",
8697
- TOKEN_REFRESH_FAILED: "Failed to refresh access token",
8698
- PROXY_REQUEST_FAILED: "Failed to proxy request with account"
8699
- };
8700
- TIMING = {
8701
- WORKER_SHUTDOWN_DELAY: 5000
8702
- };
8703
- });
8704
-
8705
- // ../../packages/proxy/src/handlers/token-manager.ts
8706
- async function refreshAccessTokenSafe(account2, ctx) {
8707
- const lastFailure = refreshFailures.get(account2.id);
8708
- if (lastFailure && Date.now() - lastFailure < TOKEN_REFRESH_BACKOFF_MS) {
8709
- log18.warn(`Account ${account2.name} is in refresh backoff period`);
8710
- throw new ServiceUnavailableError(`Token refresh for account ${account2.name} is in backoff period after recent failure`);
8711
- }
8712
- if (!ctx.refreshInFlight.has(account2.id)) {
8713
- if (!ctx.provider.refreshToken) {
8714
- throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
8715
- }
8716
- const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
8717
- ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
8718
- account2.access_token = result.accessToken;
8719
- account2.expires_at = result.expiresAt;
8720
- if (result.refreshToken) {
8721
- account2.refresh_token = result.refreshToken;
8722
- }
8723
- account2.last_used = Date.now();
8724
- refreshFailures.delete(account2.id);
8725
- log18.info(`Successfully refreshed token for account: ${account2.name}`);
8726
- return result.accessToken;
8727
- }).catch((error) => {
8728
- refreshFailures.set(account2.id, Date.now());
8729
- log18.error(`Token refresh failed for account ${account2.name}`, error);
8730
- throw new TokenRefreshError(account2.id, error);
8731
- }).finally(() => {
8732
- ctx.refreshInFlight.delete(account2.id);
8733
- });
8734
- ctx.refreshInFlight.set(account2.id, refreshPromise);
8735
- }
8736
- const promise = ctx.refreshInFlight.get(account2.id);
8737
- if (!promise) {
8738
- throw new ServiceUnavailableError(`${ERROR_MESSAGES.REFRESH_NOT_FOUND} ${account2.id}`);
8739
- }
8740
- return promise;
8741
- }
8742
- async function getValidAccessToken(account2, ctx) {
8743
- if (!account2.refresh_token && account2.api_key) {
8744
- return "";
8745
- }
8746
- if (account2.access_token && account2.expires_at && account2.expires_at - Date.now() > TOKEN_SAFETY_WINDOW_MS) {
8747
- return account2.access_token;
8748
- }
8749
- const reason = !account2.access_token ? "missing" : !account2.expires_at ? "no expiry" : account2.expires_at <= Date.now() ? "expired" : "expiring soon";
8750
- log18.info(`Token ${reason} for account: ${account2.name}`);
8751
- return await refreshAccessTokenSafe(account2, ctx);
8752
- }
8753
- var log18, refreshFailures;
8754
- var init_token_manager = __esm(() => {
8755
- init_src2();
8756
- init_src3();
8757
- init_constants2();
8758
- init_proxy_types();
8759
- log18 = new Logger("TokenManager");
8760
- refreshFailures = new Map;
8761
- });
8762
-
8763
8801
  // ../../packages/proxy/src/outside-spend.ts
8764
8802
  class OutsideSpendTracker {
8765
8803
  now;
@@ -8969,7 +9007,12 @@ class TeamAdmission {
8969
9007
  holdSeconds: 0,
8970
9008
  quotaProbeSeconds: 0
8971
9009
  });
8972
- account2.switchedAt = this.now();
9010
+ if (account2.active > 0 || account2.queue.length > 0)
9011
+ return;
9012
+ const now = this.now();
9013
+ if (account2.switchedAt === undefined || now - account2.switchedAt >= RAMP_WINDOW_MS) {
9014
+ account2.switchedAt = now;
9015
+ }
8973
9016
  this.scheduleRamp(accountId, account2);
8974
9017
  }
8975
9018
  advance() {
@@ -9661,17 +9704,6 @@ var init_stream_failure = __esm(() => {
9661
9704
  });
9662
9705
 
9663
9706
  // ../../packages/proxy/src/handlers/proxy-operations.ts
9664
- function shouldQuarantineAfterRefreshFailure(error) {
9665
- if (!(error instanceof TokenRefreshError))
9666
- return false;
9667
- const status = error.originalError?.status;
9668
- return typeof status === "number" && status >= 400 && status < 500;
9669
- }
9670
- function quarantineAccount(account2, ctx, reason) {
9671
- account2.paused = true;
9672
- account2.error_reason = reason;
9673
- ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
9674
- }
9675
9707
  function createUpstreamSender(input) {
9676
9708
  const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
9677
9709
  return async (token) => {
@@ -9704,10 +9736,7 @@ async function sendAuthorizedRequest(input, send) {
9704
9736
  try {
9705
9737
  accessToken = await refreshAccessTokenSafe(input.account, input.ctx);
9706
9738
  upstream = await send(accessToken);
9707
- } catch (error) {
9708
- if (shouldQuarantineAfterRefreshFailure(error)) {
9709
- quarantineAccount(input.account, input.ctx, "OAuth refresh was rejected by the upstream");
9710
- }
9739
+ } catch {
9711
9740
  return { kind: "failed" };
9712
9741
  }
9713
9742
  return upstream.response.status === 401 ? { kind: "authentication-failure" } : upstream;
@@ -9823,6 +9852,15 @@ var init_proxy_operations = __esm(() => {
9823
9852
  });
9824
9853
 
9825
9854
  // ../../packages/proxy/src/handlers/proxy-attempts.ts
9855
+ function admissionRetrySeconds(req) {
9856
+ if (req.signal.aborted)
9857
+ return;
9858
+ const count = req.headers.get("x-stainless-retry-count") ?? "0";
9859
+ if (!/^\d+$/.test(count))
9860
+ return 1;
9861
+ const ordinal = Number(count);
9862
+ return ordinal === 0 ? 1 : ordinal === 1 ? 10 : 30;
9863
+ }
9826
9864
  function createBodyStream(body) {
9827
9865
  if (!body)
9828
9866
  return;
@@ -9882,7 +9920,7 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9882
9920
  permit = request2.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request2.ctx.runtime.teamRouting, request2.req.signal) : undefined;
9883
9921
  } catch (error) {
9884
9922
  if (error instanceof TeamAdmissionError) {
9885
- throw new ServiceUnavailableError(error.message, request2.ctx.providerName);
9923
+ throw new ServiceUnavailableError(error.message, request2.ctx.providerName, admissionRetrySeconds(request2.req));
9886
9924
  }
9887
9925
  throw error;
9888
9926
  }
@@ -11853,7 +11891,7 @@ function exposureFailure(req, url, server, config) {
11853
11891
  if (!isSameOriginManagementRequest(req, url)) {
11854
11892
  return jsonError(403, "Cross-origin management requests are not allowed");
11855
11893
  }
11856
- if (MUTATING_METHODS.has(req.method)) {
11894
+ if (url.pathname === "/api/drain" || MUTATING_METHODS.has(req.method)) {
11857
11895
  if (role !== "admin") {
11858
11896
  return jsonError(401, "An admin key is required for management writes");
11859
11897
  }
@@ -11910,7 +11948,7 @@ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig
11910
11948
  }
11911
11949
  });
11912
11950
  }
11913
- function bootstrapRuntime(port, serverLog) {
11951
+ function bootstrapRuntime(port, serverLog, deploymentDrain) {
11914
11952
  container.registerInstance(SERVICE_KEYS.Config, new Config);
11915
11953
  container.registerInstance(SERVICE_KEYS.Logger, serverLog);
11916
11954
  const config = container.resolve(SERVICE_KEYS.Config);
@@ -11929,6 +11967,7 @@ function bootstrapRuntime(port, serverLog) {
11929
11967
  container.registerInstance(SERVICE_KEYS.PricingLogger, pricingLogger);
11930
11968
  setPricingLogger(pricingLogger);
11931
11969
  const apiRouter = new APIRouter({
11970
+ deploymentDrain,
11932
11971
  enrollmentOrigin: process.env.AGENT_SMITH_ENROLLMENT_ORIGIN,
11933
11972
  config,
11934
11973
  dbOps,
@@ -12089,6 +12128,48 @@ var init_dashboard_assets = __esm(() => {
12089
12128
  init_src2();
12090
12129
  });
12091
12130
 
12131
+ // ../../packages/runtime-server/src/deployment-drain.ts
12132
+ class DeploymentDrain {
12133
+ activity;
12134
+ now;
12135
+ expiresAt = null;
12136
+ stopping = false;
12137
+ log = new Logger("DeploymentDrain");
12138
+ constructor(activity, now = () => Date.now()) {
12139
+ this.activity = activity;
12140
+ this.now = now;
12141
+ }
12142
+ isDraining = () => {
12143
+ if (this.expiresAt !== null && this.now() >= this.expiresAt) {
12144
+ this.expiresAt = null;
12145
+ this.log.info("Deployment pause expired; accepting new inference");
12146
+ }
12147
+ return this.stopping || this.expiresAt !== null;
12148
+ };
12149
+ control = (action) => {
12150
+ if (action === "start" && !this.stopping) {
12151
+ if (!this.isDraining())
12152
+ this.log.info("Deployment pause started");
12153
+ this.expiresAt = this.now() + 120000;
12154
+ } else if (action === "resume" && !this.stopping) {
12155
+ this.expiresAt = null;
12156
+ this.log.info("Deployment pause cancelled; accepting new inference");
12157
+ }
12158
+ return {
12159
+ draining: this.isDraining(),
12160
+ expiresAt: this.expiresAt,
12161
+ ...this.activity()
12162
+ };
12163
+ };
12164
+ shutdown() {
12165
+ this.stopping = true;
12166
+ this.expiresAt = null;
12167
+ }
12168
+ }
12169
+ var init_deployment_drain = __esm(() => {
12170
+ init_src3();
12171
+ });
12172
+
12092
12173
  // ../../packages/runtime-server/src/oauth-token.ts
12093
12174
  async function forwardOAuthTokenRequest(req, body) {
12094
12175
  const headers3 = new Headers(req.headers);
@@ -12137,7 +12218,8 @@ function createServerFetchHandler({
12137
12218
  handleProxyRequest = handleProxy,
12138
12219
  handleWebSocketUpgrade = handleWebSocketUpgradeRequest,
12139
12220
  handleOAuthTokenRequest = forwardOAuthTokenRequest,
12140
- serveDashboardAsset = serveDashboardRoute
12221
+ serveDashboardAsset = serveDashboardRoute,
12222
+ isDeploymentDraining = () => false
12141
12223
  }) {
12142
12224
  return async (req, server) => {
12143
12225
  const url = new URL(req.url);
@@ -12165,6 +12247,9 @@ function createServerFetchHandler({
12165
12247
  }
12166
12248
  const isProviderRoute = url.pathname === "/v1" || url.pathname.startsWith("/v1/") || url.pathname.startsWith("/tc-acct/");
12167
12249
  if (isProviderRoute) {
12250
+ if (isDeploymentDraining()) {
12251
+ return errorResponse(new ServiceUnavailableError("Pool is draining for deployment", undefined, 30));
12252
+ }
12168
12253
  if (server) {
12169
12254
  const websocketResponse = await handleWebSocketUpgrade(req, url, proxyContext, server);
12170
12255
  if (websocketResponse) {
@@ -12279,17 +12364,38 @@ async function stopServerRuntime() {
12279
12364
  const errors2 = [];
12280
12365
  const activeServer = serverInstance;
12281
12366
  const activeUnixServer = unixServerInstance;
12282
- serverInstance = null;
12283
- unixServerInstance = null;
12367
+ deploymentDrain?.shutdown();
12368
+ const listeners = [activeUnixServer, activeServer].filter((listener) => listener !== null);
12369
+ const shutdownDeadline = Date.now() + 25000;
12284
12370
  try {
12285
- await activeUnixServer?.stop(true);
12286
- } catch (error) {
12287
- errors2.push(toError("Failed to stop Unix server", error));
12288
- }
12289
- try {
12290
- await activeServer?.stop(true);
12291
- } catch (error) {
12292
- errors2.push(toError("Failed to stop Bun server", error));
12371
+ await new Promise((resolve3) => {
12372
+ let timer;
12373
+ const finish = () => {
12374
+ clearInterval(timer);
12375
+ resolve3();
12376
+ };
12377
+ const check = () => {
12378
+ const pending = listeners.some((listener) => listener.pendingRequests > 0 || listener.pendingWebSockets > 0);
12379
+ if (!pending)
12380
+ finish();
12381
+ else if (Date.now() >= shutdownDeadline) {
12382
+ lifecycleLog.warn("Shutdown grace expired; closing remaining connections");
12383
+ finish();
12384
+ }
12385
+ };
12386
+ checkShutdownDrain = check;
12387
+ timer = setInterval(check, 50);
12388
+ check();
12389
+ });
12390
+ const stopped = await Promise.allSettled(listeners.map((listener) => listener.stop(true)));
12391
+ for (const result of stopped) {
12392
+ if (result.status === "rejected")
12393
+ errors2.push(toError("Failed to stop listener", result.reason));
12394
+ }
12395
+ } finally {
12396
+ checkShutdownDrain = undefined;
12397
+ serverInstance = null;
12398
+ unixServerInstance = null;
12293
12399
  }
12294
12400
  stopRetentionMaintenance();
12295
12401
  try {
@@ -12337,6 +12443,11 @@ function startServer(options) {
12337
12443
  if (withDashboard) {
12338
12444
  loadDashboardAssets();
12339
12445
  }
12446
+ const drain = new DeploymentDrain(() => ({
12447
+ activeRequests: Math.max(0, (serverInstance?.pendingRequests ?? 0) + (unixServerInstance?.pendingRequests ?? 0) - 1),
12448
+ activeWebSockets: (serverInstance?.pendingWebSockets ?? 0) + (unixServerInstance?.pendingWebSockets ?? 0)
12449
+ }));
12450
+ deploymentDrain = drain;
12340
12451
  const {
12341
12452
  config,
12342
12453
  dbOps,
@@ -12346,13 +12457,14 @@ function startServer(options) {
12346
12457
  proxyContext,
12347
12458
  providerRegistry,
12348
12459
  runtimeConfig: runtimeConfig2
12349
- } = bootstrapRuntime(port, serverLog);
12460
+ } = bootstrapRuntime(port, serverLog, drain.control);
12350
12461
  stopRetentionJob = runStartupMaintenance(config, dbOps);
12351
12462
  const fetchHandler = createServerFetchHandler({
12352
12463
  apiRouter,
12353
12464
  exposureConfig,
12354
12465
  proxyContext,
12355
- withDashboard
12466
+ withDashboard,
12467
+ isDeploymentDraining: drain.isDraining
12356
12468
  });
12357
12469
  try {
12358
12470
  if (options?.additionalUnixSocket) {
@@ -12391,6 +12503,7 @@ function startServer(options) {
12391
12503
  advanceRoutingClock: () => {
12392
12504
  proxyContext.teamAdmission?.advance();
12393
12505
  proxyContext.quotaHold?.advance();
12506
+ checkShutdownDrain?.();
12394
12507
  }
12395
12508
  };
12396
12509
  }
@@ -12405,7 +12518,7 @@ async function handleGracefulShutdown(signal) {
12405
12518
  process.exit(1);
12406
12519
  }
12407
12520
  }
12408
- var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null;
12521
+ var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null, deploymentDrain, checkShutdownDrain;
12409
12522
  var init_src11 = __esm(() => {
12410
12523
  init_src9();
12411
12524
  init_src2();
@@ -12414,6 +12527,7 @@ var init_src11 = __esm(() => {
12414
12527
  init_src10();
12415
12528
  init_bootstrap_runtime();
12416
12529
  init_dashboard_assets();
12530
+ init_deployment_drain();
12417
12531
  init_fetch_handler();
12418
12532
  init_startup_banner();
12419
12533
  init_startup_maintenance();
package/dist/edge.js CHANGED
@@ -35,6 +35,7 @@ var REQUEST_HEADERS = [
35
35
  "session-id",
36
36
  "openai-beta",
37
37
  "x-client-request-id",
38
+ "x-stainless-retry-count",
38
39
  "user-agent"
39
40
  ];
40
41
  var RESPONSE_HEADERS = [
@@ -48,35 +49,45 @@ var RESPONSE_HEADERS = [
48
49
  "anthropic-ratelimit-requests-reset",
49
50
  "anthropic-ratelimit-tokens-limit",
50
51
  "anthropic-ratelimit-tokens-remaining",
51
- "anthropic-ratelimit-tokens-reset"
52
+ "anthropic-ratelimit-tokens-reset",
53
+ "content-security-policy",
54
+ "referrer-policy",
55
+ "x-frame-options"
52
56
  ];
57
+ function isEnrollmentRoute(method, path) {
58
+ return method === "GET" && path === "/pool-enroll" || method === "POST" && ["request", "start", "verify", "confirm", "disconnect"].some((action) => path === `/pool-enroll/${action}`);
59
+ }
53
60
  function selectHeaders(headers, names) {
54
61
  return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
55
62
  }
56
- function requestFailure(req, origin, maxBodyBytes) {
63
+ function requestFailure(req, origin, maxBodyBytes, enrollment) {
57
64
  const health = req.method === "GET" && req.url === "/pool-health";
58
- if (!health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
65
+ if (!enrollment && !health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
59
66
  return 404;
60
- if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
67
+ if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !(enrollment && req.method === "GET") && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
61
68
  return 403;
62
69
  if (req.headers.upgrade || req.headers.expect)
63
70
  return 400;
64
71
  if (req.headers["content-length"] !== undefined && (!/^\d+$/.test(req.headers["content-length"]) || Number(req.headers["content-length"]) > maxBodyBytes))
65
72
  return 413;
66
- if (!req.headers["x-api-key"] && !req.headers.authorization)
73
+ if (enrollment) {
74
+ if (req.method === "POST" && req.headers.origin !== origin)
75
+ return 403;
76
+ } else if (!req.headers["x-api-key"] && !req.headers.authorization)
67
77
  return 401;
68
78
  return null;
69
79
  }
70
80
  function createProxyEdgeHandler({
71
81
  origin,
72
82
  socketPath,
83
+ enrollmentOrigin,
73
84
  maxBodyBytes = 64 * 1024 * 1024,
74
85
  timeoutMs = 300000,
75
86
  maxConcurrentRequests = 128
76
87
  }) {
77
88
  const url = new URL(origin);
78
- if (url.protocol !== "https:" || url.origin !== origin || !isAbsolute(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
79
- throw new Error("Proxy edge requires an exact HTTPS origin, an absolute socket path and positive limits");
89
+ if (url.protocol !== "https:" || url.origin !== origin || enrollmentOrigin !== undefined && enrollmentOrigin !== origin || !isAbsolute(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || !Number.isSafeInteger(maxConcurrentRequests) || maxConcurrentRequests < 1) {
90
+ throw new Error("Proxy edge requires an exact HTTPS origin, a matching enrollment origin, an absolute socket path and positive limits");
80
91
  }
81
92
  let activeRequests = 0;
82
93
  return (req, res) => {
@@ -93,7 +104,9 @@ function createProxyEdgeHandler({
93
104
  });
94
105
  res.end();
95
106
  };
96
- const rejected = requestFailure(req, origin, maxBodyBytes);
107
+ const enrollment = enrollmentOrigin !== undefined && isEnrollmentRoute(req.method ?? "", req.url ?? "");
108
+ const bodyLimit = enrollment ? Math.min(maxBodyBytes, 8192) : maxBodyBytes;
109
+ const rejected = requestFailure(req, origin, bodyLimit, enrollment);
97
110
  if (rejected)
98
111
  return finish(rejected);
99
112
  if (activeRequests >= maxConcurrentRequests)
@@ -101,7 +114,9 @@ function createProxyEdgeHandler({
101
114
  activeRequests++;
102
115
  const path = req.method === "GET" && req.url === "/pool-health" ? "/health" : req.url ?? "";
103
116
  const headers = selectHeaders(req.headers, REQUEST_HEADERS);
104
- headers.host = "localhost";
117
+ headers.host = enrollment ? url.host : "localhost";
118
+ if (enrollment && req.headers.origin)
119
+ headers.origin = req.headers.origin;
105
120
  headers.connection = "keep-alive";
106
121
  headers["x-forwarded-for"] = "proxy-edge";
107
122
  let upstreamResponse;
@@ -146,7 +161,7 @@ function createProxyEdgeHandler({
146
161
  let bytes = 0;
147
162
  req.on("data", (chunk) => {
148
163
  bytes += chunk.length;
149
- if (bytes > maxBodyBytes) {
164
+ if (bytes > bodyLimit) {
150
165
  req.unpipe(upstream);
151
166
  upstream.destroy();
152
167
  finish(413);