claudish 14.18.0 → 14.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +665 -362
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -5494,7 +5494,7 @@ var init_onepassword_config = __esm(() => {
5494
5494
  });
5495
5495
 
5496
5496
  // src/version.ts
5497
- var VERSION = "14.18.0";
5497
+ var VERSION = "14.18.2";
5498
5498
 
5499
5499
  // src/redact.ts
5500
5500
  function isPlaceholder(value) {
@@ -5584,6 +5584,19 @@ function redactExactValues(text, values) {
5584
5584
  }
5585
5585
  return out;
5586
5586
  }
5587
+ function containsExactValue(text, values) {
5588
+ if (!text)
5589
+ return false;
5590
+ for (const value of values) {
5591
+ if (typeof value !== "string" || value.length < SIGNING_VALUE_MIN_LENGTH)
5592
+ continue;
5593
+ for (const form of signingValueForms(value)) {
5594
+ if (text.includes(form))
5595
+ return true;
5596
+ }
5597
+ }
5598
+ return false;
5599
+ }
5587
5600
  function redactForClient(text) {
5588
5601
  return redactSigningValues(text);
5589
5602
  }
@@ -26388,6 +26401,7 @@ var version2 = null, readForToken = null;
26388
26401
 
26389
26402
  // src/auth/antigravity-token.ts
26390
26403
  import { execFileSync } from "child_process";
26404
+ import { createHash as createHash3 } from "crypto";
26391
26405
  import { existsSync as existsSync11 } from "fs";
26392
26406
  import { homedir as homedir12 } from "os";
26393
26407
  import { join as join12 } from "path";
@@ -26395,6 +26409,8 @@ function invalidateReadStoreMemo() {
26395
26409
  cachedRawStore = null;
26396
26410
  }
