claude-use 11.83.4 → 11.83.7

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/cli.cjs CHANGED
@@ -23762,9 +23762,9 @@ var require_env_paths = __commonJS({
23762
23762
  "node_modules/.pnpm/env-paths@2.2.1/node_modules/env-paths/index.js"(exports2, module2) {
23763
23763
  "use strict";
23764
23764
  var path79 = require("path");
23765
- var os16 = require("os");
23766
- var homedir = os16.homedir();
23767
- var tmpdir = os16.tmpdir();
23765
+ var os17 = require("os");
23766
+ var homedir = os17.homedir();
23767
+ var tmpdir = os17.tmpdir();
23768
23768
  var { env } = process;
23769
23769
  var macos = (name) => {
23770
23770
  const library = path79.join(homedir, "Library");
@@ -36845,13 +36845,18 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
36845
36845
  });
36846
36846
  const { predecessor } = ports;
36847
36847
  const sourceOf = (listener, preferredPort) => predecessor === void 0 ? { preferredPort } : { inherit: async () => await predecessor.take(listener) };
36848
- const fail = (message) => {
36848
+ const fail = async (message) => {
36849
36849
  ports.closeRcStreamHub();
36850
36850
  if (predecessor === void 0) {
36851
36851
  writeFrontDoorState(fs32, paths.frontdoorStateFile, { lastError: message, ...sticky() });
36852
36852
  fs32.removeRecursive(paths.frontdoorLockFile);
36853
36853
  }
36854
36854
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
36855
+ const chain = ports.respawnChain;
36856
+ if (predecessor === void 0 && chain !== void 0 && chain.generation > 0) {
36857
+ ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: this door is generation ${String(chain.generation)} of the watchdog's respawn chain and nothing waits on it, so it starts generation ${String(chain.generation + 1)} rather than leaving no door`);
36858
+ await chain.startNext();
36859
+ }
36855
36860
  return 1;
36856
36861
  };
36857
36862
  if (predecessor === void 0) {
@@ -36863,7 +36868,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
36863
36868
  http9 = await ports.startProviderListener(sourceOf("provider", lastPort));
36864
36869
  } catch (error63) {
36865
36870
  ports.doorHealth.listenerFailed("provider", error63 instanceof Error ? error63.message : String(error63));
36866
- return fail(`could not start the provider listener: ${error63 instanceof Error ? error63.message : String(error63)}`);
36871
+ return await fail(`could not start the provider listener: ${error63 instanceof Error ? error63.message : String(error63)}`);
36867
36872
  }
36868
36873
  if (previousSticky !== void 0 && http9.port !== previousSticky) {
36869
36874
  ports.log(`agent-shim frontdoor supervisor: sticky port ${String(previousSticky)} was occupied; moving to ${String(http9.port)} (sessions launched against the old port are stale until they relaunch)`);
@@ -36876,7 +36881,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
36876
36881
  } catch (error63) {
36877
36882
  await http9.close();
36878
36883
  ports.doorHealth.listenerFailed("connect", error63 instanceof Error ? error63.message : String(error63));
36879
- return fail(`could not start the CONNECT surface: ${error63 instanceof Error ? error63.message : String(error63)}`);
36884
+ return await fail(`could not start the CONNECT surface: ${error63 instanceof Error ? error63.message : String(error63)}`);
36880
36885
  }
36881
36886
  if (previousStickyConnect !== void 0 && connect3.port !== previousStickyConnect) {
36882
36887
  ports.log(`agent-shim frontdoor supervisor: sticky CONNECT port ${String(previousStickyConnect)} was occupied; moving to ${String(connect3.port)} (OAuth sessions launched against the old port are stale until they relaunch)`);
@@ -36890,7 +36895,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
36890
36895
  await connect3.close();
36891
36896
  await http9.close();
36892
36897
  ports.doorHealth.listenerFailed("direct", error63 instanceof Error ? error63.message : String(error63));
36893
- return fail(`could not start the direct listener: ${error63 instanceof Error ? error63.message : String(error63)}`);
36898
+ return await fail(`could not start the direct listener: ${error63 instanceof Error ? error63.message : String(error63)}`);
36894
36899
  }
36895
36900
  if (previousStickyDirect !== void 0 && direct.port !== previousStickyDirect) {
36896
36901
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom admits the new address once its supervisor rewrites the allowlist file)`);
@@ -39981,7 +39986,7 @@ var init_package = __esm({
39981
39986
  "package.json"() {
39982
39987
  package_default = {
39983
39988
  name: "claude-use",
39984
- version: "11.83.4",
39989
+ version: "11.83.7",
39985
39990
  description: "A profile manager and launcher for Claude Code that lets one person run multiple logins from one machine while controlling what gets shared between them.",
39986
39991
  license: "MIT",
39987
39992
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -68701,33 +68706,41 @@ async function* callCloudAntigravity(params, fetchFn = fetch) {
68701
68706
  }
68702
68707
  const decoder = new TextDecoder("utf-8");
68703
68708
  let buffer2 = "";
68704
- const sseDataPrefix = "data:";
68705
68709
  for await (const rawChunk of response.body) {
68706
68710
  const chunk2 = rawChunk instanceof Uint8Array ? rawChunk : Buffer.from(String(rawChunk));
68707
68711
  buffer2 += decoder.decode(chunk2, { stream: true });
68708
68712
  const lines = buffer2.split("\n");
68709
68713
  buffer2 = lines.pop() ?? "";
68710
68714
  for (const line of lines) {
68711
- const trimmed = line.trim();
68712
- if (trimmed.startsWith(sseDataPrefix)) {
68713
- const jsonStr = trimmed.slice(sseDataPrefix.length).trim();
68714
- if (jsonStr.length > 0) {
68715
- try {
68716
- const parsed = JSON.parse(jsonStr);
68717
- if (isRecord6(parsed)) {
68718
- const unwrapped = isRecord6(parsed.response) ? parsed.response : parsed;
68719
- if (isGeminiChunk(unwrapped)) {
68720
- yield unwrapped;
68721
- }
68722
- }
68723
- } catch {
68724
- }
68725
- }
68726
- }
68715
+ yield* chunksOfLine(line);
68727
68716
  }
68728
68717
  }
68718
+ buffer2 += decoder.decode();
68719
+ yield* chunksOfLine(buffer2);
68729
68720
  }
68730
- var import_node_crypto18, CCPA_ENDPOINT, CCPA_DEFAULT_PROJECT_ID, CCPA_USER_AGENT, AntigravityUpstreamError;
68721
+ function* chunksOfLine(line) {
68722
+ const trimmed = line.trim();
68723
+ if (!trimmed.startsWith(SSE_DATA_PREFIX)) {
68724
+ return;
68725
+ }
68726
+ const jsonStr = trimmed.slice(SSE_DATA_PREFIX.length).trim();
68727
+ if (jsonStr.length === 0) {
68728
+ return;
68729
+ }
68730
+ let parsed;
68731
+ try {
68732
+ parsed = JSON.parse(jsonStr);
68733
+ } catch {
68734
+ return;
68735
+ }
68736
+ if (isRecord6(parsed)) {
68737
+ const unwrapped = isRecord6(parsed.response) ? parsed.response : parsed;
68738
+ if (isGeminiChunk(unwrapped)) {
68739
+ yield unwrapped;
68740
+ }
68741
+ }
68742
+ }
68743
+ var import_node_crypto18, CCPA_ENDPOINT, CCPA_DEFAULT_PROJECT_ID, CCPA_USER_AGENT, AntigravityUpstreamError, SSE_DATA_PREFIX;
68731
68744
  var init_cloudUpstream = __esm({
68732
68745
  "src/antigravity/cloudUpstream.ts"() {
68733
68746
  "use strict";
@@ -68738,13 +68751,17 @@ var init_cloudUpstream = __esm({
68738
68751
  AntigravityUpstreamError = class extends Error {
68739
68752
  status;
68740
68753
  retryAfter;
68754
+ /** The backend's own answer, as it sent it, which carries more than the message says (the model a 429 names and when its allowance lifts). */
68755
+ body;
68741
68756
  constructor(status, message, retryAfter) {
68742
68757
  super(`Google Antigravity API error (${String(status)}): ${message}`);
68743
68758
  this.name = "AntigravityUpstreamError";
68759
+ this.body = message;
68744
68760
  this.status = status;
68745
68761
  this.retryAfter = retryAfter;
68746
68762
  }
68747
68763
  };
68764
+ SSE_DATA_PREFIX = "data:";
68748
68765
  }
68749
68766
  });
68750
68767
 
@@ -68789,6 +68806,60 @@ function antigravityQuotaPressure(quota, model) {
68789
68806
  const pressures = [windowPressure(fiveHour, FIVE_HOUR_PERIOD_SECONDS), windowPressure(weekly, WEEK_PERIOD_SECONDS)].filter((pressure) => pressure !== void 0);
68790
68807
  return pressures.length === 0 ? void 0 : Math.min(...pressures);
68791
68808
  }
68809
+ function parseQuotaExhaustion(body, nowMs) {
68810
+ let parsed;
68811
+ try {
68812
+ parsed = JSON.parse(body);
68813
+ } catch {
68814
+ return void 0;
68815
+ }
68816
+ const details = isRecord7(parsed) && isRecord7(parsed.error) && Array.isArray(parsed.error.details) ? parsed.error.details : [];
68817
+ let model;
68818
+ let resetAtMs;
68819
+ for (const detail of details) {
68820
+ if (!isRecord7(detail)) {
68821
+ continue;
68822
+ }
68823
+ if (detail.reason === "QUOTA_EXHAUSTED" && isRecord7(detail.metadata)) {
68824
+ const named = detail.metadata.model;
68825
+ const stamp = typeof detail.metadata.quotaResetTimeStamp === "string" ? Date.parse(detail.metadata.quotaResetTimeStamp) : Number.NaN;
68826
+ model = typeof named === "string" && named !== "" ? named : void 0;
68827
+ resetAtMs = Number.isNaN(stamp) ? void 0 : stamp;
68828
+ } else if (typeof detail.retryDelay === "string" && resetAtMs === void 0) {
68829
+ const seconds = RETRY_DELAY.exec(detail.retryDelay)?.groups?.seconds;
68830
+ resetAtMs = seconds === void 0 ? void 0 : nowMs + Math.ceil(Number(seconds) * MS_PER_SECOND9);
68831
+ }
68832
+ }
68833
+ return model === void 0 || resetAtMs === void 0 ? void 0 : { model, resetAtMs };
68834
+ }
68835
+ function bucketKeyOf(model, resetInSeconds) {
68836
+ const lower = model.toLowerCase();
68837
+ if (lower.includes("argon")) {
68838
+ return "gemini-argon-wtu-weekly";
68839
+ }
68840
+ const withinFiveHours = resetInSeconds <= FIVE_HOUR_PERIOD_SECONDS;
68841
+ if (lower.includes("gemini")) {
68842
+ return withinFiveHours ? "gemini-5h" : "gemini-weekly";
68843
+ }
68844
+ return withinFiveHours ? "3p-5h" : "3p-weekly";
68845
+ }
68846
+ function quotaWithExhaustions(quota, exhaustions, nowMs) {
68847
+ const spent = [...exhaustions].filter(([, resetAtMs]) => resetAtMs > nowMs);
68848
+ if (spent.length === 0) {
68849
+ return quota;
68850
+ }
68851
+ const merged = { ...quota };
68852
+ for (const [model, resetAtMs] of spent) {
68853
+ const resetIn = Math.ceil((resetAtMs - nowMs) / MS_PER_SECOND9);
68854
+ const key = bucketKeyOf(model, resetIn);
68855
+ const known = merged[key];
68856
+ if (known?.remaining_fraction === 0 && (known.reset_in_seconds ?? 0) >= resetIn) {
68857
+ continue;
68858
+ }
68859
+ merged[key] = { remaining_fraction: 0, reset_in_seconds: resetIn };
68860
+ }
68861
+ return merged;
68862
+ }
68792
68863
  function calculateUtilization(remainingFraction) {
68793
68864
  if (remainingFraction === void 0 || !Number.isFinite(remainingFraction)) {
68794
68865
  return void 0;
@@ -68970,7 +69041,7 @@ function ageQuotaMap(quota, elapsedMs) {
68970
69041
  Object.entries(quota).map(([key, bucket]) => [key, bucket?.reset_in_seconds === void 0 ? bucket : { ...bucket, reset_in_seconds: Math.max(0, bucket.reset_in_seconds - elapsedSec) }])
68971
69042
  );
68972
69043
  }
68973
- var MS_PER_SECOND9, DEFAULT_RETRY_AFTER_SECONDS, FRACTION_DIGITS, GEMINI_5H_KEYS, GEMINI_WEEKLY_KEYS, ARGON_WEEKLY_KEYS, THIRD_PARTY_5H_KEYS, THIRD_PARTY_WEEKLY_KEYS, QUOTA_FAMILY_WINDOWS, SECONDS_PER_HOUR, HOURS_PER_FIVE_HOUR_WINDOW, DAYS_PER_WEEK, HOURS_PER_DAY4, FIVE_HOUR_PERIOD_SECONDS, WEEK_PERIOD_SECONDS, ANTIGRAVITY_QUOTA_REFRESH_MS;
69044
+ var MS_PER_SECOND9, DEFAULT_RETRY_AFTER_SECONDS, FRACTION_DIGITS, GEMINI_5H_KEYS, GEMINI_WEEKLY_KEYS, ARGON_WEEKLY_KEYS, THIRD_PARTY_5H_KEYS, THIRD_PARTY_WEEKLY_KEYS, QUOTA_FAMILY_WINDOWS, SECONDS_PER_HOUR, HOURS_PER_FIVE_HOUR_WINDOW, DAYS_PER_WEEK, HOURS_PER_DAY4, FIVE_HOUR_PERIOD_SECONDS, WEEK_PERIOD_SECONDS, RETRY_DELAY, ANTIGRAVITY_QUOTA_REFRESH_MS;
68974
69045
  var init_quota = __esm({
68975
69046
  "src/antigravity/quota.ts"() {
68976
69047
  "use strict";
@@ -68997,6 +69068,7 @@ var init_quota = __esm({
68997
69068
  HOURS_PER_DAY4 = 24;
68998
69069
  FIVE_HOUR_PERIOD_SECONDS = HOURS_PER_FIVE_HOUR_WINDOW * SECONDS_PER_HOUR;
68999
69070
  WEEK_PERIOD_SECONDS = DAYS_PER_WEEK * HOURS_PER_DAY4 * SECONDS_PER_HOUR;
69071
+ RETRY_DELAY = /^(?<seconds>\d+(?:\.\d+)?)s$/u;
69000
69072
  ANTIGRAVITY_QUOTA_REFRESH_MS = 6e4;
69001
69073
  }
69002
69074
  });
@@ -71163,7 +71235,13 @@ var init_providerQuota = __esm({
71163
71235
  /** The account's paid subscription; absent when the account has none. */
71164
71236
  paidTier: external_exports.object({ name: external_exports.string().optional(), id: external_exports.string().optional() }).optional()
71165
71237
  });
71166
- ANTIGRAVITY_WINDOW_MS = { "gemini-5h": FIVE_HOURS_MS, "3p-5h": FIVE_HOURS_MS, "gemini-weekly": WEEK_MS, "3p-weekly": WEEK_MS };
71238
+ ANTIGRAVITY_WINDOW_MS = {
71239
+ "gemini-5h": FIVE_HOURS_MS,
71240
+ "3p-5h": FIVE_HOURS_MS,
71241
+ "gemini-weekly": WEEK_MS,
71242
+ "3p-weekly": WEEK_MS,
71243
+ "gemini-argon-wtu-weekly": WEEK_MS
71244
+ };
71167
71245
  antigravityQuotaAdapter = {
71168
71246
  source: ANTIGRAVITY_SOURCE,
71169
71247
  matches: (baseUrl) => URL.canParse(baseUrl) && new URL(baseUrl).hostname === ANTIGRAVITY_HOST,
@@ -126078,6 +126156,17 @@ var import_node_https = __toESM(require("node:https"), 1);
126078
126156
  var import_node_net2 = __toESM(require("node:net"), 1);
126079
126157
  init_legacy();
126080
126158
 
126159
+ // src/frontdoor/machineLoad.ts
126160
+ var import_node_os14 = __toESM(require("node:os"), 1);
126161
+ var processorShare = (reading) => reading.loadAverage <= reading.cpus ? 1 : reading.cpus / reading.loadAverage;
126162
+ function readMachineLoad() {
126163
+ const [oneMinute] = import_node_os14.default.loadavg();
126164
+ if (oneMinute === void 0) {
126165
+ throw new Error("os.loadavg() returned no one-minute load average");
126166
+ }
126167
+ return { loadAverage: oneMinute, cpus: import_node_os14.default.cpus().length };
126168
+ }
126169
+
126081
126170
  // src/frontdoor/rcControl.ts
126082
126171
  var https = __toESM(require("node:https"), 1);
126083
126172
  init_capability();
@@ -126764,35 +126853,54 @@ async function listenFrontDoor(server, options = {}) {
126764
126853
  if (options.onError !== void 0) {
126765
126854
  server.on("error", options.onError);
126766
126855
  }
126767
- const deadline = Date.now() + HEALTH_START_BUDGET_MS;
126856
+ await awaitStartHealth(
126857
+ {
126858
+ probe: async () => await frontDoorHealthy(bound, ca2),
126859
+ now: () => Date.now(),
126860
+ sleep: async (ms) => {
126861
+ await new Promise((resolve3) => {
126862
+ setTimeout(resolve3, ms);
126863
+ });
126864
+ },
126865
+ readLoad: readMachineLoad
126866
+ },
126867
+ `127.0.0.1:${String(bound)}`
126868
+ );
126869
+ return {
126870
+ port: bound,
126871
+ close: async () => {
126872
+ await new Promise((resolve3) => {
126873
+ server.close(() => {
126874
+ resolve3(void 0);
126875
+ });
126876
+ server.closeAllConnections();
126877
+ });
126878
+ },
126879
+ // The port is released as the close runs, before the first await (see `trackConnections` for what happens to the connections already accepted).
126880
+ drain: async () => {
126881
+ await new Promise((resolve3) => {
126882
+ connections.drain(() => {
126883
+ resolve3(void 0);
126884
+ });
126885
+ });
126886
+ }
126887
+ };
126888
+ }
126889
+ async function awaitStartHealth(ports, address) {
126890
+ const startedAt = ports.now();
126891
+ let scheduledMs = 0;
126892
+ let countedTo = startedAt;
126768
126893
  for (; ; ) {
126769
- if (await frontDoorHealthy(bound, ca2)) {
126770
- return {
126771
- port: bound,
126772
- close: async () => {
126773
- await new Promise((resolve3) => {
126774
- server.close(() => {
126775
- resolve3(void 0);
126776
- });
126777
- server.closeAllConnections();
126778
- });
126779
- },
126780
- // The port is released as the close runs, before the first await (see `trackConnections` for what happens to the connections already accepted).
126781
- drain: async () => {
126782
- await new Promise((resolve3) => {
126783
- connections.drain(() => {
126784
- resolve3(void 0);
126785
- });
126786
- });
126787
- }
126788
- };
126894
+ if (await ports.probe()) {
126895
+ return;
126789
126896
  }
126790
- if (Date.now() >= deadline) {
126791
- throw new Error(`the front door listener on 127.0.0.1:${String(bound)} did not answer its health probe`);
126897
+ const now = ports.now();
126898
+ scheduledMs += (now - countedTo) * processorShare(ports.readLoad());
126899
+ countedTo = now;
126900
+ if (scheduledMs >= HEALTH_START_BUDGET_MS) {
126901
+ throw new Error(`the front door listener on ${address} did not answer its health probe within ${String(HEALTH_START_BUDGET_MS)}ms of processor time (${String(now - startedAt)}ms of wall time)`);
126792
126902
  }
126793
- await new Promise((resolve3) => {
126794
- setTimeout(resolve3, HEALTH_RETRY_MS);
126795
- });
126903
+ await ports.sleep(HEALTH_RETRY_MS);
126796
126904
  }
126797
126905
  }
126798
126906
  function trackConnections(server) {
@@ -134484,7 +134592,7 @@ var Builder = class _Builder {
134484
134592
  });
134485
134593
  }
134486
134594
  };
134487
- var os13 = Builder.create();
134595
+ var os14 = Builder.create();
134488
134596
 
134489
134597
  // node_modules/.pnpm/@orpc+openapi@2.0.0-beta.43/node_modules/@orpc/openapi/dist/index.mjs
134490
134598
  var DEFS_REF_PREFIX = "#/$defs/";
@@ -138848,7 +138956,7 @@ function doorApiBearer(headers) {
138848
138956
  return typeof presented === "string" && presented.slice(0, bearerPrefix).toLowerCase() === "bearer " ? presented.slice(bearerPrefix) : void 0;
138849
138957
  }
138850
138958
  function doorApiAuth(expectedToken) {
138851
- return os13.$context().use(({ context, next }) => {
138959
+ return os14.$context().use(({ context, next }) => {
138852
138960
  const token = doorApiBearer(context.headers);
138853
138961
  if (token === void 0 || !isLiveCapability(token, [expectedToken])) {
138854
138962
  throw new ORPCError("UNAUTHORIZED", { message: "the front door's typed API demands this generation's control token as a Bearer credential" });
@@ -141811,6 +141919,15 @@ function exhaustedMessage(exhaustion) {
141811
141919
  function createAntigravityRoute(ports) {
141812
141920
  const fallbackId = ports.fallbackId ?? (() => (0, import_node_crypto24.randomUUID)());
141813
141921
  const lastRouted = ports.lastRouted ?? /* @__PURE__ */ new Map();
141922
+ const exhaustedModels = ports.exhaustedModels ?? /* @__PURE__ */ new Map();
141923
+ const liveQuota = (nowMs) => {
141924
+ for (const [model, resetAtMs] of exhaustedModels) {
141925
+ if (resetAtMs <= nowMs) {
141926
+ exhaustedModels.delete(model);
141927
+ }
141928
+ }
141929
+ return quotaWithExhaustions(ports.quotaSource?.(), exhaustedModels, nowMs);
141930
+ };
141814
141931
  return async (request7) => {
141815
141932
  await Promise.resolve();
141816
141933
  if (request7.method !== "POST") {
@@ -141864,71 +141981,90 @@ function createAntigravityRoute(ports) {
141864
141981
  const requestedModel = parsed.data.model ?? config2.defaultModel;
141865
141982
  const nowMs = ports.now?.() ?? Date.now();
141866
141983
  const sessionKey = parsed.data.metadata?.user_id === void 0 ? void 0 : `${parsed.data.metadata.user_id}\0${parsed.data.model ?? ""}`;
141867
- const translated = translateRequest(parsed.data, config2, { quota: ports.quotaSource?.(), nowMs, previous: sessionKey === void 0 ? void 0 : lastRouted.get(sessionKey) });
141868
- if (sessionKey !== void 0) {
141869
- lastRouted.delete(sessionKey);
141870
- lastRouted.set(sessionKey, translated.model);
141871
- if (lastRouted.size > ROUTING_MEMORY_SESSIONS) {
141872
- const oldest = lastRouted.keys().next();
141873
- if (oldest.done !== true) {
141874
- lastRouted.delete(oldest.value);
141984
+ const routeRequest = () => {
141985
+ const routed = translateRequest(parsed.data, config2, { quota: liveQuota(nowMs), nowMs, previous: sessionKey === void 0 ? void 0 : lastRouted.get(sessionKey) });
141986
+ if (sessionKey !== void 0) {
141987
+ lastRouted.delete(sessionKey);
141988
+ lastRouted.set(sessionKey, routed.model);
141989
+ if (lastRouted.size > ROUTING_MEMORY_SESSIONS) {
141990
+ const oldest = lastRouted.keys().next();
141991
+ if (oldest.done !== true) {
141992
+ lastRouted.delete(oldest.value);
141993
+ }
141875
141994
  }
141876
141995
  }
141877
- }
141878
- const relay = createAntigravityRelay({
141879
- // The frame carries the model that actually served the request, as the real API echoes the concrete model behind an alias: a usage record read from the response then attributes quota to the backend model, not the tier alias the session typed.
141880
- servedModel: translated.model,
141881
- toolNames: translated.toolNames,
141882
- fallbackId
141883
- });
141884
- const upstreamChunks2 = config2.mode === "local" ? callLocalAntigravity({
141885
- config: config2,
141886
- model: translated.model,
141887
- request: translated.request,
141888
- signal: request7.signal,
141889
- connector: ports.localConnector
141890
- }) : callCloudAntigravity(
141891
- {
141996
+ return routed;
141997
+ };
141998
+ let translated = routeRequest();
141999
+ const tried = /* @__PURE__ */ new Set();
142000
+ let iterator;
142001
+ let firstResult;
142002
+ for (; ; ) {
142003
+ tried.add(translated.model);
142004
+ const upstreamChunks2 = config2.mode === "local" ? callLocalAntigravity({
141892
142005
  config: config2,
141893
142006
  model: translated.model,
141894
142007
  request: translated.request,
141895
- token,
141896
- credentialTarget,
141897
- signal: request7.signal
141898
- },
141899
- ports.fetchFn
141900
- );
141901
- const iterator = upstreamChunks2[Symbol.asyncIterator]();
141902
- let firstResult;
141903
- try {
141904
- firstResult = await iterator.next();
141905
- } catch (error63) {
141906
- if (error63 instanceof AntigravityUpstreamError) {
141907
- const is429 = error63.status === HTTP_STATUS.tooManyRequests;
141908
- const quota = ports.quotaSource?.();
141909
- const quotaHeaders3 = unifiedAntigravityQuotaHeaders({ quota, rejected: is429, nowMs, model: translated.model });
141910
- const retryAfter = is429 && quotaHeaders3["retry-after"] === void 0 ? parseRetryAfterSeconds(error63.retryAfter) : void 0;
141911
- const exhaustion = is429 ? antigravityQuotaExhaustion(quota, translated.model, nowMs) : void 0;
141912
- const errorType = is429 ? "rate_limit_error" : "api_error";
142008
+ signal: request7.signal,
142009
+ connector: ports.localConnector
142010
+ }) : callCloudAntigravity(
142011
+ {
142012
+ config: config2,
142013
+ model: translated.model,
142014
+ request: translated.request,
142015
+ token,
142016
+ credentialTarget,
142017
+ signal: request7.signal
142018
+ },
142019
+ ports.fetchFn
142020
+ );
142021
+ iterator = upstreamChunks2[Symbol.asyncIterator]();
142022
+ try {
142023
+ firstResult = await iterator.next();
142024
+ break;
142025
+ } catch (error63) {
142026
+ if (error63 instanceof AntigravityUpstreamError) {
142027
+ const is429 = error63.status === HTTP_STATUS.tooManyRequests;
142028
+ const learned = is429 ? parseQuotaExhaustion(error63.body, nowMs) : void 0;
142029
+ if (learned !== void 0) {
142030
+ exhaustedModels.set(learned.model, learned.resetAtMs);
142031
+ const next = routeRequest();
142032
+ if (!tried.has(next.model)) {
142033
+ translated = next;
142034
+ continue;
142035
+ }
142036
+ }
142037
+ const quota = liveQuota(nowMs);
142038
+ const quotaHeaders3 = unifiedAntigravityQuotaHeaders({ quota, rejected: is429, nowMs, model: translated.model });
142039
+ const retryAfter = is429 && quotaHeaders3["retry-after"] === void 0 ? parseRetryAfterSeconds(error63.retryAfter) : void 0;
142040
+ const exhaustion = is429 ? antigravityQuotaExhaustion(quota, translated.model, nowMs) : void 0;
142041
+ const errorType = is429 ? "rate_limit_error" : "api_error";
142042
+ return {
142043
+ status: error63.status,
142044
+ headers: {
142045
+ "Content-Type": "application/json",
142046
+ ...quotaHeaders3,
142047
+ ...retryAfter !== void 0 ? { "retry-after": String(retryAfter) } : {}
142048
+ },
142049
+ body: JSON.stringify({ type: "error", error: { type: errorType, message: exhaustion === void 0 ? error63.message : exhaustedMessage(exhaustion) } })
142050
+ };
142051
+ }
142052
+ const errMsg = error63 instanceof Error ? error63.message : String(error63);
141913
142053
  return {
141914
- status: error63.status,
141915
- headers: {
141916
- "Content-Type": "application/json",
141917
- ...quotaHeaders3,
141918
- ...retryAfter !== void 0 ? { "retry-after": String(retryAfter) } : {}
141919
- },
141920
- body: JSON.stringify({ type: "error", error: { type: errorType, message: exhaustion === void 0 ? error63.message : exhaustedMessage(exhaustion) } })
142054
+ status: HTTP_STATUS.badGateway,
142055
+ headers: { "Content-Type": "application/json" },
142056
+ body: JSON.stringify({ type: "error", error: { type: "api_error", message: errMsg } })
141921
142057
  };
141922
142058
  }
141923
- const errMsg = error63 instanceof Error ? error63.message : String(error63);
141924
- return {
141925
- status: HTTP_STATUS.badGateway,
141926
- headers: { "Content-Type": "application/json" },
141927
- body: JSON.stringify({ type: "error", error: { type: "api_error", message: errMsg } })
141928
- };
141929
142059
  }
142060
+ const relay = createAntigravityRelay({
142061
+ // The frame carries the model that actually served the request, as the real API echoes the concrete model behind an alias: a usage record read from the response then attributes quota to the backend model, not the tier alias the session typed.
142062
+ servedModel: translated.model,
142063
+ toolNames: translated.toolNames,
142064
+ fallbackId
142065
+ });
141930
142066
  const quotaHeaders2 = unifiedAntigravityQuotaHeaders({
141931
- quota: ports.quotaSource?.(),
142067
+ quota: liveQuota(nowMs),
141932
142068
  rejected: false,
141933
142069
  nowMs,
141934
142070
  model: translated.model
@@ -142392,6 +142528,7 @@ function createProviderRouteResolver(deps) {
142392
142528
  const resolveCredential2 = shareInFlightResolutions(resolveCredentialAsync);
142393
142529
  const antigravityQuotaSources = /* @__PURE__ */ new Map();
142394
142530
  const antigravityRoutingMemory = /* @__PURE__ */ new Map();
142531
+ const antigravityExhaustedModels = /* @__PURE__ */ new Map();
142395
142532
  const definesProvider = (name) => {
142396
142533
  try {
142397
142534
  return loadProvider(deps.providersDir, name, deps.fs) !== void 0;
@@ -142410,6 +142547,15 @@ function createProviderRouteResolver(deps) {
142410
142547
  antigravityRoutingMemory.set(provider, created);
142411
142548
  return created;
142412
142549
  };
142550
+ const exhaustedModelsFor = (provider) => {
142551
+ const existing = antigravityExhaustedModels.get(provider);
142552
+ if (existing !== void 0) {
142553
+ return existing;
142554
+ }
142555
+ const created = /* @__PURE__ */ new Map();
142556
+ antigravityExhaustedModels.set(provider, created);
142557
+ return created;
142558
+ };
142413
142559
  const antigravityQuotaOf = (provider, definition, config2) => {
142414
142560
  const existing = antigravityQuotaSources.get(provider);
142415
142561
  if (existing !== void 0) {
@@ -142505,7 +142651,8 @@ function createProviderRouteResolver(deps) {
142505
142651
  };
142506
142652
  },
142507
142653
  quotaSource: antigravityQuotaOf(provider, antigravityProvider, config2),
142508
- lastRouted: memoryFor(provider)
142654
+ lastRouted: memoryFor(provider),
142655
+ exhaustedModels: exhaustedModelsFor(provider)
142509
142656
  },
142510
142657
  directOrigin2(deps.directPort()),
142511
142658
  provider
@@ -145631,6 +145778,72 @@ var DOOR_RESPAWN_MAX_GENERATIONS = 3;
145631
145778
  var DOOR_RESPAWN_COOLDOWN_CAP_MS = DOOR_STALL_BOUND_MS * DOOR_RESPAWN_MAX_GENERATIONS;
145632
145779
  var CHECKS_PER_PROBE_DEADLINE = 2;
145633
145780
  var DOOR_WATCHDOG_CHECK_MS = PROBE_TIMEOUT_MS / CHECKS_PER_PROBE_DEADLINE;
145781
+ var RESPAWN_SOURCE = `
145782
+ const log = (line) => {
145783
+ if (logFile === undefined) return;
145784
+ try {
145785
+ fs.appendFileSync(logFile, new Date().toISOString() + " frontdoor " + String(ownPid) + ": " + line + "\\n");
145786
+ } catch (error) {
145787
+ // Nowhere left to report a failed log write to; the thread's work goes on without it.
145788
+ }
145789
+ };
145790
+ // Whether a process is alive: signal 0 only tests, and EPERM means it exists under another user.
145791
+ const isRunning = (pid) => {
145792
+ try {
145793
+ process.kill(pid, 0);
145794
+ return true;
145795
+ } catch (error) {
145796
+ return error.code === "EPERM";
145797
+ }
145798
+ };
145799
+ // The pid holding the start lock when that holder is alive, which means a door is already being started and another must not be: the launcher's ensure and this respawn are the two things that start a door, and the lock is the one protocol that keeps them from starting two. A dead holder's lock is litter and is cleared, exactly as the launcher's ensure clears it.
145800
+ const liveLockHolder = () => {
145801
+ let holder;
145802
+ try {
145803
+ holder = JSON.parse(fs.readFileSync(startLockFile, "utf8")).pid;
145804
+ } catch (error) {
145805
+ return undefined;
145806
+ }
145807
+ if (typeof holder === "number" && isRunning(holder)) return holder;
145808
+ fs.rmSync(startLockFile, { force: true });
145809
+ return undefined;
145810
+ };
145811
+ // Creates the lock naming the replacement as its holder, atomically (the wx flag), so the launcher's ensure sees a live holder while the replacement boots and waits for it instead of starting a door of its own; the replacement removes the lock once it is serving, as every door does.
145812
+ const claimStartLock = (holder) => {
145813
+ try {
145814
+ fs.writeFileSync(startLockFile, JSON.stringify({ pid: holder, at: Date.now() }) + "\\n", { flag: "wx" });
145815
+ return true;
145816
+ } catch (error) {
145817
+ if (error.code === "EEXIST") return false;
145818
+ throw error;
145819
+ }
145820
+ };
145821
+ const spawnReplacement = () => {
145822
+ if (respawn === undefined || logFile === undefined) return;
145823
+ const nextGeneration = respawnGeneration + 1;
145824
+ const cooldownMs = Math.min(Math.max(0, nextGeneration - respawnMaxGeneration) * cooldownStepMs, cooldownCapMs);
145825
+ const startingBy = liveLockHolder();
145826
+ if (startingBy !== undefined) {
145827
+ log("not starting a replacement: process " + String(startingBy) + " holds the start lock, so a door is already being started and a second one would race it for the sticky ports");
145828
+ return;
145829
+ }
145830
+ try {
145831
+ const out = fs.openSync(logFile, "a");
145832
+ const child = require("node:child_process").spawn(respawn.command, respawn.args, { detached: true, stdio: ["ignore", out, out], env: Object.assign({}, respawn.env, { [awaitPidEnv]: String(ownPid), [respawnGenerationEnv]: String(nextGeneration), [delayEnv]: String(cooldownMs) }) });
145833
+ child.unref();
145834
+ fs.closeSync(out);
145835
+ if (!claimStartLock(child.pid)) {
145836
+ // A launcher took the lock between the check and the spawn, so its door is the one that is starting: this one must not also bind.
145837
+ process.kill(child.pid, "SIGKILL");
145838
+ log("withdrew replacement door " + String(child.pid) + ": a launcher took the start lock first and its door is the one starting");
145839
+ return;
145840
+ }
145841
+ log("started replacement door " + String(child.pid) + " of generation " + String(nextGeneration) + ", which binds once this process is gone" + (cooldownMs > 0 ? " and a " + String(cooldownMs) + "ms cooldown has passed, since the chain has gone through " + String(respawnMaxGeneration) + " consecutive replacements" : ""));
145842
+ } catch (error) {
145843
+ log("could not start a replacement door: " + (error instanceof Error ? error.message : String(error)));
145844
+ }
145845
+ };
145846
+ `;
145634
145847
  var WATCHDOG_SOURCE = `
145635
145848
  const { workerData, parentPort } = require("node:worker_threads");
145636
145849
  const fs = require("node:fs");
@@ -145647,7 +145860,8 @@ let scheduledMs = 0;
145647
145860
  let waitingOutStarvation = false;
145648
145861
  let stopped = false;
145649
145862
  const readLoad = () => machineLoad === undefined ? { loadAverage: os.loadavg()[0], cpus: os.cpus().length } : machineLoad;
145650
- const processorShare = (reading) => reading.loadAverage <= reading.cpus ? 1 : reading.cpus / reading.loadAverage;
145863
+ // The main thread's own formula, embedded as its source text (see \`processorShare\`), so the stall bound and the start-up probe budget are counted alike.
145864
+ const processorShare = ${processorShare.toString()};
145651
145865
  const describeLoad = (reading) => reading.loadAverage.toFixed(1) + " across " + String(reading.cpus) + " cpus";
145652
145866
  const record = (message) => {
145653
145867
  try {
@@ -145660,14 +145874,7 @@ const record = (message) => {
145660
145874
  // The state file is a courtesy to whoever looks next; the process still has to end.
145661
145875
  }
145662
145876
  };
145663
- const log = (line) => {
145664
- if (logFile === undefined) return;
145665
- try {
145666
- fs.appendFileSync(logFile, new Date().toISOString() + " frontdoor " + String(ownPid) + ": " + line + "\\n");
145667
- } catch (error) {
145668
- // Nowhere left to report a failed log write to; the process still has to end.
145669
- }
145670
- };
145877
+ ${RESPAWN_SOURCE}
145671
145878
  const MS_PER_SECOND = 1000;
145672
145879
  // Enough of the stack to read the caller chain from the timer or socket callback down to the call that held the loop.
145673
145880
  const STACK_FRAMES_LOGGED = 12;
@@ -145708,62 +145915,6 @@ const describeMainThread = (waitMs, resume) => new Promise((resolve) => {
145708
145915
  finish("the main thread could not be inspected: " + (error instanceof Error ? error.message : String(error)));
145709
145916
  }
145710
145917
  });
145711
- // Whether a process is alive: signal 0 only tests, and EPERM means it exists under another user.
145712
- const isRunning = (pid) => {
145713
- try {
145714
- process.kill(pid, 0);
145715
- return true;
145716
- } catch (error) {
145717
- return error.code === "EPERM";
145718
- }
145719
- };
145720
- // The pid holding the start lock when that holder is alive, which means a door is already being started and another must not be: the launcher's ensure and this respawn are the two things that start a door, and the lock is the one protocol that keeps them from starting two. A dead holder's lock is litter and is cleared, exactly as the launcher's ensure clears it.
145721
- const liveLockHolder = () => {
145722
- let holder;
145723
- try {
145724
- holder = JSON.parse(fs.readFileSync(startLockFile, "utf8")).pid;
145725
- } catch (error) {
145726
- return undefined;
145727
- }
145728
- if (typeof holder === "number" && isRunning(holder)) return holder;
145729
- fs.rmSync(startLockFile, { force: true });
145730
- return undefined;
145731
- };
145732
- // Creates the lock naming the replacement as its holder, atomically (the wx flag), so the launcher's ensure sees a live holder while the replacement boots and waits for it instead of starting a door of its own; the replacement removes the lock once it is serving, as every door does.
145733
- const claimStartLock = (holder) => {
145734
- try {
145735
- fs.writeFileSync(startLockFile, JSON.stringify({ pid: holder, at: Date.now() }) + "\\n", { flag: "wx" });
145736
- return true;
145737
- } catch (error) {
145738
- if (error.code === "EEXIST") return false;
145739
- throw error;
145740
- }
145741
- };
145742
- const spawnReplacement = () => {
145743
- if (respawn === undefined || logFile === undefined) return;
145744
- const nextGeneration = respawnGeneration + 1;
145745
- const cooldownMs = Math.min(Math.max(0, nextGeneration - respawnMaxGeneration) * cooldownStepMs, cooldownCapMs);
145746
- const startingBy = liveLockHolder();
145747
- if (startingBy !== undefined) {
145748
- log("not starting a replacement: process " + String(startingBy) + " holds the start lock, so a door is already being started and a second one would race it for the sticky ports");
145749
- return;
145750
- }
145751
- try {
145752
- const out = fs.openSync(logFile, "a");
145753
- const child = require("node:child_process").spawn(respawn.command, respawn.args, { detached: true, stdio: ["ignore", out, out], env: Object.assign({}, respawn.env, { [awaitPidEnv]: String(ownPid), [respawnGenerationEnv]: String(nextGeneration), [delayEnv]: String(cooldownMs) }) });
145754
- child.unref();
145755
- fs.closeSync(out);
145756
- if (!claimStartLock(child.pid)) {
145757
- // A launcher took the lock between the check and the spawn, so its door is the one that is starting: this one must not also bind.
145758
- process.kill(child.pid, "SIGKILL");
145759
- log("withdrew replacement door " + String(child.pid) + ": a launcher took the start lock first and its door is the one starting");
145760
- return;
145761
- }
145762
- log("started replacement door " + String(child.pid) + " of generation " + String(nextGeneration) + ", which binds once this process is gone" + (cooldownMs > 0 ? " and a " + String(cooldownMs) + "ms cooldown has passed, since the stall has recurred through " + String(respawnMaxGeneration) + " consecutive replacements" : ""));
145763
- } catch (error) {
145764
- log("could not start a replacement door: " + (error instanceof Error ? error.message : String(error)));
145765
- }
145766
- };
145767
145918
  // Captures where a main thread that could not be paused is held natively, with the platform's own sampler, so a stall the inspector cannot name still leaves a stack to read. The wait is the sampling time plus the sampler's start-up and symbolication, stretched by the processor share the machine's load leaves it, and the capture never delays the process ending beyond that. The sampler writes its report only once it has finished, so one ended at the deadline, or one that failed, leaves no file, and the log says which rather than naming a file that is not there.
145768
145919
  const takeNativeSample = () => new Promise((resolve) => {
145769
145920
  if (nativeSample === undefined) { resolve(); return; }
@@ -145854,12 +146005,13 @@ parentPort.on("message", (message) => {
145854
146005
  }
145855
146006
  });
145856
146007
  `;
146008
+ var RESPAWN_ENV_NAMES = { awaitPidEnv: DOOR_AWAIT_PID_ENV, respawnGenerationEnv: DOOR_RESPAWN_GENERATION_ENV, delayEnv: DOOR_RESPAWN_DELAY_ENV };
145857
146009
  function startThreadWatchdog(params) {
145858
146010
  const shared = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
145859
146011
  const counter = new Int32Array(shared);
145860
146012
  const worker = new import_node_worker_threads2.Worker(WATCHDOG_SOURCE, {
145861
146013
  eval: true,
145862
- workerData: { shared, boundMs: params.boundMs, checkEveryMs: params.checkEveryMs, pauseWaitMs: params.pauseWaitMs, stateFile: params.stateFile, ownPid: params.ownPid, action: params.action, logFile: params.logFile, respawn: params.respawn, respawnGeneration: params.respawnGeneration, respawnMaxGeneration: params.respawnMaxGeneration, cooldownStepMs: params.cooldownStepMs, cooldownCapMs: params.cooldownCapMs, startLockFile: params.startLockFile, awaitPidEnv: DOOR_AWAIT_PID_ENV, respawnGenerationEnv: DOOR_RESPAWN_GENERATION_ENV, delayEnv: DOOR_RESPAWN_DELAY_ENV, nativeSample: params.nativeSample, machineLoad: params.machineLoad }
146014
+ workerData: { shared, boundMs: params.boundMs, checkEveryMs: params.checkEveryMs, pauseWaitMs: params.pauseWaitMs, stateFile: params.stateFile, ownPid: params.ownPid, action: params.action, logFile: params.logFile, respawn: params.respawn, respawnGeneration: params.respawnGeneration, respawnMaxGeneration: params.respawnMaxGeneration, cooldownStepMs: params.cooldownStepMs, cooldownCapMs: params.cooldownCapMs, startLockFile: params.startLockFile, ...RESPAWN_ENV_NAMES, nativeSample: params.nativeSample, machineLoad: params.machineLoad }
145863
146015
  });
145864
146016
  worker.unref();
145865
146017
  const beat = setInterval(() => {
@@ -145884,6 +146036,25 @@ function startThreadWatchdog(params) {
145884
146036
  }
145885
146037
  };
145886
146038
  }
146039
+ var NEXT_GENERATION_SOURCE = `
146040
+ const { workerData } = require("node:worker_threads");
146041
+ const fs = require("node:fs");
146042
+ const { ownPid, logFile, respawn, respawnGeneration, respawnMaxGeneration, cooldownStepMs, cooldownCapMs, startLockFile, awaitPidEnv, respawnGenerationEnv, delayEnv } = workerData;
146043
+ ${RESPAWN_SOURCE}
146044
+ spawnReplacement();
146045
+ `;
146046
+ async function startNextRespawnGeneration(params) {
146047
+ const worker = new import_node_worker_threads2.Worker(NEXT_GENERATION_SOURCE, {
146048
+ eval: true,
146049
+ workerData: { ownPid: params.ownPid, logFile: params.logFile, respawn: params.respawn, respawnGeneration: params.respawnGeneration, respawnMaxGeneration: params.respawnMaxGeneration, cooldownStepMs: params.cooldownStepMs, cooldownCapMs: params.cooldownCapMs, startLockFile: params.startLockFile, ...RESPAWN_ENV_NAMES }
146050
+ });
146051
+ await new Promise((resolve3, reject) => {
146052
+ worker.once("error", reject);
146053
+ worker.once("exit", () => {
146054
+ resolve3();
146055
+ });
146056
+ });
146057
+ }
145887
146058
 
145888
146059
  // src/frontdoor/commands.ts
145889
146060
  init_probe();
@@ -146049,6 +146220,16 @@ function realFrontDoorSupervisorPorts(paths, respawnGeneration, lifecycle, track
146049
146220
  const log = (line) => {
146050
146221
  appendDoorLog(paths, `frontdoor ${String(process.pid)}: ${line}`);
146051
146222
  };
146223
+ const respawnChain = () => ({
146224
+ ownPid: process.pid,
146225
+ logFile: paths.frontdoorLogPath,
146226
+ respawn: respawnInvocation(paths),
146227
+ respawnGeneration,
146228
+ respawnMaxGeneration: DOOR_RESPAWN_MAX_GENERATIONS,
146229
+ cooldownStepMs: DOOR_STALL_BOUND_MS,
146230
+ cooldownCapMs: DOOR_RESPAWN_COOLDOWN_CAP_MS,
146231
+ startLockFile: paths.frontdoorLockFile
146232
+ });
146052
146233
  let directPort = 0;
146053
146234
  const rcSelfHost = rcSelfHostFromEnv(process.env);
146054
146235
  const codexPorts = createCodexRoutePorts(log, paths.chatgptSignInFile);
@@ -146500,20 +146681,19 @@ function realFrontDoorSupervisorPorts(paths, respawnGeneration, lifecycle, track
146500
146681
  return { port: handle.port, listening: server, close: handle.close, drain: handle.drain };
146501
146682
  },
146502
146683
  closeRcStreamHub: rcHub.close,
146684
+ respawnChain: {
146685
+ generation: respawnGeneration,
146686
+ startNext: async () => {
146687
+ await startNextRespawnGeneration(respawnChain());
146688
+ }
146689
+ },
146503
146690
  startWatchdog: () => startThreadWatchdog({
146691
+ ...respawnChain(),
146504
146692
  stateFile: paths.frontdoorStateFile,
146505
- ownPid: process.pid,
146506
146693
  boundMs: DOOR_STALL_BOUND_MS,
146507
146694
  checkEveryMs: DOOR_WATCHDOG_CHECK_MS,
146508
146695
  pauseWaitMs: DOOR_WATCHDOG_CHECK_MS,
146509
146696
  action: "kill-process",
146510
- logFile: paths.frontdoorLogPath,
146511
- respawn: respawnInvocation(paths),
146512
- respawnGeneration,
146513
- respawnMaxGeneration: DOOR_RESPAWN_MAX_GENERATIONS,
146514
- cooldownStepMs: DOOR_STALL_BOUND_MS,
146515
- cooldownCapMs: DOOR_RESPAWN_COOLDOWN_CAP_MS,
146516
- startLockFile: paths.frontdoorLockFile,
146517
146697
  ...process.platform === "darwin" ? { nativeSample: { command: MACOS_SAMPLER, args: ["{pid}", "{seconds}", "-file", "{file}"], directory: import_node_path61.default.join(import_node_path61.default.dirname(paths.frontdoorLogPath), "stall-samples"), seconds: Math.max(1, Math.ceil(DOOR_WATCHDOG_CHECK_MS / MS_PER_SECOND17)), overheadMs: PROBE_TIMEOUT_MS, keep: DOOR_RESPAWN_MAX_GENERATIONS + 1 } } : {}
146518
146698
  }),
146519
146699
  // The launch lifecycle publisher over the same backbone the typed API serves: the tick's registry facts go in here, and the door's own register, prune and end moments come out as source-tagged events.
@@ -146627,7 +146807,7 @@ function registerFrontDoorCommand(program2, deps) {
146627
146807
 
146628
146808
  // src/statusline/commands.ts
146629
146809
  var import_node_child_process9 = require("node:child_process");
146630
- var import_node_os15 = __toESM(require("node:os"), 1);
146810
+ var import_node_os16 = __toESM(require("node:os"), 1);
146631
146811
  var import_node_path70 = __toESM(require("node:path"), 1);
146632
146812
  init_commandDeps();
146633
146813
  init_load();
@@ -146769,20 +146949,21 @@ function windowsOf(states, nowMs) {
146769
146949
  let fiveHourResetAt;
146770
146950
  let sevenDayUsed;
146771
146951
  let sevenDayResetAt;
146952
+ let bindingUsed;
146772
146953
  for (const state of states) {
146773
146954
  const unified = state.rateLimit?.unified;
146774
146955
  if (unified === void 0) {
146775
146956
  continue;
146776
146957
  }
146777
146958
  const five = livePercentOf(unified.fiveHour, nowMs);
146778
- if (five !== void 0 && (fiveHourUsed === void 0 || five > fiveHourUsed)) {
146779
- fiveHourUsed = five;
146780
- fiveHourResetAt = unified.fiveHour?.resetsAt;
146781
- }
146782
146959
  const seven = livePercentOf(unified.sevenDay, nowMs);
146783
- if (seven !== void 0 && (sevenDayUsed === void 0 || seven > sevenDayUsed)) {
146960
+ const max = five === void 0 ? seven : seven === void 0 ? five : Math.max(five, seven);
146961
+ if (max !== void 0 && (bindingUsed === void 0 || max > bindingUsed)) {
146962
+ bindingUsed = max;
146963
+ fiveHourUsed = five;
146964
+ fiveHourResetAt = five === void 0 ? void 0 : unified.fiveHour?.resetsAt;
146784
146965
  sevenDayUsed = seven;
146785
- sevenDayResetAt = unified.sevenDay?.resetsAt;
146966
+ sevenDayResetAt = seven === void 0 ? void 0 : unified.sevenDay?.resetsAt;
146786
146967
  }
146787
146968
  }
146788
146969
  return { fiveHourUsed, fiveHourResetAt, sevenDayUsed, sevenDayResetAt };
@@ -146828,8 +147009,9 @@ function antigravityQuotaMapOf(payload) {
146828
147009
  );
146829
147010
  }
146830
147011
  function bucketView(bucket, nowMs) {
147012
+ const expired = bucket?.reset_in_seconds !== void 0 && Number.isFinite(bucket.reset_in_seconds) && bucket.reset_in_seconds <= 0;
146831
147013
  return {
146832
- used: bucket?.remaining_fraction === void 0 || !Number.isFinite(bucket.remaining_fraction) ? void 0 : (1 - Math.min(1, Math.max(0, bucket.remaining_fraction))) * FULL_PERCENT2,
147014
+ used: bucket?.remaining_fraction === void 0 || !Number.isFinite(bucket.remaining_fraction) ? void 0 : expired ? 0 : (1 - Math.min(1, Math.max(0, bucket.remaining_fraction))) * FULL_PERCENT2,
146833
147015
  resetAt: bucket?.reset_in_seconds === void 0 || !Number.isFinite(bucket.reset_in_seconds) ? void 0 : isoOf(nowMs + bucket.reset_in_seconds * MS_PER_SECOND18)
146834
147016
  };
146835
147017
  }
@@ -146879,10 +147061,12 @@ function enrichStatuslinePayload(params) {
146879
147061
  ...params.modelChoice === void 0 ? {} : { modelChoice: params.modelChoice },
146880
147062
  ...params.doorCostUsd === void 0 ? {} : { doorCostUsd: params.doorCostUsd }
146881
147063
  };
147064
+ let scopedName;
146882
147065
  if (params.snapshot !== void 0) {
146883
- const scopedName = providerScopedState(params.snapshot, params.providerName, params.env.AGENT_SHIM_PROVIDER);
147066
+ const routedProvider = routedProviderOf(params);
147067
+ scopedName = providerScopedState(params.snapshot, params.providerName, params.env.AGENT_SHIM_PROVIDER) ?? providerScopedState(params.snapshot, routedProvider, routedProvider);
146884
147068
  const scopedState = scopedName === void 0 ? void 0 : params.snapshot.providers[scopedName];
146885
- const states = summary.provider === void 0 ? Object.values(params.snapshot.providers) : scopedState === void 0 ? [] : [scopedState];
147069
+ const states = summary.provider === void 0 && scopedState === void 0 ? Object.values(params.snapshot.providers) : scopedState === void 0 ? [] : [scopedState];
146886
147070
  let email3;
146887
147071
  let sub;
146888
147072
  let plan;
@@ -146913,7 +147097,7 @@ function enrichStatuslinePayload(params) {
146913
147097
  );
146914
147098
  summary = { ...summary, ...windowsOf(states, params.nowMs), providerAccountEmail: email3, providerAccountSub: sub, providerPlan: plan, providerQuotaWindows, quotaFamilies: quotaFamiliesOf(providerBuckets, params.nowMs) };
146915
147099
  }
146916
- if (summary.provider === void 0) {
147100
+ if (summary.provider === void 0 && scopedName === void 0) {
146917
147101
  const agyBuckets = antigravityQuotaMapOf(params.payload);
146918
147102
  if (agyBuckets !== void 0) {
146919
147103
  summary = { ...summary, quotaFamilies: quotaFamiliesOf(agyBuckets, params.nowMs) };
@@ -146935,6 +147119,29 @@ function enrichStatuslinePayload(params) {
146935
147119
  }
146936
147120
  return { payload: enriched, summary };
146937
147121
  }
147122
+ function routedProviderOf(params) {
147123
+ if (params.modelChoice?.provider !== void 0 && params.modelChoice.provider !== "") {
147124
+ return params.modelChoice.provider;
147125
+ }
147126
+ const targetPrefix = prefixBeforeSlash(params.routedTarget);
147127
+ if (targetPrefix !== void 0) {
147128
+ return targetPrefix;
147129
+ }
147130
+ const model = isObject4(params.payload) && isObject4(params.payload.model) ? params.payload.model : void 0;
147131
+ return prefixBeforeSlash(typeof model?.id === "string" ? model.id : void 0) ?? prefixBeforeSlash(typeof model?.display_name === "string" ? model.display_name : void 0);
147132
+ }
147133
+ function prefixBeforeSlash(value3) {
147134
+ if (value3 === void 0) {
147135
+ return void 0;
147136
+ }
147137
+ const slash = value3.indexOf("/");
147138
+ if (slash <= 0) {
147139
+ return void 0;
147140
+ }
147141
+ const prefix = value3.slice(0, slash).trim();
147142
+ const rest = value3.slice(slash + 1).trim();
147143
+ return prefix === "" || rest === "" ? void 0 : prefix;
147144
+ }
146938
147145
  function providerScopedState(snapshot, providerName, providerDisplayName) {
146939
147146
  if (providerName !== void 0 && providerName in snapshot.providers) {
146940
147147
  return providerName;
@@ -147418,7 +147625,7 @@ function contextViewOf(frame) {
147418
147625
  // src/statusline/ports.ts
147419
147626
  init_blockingSpawn();
147420
147627
  var import_node_fs26 = __toESM(require("node:fs"), 1);
147421
- var import_node_os14 = __toESM(require("node:os"), 1);
147628
+ var import_node_os15 = __toESM(require("node:os"), 1);
147422
147629
  var import_node_path63 = __toESM(require("node:path"), 1);
147423
147630
 
147424
147631
  // src/statusline/memoryUse.ts
@@ -147552,7 +147759,7 @@ function discard(target) {
147552
147759
  }
147553
147760
  }
147554
147761
  function readMemoryUse() {
147555
- const totalBytes = import_node_os14.default.totalmem();
147762
+ const totalBytes = import_node_os15.default.totalmem();
147556
147763
  if (process.platform === "darwin") {
147557
147764
  const output2 = runWithPipe(RUN_TIMEOUT_MS, "/usr/bin/vm_stat", [], process.cwd());
147558
147765
  const usedBytes = output2 === void 0 ? void 0 : usedBytesFromVmStat(output2);
@@ -147562,13 +147769,13 @@ function readMemoryUse() {
147562
147769
  const meminfo = readText("/proc/meminfo");
147563
147770
  return meminfo === void 0 ? void 0 : memoryUseFromMeminfo(meminfo);
147564
147771
  }
147565
- return { usedBytes: totalBytes - import_node_os14.default.freemem(), totalBytes };
147772
+ return { usedBytes: totalBytes - import_node_os15.default.freemem(), totalBytes };
147566
147773
  }
147567
147774
  function realStatuslinePorts(env, stateDirectory, runTimeoutMs = RUN_TIMEOUT_MS) {
147568
147775
  const { locale, timeZone } = Intl.DateTimeFormat().resolvedOptions();
147569
147776
  return {
147570
147777
  env,
147571
- homeDirectory: import_node_os14.default.homedir(),
147778
+ homeDirectory: import_node_os15.default.homedir(),
147572
147779
  stateDirectory,
147573
147780
  clock: { locale, timeZone },
147574
147781
  readText,
@@ -151240,7 +151447,7 @@ function registerStatuslineCommand(program2, deps) {
151240
151447
  } else {
151241
151448
  const configDir = process.env.CLAUDE_CONFIG_DIR;
151242
151449
  try {
151243
- account = readAccountMetadataFile(realFarmFs, configDir === void 0 || configDir === "" ? import_node_path70.default.join(import_node_os15.default.homedir(), ".claude.json") : import_node_path70.default.join(configDir, ".claude.json"));
151450
+ account = readAccountMetadataFile(realFarmFs, configDir === void 0 || configDir === "" ? import_node_path70.default.join(import_node_os16.default.homedir(), ".claude.json") : import_node_path70.default.join(configDir, ".claude.json"));
151244
151451
  } catch {
151245
151452
  account = void 0;
151246
151453
  }
@@ -151289,7 +151496,7 @@ function registerStatuslineCommand(program2, deps) {
151289
151496
  });
151290
151497
  return;
151291
151498
  }
151292
- const live = statuslineSettingsForRender({ env: process.env, cwd: process.cwd(), home: import_node_os15.default.homedir(), paths: deps.paths, fs: { ...realFsPort, readConfigFile: cosmiconfigReader() } });
151499
+ const live = statuslineSettingsForRender({ env: process.env, cwd: process.cwd(), home: import_node_os16.default.homedir(), paths: deps.paths, fs: { ...realFsPort, readConfigFile: cosmiconfigReader() } });
151293
151500
  if (live.problem !== void 0) {
151294
151501
  process.stderr.write(`agent-shim: statusline: ${live.problem}. Drawing with the defaults.
151295
151502
  `);
@@ -151302,7 +151509,7 @@ function registerStatuslineCommand(program2, deps) {
151302
151509
  let stackedUnderDefault = false;
151303
151510
  if (isAntigravityPayload(payload)) {
151304
151511
  try {
151305
- stackedUnderDefault = antigravityStacksWithDefault(realFarmFs, import_node_os15.default.homedir());
151512
+ stackedUnderDefault = antigravityStacksWithDefault(realFarmFs, import_node_os16.default.homedir());
151306
151513
  } catch {
151307
151514
  stackedUnderDefault = false;
151308
151515
  }
package/dist/index.cjs CHANGED
@@ -4183,13 +4183,18 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4183
4183
  });
4184
4184
  const { predecessor } = ports;
4185
4185
  const sourceOf = (listener, preferredPort) => predecessor === void 0 ? { preferredPort } : { inherit: async () => await predecessor.take(listener) };
4186
- const fail = (message) => {
4186
+ const fail = async (message) => {
4187
4187
  ports.closeRcStreamHub();
4188
4188
  if (predecessor === void 0) {
4189
4189
  writeFrontDoorState(fs15, paths.frontdoorStateFile, { lastError: message, ...sticky() });
4190
4190
  fs15.removeRecursive(paths.frontdoorLockFile);
4191
4191
  }
4192
4192
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
4193
+ const chain = ports.respawnChain;
4194
+ if (predecessor === void 0 && chain !== void 0 && chain.generation > 0) {
4195
+ ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: this door is generation ${String(chain.generation)} of the watchdog's respawn chain and nothing waits on it, so it starts generation ${String(chain.generation + 1)} rather than leaving no door`);
4196
+ await chain.startNext();
4197
+ }
4193
4198
  return 1;
4194
4199
  };
4195
4200
  if (predecessor === void 0) {
@@ -4201,7 +4206,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4201
4206
  http3 = await ports.startProviderListener(sourceOf("provider", lastPort));
4202
4207
  } catch (error) {
4203
4208
  ports.doorHealth.listenerFailed("provider", error instanceof Error ? error.message : String(error));
4204
- return fail(`could not start the provider listener: ${error instanceof Error ? error.message : String(error)}`);
4209
+ return await fail(`could not start the provider listener: ${error instanceof Error ? error.message : String(error)}`);
4205
4210
  }
4206
4211
  if (previousSticky !== void 0 && http3.port !== previousSticky) {
4207
4212
  ports.log(`agent-shim frontdoor supervisor: sticky port ${String(previousSticky)} was occupied; moving to ${String(http3.port)} (sessions launched against the old port are stale until they relaunch)`);
@@ -4214,7 +4219,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4214
4219
  } catch (error) {
4215
4220
  await http3.close();
4216
4221
  ports.doorHealth.listenerFailed("connect", error instanceof Error ? error.message : String(error));
4217
- return fail(`could not start the CONNECT surface: ${error instanceof Error ? error.message : String(error)}`);
4222
+ return await fail(`could not start the CONNECT surface: ${error instanceof Error ? error.message : String(error)}`);
4218
4223
  }
4219
4224
  if (previousStickyConnect !== void 0 && connect3.port !== previousStickyConnect) {
4220
4225
  ports.log(`agent-shim frontdoor supervisor: sticky CONNECT port ${String(previousStickyConnect)} was occupied; moving to ${String(connect3.port)} (OAuth sessions launched against the old port are stale until they relaunch)`);
@@ -4228,7 +4233,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4228
4233
  await connect3.close();
4229
4234
  await http3.close();
4230
4235
  ports.doorHealth.listenerFailed("direct", error instanceof Error ? error.message : String(error));
4231
- return fail(`could not start the direct listener: ${error instanceof Error ? error.message : String(error)}`);
4236
+ return await fail(`could not start the direct listener: ${error instanceof Error ? error.message : String(error)}`);
4232
4237
  }
4233
4238
  if (previousStickyDirect !== void 0 && direct.port !== previousStickyDirect) {
4234
4239
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom admits the new address once its supervisor rewrites the allowlist file)`);
@@ -4848,7 +4853,7 @@ var init_package = __esm({
4848
4853
  "package.json"() {
4849
4854
  package_default = {
4850
4855
  name: "claude-use",
4851
- version: "11.83.4",
4856
+ version: "11.83.7",
4852
4857
  description: "A profile manager and launcher for Claude Code that lets one person run multiple logins from one machine while controlling what gets shared between them.",
4853
4858
  license: "MIT",
4854
4859
  author: "Joseph Mearman <joseph@mearman.co.uk>",
package/dist/index.mjs CHANGED
@@ -4160,13 +4160,18 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4160
4160
  });
4161
4161
  const { predecessor } = ports;
4162
4162
  const sourceOf = (listener, preferredPort) => predecessor === void 0 ? { preferredPort } : { inherit: async () => await predecessor.take(listener) };
4163
- const fail = (message) => {
4163
+ const fail = async (message) => {
4164
4164
  ports.closeRcStreamHub();
4165
4165
  if (predecessor === void 0) {
4166
4166
  writeFrontDoorState(fs15, paths.frontdoorStateFile, { lastError: message, ...sticky() });
4167
4167
  fs15.removeRecursive(paths.frontdoorLockFile);
4168
4168
  }
4169
4169
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
4170
+ const chain = ports.respawnChain;
4171
+ if (predecessor === void 0 && chain !== void 0 && chain.generation > 0) {
4172
+ ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: this door is generation ${String(chain.generation)} of the watchdog's respawn chain and nothing waits on it, so it starts generation ${String(chain.generation + 1)} rather than leaving no door`);
4173
+ await chain.startNext();
4174
+ }
4170
4175
  return 1;
4171
4176
  };
4172
4177
  if (predecessor === void 0) {
@@ -4178,7 +4183,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4178
4183
  http3 = await ports.startProviderListener(sourceOf("provider", lastPort));
4179
4184
  } catch (error) {
4180
4185
  ports.doorHealth.listenerFailed("provider", error instanceof Error ? error.message : String(error));
4181
- return fail(`could not start the provider listener: ${error instanceof Error ? error.message : String(error)}`);
4186
+ return await fail(`could not start the provider listener: ${error instanceof Error ? error.message : String(error)}`);
4182
4187
  }
4183
4188
  if (previousSticky !== void 0 && http3.port !== previousSticky) {
4184
4189
  ports.log(`agent-shim frontdoor supervisor: sticky port ${String(previousSticky)} was occupied; moving to ${String(http3.port)} (sessions launched against the old port are stale until they relaunch)`);
@@ -4191,7 +4196,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4191
4196
  } catch (error) {
4192
4197
  await http3.close();
4193
4198
  ports.doorHealth.listenerFailed("connect", error instanceof Error ? error.message : String(error));
4194
- return fail(`could not start the CONNECT surface: ${error instanceof Error ? error.message : String(error)}`);
4199
+ return await fail(`could not start the CONNECT surface: ${error instanceof Error ? error.message : String(error)}`);
4195
4200
  }