26397
26411
  function defaultReadStore() {
26412
+ if (process.env.CLAUDISH_DISABLE_KEYCHAIN === "1")
26413
+ return null;
26398
26414
  if (process.platform !== "darwin") {
26399
26415
  logStderr("[Antigravity] Shared token store is macOS-only for now (other keyring backends are a follow-up).");
26400
26416
  return null;
@@ -26536,7 +26552,7 @@ function encodeRecord(rec) {
26536
26552
  return PREFIX + Buffer.from(JSON.stringify(rec), "utf8").toString("base64");
26537
26553
  }
26538
26554
  function readSharedAntigravityToken(deps = defaultDeps3) {
26539
- const rec = parseRecord2(deps.readStore());
26555
+ const rec = readObservedRecord(deps);
26540
26556
  return rec ? rec.token : null;
26541
26557
  }
26542
26558
  function hasSharedAntigravityToken(deps = defaultDeps3) {
@@ -26583,11 +26599,44 @@ function captureAgyClientVersion(accessToken, deps) {
26583
26599
  log("[Antigravity] Could not read the agy version" + (kept ? `; keeping ${kept}.` : "; using the fallback version."));
26584
26600
  }
26585
26601
  }
26602
+ function antigravityTokenLineageMaterial(token) {
26603
+ if (token.refresh_token)
26604
+ return `refresh:${token.refresh_token}`;
26605
+ if (token.access_token)
26606
+ return `access:${token.access_token}`;
26607
+ return;
26608
+ }
26609
+ function sha256(value) {
26610
+ return createHash3("sha256").update(value).digest("hex");
26611
+ }
26612
+ function observeLineage(token) {
26613
+ const material = token ? antigravityTokenLineageMaterial(token) : undefined;
26614
+ observedLineage = material ? sha256(material) : null;
26615
+ if (!observedLineage || !token?.access_token)
26616
+ return;
26617
+ const key = sha256(token.access_token);
26618
+ lineageByAccessToken.delete(key);
26619
+ lineageByAccessToken.set(key, observedLineage);
26620
+ if (lineageByAccessToken.size > MAX_TRACKED_ACCESS_TOKENS) {
26621
+ lineageByAccessToken.delete(lineageByAccessToken.keys().next().value);
26622
+ }
26623
+ }
26624
+ function readObservedRecord(deps) {
26625
+ const rec = parseRecord2(deps.readStore());
26626
+ observeLineage(rec ? rec.token : null);
26627
+ return rec;
26628
+ }
26629
+ function currentAntigravityTokenLineage() {
26630
+ return observedLineage;
26631
+ }
26632
+ function lineageForAntigravityAccessToken(accessToken) {
26633
+ return lineageByAccessToken.get(sha256(accessToken)) ?? null;
26634
+ }
26586
26635
  async function resolveValidToken(deps) {
26587
26636
  if (process.platform !== "darwin") {
26588
26637
  throw terminalCredentialError("[Antigravity] The shared Antigravity token store is macOS-only for now. " + "Use g@<model> with GEMINI_API_KEY on this platform.");
26589
26638
  }
26590
- const rec = parseRecord2(deps.readStore());
26639
+ const rec = readObservedRecord(deps);
26591
26640
  if (!rec) {
26592
26641
  throw terminalCredentialError("[Antigravity] No Antigravity session found. Sign in with `claudish login antigravity`, " + "or use g@<model> with GEMINI_API_KEY " + "(get one at https://aistudio.google.com/app/apikey).");
26593
26642
  }
@@ -26597,7 +26646,7 @@ async function resolveValidToken(deps) {
26597
26646
  }
26598
26647
  log("[Antigravity] Access token expired/near-expiry \u2014 asking the Antigravity CLI to refresh.");
26599
26648
  const outcome = deps.runAgyRefresh();
26600
- const refreshedRec = parseRecord2(deps.readStore());
26649
+ const refreshedRec = readObservedRecord(deps);
26601
26650
  if (refreshedRec && !needsRefresh(refreshedRec.token, deps.now())) {
26602
26651
  log("[Antigravity] Shared token refreshed by the Antigravity CLI.");
26603
26652
  captureAgyClientVersion(refreshedRec.token.access_token, deps);
@@ -26634,8 +26683,8 @@ async function forceRefreshAntigravityToken(deps = defaultDeps3) {
26634
26683
  if (process.platform !== "darwin") {
26635
26684
  throw terminalCredentialError("[Antigravity] The shared Antigravity token store is macOS-only for now. " + "Use g@<model> with GEMINI_API_KEY on this platform.");
26636
26685
  }
26637
- _resetAntigravityTokenState();
26638
- const rec = parseRecord2(deps.readStore());
26686
+ resetObservedTokenState();
26687
+ const rec = readObservedRecord(deps);
26639
26688
  if (!rec) {
26640
26689
  throw terminalCredentialError("[Antigravity] No Antigravity session found. Sign in with `claudish login antigravity`, " + "or use g@<model> with GEMINI_API_KEY " + "(get one at https://aistudio.google.com/app/apikey).");
26641
26690
  }
@@ -26643,7 +26692,7 @@ async function forceRefreshAntigravityToken(deps = defaultDeps3) {
26643
26692
  log("[Antigravity] Upstream rejected the current token \u2014 asking the Antigravity CLI to re-mint.");
26644
26693
  writeSharedAntigravityToken({ ...original, expiry: new Date(deps.now() - 1000).toISOString() }, deps);
26645
26694
  const outcome = deps.runAgyRefresh();
26646
- const refreshed = parseRecord2(deps.readStore());
26695
+ const refreshed = readObservedRecord(deps);
26647
26696
  const token = refreshed?.token;
26648
26697
  if (token && token.access_token !== original.access_token && !needsRefresh(token, deps.now())) {
26649
26698
  log("[Antigravity] Shared token re-minted by the Antigravity CLI.");
@@ -26653,7 +26702,7 @@ async function forceRefreshAntigravityToken(deps = defaultDeps3) {
26653
26702
  if (!refreshed || refreshed.token.access_token === original.access_token) {
26654
26703
  writeSharedAntigravityToken(original, deps);
26655
26704
  }
26656
- _resetAntigravityTokenState();
26705
+ resetObservedTokenState();
26657
26706
  if (outcome.kind === "timeout" || outcome.kind === "failed") {
26658
26707
  const message = `[Antigravity] ${describeRefreshFailure(outcome)}`;
26659
26708
  if (outcome.kind === "timeout") {
@@ -26667,11 +26716,16 @@ async function forceRefreshAntigravityToken(deps = defaultDeps3) {
26667
26716
  throw terminalCredentialError("[Antigravity] The Antigravity session was rejected upstream and could not be re-minted. " + "Run `claudish login antigravity` to sign in again.");
26668
26717
  }
26669
26718
  function _resetAntigravityTokenState() {
26719
+ resetObservedTokenState();
26720
+ lineageByAccessToken.clear();
26721
+ }
26722
+ function resetObservedTokenState() {
26670
26723
  inFlight = null;
26671
26724
  cachedHasToken = null;
26725
+ observedLineage = null;
26672
26726
  invalidateReadStoreMemo();
26673
26727
  }
26674
- var KC_SERVICE = "gemini", KC_ACCOUNT = "antigravity", PREFIX = "go-keyring-base64:", EXPIRY_SKEW_MS = 120000, AGY_REFRESH_TIMEOUT_MS = 12000, AGY_VERSION_TIMEOUT_MS = 5000, READ_STORE_TTL_MS = 3000, cachedRawStore = null, defaultDeps3, KEYCHAIN_LOCKED_EXIT_CODES, cachedHasToken = null, HAS_TOKEN_TTL_MS = 5000, inFlight = null;
26728
+ var KC_SERVICE = "gemini", KC_ACCOUNT = "antigravity", PREFIX = "go-keyring-base64:", EXPIRY_SKEW_MS = 120000, AGY_REFRESH_TIMEOUT_MS = 12000, AGY_VERSION_TIMEOUT_MS = 5000, READ_STORE_TTL_MS = 3000, cachedRawStore = null, defaultDeps3, KEYCHAIN_LOCKED_EXIT_CODES, cachedHasToken = null, HAS_TOKEN_TTL_MS = 5000, inFlight = null, observedLineage = null, MAX_TRACKED_ACCESS_TOKENS = 8, lineageByAccessToken;
26675
26729
  var init_antigravity_token = __esm(() => {
26676
26730
  init_logger();
26677
26731
  init_keychain();
@@ -26684,6 +26738,7 @@ var init_antigravity_token = __esm(() => {
26684
26738
  now: () => Date.now()
26685
26739
  };
26686
26740
  KEYCHAIN_LOCKED_EXIT_CODES = new Set([36, 51, 128]);
26741
+ lineageByAccessToken = new Map;
26687
26742
  });
26688
26743
 
26689
26744
  // src/auth/antigravity-user.ts
@@ -26736,6 +26791,26 @@ function resetAntigravityUserCache() {
26736
26791
  agServedCache = null;
26737
26792
  agServedCacheAt = 0;
26738
26793
  agServedCacheVersion = null;
26794
+ cachedAgLineage = null;
26795
+ }
26796
+ function syncAccountCaches() {
26797
+ const lineage = currentAntigravityTokenLineage();
26798
+ if (lineage === cachedAgLineage)
26799
+ return;
26800
+ if (cachedAgProjectId || agServedCache) {
26801
+ log("[Antigravity] Token lineage changed; dropping the cached project, tier and models.");
26802
+ }
26803
+ resetAntigravityUserCache();
26804
+ cachedAgLineage = lineage;
26805
+ }
26806
+ function lineageOfToken(accessToken) {
26807
+ return lineageForAntigravityAccessToken(accessToken) ?? currentAntigravityTokenLineage();
26808
+ }
26809
+ function mayPublishFor(lineage) {
26810
+ if (currentAntigravityTokenLineage() !== lineage)
26811
+ return false;
26812
+ syncAccountCaches();
26813
+ return true;
26739
26814
  }
26740
26815
  async function callLoadCodeAssistAntigravity(accessToken) {
26741
26816
  const res = await fetch(`${apiBase()}:loadCodeAssist`, {
@@ -26753,7 +26828,9 @@ async function callLoadCodeAssistAntigravity(accessToken) {
26753
26828
  return await res.json();
26754
26829
  }
26755
26830
  async function setupAntigravityUser(accessToken) {
26756
- if (cachedAgProjectId && cachedAgTierId) {
26831
+ syncAccountCaches();
26832
+ const lineage = lineageOfToken(accessToken);
26833
+ if (lineage === cachedAgLineage && cachedAgProjectId && cachedAgTierId) {
26757
26834
  return { projectId: cachedAgProjectId, tierId: cachedAgTierId };
26758
26835
  }
26759
26836
  const loadRes = await callLoadCodeAssistAntigravity(accessToken);
@@ -26763,13 +26840,18 @@ async function setupAntigravityUser(accessToken) {
26763
26840
  if (!projectId) {
26764
26841
  throw makeTerminalSetupError("Antigravity did not return a project for this account. Sign in to Antigravity " + "(`claudish login antigravity`) and try again, or use g@<model> with GEMINI_API_KEY " + "(get one at https://aistudio.google.com/app/apikey).");
26765
26842
  }
26766
- cachedAgProjectId = projectId;
26767
- cachedAgTierId = resolvedTier;
26768
- cachedAgTierName = loadRes.paidTier?.name || null;
26843
+ if (mayPublishFor(lineage)) {
26844
+ cachedAgProjectId = projectId;
26845
+ cachedAgTierId = resolvedTier;
26846
+ cachedAgTierName = loadRes.paidTier?.name || null;
26847
+ } else {
26848
+ log("[Antigravity] Token lineage changed during setup; the result is not cached.");
26849
+ }
26769
26850
  log(`[Antigravity] User set up, project: ${projectId}, tier: ${resolvedTier}`);
26770
26851
  return { projectId, tierId: resolvedTier };
26771
26852
  }
26772
26853
  function getAntigravityTierDisplayName() {
26854
+ syncAccountCaches();
26773
26855
  if (!cachedAgTierName && !cachedAgTierId)
26774
26856
  return "Antigravity";
26775
26857
  const id = cachedAgTierId || "";
@@ -26859,6 +26941,9 @@ async function fetchAntigravityAvailableModelsRaw(accessToken, projectId, opts)
26859
26941
  }
26860
26942
  }
26861
26943
  async function getServedAntigravityModels(accessToken, projectId, opts) {
26944
+ syncAccountCaches();
26945
+ const lineage = lineageOfToken(accessToken);
26946
+ const ownList = lineage === cachedAgLineage;
26862
26947
  const now = Date.now();
26863
26948
  const version = antigravityClientVersion();
26864
26949
  if (agServedCache && agServedCacheVersion !== version) {
@@ -26866,9 +26951,10 @@ async function getServedAntigravityModels(accessToken, projectId, opts) {
26866
26951
  agServedCache = null;
26867
26952
  agServedCacheAt = 0;
26868
26953
  }
26869
- if (!opts?.force && agServedCache && now - agServedCacheAt < SERVED_MODELS_TTL_MS) {
26954
+ if (!opts?.force && ownList && agServedCache && now - agServedCacheAt < SERVED_MODELS_TTL_MS) {
26870
26955
  return agServedCache;
26871
26956
  }
26957
+ const prior = ownList ? agServedCache : null;
26872
26958
  try {
26873
26959
  const raw = await fetchAntigravityAvailableModelsRaw(accessToken, projectId);
26874
26960
  if (raw.kind === "unreachable") {
@@ -26916,7 +27002,7 @@ async function getServedAntigravityModels(accessToken, projectId, opts) {
26916
27002
  deprecatedReplacements[oldId] = info.newModelId;
26917
27003
  }
26918
27004
  const agentModelIds = flattenAgentModelSorts(data.agentModelSorts);
26919
- agServedCache = {
27005
+ const served = {
26920
27006
  servedIds,
26921
27007
  defaultId,
26922
27008
  meta,
@@ -26924,26 +27010,34 @@ async function getServedAntigravityModels(accessToken, projectId, opts) {
26924
27010
  deprecatedReplacements,
26925
27011
  ...agentModelIds ? { agentModelIds } : {}
26926
27012
  };
27013
+ if (!mayPublishFor(lineage)) {
27014
+ log("[Antigravity] Token lineage changed during discovery; the result is not cached.");
27015
+ return served;
27016
+ }
27017
+ agServedCache = served;
26927
27018
  agServedCacheAt = now;
26928
27019
  agServedCacheVersion = raw.clientVersion;
26929
- return agServedCache;
27020
+ return served;
26930
27021
  }
26931
27022
  }
26932
27023
  } catch (err) {
26933
27024
  log(`[Antigravity] fetchAvailableModels error: ${err}`);
26934
27025
  }
26935
- if (agServedCache)
26936
- return agServedCache;
27026
+ if (prior)
27027
+ return prior;
26937
27028
  return { servedIds: [], defaultId: null, meta: {} };
26938
27029
  }
26939
27030
  function peekServedAntigravityModels() {
26940
27031
  if (!agServedCache || agServedCacheVersion !== antigravityClientVersion())
26941
27032
  return null;
27033
+ if (cachedAgLineage !== currentAntigravityTokenLineage())
27034
+ return null;
26942
27035
  return agServedCache;
26943
27036
  }
26944
- var ANTIGRAVITY_DEFAULT_HOST = "https://daily-cloudcode-pa.googleapis.com", SERVED_MODELS_TTL_MS, ANTIGRAVITY_IDE_TYPE = "ANTIGRAVITY", AGY_FALLBACK_CLIENT_VERSION = "1.1.9", cachedAgProjectId = null, cachedAgTierId = null, cachedAgTierName = null, agServedCache = null, agServedCacheAt = 0, agServedCacheVersion = null;
27037
+ var ANTIGRAVITY_DEFAULT_HOST = "https://daily-cloudcode-pa.googleapis.com", SERVED_MODELS_TTL_MS, ANTIGRAVITY_IDE_TYPE = "ANTIGRAVITY", AGY_FALLBACK_CLIENT_VERSION = "1.1.9", cachedAgProjectId = null, cachedAgTierId = null, cachedAgTierName = null, cachedAgLineage = null, agServedCache = null, agServedCacheAt = 0, agServedCacheVersion = null;
26945
27038
  var init_antigravity_user = __esm(() => {
26946
27039
  init_logger();
27040
+ init_antigravity_token();
26947
27041
  SERVED_MODELS_TTL_MS = 10 * 60 * 1000;
26948
27042
  });
26949
27043
 
@@ -27305,7 +27399,7 @@ var init_credential_file = __esm(() => {
27305
27399
 
27306
27400
  // src/auth/oauth-manager.ts
27307
27401
  import { exec as exec2 } from "child_process";
27308
- import { createHash as createHash3, randomBytes as randomBytes5 } from "crypto";
27402
+ import { createHash as createHash4, randomBytes as randomBytes5 } from "crypto";
27309
27403
  import { existsSync as existsSync12, mkdirSync as mkdirSync10, unlinkSync as unlinkSync5 } from "fs";
27310
27404
  import { homedir as homedir13 } from "os";
27311
27405
  import { join as join13 } from "path";
@@ -27408,7 +27502,7 @@ class OAuthManager {
27408
27502
  return randomBytes5(64).toString("base64url");
27409
27503
  }
27410
27504
  generateCodeChallenge(verifier) {
27411
- return createHash3("sha256").update(verifier).digest("base64url");
27505
+ return createHash4("sha256").update(verifier).digest("base64url");
27412
27506
  }
27413
27507
  async openBrowser(url, message) {
27414
27508
  try {
@@ -28774,9 +28868,9 @@ var init_registry2 = __esm(() => {
28774
28868
  });
28775
28869
 
28776
28870
  // src/code-mode/ids.ts
28777
- import { createHash as createHash4 } from "crypto";
28871
+ import { createHash as createHash5 } from "crypto";
28778
28872
  function sha256Hex(input) {
28779
- return createHash4("sha256").update(input).digest("hex");
28873
+ return createHash5("sha256").update(input).digest("hex");
28780
28874
  }
28781
28875
  function accountKeyFromBinding(binding) {
28782
28876
  const auth = binding?.auth;
@@ -28814,8 +28908,8 @@ function decodeNestedId(id) {
28814
28908
  return { execKey: match[1], seq: Number(match[2]) };
28815
28909
  }
28816
28910
  function uuidV5(namespace, name) {
28817
- const ns = createHash4("sha256").update(namespace).digest().subarray(0, 16);
28818
- const hash = createHash4("sha1").update(ns).update(name).digest();
28911
+ const ns = createHash5("sha256").update(namespace).digest().subarray(0, 16);
28912
+ const hash = createHash5("sha1").update(ns).update(name).digest();
28819
28913
  const bytes = Buffer.from(hash.subarray(0, 16));
28820
28914
  bytes[6] = bytes[6] & 15 | 80;
28821
28915
  bytes[8] = bytes[8] & 63 | 128;
@@ -29177,7 +29271,7 @@ var init_exec_tool = __esm(() => {
29177
29271
  });
29178
29272
 
29179
29273
  // src/code-mode/hashes.ts
29180
- import { createHash as createHash5 } from "crypto";
29274
+ import { createHash as createHash6 } from "crypto";
29181
29275
  function withoutCacheMarkers(value) {
29182
29276
  if (Array.isArray(value))
29183
29277
  return value.map(withoutCacheMarkers);
@@ -29200,7 +29294,7 @@ function canonicalJson(value) {
29200
29294
  return `{${body}}`;
29201
29295
  }
29202
29296
  function inputHash(input) {
29203
- return createHash5("sha256").update(canonicalJson(input ?? {})).digest("hex");
29297
+ return createHash6("sha256").update(canonicalJson(input ?? {})).digest("hex");
29204
29298
  }
29205
29299
  function compareIds(a, b) {
29206
29300
  const da = decodeNestedId(a);
@@ -29211,7 +29305,7 @@ function compareIds(a, b) {
29211
29305
  }
29212
29306
  function batchHash(entries) {
29213
29307
  const ordered = [...entries].sort((a, b) => compareIds(a.toolUseId, b.toolUseId));
29214
- const hash = createHash5("sha256");
29308
+ const hash = createHash6("sha256");
29215
29309
  for (const entry of ordered) {
29216
29310
  const canonical = entry.result ? canonicalJson([
29217
29311
  entry.toolUseId,
@@ -29225,7 +29319,7 @@ function batchHash(entries) {
29225
29319
  return hash.digest("hex");
29226
29320
  }
29227
29321
  function completionKey(batchHashes) {
29228
- const hash = createHash5("sha256");
29322
+ const hash = createHash6("sha256");
29229
29323
  for (const h of batchHashes) {
29230
29324
  hash.update(h);
29231
29325
  hash.update(`
@@ -33358,9 +33452,9 @@ var init_prelude = __esm(() => {
33358
33452
  });
33359
33453
 
33360
33454
  // src/code-mode/sandbox/script-runtime.ts
33361
- import { createHash as createHash6 } from "crypto";
33455
+ import { createHash as createHash7 } from "crypto";
33362
33456
  function seedNumber(seed) {
33363
- return createHash6("sha256").update(seed).digest().readUInt32BE(0);
33457
+ return createHash7("sha256").update(seed).digest().readUInt32BE(0);
33364
33458
  }
33365
33459
  function utf8Bytes2(text) {
33366
33460
  return Buffer.byteLength(text, "utf8");
@@ -33906,9 +34000,9 @@ var init_script_runtime = __esm(() => {
33906
34000
  });
33907
34001
 
33908
34002
  // src/code-mode/turn-records.ts
33909
- import { createHash as createHash7 } from "crypto";
34003
+ import { createHash as createHash8 } from "crypto";
33910
34004
  function sha256Hex2(text) {
33911
- return createHash7("sha256").update(text).digest("hex");
34005
+ return createHash8("sha256").update(text).digest("hex");
33912
34006
  }
33913
34007
  function recordKey(sessionKey, anchor) {
33914
34008
  return `${sessionKey}\x00${anchor}`;
@@ -34251,6 +34345,236 @@ var init_harness = __esm(() => {
34251
34345
  SKILL_LINE = /^-\s+([a-z0-9][a-z0-9:_-]*):\s*(.+)$/i;
34252
34346
  });
34253
34347
 
34348
+ // src/handlers/shared/call-context.ts
34349
+ function createSigningSecrets() {
34350
+ return { values: new Set, lease: acquireSigningLease() };
34351
+ }
34352
+ function signingSecretsOf(c) {
34353
+ const installed = readCallVar(c, SIGNING_SECRETS_KEY);
34354
+ if (installed)
34355
+ return installed;
34356
+ const lazy = createSigningSecrets();
34357
+ writeCallVar(c, SIGNING_SECRETS_KEY, lazy);
34358
+ return lazy;
34359
+ }
34360
+ function readCallVar(c, key) {
34361
+ if (!c || typeof c !== "object")
34362
+ return;
34363
+ const store = c;
34364
+ if (typeof store.get === "function")
34365
+ return store.get(key);
34366
+ return detachedCallVars.get(c)?.get(key);
34367
+ }
34368
+ function writeCallVar(c, key, value) {
34369
+ if (!c || typeof c !== "object")
34370
+ return;
34371
+ const store = c;
34372
+ if (typeof store.set === "function") {
34373
+ store.set(key, value);
34374
+ return;
34375
+ }
34376
+ let vars = detachedCallVars.get(c);
34377
+ if (!vars) {
34378
+ vars = new Map;
34379
+ detachedCallVars.set(c, vars);
34380
+ }
34381
+ vars.set(key, value);
34382
+ }
34383
+ function addSigningSecrets(c, values) {
34384
+ const secrets = signingSecretsOf(c);
34385
+ const list = [...values].filter((v) => typeof v === "string" && v.length > 0);
34386
+ for (const value of list)
34387
+ secrets.values.add(value);
34388
+ secrets.lease.add(list);
34389
+ }
34390
+ function isCredentialHeader(name) {
34391
+ const lower = name.toLowerCase();
34392
+ if (CREDENTIAL_HEADER_NAMES.has(lower))
34393
+ return true;
34394
+ return CREDENTIAL_HEADER_FRAGMENTS.some((fragment) => lower.includes(fragment));
34395
+ }
34396
+ function credentialPartsOf(name, value) {
34397
+ const parts = [value];
34398
+ const bare = value.replace(AUTH_SCHEME_PREFIX, "");
34399
+ if (bare !== value)
34400
+ parts.push(bare);
34401
+ if (name.toLowerCase() === "cookie") {
34402
+ for (const pair of value.split(";")) {
34403
+ const eq = pair.indexOf("=");
34404
+ if (eq > 0)
34405
+ parts.push(pair.slice(eq + 1).trim());
34406
+ }
34407
+ }
34408
+ return parts;
34409
+ }
34410
+ function credentialValuesFromRequest(headers, endpoint) {
34411
+ const out = [];
34412
+ for (const [name, value] of Object.entries(headers ?? {})) {
34413
+ if (typeof value !== "string" || !value || !isCredentialHeader(name))
34414
+ continue;
34415
+ out.push(...credentialPartsOf(name, value));
34416
+ }
34417
+ if (endpoint) {
34418
+ try {
34419
+ for (const [name, value] of new URL(endpoint).searchParams) {
34420
+ if (value && CREDENTIAL_QUERY_NAMES.has(name.toLowerCase()))
34421
+ out.push(value);
34422
+ }
34423
+ } catch {}
34424
+ }
34425
+ return out;
34426
+ }
34427
+ function releaseWhenBodyEnds(response, release) {
34428
+ const source = response.body;
34429
+ if (!source) {
34430
+ release();
34431
+ return response;
34432
+ }
34433
+ const reader = source.getReader();
34434
+ let cancelling = false;
34435
+ const stream = new ReadableStream({
34436
+ async pull(controller) {
34437
+ let result;
34438
+ try {
34439
+ result = await reader.read();
34440
+ } catch (err) {
34441
+ if (cancelling)
34442
+ return;
34443
+ release();
34444
+ controller.error(err);
34445
+ return;
34446
+ }
34447
+ if (cancelling)
34448
+ return;
34449
+ if (result.done) {
34450
+ release();
34451
+ controller.close();
34452
+ return;
34453
+ }
34454
+ controller.enqueue(result.value);
34455
+ },
34456
+ async cancel(reason) {
34457
+ cancelling = true;
34458
+ try {
34459
+ await reader.cancel(reason);
34460
+ } catch {} finally {
34461
+ release();
34462
+ }
34463
+ }
34464
+ }, { highWaterMark: 0 });
34465
+ return new Response(stream, {
34466
+ status: response.status,
34467
+ statusText: response.statusText,
34468
+ headers: response.headers
34469
+ });
34470
+ }
34471
+ function callAbortSignal(c) {
34472
+ return readCallVar(c, CALL_ABORT_SIGNAL_KEY);
34473
+ }
34474
+ function callAborted(c) {
34475
+ return callAbortSignal(c)?.aborted === true;
34476
+ }
34477
+ function callAbortError() {
34478
+ return new DOMException("the call's deadline passed; claudish stopped its work", "AbortError");
34479
+ }
34480
+ function raceCallAbort(p, signal) {
34481
+ if (!signal)
34482
+ return p;
34483
+ p.catch(() => {});
34484
+ if (signal.aborted)
34485
+ return Promise.reject(callAbortError());
34486
+ return new Promise((resolve, reject) => {
34487
+ const onAbort = () => reject(callAbortError());
34488
+ signal.addEventListener("abort", onAbort, { once: true });
34489
+ p.then((value) => {
34490
+ signal.removeEventListener("abort", onAbort);
34491
+ resolve(value);
34492
+ }, (err) => {
34493
+ signal.removeEventListener("abort", onAbort);
34494
+ reject(err);
34495
+ });
34496
+ });
34497
+ }
34498
+ function sleepUnlessAborted(ms, signal) {
34499
+ if (signal?.aborted)
34500
+ return Promise.resolve(true);
34501
+ return new Promise((resolve) => {
34502
+ const onAbort = () => {
34503
+ clearTimeout(timer);
34504
+ resolve(true);
34505
+ };
34506
+ const timer = setTimeout(() => {
34507
+ signal?.removeEventListener("abort", onAbort);
34508
+ resolve(false);
34509
+ }, ms);
34510
+ signal?.addEventListener("abort", onAbort, { once: true });
34511
+ });
34512
+ }
34513
+ function withCallSignal(sig, callSignal) {
34514
+ if (!callSignal)
34515
+ return sig;
34516
+ if (!sig)
34517
+ return callSignal;
34518
+ return AbortSignal.any([sig, callSignal]);
34519
+ }
34520
+ function abortedResponse() {
34521
+ return new Response(JSON.stringify({
34522
+ type: "error",
34523
+ error: {
34524
+ type: "timeout_error",
34525
+ message: "claudish stopped this call: its deadline passed"
34526
+ }
34527
+ }), {
34528
+ status: 408,
34529
+ headers: { "content-type": "application/json", [CALL_ABORTED_HEADER]: "1" }
34530
+ });
34531
+ }
34532
+ function hopLogOf(c) {
34533
+ return readCallVar(c, HOP_LOG_KEY);
34534
+ }
34535
+ function recordHopEntry(c, provider, wireModel) {
34536
+ const hops = hopLogOf(c);
34537
+ if (!hops)
34538
+ return;
34539
+ const plannedUid = readCallVar(c, PLANNED_HOP_KEY);
34540
+ const entry = {
34541
+ provider,
34542
+ wireModel,
34543
+ arm: null,
34544
+ billing: null,
34545
+ ...plannedUid ? { plannedUid } : {}
34546
+ };
34547
+ hops.push(entry);
34548
+ return entry;
34549
+ }
34550
+ async function withPlannedHop(c, plannedUid, work) {
34551
+ if (!hopLogOf(c))
34552
+ return work();
34553
+ const previous = readCallVar(c, PLANNED_HOP_KEY);
34554
+ writeCallVar(c, PLANNED_HOP_KEY, plannedUid);
34555
+ try {
34556
+ return await work();
34557
+ } finally {
34558
+ writeCallVar(c, PLANNED_HOP_KEY, previous);
34559
+ }
34560
+ }
34561
+ var SIGNING_SECRETS_KEY = "claudishSigningSecrets", detachedCallVars, CREDENTIAL_HEADER_NAMES, CREDENTIAL_HEADER_FRAGMENTS, CREDENTIAL_QUERY_NAMES, AUTH_SCHEME_PREFIX, CALL_ABORT_SIGNAL_KEY = "claudishCallAbortSignal", CALL_ABORTED_HEADER = "x-claudish-call-aborted", HOP_LOG_KEY = "claudishHopLog", PLANNED_HOP_KEY = "claudishPlannedHop";
34562
+ var init_call_context = __esm(() => {
34563
+ init_redact();
34564
+ detachedCallVars = new WeakMap;
34565
+ CREDENTIAL_HEADER_NAMES = new Set([
34566
+ "authorization",
34567
+ "proxy-authorization",
34568
+ "x-api-key",
34569
+ "api-key",
34570
+ "x-goog-api-key",
34571
+ "cookie"
34572
+ ]);
34573
+ CREDENTIAL_HEADER_FRAGMENTS = ["token", "secret", "key"];
34574
+ CREDENTIAL_QUERY_NAMES = new Set(["key", "api_key", "token", "access_token"]);
34575
+ AUTH_SCHEME_PREFIX = /^(?:Bearer|Basic|Token)\s+/i;
34576
+ });
34577
+
34254
34578
  // src/providers/codex-models-discovery.ts
34255
34579
  import { existsSync as existsSync14, readFileSync as readFileSync18 } from "fs";
34256
34580
  import { homedir as homedir16 } from "os";
@@ -34322,6 +34646,21 @@ function toModelTable(body) {
34322
34646
  }
34323
34647
  return table;
34324
34648
  }
34649
+ function dropCredentialTiers(table, credentialValues) {
34650
+ let dropped = 0;
34651
+ for (const info of table.values()) {
34652
+ if (info.serviceTiers) {
34653
+ const kept = info.serviceTiers.filter((tier) => !containsExactValue(tier.id, credentialValues) && !containsExactValue(tier.name, credentialValues));
34654
+ dropped += info.serviceTiers.length - kept.length;
34655
+ info.serviceTiers = kept;
34656
+ }
34657
+ if (info.defaultServiceTier !== undefined && containsExactValue(info.defaultServiceTier, credentialValues)) {
34658
+ delete info.defaultServiceTier;
34659
+ dropped++;
34660
+ }
34661
+ }
34662
+ return dropped;
34663
+ }
34325
34664
  function discoveryHeaders(binding) {
34326
34665
  const headers = {};
34327
34666
  for (const [name, value] of Object.entries(binding.auth?.headers ?? {})) {
@@ -34355,6 +34694,10 @@ async function fetchModelTable(binding, opts) {
34355
34694
  log("[CodexDiscovery] GET /models body has no models array");
34356
34695
  return;
34357
34696
  }
34697
+ const dropped = dropCredentialTiers(table, credentialValuesFromRequest(binding.auth?.headers, binding.auth?.endpoint));
34698
+ if (dropped > 0) {
34699
+ log(`[CodexDiscovery] dropped ${dropped} service tier(s) that contain a credential value`);
34700
+ }
34358
34701
  log(`[CodexDiscovery] GET /models: ${table.size} model(s)`);
34359
34702
  return table;
34360
34703
  } catch (err) {
@@ -34437,7 +34780,9 @@ async function getCodexModelInfo(slug, binding, accountKey, opts = {}) {
34437
34780
  }
34438
34781
  var CODEX_DISCOVERY_CLIENT_VERSION = "0.161.0", CODEX_DISCOVERY_TTL_MS, CODEX_DISCOVERY_FETCH_TIMEOUT_MS = 1e4, CODEX_DISCOVERY_DEFAULT_WAIT_MS = 2000, FAILURE_RETRY_AFTER_MS, memo;
34439
34782
  var init_codex_models_discovery = __esm(() => {
34783
+ init_call_context();
34440
34784
  init_logger();
34785
+ init_redact();
34441
34786
  CODEX_DISCOVERY_TTL_MS = 60 * 60 * 1000;
34442
34787
  FAILURE_RETRY_AFTER_MS = 60 * 1000;
34443
34788
  memo = new Map;
@@ -34494,9 +34839,9 @@ var init_tool_results = __esm(() => {
34494
34839
  });
34495
34840
 
34496
34841
  // src/code-mode/transliterate.ts
34497
- import { createHash as createHash8 } from "crypto";
34842
+ import { createHash as createHash9 } from "crypto";
34498
34843
  function transliteratedCallId(firstToolUseId) {
34499
- return `call_${createHash8("sha256").update(firstToolUseId).digest("hex").slice(0, 32)}`;
34844
+ return `call_${createHash9("sha256").update(firstToolUseId).digest("hex").slice(0, 32)}`;
34500
34845
  }
34501
34846
  function callExpression(use, names) {
34502
34847
  const name = typeof use.name === "string" ? use.name : "";
@@ -34570,12 +34915,12 @@ function relayNestedInput(block, repair) {
34570
34915
  }
34571
34916
 
34572
34917
  // src/code-mode/input-builder.ts
34573
- import { createHash as createHash9 } from "crypto";
34918
+ import { createHash as createHash10 } from "crypto";
34574
34919
  function blocksOf2(message) {
34575
34920
  return message && Array.isArray(message.content) ? message.content : [];
34576
34921
  }
34577
34922
  function sha256Hex3(text) {
34578
- return createHash9("sha256").update(text).digest("hex");
34923
+ return createHash10("sha256").update(text).digest("hex");
34579
34924
  }
34580
34925
  function reasoningKey(item) {
34581
34926
  if (typeof item.id === "string" && item.id)
@@ -35326,7 +35671,7 @@ var init_stores = __esm(() => {
35326
35671
  });
35327
35672
 
35328
35673
  // src/code-mode/request.ts
35329
- import { createHash as createHash10 } from "crypto";
35674
+ import { createHash as createHash11 } from "crypto";
35330
35675
  function isLiteFallbackActive(model, now = Date.now()) {
35331
35676
  const until = liteFallbackUntil.get(model.toLowerCase());
35332
35677
  if (until === undefined)
@@ -35369,7 +35714,7 @@ function applyCodeModeToPayload(payload, ctx) {
35369
35714
  if (shape === "lite") {
35370
35715
  const reasoning = liteReasoning(payload, ctx.modelInfo);
35371
35716
  if (reasoning) {
35372
- const toolsHash = createHash10("sha256").update(JSON.stringify(ctx.execTool)).digest("hex");
35717
+ const toolsHash = createHash11("sha256").update(JSON.stringify(ctx.execTool)).digest("hex");
35373
35718
  payload.reasoning = reasoning;
35374
35719
  delete payload.tools;
35375
35720
  delete payload.instructions;
@@ -37647,7 +37992,7 @@ var init_output_capture = __esm(() => {
37647
37992
  });
37648
37993
 
37649
37994
  // src/hooks/telemetry/aggregate.ts
37650
- import { createHash as createHash11, randomBytes as randomBytes6 } from "crypto";
37995
+ import { createHash as createHash12, randomBytes as randomBytes6 } from "crypto";
37651
37996
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync11 } from "fs";
37652
37997
  import { homedir as homedir19 } from "os";
37653
37998
  import { dirname as dirname11, join as join19 } from "path";
@@ -37671,7 +38016,7 @@ function contextFillPct(peakTokens, window2 = enforcedContextWindow) {
37671
38016
  return Math.min(100, Math.max(0, Math.round(peakTokens / window2 * 100)));
37672
38017
  }
37673
38018
  function hashSessionId(rawSessionId, model) {
37674
- return createHash11("sha256").update(`${SESSION_SALT}:${rawSessionId}:${model}`).digest("hex");
38019
+ return createHash12("sha256").update(`${SESSION_SALT}:${rawSessionId}:${model}`).digest("hex");
37675
38020
  }
37676
38021
  function setTelemetryConsent(value) {
37677
38022
  consent = value;
@@ -41218,236 +41563,6 @@ function decideCodexSpeed(speed, modelInfo) {
41218
41563
  }
41219
41564
  var CODEX_SERVICE_TIER_POINTER = "/service_tier";
41220
41565
 
41221
- // src/handlers/shared/call-context.ts
41222
- function createSigningSecrets() {
41223
- return { values: new Set, lease: acquireSigningLease() };
41224
- }
41225
- function signingSecretsOf(c) {
41226
- const installed = readCallVar(c, SIGNING_SECRETS_KEY);
41227
- if (installed)
41228
- return installed;
41229
- const lazy = createSigningSecrets();
41230
- writeCallVar(c, SIGNING_SECRETS_KEY, lazy);
41231
- return lazy;
41232
- }
41233
- function readCallVar(c, key) {
41234
- if (!c || typeof c !== "object")
41235
- return;
41236
- const store = c;
41237
- if (typeof store.get === "function")
41238
- return store.get(key);
41239
- return detachedCallVars.get(c)?.get(key);
41240
- }
41241
- function writeCallVar(c, key, value) {
41242
- if (!c || typeof c !== "object")
41243
- return;
41244
- const store = c;
41245
- if (typeof store.set === "function") {
41246
- store.set(key, value);
41247
- return;
41248
- }
41249
- let vars = detachedCallVars.get(c);
41250
- if (!vars) {
41251
- vars = new Map;
41252
- detachedCallVars.set(c, vars);
41253
- }
41254
- vars.set(key, value);
41255
- }
41256
- function addSigningSecrets(c, values) {
41257
- const secrets = signingSecretsOf(c);
41258
- const list = [...values].filter((v) => typeof v === "string" && v.length > 0);
41259
- for (const value of list)
41260
- secrets.values.add(value);
41261
- secrets.lease.add(list);
41262
- }
41263
- function isCredentialHeader(name) {
41264
- const lower = name.toLowerCase();
41265
- if (CREDENTIAL_HEADER_NAMES.has(lower))
41266
- return true;
41267
- return CREDENTIAL_HEADER_FRAGMENTS.some((fragment) => lower.includes(fragment));
41268
- }
41269
- function credentialPartsOf(name, value) {
41270
- const parts = [value];
41271
- const bare = value.replace(AUTH_SCHEME_PREFIX, "");
41272
- if (bare !== value)
41273
- parts.push(bare);
41274
- if (name.toLowerCase() === "cookie") {
41275
- for (const pair of value.split(";")) {
41276
- const eq = pair.indexOf("=");
41277
- if (eq > 0)
41278
- parts.push(pair.slice(eq + 1).trim());
41279
- }
41280
- }
41281
- return parts;
41282
- }
41283
- function credentialValuesFromRequest(headers, endpoint) {
41284
- const out = [];
41285
- for (const [name, value] of Object.entries(headers ?? {})) {
41286
- if (typeof value !== "string" || !value || !isCredentialHeader(name))
41287
- continue;
41288
- out.push(...credentialPartsOf(name, value));
41289
- }
41290
- if (endpoint) {
41291
- try {
41292
- for (const [name, value] of new URL(endpoint).searchParams) {
41293
- if (value && CREDENTIAL_QUERY_NAMES.has(name.toLowerCase()))
41294
- out.push(value);
41295
- }
41296
- } catch {}
41297
- }
41298
- return out;
41299
- }
41300
- function releaseWhenBodyEnds(response, release) {
41301
- const source = response.body;
41302
- if (!source) {
41303
- release();
41304
- return response;
41305
- }
41306
- const reader = source.getReader();
41307
- let cancelling = false;
41308
- const stream = new ReadableStream({
41309
- async pull(controller) {
41310
- let result;
41311
- try {
41312
- result = await reader.read();
41313
- } catch (err) {
41314
- if (cancelling)
41315
- return;
41316
- release();
41317
- controller.error(err);
41318
- return;
41319
- }
41320
- if (cancelling)
41321
- return;
41322
- if (result.done) {
41323
- release();
41324
- controller.close();
41325
- return;
41326
- }
41327
- controller.enqueue(result.value);
41328
- },
41329
- async cancel(reason) {
41330
- cancelling = true;
41331
- try {
41332
- await reader.cancel(reason);
41333
- } catch {} finally {
41334
- release();
41335
- }
41336
- }
41337
- }, { highWaterMark: 0 });
41338
- return new Response(stream, {
41339
- status: response.status,
41340
- statusText: response.statusText,
41341
- headers: response.headers
41342
- });
41343
- }
41344
- function callAbortSignal(c) {
41345
- return readCallVar(c, CALL_ABORT_SIGNAL_KEY);
41346
- }
41347
- function callAborted(c) {
41348
- return callAbortSignal(c)?.aborted === true;
41349
- }
41350
- function callAbortError() {
41351
- return new DOMException("the call's deadline passed; claudish stopped its work", "AbortError");
41352
- }
41353
- function raceCallAbort(p, signal) {
41354
- if (!signal)
41355
- return p;
41356
- p.catch(() => {});
41357
- if (signal.aborted)
41358
- return Promise.reject(callAbortError());
41359
- return new Promise((resolve, reject) => {
41360
- const onAbort = () => reject(callAbortError());
41361
- signal.addEventListener("abort", onAbort, { once: true });
41362
- p.then((value) => {
41363
- signal.removeEventListener("abort", onAbort);
41364
- resolve(value);
41365
- }, (err) => {
41366
- signal.removeEventListener("abort", onAbort);
41367
- reject(err);
41368
- });
41369
- });
41370
- }
41371
- function sleepUnlessAborted(ms, signal) {
41372
- if (signal?.aborted)
41373
- return Promise.resolve(true);
41374
- return new Promise((resolve) => {
41375
- const onAbort = () => {
41376
- clearTimeout(timer);
41377
- resolve(true);
41378
- };
41379
- const timer = setTimeout(() => {
41380
- signal?.removeEventListener("abort", onAbort);
41381
- resolve(false);
41382
- }, ms);
41383
- signal?.addEventListener("abort", onAbort, { once: true });
41384
- });
41385
- }
41386
- function withCallSignal(sig, callSignal) {
41387
- if (!callSignal)
41388
- return sig;
41389
- if (!sig)
41390
- return callSignal;
41391
- return AbortSignal.any([sig, callSignal]);
41392
- }
41393
- function abortedResponse() {
41394
- return new Response(JSON.stringify({
41395
- type: "error",
41396
- error: {
41397
- type: "timeout_error",
41398
- message: "claudish stopped this call: its deadline passed"
41399
- }
41400
- }), {
41401
- status: 408,
41402
- headers: { "content-type": "application/json", [CALL_ABORTED_HEADER]: "1" }
41403
- });
41404
- }
41405
- function hopLogOf(c) {
41406
- return readCallVar(c, HOP_LOG_KEY);
41407
- }
41408
- function recordHopEntry(c, provider, wireModel) {
41409
- const hops = hopLogOf(c);
41410
- if (!hops)
41411
- return;
41412
- const plannedUid = readCallVar(c, PLANNED_HOP_KEY);
41413
- const entry = {
41414
- provider,
41415
- wireModel,
41416
- arm: null,
41417
- billing: null,
41418
- ...plannedUid ? { plannedUid } : {}
41419
- };
41420
- hops.push(entry);
41421
- return entry;
41422
- }
41423
- async function withPlannedHop(c, plannedUid, work) {
41424
- if (!hopLogOf(c))
41425
- return work();
41426
- const previous = readCallVar(c, PLANNED_HOP_KEY);
41427
- writeCallVar(c, PLANNED_HOP_KEY, plannedUid);
41428
- try {
41429
- return await work();
41430
- } finally {
41431
- writeCallVar(c, PLANNED_HOP_KEY, previous);
41432
- }
41433
- }
41434
- var SIGNING_SECRETS_KEY = "claudishSigningSecrets", detachedCallVars, CREDENTIAL_HEADER_NAMES, CREDENTIAL_HEADER_FRAGMENTS, CREDENTIAL_QUERY_NAMES, AUTH_SCHEME_PREFIX, CALL_ABORT_SIGNAL_KEY = "claudishCallAbortSignal", CALL_ABORTED_HEADER = "x-claudish-call-aborted", HOP_LOG_KEY = "claudishHopLog", PLANNED_HOP_KEY = "claudishPlannedHop";
41435
- var init_call_context = __esm(() => {
41436
- init_redact();
41437
- detachedCallVars = new WeakMap;
41438
- CREDENTIAL_HEADER_NAMES = new Set([
41439
- "authorization",
41440
- "proxy-authorization",
41441
- "x-api-key",
41442
- "api-key",
41443
- "x-goog-api-key",
41444
- "cookie"
41445
- ]);
41446
- CREDENTIAL_HEADER_FRAGMENTS = ["token", "secret", "key"];
41447
- CREDENTIAL_QUERY_NAMES = new Set(["key", "api_key", "token", "access_token"]);
41448
- AUTH_SCHEME_PREFIX = /^(?:Bearer|Basic|Token)\s+/i;
41449
- });
41450
-
41451
41566
  // src/handlers/shared/gemini-queue.ts
41452
41567
  function rejectIfAborted(request) {
41453
41568
  if (request.onAbort)
@@ -42094,7 +42209,7 @@ class AntigravityCredentialProvider {
42094
42209
  const token = readSharedAntigravityToken();
42095
42210
  if (!token)
42096
42211
  return;
42097
- const lineage = token.refresh_token ? `refresh:${token.refresh_token}` : token.access_token ? `access:${token.access_token}` : undefined;
42212
+ const lineage = antigravityTokenLineageMaterial(token);
42098
42213
  return lineage ? `${lineage}
42099
42214
  ${antigravityHost()}` : undefined;
42100
42215
  }
@@ -44707,7 +44822,7 @@ var init_dist12 = __esm(() => {
44707
44822
 
44708
44823
  // src/auth/codex-pkce.ts
44709
44824
  import { exec as exec4 } from "child_process";
44710
- import { createHash as createHash12, randomBytes as randomBytes7 } from "crypto";
44825
+ import { createHash as createHash13, randomBytes as randomBytes7 } from "crypto";
44711
44826
  import { createServer } from "http";
44712
44827
  import { promisify as promisify3 } from "util";
44713
44828
  function loginClaims(idToken) {
@@ -44819,7 +44934,7 @@ function waitForCallback(options, deps) {
44819
44934
  async function loginCodexPkce(deps = {}) {
44820
44935
  log("[CodexOAuth] Starting OAuth login flow");
44821
44936
  const verifier = randomBytes7(64).toString("base64url");
44822
- const challenge = createHash12("sha256").update(verifier).digest("base64url");
44937
+ const challenge = createHash13("sha256").update(verifier).digest("base64url");
44823
44938
  const state = randomBytes7(32).toString("base64url");
44824
44939
  const options = {
44825
44940
  port: 1455,
@@ -48499,10 +48614,6 @@ var init_dynamic_models_catalog_store = __esm(() => {
48499
48614
 
48500
48615
  // src/providers/dynamic-models-catalog.ts
48501
48616
  import { createHmac as createHmac2, randomBytes as randomBytes11 } from "crypto";
48502
- function isPersistedListProvider(provider) {
48503
- const def = getProviderByName(provider);
48504
- return def !== undefined && def.modelDiscovery !== undefined && !def.isLocal && (def.tier === "subscription" || def.tier === "dynamic-subscription");
48505
- }
48506
48617
  function nowOf2(opts) {
48507
48618
  return opts?.now ? opts.now() : Date.now();
48508
48619
  }
@@ -48706,6 +48817,7 @@ var init_dynamic_models_catalog = __esm(() => {
48706
48817
  inFlight4 = new Map;
48707
48818
  listeners = new Set;
48708
48819
  credentials.onInvalidate((name) => {
48820
+ invalidateModelDiscovery(name);
48709
48821
  if (name) {
48710
48822
  identityMemo.delete(name);
48711
48823
  liveMemory.delete(name);
@@ -50149,6 +50261,7 @@ var init_devin_request = __esm(() => {
50149
50261
  });
50150
50262
 
50151
50263
  // src/providers/devin/devin-models.ts
50264
+ import { createHash as createHash14 } from "crypto";
50152
50265
  function unaryMetadata(apiKey) {
50153
50266
  return msg(bytes(1, "chisel"), bytes(2, DEVIN_CLI_VERSION), bytes(3, apiKey), bytes(4, "en"), bytes(5, process.platform), bytes(7, DEVIN_CLI_VERSION));
50154
50267
  }
@@ -50336,20 +50449,25 @@ function decodeAllowedUids(body) {
50336
50449
  }
50337
50450
  return uids;
50338
50451
  }
50452
+ function hashApiKey(apiKey) {
50453
+ return createHash14("sha256").update(apiKey).digest("hex");
50454
+ }
50339
50455
  async function getServedDevinModels(opts) {
50340
50456
  const now = Date.now();
50341
- if (!opts?.force && modelsCatalogCache && now - modelsCatalogCacheAt < MODELS_CATALOG_TTL_MS)
50342
- return modelsCatalogCache;
50343
50457
  const apiKey = opts?.apiKey ?? readDevinApiKey();
50344
50458
  if (!apiKey)
50345
- return modelsCatalogCache ?? [];
50459
+ return [];
50460
+ const keyHash = hashApiKey(apiKey);
50461
+ const sameKeyCache = modelsCatalogCacheKeyHash === keyHash ? modelsCatalogCache : null;
50462
+ if (!opts?.force && sameKeyCache && now - modelsCatalogCacheAt < MODELS_CATALOG_TTL_MS)
50463
+ return sameKeyCache;
50346
50464
  try {
50347
50465
  const [configs, allowed] = await Promise.all([
50348
50466
  fetchDevinModelConfigs(apiKey),
50349
50467
  fetchDevinAllowedUids(apiKey)
50350
50468
  ]);
50351
50469
  if (configs.length === 0)
50352
- return modelsCatalogCache ?? [];
50470
+ return sameKeyCache ?? [];
50353
50471
  const entitled = new Set(allowed);
50354
50472
  const served = configs.filter((config) => config.contextWindow > 0 && (entitled.size === 0 || entitled.has(config.uid)));
50355
50473
  if (entitled.size === 0) {
@@ -50357,13 +50475,14 @@ async function getServedDevinModels(opts) {
50357
50475
  }
50358
50476
  modelsCatalogCache = served;
50359
50477
  modelsCatalogCacheAt = now;
50478
+ modelsCatalogCacheKeyHash = keyHash;
50360
50479
  return served;
50361
50480
  } catch (err) {
50362
50481
  log(`[Devin] served-model discovery error: ${err}`);
50363
- return modelsCatalogCache ?? [];
50482
+ return sameKeyCache ?? [];
50364
50483
  }
50365
50484
  }
50366
- var MODEL_CONFIGS_PATH = "/exa.api_server_pb.ApiServerService/GetCliModelConfigs", TEAM_SETTINGS_PATH = "/exa.seat_management_pb.SeatManagementService/GetCliTeamSettings", MODELS_CATALOG_TTL_MS, UNARY_TIMEOUT_MS = 1e4, modelsCatalogCache = null, modelsCatalogCacheAt = 0;
50485
+ var MODEL_CONFIGS_PATH = "/exa.api_server_pb.ApiServerService/GetCliModelConfigs", TEAM_SETTINGS_PATH = "/exa.seat_management_pb.SeatManagementService/GetCliTeamSettings", MODELS_CATALOG_TTL_MS, UNARY_TIMEOUT_MS = 1e4, modelsCatalogCache = null, modelsCatalogCacheAt = 0, modelsCatalogCacheKeyHash = null;
50367
50486
  var init_devin_models = __esm(() => {
50368
50487
  init_logger();
50369
50488
  init_devin_credentials();
@@ -50829,6 +50948,7 @@ var init_model_discovery_builtins = __esm(() => {
50829
50948
  });
50830
50949
 
50831
50950
  // src/providers/model-discovery.ts
50951
+ import { createHash as createHash15 } from "crypto";
50832
50952
  function toModelsCatalogEntry(model) {
50833
50953
  const { id, ...rest } = model;
50834
50954
  return { wireId: id, ...rest };
@@ -50839,6 +50959,10 @@ function registerModelDiscoveryFetcher(format, fetcher) {
50839
50959
  function getModelDiscoveryFetcher(format) {
50840
50960
  return _fetchers.get(format);
50841
50961
  }
50962
+ async function accountFingerprint(providerName) {
50963
+ const identity = await credentials.accountIdentity(providerName, { allowOpPrompt: false });
50964
+ return identity ? createHash15("sha256").update(identity).digest("hex") : undefined;
50965
+ }
50842
50966
  function recordFailure(failure) {
50843
50967
  _failures.set(failure.provider, failure);
50844
50968
  log(`[model-discovery:${failure.provider}] ${describeDiscoveryFailure(failure)}`);
@@ -50876,15 +51000,20 @@ function describeDiscoveryFailure(failure) {
50876
51000
  return `the endpoint answered${at} but listed no models`;
50877
51001
  }
50878
51002
  }
51003
+ function invalidationCount(providerName) {
51004
+ return invalidationsOfAll + (invalidationsByProvider.get(providerName) ?? 0);
51005
+ }
50879
51006
  function invalidateModelDiscovery(provider) {
50880
51007
  if (provider) {
50881
51008
  _cache2.delete(provider);
50882
51009
  _failures.delete(provider);
50883
51010
  coldRefreshes.delete(provider);
51011
+ invalidationsByProvider.set(provider, (invalidationsByProvider.get(provider) ?? 0) + 1);
50884
51012
  } else {
50885
51013
  _cache2.clear();
50886
51014
  _failures.clear();
50887
51015
  coldRefreshes.clear();
51016
+ invalidationsOfAll++;
50888
51017
  }
50889
51018
  }
50890
51019
  function registryModelsEndpoint(providerName, def) {
@@ -51007,7 +51136,6 @@ async function discoverViaFetcher(providerName, format) {
51007
51136
  }
51008
51137
  _failures.delete(providerName);
51009
51138
  log(`[model-discovery:${providerName}] discovered ${models.length} models`);
51010
- _cache2.set(providerName, { models, expiresAt: Date.now() + CACHE_TTL_MS2 });
51011
51139
  return { kind: "served", models };
51012
51140
  }
51013
51141
  async function discoverProviderModelsCatalog(providerName) {
@@ -51041,9 +51169,32 @@ function peekDiscoveredModels(providerName) {
51041
51169
  return cached && cached.expiresAt > Date.now() ? cached.models : undefined;
51042
51170
  }
51043
51171
  async function discoverEveryServedModel(providerName) {
51172
+ if (!getProviderByName(providerName)?.modelDiscovery) {
51173
+ return { kind: "unsupported", reason: "no-descriptor" };
51174
+ }
51175
+ const invalidationsBefore = invalidationCount(providerName);
51176
+ const perAccount = isPersistedListProvider(providerName);
51177
+ const accountBefore = perAccount ? await accountFingerprint(providerName) : undefined;
51044
51178
  const cached = _cache2.get(providerName);
51045
- if (cached && cached.expiresAt > Date.now())
51179
+ if (cached && cached.expiresAt > Date.now() && cached.account === accountBefore) {
51046
51180
  return { kind: "served", models: cached.models };
51181
+ }
51182
+ const outcome = await fetchServedModels(providerName);
51183
+ if (outcome.kind !== "served")
51184
+ return outcome;
51185
+ const accountAfter = perAccount ? await accountFingerprint(providerName) : undefined;
51186
+ if (accountBefore && accountAfter && accountBefore !== accountAfter)
51187
+ return outcome;
51188
+ if (invalidationCount(providerName) !== invalidationsBefore)
51189
+ return outcome;
51190
+ _cache2.set(providerName, {
51191
+ models: outcome.models,
51192
+ expiresAt: Date.now() + CACHE_TTL_MS2,
51193
+ account: accountAfter ?? accountBefore
51194
+ });
51195
+ return outcome;
51196
+ }
51197
+ async function fetchServedModels(providerName) {
51047
51198
  const def = getProviderByName(providerName);
51048
51199
  const descriptor = def?.modelDiscovery;
51049
51200
  if (!def || !descriptor)
@@ -51137,7 +51288,6 @@ async function discoverEveryServedModel(providerName) {
51137
51288
  const models = parsed.models;
51138
51289
  _failures.delete(providerName);
51139
51290
  log(`[model-discovery:${providerName}] discovered ${models.length} models from ${endpoint}: ` + models.map((m) => `${m.id}(${m.contextWindow ?? "?"})`).join(", "));
51140
- _cache2.set(providerName, { models, expiresAt: Date.now() + CACHE_TTL_MS2 });
51141
51291
  return { kind: "served", models };
51142
51292
  }
51143
51293
  async function discoverProviderModels(providerName) {
@@ -51200,7 +51350,7 @@ function rankDiscoveredModels(models) {
51200
51350
  return diff !== 0 ? diff : compareByReleaseDateDesc(a, b);
51201
51351
  });
51202
51352
  }
51203
- var _fetchers, CACHE_TTL_MS2, FETCH_TIMEOUT_MS3 = 5000, _cache2, _failures, coldRefreshes, MIN_CREATED_SECONDS = 946684800, MAX_CREATED_SECONDS = 4102444800, CONTINUATION_FIELDS, LIVE_DISCOVERY_BOUND_MS = 2000;
51353
+ var _fetchers, CACHE_TTL_MS2, FETCH_TIMEOUT_MS3 = 5000, _cache2, _failures, coldRefreshes, invalidationsByProvider, invalidationsOfAll = 0, MIN_CREATED_SECONDS = 946684800, MAX_CREATED_SECONDS = 4102444800, CONTINUATION_FIELDS, LIVE_DISCOVERY_BOUND_MS = 2000;
51204
51354
  var init_model_discovery = __esm(() => {
51205
51355
  init_authority();
51206
51356
  init_logger();
@@ -51211,6 +51361,7 @@ var init_model_discovery = __esm(() => {
51211
51361
  _cache2 = new Map;
51212
51362
  _failures = new Map;
51213
51363
  coldRefreshes = new Map;
51364
+ invalidationsByProvider = new Map;
51214
51365
  CONTINUATION_FIELDS = ["has_more", "next", "next_page", "next_page_token"];
51215
51366
  });
51216
51367
 
@@ -59756,12 +59907,12 @@ var init_ollamacloud = __esm(() => {
59756
59907
  });
59757
59908
 
59758
59909
  // src/providers/transport/conversation-key.ts
59759
- import { createHash as createHash13, randomBytes as randomBytes13 } from "crypto";
59910
+ import { createHash as createHash16, randomBytes as randomBytes13 } from "crypto";
59760
59911
  function conversationKey(claudeRequest) {
59761
59912
  const sessionId = extractSessionId(claudeRequest);
59762
59913
  if (!sessionId)
59763
59914
  return `claudish_${FALLBACK_CONVERSATION_KEY}`;
59764
- return `claudish_${createHash13("sha256").update(sessionId).digest("hex").slice(0, 32)}`;
59915
+ return `claudish_${createHash16("sha256").update(sessionId).digest("hex").slice(0, 32)}`;
59765
59916
  }
59766
59917
  var FALLBACK_CONVERSATION_KEY;
59767
59918
  var init_conversation_key = __esm(() => {
@@ -61281,6 +61432,10 @@ function getProviderByName(name) {
61281
61432
  return builtin;
61282
61433
  return getRuntimeProviders().get(name);
61283
61434
  }
61435
+ function isPersistedListProvider(provider) {
61436
+ const def = getProviderByName(provider);
61437
+ return def !== undefined && def.modelDiscovery !== undefined && !def.isLocal && (def.tier === "subscription" || def.tier === "dynamic-subscription");
61438
+ }
61284
61439
  function getApiKeyInfo(providerName) {
61285
61440
  const def = getProviderByName(providerName);
61286
61441
  if (!def)
@@ -74619,14 +74774,14 @@ var init_prehydrate = __esm(() => {
74619
74774
  });
74620
74775
 
74621
74776
  // src/auth/claude-code-facts.ts
74622
- import { createHash as createHash14 } from "crypto";
74777
+ import { createHash as createHash17 } from "crypto";
74623
74778
  import { homedir as homedir33 } from "os";
74624
74779
  import { isAbsolute as isAbsolute2, resolve as resolve4 } from "path";
74625
74780
  function defaultConfigDir(env) {
74626
74781
  return resolve4(env.HOME || homedir33(), ".claude");
74627
74782
  }
74628
74783
  function configDirHash(configDir) {
74629
- return createHash14("sha256").update(configDir).digest("hex").slice(0, 8);
74784
+ return createHash17("sha256").update(configDir).digest("hex").slice(0, 8);
74630
74785
  }
74631
74786
  function claudeCodeKeychainService(env = process.env) {
74632
74787
  const raw = env.CLAUDE_CONFIG_DIR?.trim();
@@ -92866,6 +93021,111 @@ var init_handler_set = __esm(() => {
92866
93021
  init_composed_handler();
92867
93022
  });
92868
93023
 
93024
+ // src/handlers/shared/anthropic-forward.ts
93025
+ function inboundAuthHeaders(incoming) {
93026
+ const out = {};
93027
+ const authorization = incoming.get("authorization");
93028
+ const apiKey = incoming.get("x-api-key");
93029
+ if (authorization)
93030
+ out.authorization = authorization;
93031
+ if (apiKey)
93032
+ out["x-api-key"] = apiKey;
93033
+ return out;
93034
+ }
93035
+ function connectionNamed(headers) {
93036
+ const named = new Set;
93037
+ for (const token of (headers.get("connection") ?? "").split(",")) {
93038
+ const name = token.trim().toLowerCase();
93039
+ if (name)
93040
+ named.add(name);
93041
+ }
93042
+ return named;
93043
+ }
93044
+ function requestHeadersToForward(incoming) {
93045
+ const named = connectionNamed(incoming);
93046
+ const out = {};
93047
+ incoming.forEach((value, name) => {
93048
+ const key = name.toLowerCase();
93049
+ if (!ALLOWED_NAMES.has(key))
93050
+ return;
93051
+ if (HOP_BY_HOP.has(key) || named.has(key) || key.startsWith(INTERNAL_PREFIX))
93052
+ return;
93053
+ out[key] = value;
93054
+ });
93055
+ return out;
93056
+ }
93057
+ function querySegmentName(segment) {
93058
+ const eq = segment.indexOf("=");
93059
+ const rawName = eq < 0 ? segment : segment.slice(0, eq);
93060
+ try {
93061
+ return decodeURIComponent(rawName.replace(/\+/g, " "));
93062
+ } catch {
93063
+ return null;
93064
+ }
93065
+ }
93066
+ function forwardedSearch(c) {
93067
+ const url = c.req.url;
93068
+ if (typeof url !== "string" || url.length === 0)
93069
+ return "";
93070
+ let search;
93071
+ try {
93072
+ search = new URL(url).search;
93073
+ } catch {
93074
+ return "";
93075
+ }
93076
+ const kept = search.slice(1).split("&").filter((segment) => {
93077
+ const name = querySegmentName(segment);
93078
+ return name !== null && ALLOWED_QUERY_NAMES.has(name);
93079
+ });
93080
+ return kept.length > 0 ? `?${kept.join("&")}` : "";
93081
+ }
93082
+ function recordInboundBody(c, raw, parsed) {
93083
+ c.set(INBOUND_BODY_KEY, { raw, canonical: JSON.stringify(parsed) });
93084
+ }
93085
+ function bodyToForward(c, payload) {
93086
+ const serialized = JSON.stringify(payload);
93087
+ const inbound = c.get(INBOUND_BODY_KEY);
93088
+ return inbound !== undefined && inbound.canonical === serialized ? inbound.raw : serialized;
93089
+ }
93090
+ var ALLOWED_NAMES, HOP_BY_HOP, INTERNAL_PREFIX = "x-claudish-", ALLOWED_QUERY_NAMES, INBOUND_BODY_KEY = "inboundBody";
93091
+ var init_anthropic_forward = __esm(() => {
93092
+ ALLOWED_NAMES = new Set([
93093
+ "authorization",
93094
+ "x-api-key",
93095
+ "content-type",
93096
+ "accept",
93097
+ "accept-encoding",
93098
+ "user-agent",
93099
+ "x-app",
93100
+ "anthropic-beta",
93101
+ "anthropic-version",
93102
+ "anthropic-dangerous-direct-browser-access",
93103
+ "x-claude-code-session-id",
93104
+ "x-stainless-arch",
93105
+ "x-stainless-lang",
93106
+ "x-stainless-os",
93107
+ "x-stainless-package-version",
93108
+ "x-stainless-retry-count",
93109
+ "x-stainless-runtime",
93110
+ "x-stainless-runtime-version",
93111
+ "x-stainless-timeout"
93112
+ ]);
93113
+ HOP_BY_HOP = new Set([
93114
+ "connection",
93115
+ "keep-alive",
93116
+ "proxy-connection",
93117
+ "proxy-authenticate",
93118
+ "proxy-authorization",
93119
+ "te",
93120
+ "trailer",
93121
+ "transfer-encoding",
93122
+ "upgrade",
93123
+ "host",
93124
+ "content-length"
93125
+ ]);
93126
+ ALLOWED_QUERY_NAMES = new Set(["beta"]);
93127
+ });
93128
+
92869
93129
  // src/handlers/shared/thinking-signature.ts
92870
93130
  function isUnsignedThinking(block) {
92871
93131
  if (!block || typeof block !== "object")
@@ -92956,7 +93216,10 @@ class NativeHandler {
92956
93216
  }
92957
93217
  async handle(c, incoming) {
92958
93218
  const payload = await this.applyRequestHooks(c, incoming);
92959
- const originalHeaders = c.req.header();
93219
+ const headers = {
93220
+ ...requestHeadersToForward(c.req.raw.headers),
93221
+ ...inboundAuthHeaders(c.req.raw.headers)
93222
+ };
92960
93223
  const target = payload.model;
92961
93224
  const strippedThinking = stripUnsignedThinkingBlocks(payload.messages);
92962
93225
  if (strippedThinking > 0) {
@@ -92965,22 +93228,15 @@ class NativeHandler {
92965
93228
  const advisorSwapped = c.get(ADVISOR_SWAPPED_CONTEXT_KEY) === true;
92966
93229
  log(`
92967
93230
  === [NATIVE] Claude Code \u2192 Anthropic API Request ===`);
92968
- log(`[Native] x-api-key: ${originalHeaders["x-api-key"] ? maskCredential(originalHeaders["x-api-key"]) : "(not set)"}`);
92969
- log(`[Native] authorization: ${originalHeaders.authorization ? maskCredential(originalHeaders.authorization) : "(not set)"}`);
93231
+ log(`[Native] x-api-key: ${headers["x-api-key"] ? maskCredential(headers["x-api-key"]) : "(not set)"}`);
93232
+ log(`[Native] authorization: ${headers.authorization ? maskCredential(headers.authorization) : "(not set)"}`);
92970
93233
  log(`Request body (Model: ${target}):`);
92971
93234
  log(`=== End Request ===
92972
93235
  `);
92973
- const headers = {
92974
- "Content-Type": "application/json",
92975
- "anthropic-version": originalHeaders["anthropic-version"] || "2023-06-01"
92976
- };
92977
- if (originalHeaders.authorization) {
92978
- headers.authorization = originalHeaders.authorization;
92979
- }
92980
- if (originalHeaders["x-api-key"]) {
92981
- headers["x-api-key"] = originalHeaders["x-api-key"];
92982
- }
92983
- if (!originalHeaders.authorization && !originalHeaders["x-api-key"]) {
93236
+ headers["content-type"] = "application/json";
93237
+ if (!headers["anthropic-version"])
93238
+ headers["anthropic-version"] = "2023-06-01";
93239
+ if (!headers.authorization && !headers["x-api-key"]) {
92984
93240
  let fallbackKey = this.apiKey;
92985
93241
  if (!fallbackKey) {
92986
93242
  const auth = await credentials.getRequestAuth("native-anthropic", { model: target });
@@ -92990,28 +93246,27 @@ class NativeHandler {
92990
93246
  headers["x-api-key"] = fallbackKey;
92991
93247
  }
92992
93248
  }
92993
- if (originalHeaders["anthropic-beta"]) {
92994
- const incomingBeta = originalHeaders["anthropic-beta"];
92995
- if (advisorSwapped) {
92996
- const { stripped, changed } = stripAdvisorBeta(incomingBeta);
92997
- if (changed) {
92998
- log(`[Native][advisor-swap] stripped advisor-tool beta; before=${incomingBeta} after=${stripped ?? "(empty)"}`);
92999
- logAdvisorEvent(loadAdvisorSwapConfig(this.advisorModels, this.advisorCollector), {
93000
- kind: "beta_stripped",
93001
- before: incomingBeta,
93002
- after: stripped ?? ""
93003
- });
93004
- }
93005
- if (stripped)
93006
- headers["anthropic-beta"] = stripped;
93007
- } else {
93008
- headers["anthropic-beta"] = incomingBeta;
93249
+ const incomingBeta = headers["anthropic-beta"];
93250
+ if (incomingBeta && advisorSwapped) {
93251
+ const { stripped, changed } = stripAdvisorBeta(incomingBeta);
93252
+ if (changed) {
93253
+ log(`[Native][advisor-swap] stripped advisor-tool beta; before=${incomingBeta} after=${stripped ?? "(empty)"}`);
93254
+ logAdvisorEvent(loadAdvisorSwapConfig(this.advisorModels, this.advisorCollector), {
93255
+ kind: "beta_stripped",
93256
+ before: incomingBeta,
93257
+ after: stripped ?? ""
93258
+ });
93009
93259
  }
93260
+ if (stripped)
93261
+ headers["anthropic-beta"] = stripped;
93262
+ else
93263
+ delete headers["anthropic-beta"];
93010
93264
  }
93011
- addSigningSecrets(c, credentialValuesFromRequest(headers));
93012
- const body = JSON.stringify(payload);
93265
+ const url = `${this.baseUrl}/v1/messages${forwardedSearch(c)}`;
93266
+ addSigningSecrets(c, credentialValuesFromRequest(headers, url));
93267
+ const body = bodyToForward(c, payload);
93013
93268
  try {
93014
- const anthropicResponse = await fetch(`${this.baseUrl}/v1/messages`, {
93269
+ const anthropicResponse = await fetch(url, {
93015
93270
  method: "POST",
93016
93271
  headers,
93017
93272
  body
@@ -93163,6 +93418,7 @@ var init_native_handler = __esm(() => {
93163
93418
  init_advisor_decorator();
93164
93419
  init_native_handler_advisor();
93165
93420
  init_anthropic_error();
93421
+ init_anthropic_forward();
93166
93422
  init_call_context();
93167
93423
  });
93168
93424
 
@@ -94281,7 +94537,9 @@ ${plan.hint}` : `[Route] ${plan.reason}`;
94281
94537
  app.post("/v1/messages", async (c) => {
94282
94538
  let handlerThrew = false;
94283
94539
  try {
94284
- const body = await c.req.json();
94540
+ const raw = await c.req.text();
94541
+ const body = JSON.parse(raw);
94542
+ recordInboundBody(c, raw, body);
94285
94543
  log(`[RequestMeta] model=${body.model} output_config=${JSON.stringify(body.output_config) ?? "(none)"} metadata=${JSON.stringify(body.metadata) ?? "(none)"} anthropic-beta=${c.req.header("anthropic-beta") ?? "(none)"}`);
94286
94544
  maybeCaptureClassifierRequest(c, body);
94287
94545
  if (!monitorMode && options.classifier?.enabled && isAutoModeClassifierRequest(body)) {
@@ -94359,6 +94617,7 @@ var init_proxy_server = __esm(() => {
94359
94617
  init_native_handler_advisor();
94360
94618
  init_native_handler();
94361
94619
  init_anthropic_error();
94620
+ init_anthropic_forward();
94362
94621
  init_call_context();
94363
94622
  init_hop_decision();
94364
94623
  init_hooks();
@@ -97189,6 +97448,30 @@ var init_pane_launch = __esm(() => {
97189
97448
  FATAL_MAGMUX_STDERR = /ignoring --id|magmux: (?:--sock-dir|MAGMUX_SOCK_DIR) |magmux: socket/;
97190
97449
  });
97191
97450
 
97451
+ // src/process-tree.ts
97452
+ function waitForExit(proc, ms) {
97453
+ if (proc.exitCode !== null || proc.signalCode !== null)
97454
+ return Promise.resolve(true);
97455
+ return new Promise((resolve) => {
97456
+ let settled = false;
97457
+ const done = (value) => {
97458
+ if (settled)
97459
+ return;
97460
+ settled = true;
97461
+ proc.off("exit", onExit);
97462
+ resolve(value);
97463
+ };
97464
+ const onExit = () => done(true);
97465
+ proc.once("exit", onExit);
97466
+ const t = setTimeout(() => done(false), ms);
97467
+ t.unref?.();
97468
+ });
97469
+ }
97470
+ var KILL_PROCESS_GROUP;
97471
+ var init_process_tree = __esm(() => {
97472
+ KILL_PROCESS_GROUP = process.platform !== "win32";
97473
+ });
97474
+
97192
97475
  // src/recovery/types.ts
97193
97476
  var UI_LEASE_MS = 1e4, FRAME_TICK_MS = 1000;
97194
97477
 
@@ -98655,7 +98938,7 @@ Or set CLAUDE_PATH to your custom installation:`);
98655
98938
  } catch {}
98656
98939
  });
98657
98940
  }
98658
- setupSignalHandlers(proc, tempSettingsPath, config.quiet, onCleanup);
98941
+ const signalShutdown = setupSignalHandlers(proc, tempSettingsPath, config.quiet, onCleanup);
98659
98942
  const { exitCode, exitSignal } = await new Promise((resolve) => {
98660
98943
  proc.on("exit", (code, signal) => {
98661
98944
  setClaudeCodeRunning(false);
@@ -98682,22 +98965,45 @@ Or set CLAUDE_PATH to your custom installation:`);
98682
98965
  try {
98683
98966
  unlinkSync11(tempSettingsPath);
98684
98967
  } catch {}
98968
+ signalShutdown.launcherCleanupDone();
98969
+ if (signalShutdown.started())
98970
+ return new Promise(() => {});
98685
98971
  return exitCode;
98686
98972
  }
98687
98973
  function sessionOutcomeOf(exitCode) {
98688
98974
  return exitCode === 0 ? { state: "COMPLETED", reason: null, exitCode } : { state: "FAILED", reason: "child_exited", exitCode };
98689
98975
  }
98976
+ function delay(ms) {
98977
+ return new Promise((resolve) => {
98978
+ const t = setTimeout(resolve, Math.max(0, ms));
98979
+ t.unref?.();
98980
+ });
98981
+ }
98690
98982
  function setupSignalHandlers(proc, tempSettingsPath, quiet, onCleanup) {
98691
98983
  const signals = isWindows2() ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"];
98692
- claimSignalExit();
98693
- for (const signal of signals) {
98694
- process.on(signal, () => {
98695
- releaseTerminalIsolation();
98696
- if (!quiet) {
98697
- console.error(`
98698
- [claudish] Received ${signal}, shutting down...`);
98984
+ let shuttingDown = null;
98985
+ let markLauncherCleanupDone = () => {};
98986
+ const launcherCleanup = new Promise((resolve) => {
98987
+ markLauncherCleanupDone = resolve;
98988
+ });
98989
+ const shutdown = async (signal) => {
98990
+ const startedAt = Date.now();
98991
+ try {
98992
+ proc.kill("SIGTERM");
98993
+ if (!await waitForExit(proc, SIGNAL_CHILD_EXIT_GRACE_MS)) {
98994
+ log(`[claudish] Claude Code did not exit within ${SIGNAL_CHILD_EXIT_GRACE_MS} ms of SIGTERM; sending SIGKILL`);
98995
+ try {
98996
+ proc.kill("SIGKILL");
98997
+ } catch {}
98998
+ await waitForExit(proc, SIGNAL_CHILD_KILL_WAIT_MS);
98699
98999
  }
98700
- proc.kill();
99000
+ await Promise.race([
99001
+ launcherCleanup,
99002
+ delay(SIGNAL_SHUTDOWN_BUDGET_MS - (Date.now() - startedAt))
99003
+ ]);
99004
+ } catch (err) {
99005
+ log(`[claudish] Signal shutdown error: ${err}`);
99006
+ } finally {
98701
99007
  if (onCleanup) {
98702
99008
  try {
98703
99009
  onCleanup();
@@ -98707,8 +99013,28 @@ function setupSignalHandlers(proc, tempSettingsPath, quiet, onCleanup) {
98707
99013
  unlinkSync11(tempSettingsPath);
98708
99014
  } catch {}
98709
99015
  process.exit(signalExitCode(signal));
99016
+ }
99017
+ };
99018
+ claimSignalExit();
99019
+ for (const signal of signals) {
99020
+ process.on(signal, () => {
99021
+ if (shuttingDown) {
99022
+ log(`[claudish] Received ${signal} while shutting down from ${shuttingDown}; ignored`);
99023
+ return;
99024
+ }
99025
+ shuttingDown = signal;
99026
+ releaseTerminalIsolation();
99027
+ if (!quiet) {
99028
+ console.error(`
99029
+ [claudish] Received ${signal}, shutting down...`);
99030
+ }
99031
+ shutdown(signal);
98710
99032
  });
98711
99033
  }
99034
+ return {
99035
+ started: () => shuttingDown !== null,
99036
+ launcherCleanupDone: () => markLauncherCleanupDone()
99037
+ };
98712
99038
  }
98713
99039
  async function findClaudeBinary(env = process.env) {
98714
99040
  const isWindows = process.platform === "win32";
@@ -98809,7 +99135,7 @@ var restoreTerminal = null, macosKeychainAnthropicMemo, defaultKeychainAnthropic
98809
99135
  }
98810
99136
  macosKeychainAnthropicMemo.set(memoKey, found);
98811
99137
  return found;
98812
- }, CLAUDISH_PLACEHOLDER_API_KEY = "sk-ant-api03-placeholder-not-used-proxy-handles-auth-with-openrouter-key-xxxxxxxxxxxxxxxxxxxxx", CLAUDISH_PLACEHOLDER_AUTH_TOKEN = "placeholder-token-not-used-proxy-handles-auth", STALE_TOKEN_FILE_MS, MAX_TOKEN_FILES_SCANNED = 4000, CLAUDE_CODE_DEFAULT_MAX_CONTEXT = 200000, USER_STATUS_LINE_TIMEOUT_SECONDS = 3, MIN_AUTO_COMPACT_WINDOW = 200000, MAX_AUTO_COMPACT_WINDOW = 1e6, ADVISOR_TOOL_ENV_VAR = "CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL", CLAUDISH_CHILD_ADVISOR_MODEL = "sonnet", CHILD_STDERR_NOISE;
99138
+ }, CLAUDISH_PLACEHOLDER_API_KEY = "sk-ant-api03-placeholder-not-used-proxy-handles-auth-with-openrouter-key-xxxxxxxxxxxxxxxxxxxxx", CLAUDISH_PLACEHOLDER_AUTH_TOKEN = "placeholder-token-not-used-proxy-handles-auth", STALE_TOKEN_FILE_MS, MAX_TOKEN_FILES_SCANNED = 4000, CLAUDE_CODE_DEFAULT_MAX_CONTEXT = 200000, USER_STATUS_LINE_TIMEOUT_SECONDS = 3, MIN_AUTO_COMPACT_WINDOW = 200000, MAX_AUTO_COMPACT_WINDOW = 1e6, ADVISOR_TOOL_ENV_VAR = "CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL", CLAUDISH_CHILD_ADVISOR_MODEL = "sonnet", CHILD_STDERR_NOISE, SIGNAL_CHILD_EXIT_GRACE_MS = 3000, SIGNAL_CHILD_KILL_WAIT_MS = 500, SIGNAL_SHUTDOWN_BUDGET_MS = 4000;
98813
99139
  var init_claude_runner = __esm(() => {
98814
99140
  init_model_catalog();
98815
99141
  init_claude_code_facts();
@@ -98825,6 +99151,7 @@ var init_claude_runner = __esm(() => {
98825
99151
  init_logger();
98826
99152
  init_child_env();
98827
99153
  init_pane_launch();
99154
+ init_process_tree();
98828
99155
  init_profile_config();
98829
99156
  init_model_discovery();
98830
99157
  init_model_parser();
@@ -99858,30 +100185,6 @@ var init_gate_binding = __esm(() => {
99858
100185
  init_input_gate();
99859
100186
  });
99860
100187
 
99861
- // src/process-tree.ts
99862
- function waitForExit(proc, ms) {
99863
- if (proc.exitCode !== null || proc.signalCode !== null)
99864
- return Promise.resolve(true);
99865
- return new Promise((resolve) => {
99866
- let settled = false;
99867
- const done = (value) => {
99868
- if (settled)
99869
- return;
99870
- settled = true;
99871
- proc.off("exit", onExit);
99872
- resolve(value);
99873
- };
99874
- const onExit = () => done(true);
99875
- proc.once("exit", onExit);
99876
- const t = setTimeout(() => done(false), ms);
99877
- t.unref?.();
99878
- });
99879
- }
99880
- var KILL_PROCESS_GROUP;
99881
- var init_process_tree = __esm(() => {
99882
- KILL_PROCESS_GROUP = process.platform !== "win32";
99883
- });
99884
-
99885
100188
  // src/pane/pane-reap.ts
99886
100189
  function alive(p) {
99887
100190
  return !!p && p.exitCode === null && p.signalCode === null;
@@ -121887,14 +122190,14 @@ function reportFetchFailure(state, cache, now) {
121887
122190
  if (state === "stale") {
121888
122191
  const ageMs = now.getTime() - Date.parse(cache.lastUpdated);
121889
122192
  const ageStr = humanizeAge(ageMs);
121890
- process.stderr.write(`WARNING: Catalog stale (${ageStr}). Using cached version. Run \`claudish --models-refresh\` to retry.
122193
+ process.stderr.write(`WARNING: The ${MODEL_CATALOG_NAME} is stale (${ageStr}). Using cached version. Run \`claudish --models-refresh\` to retry.
121891
122194
  `);
121892
122195
  return "warned";
121893
122196
  }
121894
122197
  if (state === "fresh") {
121895
122198
  const ageMs = now.getTime() - Date.parse(cache.lastUpdated);
121896
122199
  const ageStr = humanizeAge(ageMs);
121897
- process.stderr.write(`WARNING: Catalog refresh failed (cache age ${ageStr}). Using cached version.
122200
+ process.stderr.write(`WARNING: Could not refresh the ${MODEL_CATALOG_NAME} (cache age ${ageStr}). Using cached version.
121898
122201
  `);
121899
122202
  return "warned";
121900
122203
  }