4196
4201
  if (previousStickyConnect !== void 0 && connect3.port !== previousStickyConnect) {
4197
4202
  ports.log(`agent-shim frontdoor supervisor: sticky CONNECT port ${String(previousStickyConnect)} was occupied; moving to ${String(connect3.port)} (OAuth sessions launched against the old port are stale until they relaunch)`);
@@ -4205,7 +4210,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4205
4210
  await connect3.close();
4206
4211
  await http3.close();
4207
4212
  ports.doorHealth.listenerFailed("direct", error instanceof Error ? error.message : String(error));
4208
- return fail(`could not start the direct listener: ${error instanceof Error ? error.message : String(error)}`);
4213
+ return await fail(`could not start the direct listener: ${error instanceof Error ? error.message : String(error)}`);
4209
4214
  }
4210
4215
  if (previousStickyDirect !== void 0 && direct.port !== previousStickyDirect) {
4211
4216
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom admits the new address once its supervisor rewrites the allowlist file)`);
@@ -4824,7 +4829,7 @@ var init_package = __esm({
4824
4829
  "package.json"() {
4825
4830
  package_default = {
4826
4831
  name: "claude-use",
4827
- version: "11.83.4",
4832
+ version: "11.83.7",
4828
4833
  description: "A profile manager and launcher for Claude Code that lets one person run multiple logins from one machine while controlling what gets shared between them.",
4829
4834
  license: "MIT",
4830
4835
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -26355,6 +26355,13 @@ interface FrontDoorSupervisorPorts {
26355
26355
  * The door this one replaces through a handover, when it was started for one: its listeners are adopted from that door's sockets instead of bound, the state file is not written until this door accepts on all three (the old door owns it and keeps serving until then), and the old door is told once this door serves. Absent for every other start.
26356
26356
  */
26357
26357
  readonly predecessor?: Predecessor;
26358
+ /**
26359
+ * The watchdog's respawn chain this door belongs to: `generation` is how many watchdog replacements produced it (0 for a door a launch or `frontdoor restart` started), and `startNext` starts the door of the next generation the way the watchdog starts one on a stall (see `startNextRespawnGeneration`). A door of generation 1 or more whose start fails calls `startNext` before it exits, once its listeners are down and it has released the start lock, because nobody else would start a door: the stalled door that started it is gone and no launch is waiting on it, so every registered session would get connection refused until some later launch happened to start one. A door a launch started reports its failure to that launch instead, and a handover successor leaves the door it was replacing serving. Optional for a host that does not respawn.
26360
+ */
26361
+ readonly respawnChain?: {
26362
+ readonly generation: number;
26363
+ readonly startNext: () => Promise<void>;
26364
+ };
26358
26365
  /** Stops the work the door runs on its own account rather than for a request (the usage, window, job and catalogue keepers), called once when a drain begins so the successor's are the only ones acting. Optional because a host without such work has nothing to stop. */
26359
26366
  readonly stopBackgroundWork?: () => void;
26360
26367
  /**
@@ -26383,7 +26390,7 @@ interface RunFrontDoorSupervisorOptions {
26383
26390
  /**
26384
26391
  * Runs the front-door supervisor: binds all three listeners (the HTTPS provider listener, the CONNECT surface and the plain-HTTP direct listener, each on its sticky port), records the serving state, and shuts down with an empty session registry, either at the first such tick after the executable it serves as has been replaced on disk (so an applied update reaches the door without waiting out the idle window) or after `idleShutdownMinutes` of it. A door whose state file comes to name another live supervisor is superseded: from then on it takes no new sessions, never writes the state file again, and exits as soon as the sessions it was serving have ended. Returns the exit code: 0 for any of these retirements, 1 for a fatal start failure.
26385
26392
  *
26386
- * The listeners live in this process, so there is no child to keep alive: a crash of this process is a crash of every routed session's door at once, and recovery is the next launch's ensure spawning a replacement on the same sticky ports, which is exactly the failure model the issue asks to settle with tests. Keeping the headroom daemon alive is the headroom supervisor's job, not this one's; the two daemons idle out independently.
26393
+ * The listeners live in this process, so there is no child to keep alive: a crash of this process is a crash of every routed session's door at once, and recovery is the next launch's ensure spawning a replacement on the same sticky ports, or, for a stall or a failed start in a door the watchdog's respawn chain started, the next generation of that chain (see `FrontDoorSupervisorPorts.respawnChain`). Keeping the headroom daemon alive is the headroom supervisor's job, not this one's; the two daemons idle out independently.
26387
26394
  */
26388
26395
  declare function runFrontDoorSupervisor(idleShutdownMinutes: number, ports: FrontDoorSupervisorPorts, options?: RunFrontDoorSupervisorOptions): Promise<number>;
26389
26396
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-use",
3
- "version": "11.83.4",
3
+ "version": "11.83.7",
4
4
  "description": "A profile manager and launcher for Claude Code that lets one person run multiple logins from one machine while controlling what gets shared between them.",
5
5
  "license": "MIT",
6
6
  "author": "Joseph Mearman <joseph@mearman.co.uk>",