claude-use 12.0.1 → 12.2.0

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/index.cjs CHANGED
@@ -1012,6 +1012,8 @@ var init_schema = __esm({
1012
1012
  kind: import_zod3.z.literal("http").optional(),
1013
1013
  displayName: import_zod3.z.string().min(1),
1014
1014
  baseUrl: import_zod3.z.url(),
1015
+ /** How long opening a TCP connection to `baseUrl` may take before the provider counts as unreachable: the door's forwarding gives up and answers naming the provider, and `doctor`, `check` and a launch's probe are bounded by it. Defaults to `DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS`. Bounds the connect only, never the wait for the answer. */
1016
+ connectTimeoutMs: import_zod3.z.int().positive().optional(),
1015
1017
  credential: ProviderCredentialSchema,
1016
1018
  env: ProviderEnvSchema.optional(),
1017
1019
  /** Extra models `/model` lists beside the ones the tier settings name. */
@@ -5269,6 +5271,23 @@ function identityIdResolver(identitiesDir, fs17) {
5269
5271
  return identityIdIn(records, name);
5270
5272
  };
5271
5273
  }
5274
+ function identityReader(identitiesDir, fs17) {
5275
+ const read = /* @__PURE__ */ new Map();
5276
+ const readOnce = (file) => {
5277
+ if (!read.has(file)) {
5278
+ read.set(file, fs17.readConfigFile(file));
5279
+ }
5280
+ return read.get(file);
5281
+ };
5282
+ const idOf = identityIdResolver(identitiesDir, { readdir: fs17.readdir, readConfigFile: readOnce });
5283
+ return {
5284
+ idOf,
5285
+ load: (name) => {
5286
+ const id = idOf(name);
5287
+ return id === void 0 ? void 0 : loadConfigFile(import_node_path15.default.join(identitiesDir, id, IDENTITY_FILE), IdentitySchema, readOnce)?.config;
5288
+ }
5289
+ };
5290
+ }
5272
5291
  function loadIdentity(identitiesDir, name, fs17) {
5273
5292
  if (!isFileName(name)) {
5274
5293
  throw new UnsafeNameError(name, "identity", FILE_NAME_RULE);
@@ -9243,7 +9262,8 @@ var init_identityAccounts = __esm({
9243
9262
  function candidateHeading(candidate) {
9244
9263
  const score = candidate.score === void 0 ? "" : ` score ${candidate.score.toFixed(2)}${candidate.scoreWindow === "fiveHour" ? " by 5h reset" : " by 7d reset"}`;
9245
9264
  const dry = candidate.feasible ? "" : " (5h would run dry)";
9246
- return `[${candidate.class}${score}]${dry}`;
9265
+ const onProvider = candidate.provider === void 0 ? "" : ` on provider ${candidate.provider}`;
9266
+ return `[${candidate.class}${score}]${dry}${onProvider}`;
9247
9267
  }
9248
9268
  function percent(fraction) {
9249
9269
  return `${String(Math.round(fraction * PERCENT))}%`;
@@ -9285,6 +9305,9 @@ function planOf(account) {
9285
9305
  }
9286
9306
  return { kind: "subscription", capacity: 1, recognised: BASE_TIER.test(tier), ...tierField };
9287
9307
  }
9308
+ function planOfProviderQuota(quota) {
9309
+ return planOf(quota?.level === void 0 ? void 0 : { organizationRateLimitTier: quota.level });
9310
+ }
9288
9311
  var import_zod17, PlanClassSchema, TIER_MULTIPLIER, ZERO_TIER, BASE_TIER;
9289
9312
  var init_plan2 = __esm({
9290
9313
  "src/usage/plan.ts"() {
@@ -9344,12 +9367,58 @@ var init_middleware = __esm({
9344
9367
  }
9345
9368
  });
9346
9369
 
9370
+ // src/usage/windowLengths.ts
9371
+ var MS_PER_HOUR2, HOURS_PER_DAY3, FIVE_HOURS, SEVEN_DAYS, FIVE_HOUR_WINDOW_MS, SEVEN_DAY_WINDOW_MS;
9372
+ var init_windowLengths = __esm({
9373
+ "src/usage/windowLengths.ts"() {
9374
+ "use strict";
9375
+ MS_PER_HOUR2 = 36e5;
9376
+ HOURS_PER_DAY3 = 24;
9377
+ FIVE_HOURS = 5;
9378
+ SEVEN_DAYS = 7;
9379
+ FIVE_HOUR_WINDOW_MS = FIVE_HOURS * MS_PER_HOUR2;
9380
+ SEVEN_DAY_WINDOW_MS = SEVEN_DAYS * HOURS_PER_DAY3 * MS_PER_HOUR2;
9381
+ }
9382
+ });
9383
+
9384
+ // src/usage/providerWindows.ts
9385
+ function bindingWindow(quota, periodMs) {
9386
+ const same = quota.windows.filter((window) => window.periodMs === periodMs);
9387
+ const tightest = same.reduce((binding, window) => binding === void 0 || window.utilization > binding.utilization ? window : binding, void 0);
9388
+ if (tightest === void 0) {
9389
+ return void 0;
9390
+ }
9391
+ return { utilization: tightest.utilization, ...tightest.resetsAt === void 0 ? {} : { resetsAt: tightest.resetsAt }, status: tightest.utilization >= 1 ? "rejected" : "allowed" };
9392
+ }
9393
+ function unifiedFromQuota(quota) {
9394
+ const fiveHour = bindingWindow(quota, FIVE_HOUR_WINDOW_MS);
9395
+ const sevenDay = bindingWindow(quota, SEVEN_DAY_WINDOW_MS);
9396
+ return fiveHour === void 0 && sevenDay === void 0 ? void 0 : { ...fiveHour === void 0 ? {} : { fiveHour }, ...sevenDay === void 0 ? {} : { sevenDay } };
9397
+ }
9398
+ function rankingWindowsOf(provider, state) {
9399
+ const recorded = state?.rateLimit;
9400
+ if (provider === void 0) {
9401
+ return recorded?.unified === void 0 ? void 0 : { unified: recorded.unified, observedAt: recorded.observedAt };
9402
+ }
9403
+ if (recorded?.unified !== void 0 && (recorded.unified.fiveHour !== void 0 || recorded.unified.sevenDay !== void 0)) {
9404
+ return { unified: recorded.unified, observedAt: recorded.observedAt };
9405
+ }
9406
+ const pulled = state?.quota === void 0 ? void 0 : unifiedFromQuota(state.quota);
9407
+ return state?.quota === void 0 || pulled === void 0 ? void 0 : { unified: pulled, observedAt: state.quota.observedAt };
9408
+ }
9409
+ var init_providerWindows = __esm({
9410
+ "src/usage/providerWindows.ts"() {
9411
+ "use strict";
9412
+ init_windowLengths();
9413
+ }
9414
+ });
9415
+
9347
9416
  // src/usage/quotaFacts.ts
9348
9417
  function windowFacts(window, nowMs) {
9349
9418
  if (window?.utilization === void 0 || window.resetsAt === void 0) {
9350
9419
  return void 0;
9351
9420
  }
9352
- return { remaining: Math.max(0, 1 - window.utilization), utilization: window.utilization, hoursUntilReset: Math.max(0, (Date.parse(window.resetsAt) - nowMs) / MS_PER_HOUR2) };
9421
+ return { remaining: Math.max(0, 1 - window.utilization), utilization: window.utilization, hoursUntilReset: Math.max(0, (Date.parse(window.resetsAt) - nowMs) / MS_PER_HOUR3) };
9353
9422
  }
9354
9423
  function quotaFactsOf(unified, nowMs) {
9355
9424
  const fiveHour = windowFacts(unified?.fiveHour, nowMs);
@@ -9357,19 +9426,16 @@ function quotaFactsOf(unified, nowMs) {
9357
9426
  const extraUsage = windowFacts(unified === void 0 ? void 0 : soleOverageWindow(unified), nowMs);
9358
9427
  return { ...fiveHour === void 0 ? {} : { fiveHour }, ...sevenDay === void 0 ? {} : { sevenDay }, ...extraUsage === void 0 ? {} : { extraUsage } };
9359
9428
  }
9360
- var MS_PER_HOUR2;
9429
+ var MS_PER_HOUR3;
9361
9430
  var init_quotaFacts = __esm({
9362
9431
  "src/usage/quotaFacts.ts"() {
9363
9432
  "use strict";
9364
9433
  init_rateLimit();
9365
- MS_PER_HOUR2 = 36e5;
9434
+ MS_PER_HOUR3 = 36e5;
9366
9435
  }
9367
9436
  });
9368
9437
 
9369
9438
  // src/usage/pick.ts
9370
- function unifiedOf(state) {
9371
- return state?.rateLimit?.unified;
9372
- }
9373
9439
  function limitBlockedUntil(state, nowMs) {
9374
9440
  const limit = state?.lastLimit;
9375
9441
  if (state === void 0 || limit === void 0) {
@@ -9459,6 +9525,10 @@ function assessRefusedNested(member, nested, nowMs) {
9459
9525
  };
9460
9526
  }
9461
9527
  function assess(member, nowMs) {
9528
+ const assessment = assessMember(member, nowMs);
9529
+ return member.provider === void 0 ? assessment : { ...assessment, candidate: { ...assessment.candidate, provider: member.provider } };
9530
+ }
9531
+ function assessMember(member, nowMs) {
9462
9532
  if (member.sameLoginAs !== void 0) {
9463
9533
  return { candidate: { identity: member.identity, class: "ineligible", plan: planOf(member.account), reasons: [`same login as ${member.sameLoginAs}`] } };
9464
9534
  }
@@ -9472,22 +9542,43 @@ function assess(member, nowMs) {
9472
9542
  const assessment = assessIdentity(member, nowMs);
9473
9543
  return { ...assessment, candidate: { ...assessment.candidate, reasons: [`picked by pool "${nested.pool}"`, ...nested.reasons] } };
9474
9544
  }
9545
+ function sliceOf(member) {
9546
+ return member.snapshot?.providers[member.provider ?? ANTHROPIC_PROVIDER];
9547
+ }
9548
+ function assessProviderWithoutWindows(member, provider, state, base, planReasons, nowMs) {
9549
+ const blockedUntil = limitBlockedUntil(state, nowMs);
9550
+ if (blockedUntil !== void 0) {
9551
+ return { candidate: { ...base, class: "ineligible", blockedUntilMs: blockedUntil, reasons: [`refused until ${new Date(blockedUntil).toISOString()} (in ${formatAge(blockedUntil - nowMs)})`, ...planReasons] } };
9552
+ }
9553
+ if (base.plan.kind === "pay-per-use") {
9554
+ return { candidate: { ...base, class: "pay-per-use", usageUnrecorded: true, reasons: [...planReasons, `provider ${provider} reports no plan windows, so its spend is not tracked`] } };
9555
+ }
9556
+ const why = state === void 0 ? `no usage recorded for provider ${provider} yet, so its quota is unknown` : `provider ${provider} reports no plan windows, so its quota is unknown`;
9557
+ return { candidate: { ...base, class: "unknown", reasons: [why, ...planReasons] } };
9558
+ }
9475
9559
  function assessIdentity(member, nowMs) {
9476
- const plan = planOf(member.account);
9560
+ const state = sliceOf(member);
9561
+ const plan = member.provider === void 0 ? planOf(member.account) : planOfProviderQuota(state?.quota);
9477
9562
  const planReasons = plan.kind === "pay-per-use" ? ["billed by use (no plan allowance)"] : plan.recognised ? [`${String(plan.capacity)}x plan`] : [`plan tier ${plan.tier === void 0 ? "not known" : `"${plan.tier}" not recognised`}, counted as 1x`];
9478
9563
  const base = { identity: member.identity, plan };
9479
9564
  if (member.readError !== void 0) {
9480
9565
  return { candidate: { ...base, class: "unknown", reasons: [`usage state unreadable: ${member.readError}`, ...planReasons] } };
9481
9566
  }
9482
- const state = member.snapshot?.providers[ANTHROPIC_PROVIDER];
9483
- const unified = unifiedOf(state);
9484
- if (member.snapshot === void 0 || state === void 0 || unified === void 0) {
9567
+ if (member.providerError !== void 0) {
9568
+ return { candidate: { ...base, class: "unknown", reasons: [`provider configuration unreadable: ${member.providerError}`, ...planReasons] } };
9569
+ }
9570
+ const windows = rankingWindowsOf(member.provider, state);
9571
+ if (member.snapshot === void 0 || state === void 0 || windows === void 0) {
9572
+ if (member.provider !== void 0) {
9573
+ return assessProviderWithoutWindows(member, member.provider, state, base, planReasons, nowMs);
9574
+ }
9485
9575
  if (plan.kind === "pay-per-use") {
9486
9576
  return { candidate: { ...base, class: "pay-per-use", usageUnrecorded: true, reasons: [...planReasons, "no usage recorded yet, so its spend is not tracked (turn on trackUsage for it)"] } };
9487
9577
  }
9488
9578
  return { candidate: { ...base, class: "unknown", reasons: ["no usage recorded yet, so its quota is unknown (turn on trackUsage for it)", ...planReasons] } };
9489
9579
  }
9490
- const observedAgo = state.rateLimit === void 0 ? "" : ` (last seen ${formatAge(nowMs - Date.parse(state.rateLimit.observedAt))} ago)`;
9580
+ const { unified } = windows;
9581
+ const observedAgo = ` (last seen ${formatAge(nowMs - Date.parse(windows.observedAt))} ago)`;
9491
9582
  const fiveHourWindow = unified.fiveHour;
9492
9583
  const sevenDayWindow = unified.sevenDay;
9493
9584
  const five = fiveHourWindow === void 0 ? void 0 : effectiveWindow(fiveHourWindow, nowMs);
@@ -9499,6 +9590,15 @@ function assessIdentity(member, nowMs) {
9499
9590
  const overageWindow = soleOverageWindow(unified);
9500
9591
  const overage = overageWindow === void 0 ? void 0 : effectiveWindow(overageWindow, nowMs);
9501
9592
  const overageReasons = overageWindow === void 0 || overage === void 0 ? [] : [describeWindow("extra usage", overageWindow, overage, nowMs)];
9593
+ if (member.provider !== void 0) {
9594
+ const spent = [
9595
+ { name: "5h", window: five },
9596
+ { name: "7d", window: seven }
9597
+ ].filter(({ window }) => window?.status === "rejected" && window.resetsAtMs === void 0).map(({ name }) => name);
9598
+ if (spent.length > 0) {
9599
+ return { candidate: { ...base, class: "ineligible", reasons: [`provider ${member.provider} ${spent.join(" and ")} window used in full with no reset time reported, so it is refused until it reports one`, ...windowReasons, ...planReasons] } };
9600
+ }
9601
+ }
9502
9602
  const blockedUntil = Math.max(
9503
9603
  windowBlockedUntil([five, seven, overage].flatMap((window) => window === void 0 ? [] : [window])) ?? 0,
9504
9604
  limitBlockedUntil(state, nowMs) ?? 0
@@ -9519,11 +9619,11 @@ function assessIdentity(member, nowMs) {
9519
9619
  }
9520
9620
  const remaining = Math.max(0, 1 - basis.window.utilization);
9521
9621
  const untilResetMs = basis.window.resetsAtMs === void 0 ? basis.windowMs : Math.max(basis.window.resetsAtMs - nowMs, MS_PER_SECOND5);
9522
- const weeklyScore = remaining * plan.capacity / (untilResetMs / MS_PER_HOUR3);
9622
+ const weeklyScore = remaining * plan.capacity / (untilResetMs / MS_PER_HOUR4);
9523
9623
  const fiveRemaining = five?.utilization === void 0 ? void 0 : Math.max(0, 1 - five.utilization);
9524
9624
  const fiveUntil = five?.resetsAtMs === void 0 ? FIVE_HOUR_WINDOW_MS : Math.max(five.resetsAtMs - nowMs, MS_PER_SECOND5);
9525
9625
  const ratio = windowRatio(member.records);
9526
- const fiveHourScore = basis.name === "sevenDay" && fiveRemaining !== void 0 && ratio !== void 0 ? Math.min(fiveRemaining * ratio, remaining) * plan.capacity / (fiveUntil / MS_PER_HOUR3) : void 0;
9626
+ const fiveHourScore = basis.name === "sevenDay" && fiveRemaining !== void 0 && ratio !== void 0 ? Math.min(fiveRemaining * ratio, remaining) * plan.capacity / (fiveUntil / MS_PER_HOUR4) : void 0;
9527
9627
  const fiveHourLeads = fiveHourScore !== void 0 && fiveHourScore > weeklyScore;
9528
9628
  const score = fiveHourLeads ? fiveHourScore : weeklyScore;
9529
9629
  const scoreWindow = fiveHourLeads ? "fiveHour" : basis.name;
@@ -9541,15 +9641,15 @@ function assessIdentity(member, nowMs) {
9541
9641
  };
9542
9642
  }
9543
9643
  function poolFactsOf(member, nowMs, resuming, sticky) {
9544
- const { fiveHour, sevenDay, extraUsage } = quotaFactsOf(member.snapshot?.providers[ANTHROPIC_PROVIDER]?.rateLimit?.unified, nowMs);
9644
+ const { fiveHour, sevenDay, extraUsage } = quotaFactsOf(rankingWindowsOf(member.provider, sliceOf(member))?.unified, nowMs);
9545
9645
  const burn = windowBurn(member.records, "fiveHour");
9546
9646
  return {
9547
9647
  ...fiveHour === void 0 ? {} : { fiveHour },
9548
9648
  ...sevenDay === void 0 ? {} : { sevenDay },
9549
9649
  ...extraUsage === void 0 ? {} : { extraUsage },
9550
- ...burn === void 0 ? {} : { burnPerHour: burn * MS_PER_HOUR3 },
9650
+ ...burn === void 0 ? {} : { burnPerHour: burn * MS_PER_HOUR4 },
9551
9651
  resuming,
9552
- ...sticky?.identity === member.identity ? { lastPickHoursAgo: Math.max(0, (nowMs - Date.parse(sticky.at)) / MS_PER_HOUR3) } : {}
9652
+ ...sticky?.identity === member.identity ? { lastPickHoursAgo: Math.max(0, (nowMs - Date.parse(sticky.at)) / MS_PER_HOUR4) } : {}
9553
9653
  };
9554
9654
  }
9555
9655
  function rankPool(input) {
@@ -9644,7 +9744,7 @@ function rankPool(input) {
9644
9744
  ...holdForReturn === void 0 ? {} : { holdForReturn }
9645
9745
  };
9646
9746
  }
9647
- var MS_PER_SECOND5, MS_PER_HOUR3, HOURS_PER_DAY3, FIVE_HOURS, PROMPT_CACHE_TTL_HOURS, SEVEN_DAYS, FIVE_HOUR_WINDOW_MS, SEVEN_DAY_WINDOW_MS, PROMPT_CACHE_TTL_MS, CLASS_ORDER;
9747
+ var MS_PER_SECOND5, MS_PER_HOUR4, PROMPT_CACHE_TTL_HOURS, PROMPT_CACHE_TTL_MS, CLASS_ORDER;
9648
9748
  var init_pick = __esm({
9649
9749
  "src/usage/pick.ts"() {
9650
9750
  "use strict";
@@ -9653,17 +9753,14 @@ var init_pick = __esm({
9653
9753
  init_plan2();
9654
9754
  init_middleware();
9655
9755
  init_preflight();
9756
+ init_providerWindows();
9656
9757
  init_quotaFacts();
9758
+ init_windowLengths();
9657
9759
  init_rateLimit();
9658
9760
  MS_PER_SECOND5 = 1e3;
9659
- MS_PER_HOUR3 = 36e5;
9660
- HOURS_PER_DAY3 = 24;
9661
- FIVE_HOURS = 5;
9761
+ MS_PER_HOUR4 = 36e5;
9662
9762
  PROMPT_CACHE_TTL_HOURS = 1;
9663
- SEVEN_DAYS = 7;
9664
- FIVE_HOUR_WINDOW_MS = FIVE_HOURS * MS_PER_HOUR3;
9665
- SEVEN_DAY_WINDOW_MS = SEVEN_DAYS * HOURS_PER_DAY3 * MS_PER_HOUR3;
9666
- PROMPT_CACHE_TTL_MS = PROMPT_CACHE_TTL_HOURS * MS_PER_HOUR3;
9763
+ PROMPT_CACHE_TTL_MS = PROMPT_CACHE_TTL_HOURS * MS_PER_HOUR4;
9667
9764
  CLASS_ORDER = { scored: 0, unknown: 1, "pay-per-use": 2, ineligible: 3 };
9668
9765
  }
9669
9766
  });
@@ -9798,7 +9895,7 @@ var init_store2 = __esm({
9798
9895
  function errorMessage(error) {
9799
9896
  return error instanceof Error ? error.message : String(error);
9800
9897
  }
9801
- function loadPoolMembers(fs17, paths, identities, nowMs, idOf) {
9898
+ function loadPoolMembers(fs17, paths, identities, nowMs, idOf, providerOf) {
9802
9899
  const windowStartMs = nowMs - FIVE_HOUR_WINDOW_MS;
9803
9900
  const log = readUsageLog(fs17, paths.usageLogDir, { sinceMs: windowStartMs });
9804
9901
  return identities.map((identity) => {
@@ -9806,14 +9903,20 @@ function loadPoolMembers(fs17, paths, identities, nowMs, idOf) {
9806
9903
  if (id === void 0) {
9807
9904
  return { identity, records: [] };
9808
9905
  }
9809
- const records = log.records.filter((record) => record.identity === id && record.provider === ANTHROPIC_PROVIDER && Date.parse(record.at) >= windowStartMs);
9906
+ const resolved = providerOf?.(identity);
9907
+ const provider = typeof resolved === "object" ? resolved.named : resolved;
9908
+ const providerField = {
9909
+ ...provider === void 0 ? {} : { provider },
9910
+ ...typeof resolved === "object" ? { providerError: resolved.reason } : {}
9911
+ };
9912
+ const records = log.records.filter((record) => record.identity === id && record.provider === (provider ?? ANTHROPIC_PROVIDER) && Date.parse(record.at) >= windowStartMs);
9810
9913
  try {
9811
9914
  const snapshot = readUsageSnapshot(fs17, paths.usageSnapshotsDir, id);
9812
9915
  const account = readAccountMetadata(fs17, paths.identitiesDir, id) ?? snapshot?.account;
9813
- return { identity, records, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
9916
+ return { identity, records, ...providerField, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
9814
9917
  } catch (error) {
9815
9918
  if (error instanceof UsageSnapshotError || error instanceof AccountMetadataError) {
9816
- return { identity, records, readError: errorMessage(error) };
9919
+ return { identity, records, ...providerField, readError: errorMessage(error) };
9817
9920
  }
9818
9921
  throw error;
9819
9922
  }
@@ -9823,7 +9926,7 @@ function snapshotAgeKey(member) {
9823
9926
  return member.snapshot === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(member.snapshot.updatedAt);
9824
9927
  }
9825
9928
  function collapseSharedLogins(members) {
9826
- const groups = groupSharedLogins(members, (member) => member.nested === void 0 && member.account !== void 0 ? loginKeyOf(member.account) : void 0);
9929
+ const groups = groupSharedLogins(members, (member) => member.nested === void 0 && member.provider === void 0 && member.account !== void 0 ? loginKeyOf(member.account) : void 0);
9827
9930
  const representativeOf = /* @__PURE__ */ new Map();
9828
9931
  for (const group of groups) {
9829
9932
  const representative = group.reduce((freshest, member) => snapshotAgeKey(member) > snapshotAgeKey(freshest) ? member : freshest);
@@ -9853,7 +9956,7 @@ function rankNamedPool(input, poolName, stack, sticky) {
9853
9956
  const childStack = [...stack, poolName];
9854
9957
  const direct = pool.identities.filter((entry) => poolNameOf(poolMemberIdentity(entry)) === void 0);
9855
9958
  const missing = direct.filter((entry) => input.identityIdOf(poolMemberIdentity(entry)) === void 0).map((entry) => ({ pool: poolName, identity: poolMemberIdentity(entry) }));
9856
- const loaded = new Map(loadPoolMembers(input.fs, input.paths, direct.filter((entry) => input.identityIdOf(poolMemberIdentity(entry)) !== void 0).map(poolMemberIdentity), input.nowMs, input.identityIdOf).map((member) => [member.identity, member]));
9959
+ const loaded = new Map(loadPoolMembers(input.fs, input.paths, direct.filter((entry) => input.identityIdOf(poolMemberIdentity(entry)) !== void 0).map(poolMemberIdentity), input.nowMs, input.identityIdOf, input.providerOf).map((member) => [member.identity, member]));
9857
9960
  const members = [];
9858
9961
  for (const entry of pool.identities) {
9859
9962
  const nestedName = poolNameOf(poolMemberIdentity(entry));
@@ -9894,7 +9997,7 @@ function nestedMember(input, nestedName, childStack, sticky) {
9894
9997
  const nested = rankNamedPool(input, nestedName, childStack, sticky);
9895
9998
  const pick = nested.ranking.pick;
9896
9999
  if (pick !== void 0) {
9897
- const [member] = loadPoolMembers(input.fs, input.paths, [pick.identity], input.nowMs, input.identityIdOf);
10000
+ const [member] = loadPoolMembers(input.fs, input.paths, [pick.identity], input.nowMs, input.identityIdOf, input.providerOf);
9898
10001
  return { member: { ...member ?? { identity: pick.identity, records: [] }, nested: { kind: "pick", pool: nestedName, reasons: pick.reasons } }, missing: nested.missing };
9899
10002
  }
9900
10003
  const earliestReturn = nested.ranking.earliestReturn;
@@ -9991,6 +10094,7 @@ var init_poolPick = __esm({
9991
10094
  init_read();
9992
10095
  init_middleware();
9993
10096
  init_store2();
10097
+ init_windowLengths();
9994
10098
  PoolGraphError = class extends CliError {
9995
10099
  constructor(message) {
9996
10100
  super(message);
@@ -10763,7 +10867,7 @@ var init_package = __esm({
10763
10867
  "package.json"() {
10764
10868
  package_default = {
10765
10869
  name: "claude-use",
10766
- version: "12.0.1",
10870
+ version: "12.2.0",
10767
10871
  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.",
10768
10872
  license: "MIT",
10769
10873
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -11023,93 +11127,6 @@ var init_cascade = __esm({
11023
11127
  }
11024
11128
  });
11025
11129
 
11026
- // src/paths.ts
11027
- function resolveAgentShimHome(env = process.env, home = import_node_os4.default.homedir(), isDirectory = isExistingDirectory) {
11028
- const fromEnv = env.AGENT_SHIM_HOME;
11029
- if (fromEnv !== void 0 && fromEnv !== "") {
11030
- return fromEnv;
11031
- }
11032
- const current = import_node_path36.default.join(home, HOME_DIRNAME);
11033
- const legacy = import_node_path36.default.join(home, LEGACY_HOME_DIRNAME);
11034
- return !isDirectory(current) && isDirectory(legacy) ? legacy : current;
11035
- }
11036
- function isExistingDirectory(candidate) {
11037
- return import_node_fs9.default.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() ?? false;
11038
- }
11039
- function resolveClaudeHome() {
11040
- const fromEnv = process.env.AGENT_SHIM_CLAUDE_HOME;
11041
- if (fromEnv !== void 0 && fromEnv !== "") {
11042
- return fromEnv;
11043
- }
11044
- return import_node_path36.default.join(import_node_os4.default.homedir(), ".claude");
11045
- }
11046
- function buildLayoutPaths(root) {
11047
- return {
11048
- root,
11049
- identitiesDir: import_node_path36.default.join(root, "identities"),
11050
- configProfilesDir: import_node_path36.default.join(root, "config-profiles"),
11051
- providersDir: import_node_path36.default.join(root, "providers"),
11052
- providerAliasesFile: import_node_path36.default.join(root, "provider-aliases.json"),
11053
- directoryRulesFile: import_node_path36.default.join(root, "directory-rules.json"),
11054
- activeIdentityFile: import_node_path36.default.join(root, "active-identity"),
11055
- globalConfigFile: import_node_path36.default.join(root, "config.json"),
11056
- categoriesLocalFile: import_node_path36.default.join(root, "categories.local.json"),
11057
- claudeShimFile: import_node_path36.default.join(root, "claude-shim.json"),
11058
- headroomDir: import_node_path36.default.join(root, "headroom"),
11059
- headroomStateFile: import_node_path36.default.join(root, "headroom", "state.json"),
11060
- headroomRoutingFile: import_node_path36.default.join(root, "headroom", "routing.json"),
11061
- headroomLegacyStateFile: import_node_path36.default.join(root, "headroom", "state.v2.json"),
11062
- headroomAllowlistFile: import_node_path36.default.join(root, "headroom", "run", "allowlist.txt"),
11063
- headroomSocketDir: import_node_path36.default.join(root, "headroom", "run"),
11064
- headroomLockFile: import_node_path36.default.join(root, "headroom", "start.lock"),
11065
- headroomSessionsDir: import_node_path36.default.join(root, "headroom", "sessions"),
11066
- logsDir: import_node_path36.default.join(root, "logs"),
11067
- headroomLogPath: import_node_path36.default.join(root, "logs", "headroom.log"),
11068
- frontdoorDir: import_node_path36.default.join(root, "frontdoor"),
11069
- frontdoorCaDir: import_node_path36.default.join(root, "frontdoor", "ca"),
11070
- frontdoorCaCertFile: import_node_path36.default.join(root, "frontdoor", "ca", "ca.pem"),
11071
- frontdoorCaKeyFile: import_node_path36.default.join(root, "frontdoor", "ca", "ca.key"),
11072
- frontdoorCaBundlesDir: import_node_path36.default.join(root, "frontdoor", "ca", "bundles"),
11073
- chatgptSignInFile: import_node_path36.default.join(root, "codex", "chatgpt-sign-in.json"),
11074
- frontdoorStateFile: import_node_path36.default.join(root, "frontdoor", "state.json"),
11075
- frontdoorLockFile: import_node_path36.default.join(root, "frontdoor", "start.lock"),
11076
- frontdoorControlTokenFile: import_node_path36.default.join(root, "frontdoor", "control-token"),
11077
- frontdoorSessionsDir: import_node_path36.default.join(root, "frontdoor", "sessions"),
11078
- frontdoorDirectRecordsDir: import_node_path36.default.join(root, "frontdoor", "direct"),
11079
- frontdoorDrainingDir: import_node_path36.default.join(root, "frontdoor", "draining"),
11080
- frontdoorRcCredentialsDir: import_node_path36.default.join(root, "frontdoor", "rc-credentials"),
11081
- frontdoorLogPath: import_node_path36.default.join(root, "logs", "frontdoor.log"),
11082
- usageDir: import_node_path36.default.join(root, "usage"),
11083
- usageLogDir: import_node_path36.default.join(root, "usage", "log"),
11084
- usageSnapshotsDir: import_node_path36.default.join(root, "usage", "snapshots"),
11085
- statuslineDir: import_node_path36.default.join(root, "statusline"),
11086
- catalogueDir: import_node_path36.default.join(root, "catalogues"),
11087
- usagePicksFile: import_node_path36.default.join(root, "usage", "picks.json"),
11088
- usageAnchorsFile: import_node_path36.default.join(root, "usage", "anchors.json"),
11089
- usageJobsFile: import_node_path36.default.join(root, "usage", "jobs.json"),
11090
- jobLogsDir: import_node_path36.default.join(root, "logs", "jobs"),
11091
- identityRenamesDir: import_node_path36.default.join(root, "identity-renames"),
11092
- identityNameRenamesDir: import_node_path36.default.join(root, "identity-name-renames"),
11093
- launchesDir: import_node_path36.default.join(root, "launches"),
11094
- superviseDir: import_node_path36.default.join(root, "supervise"),
11095
- modelMovesDir: import_node_path36.default.join(root, "model-moves"),
11096
- mcpPermissionsFile: import_node_path36.default.join(root, "mcp", "permissions.json")
11097
- };
11098
- }
11099
- function resolveLayoutPaths() {
11100
- return buildLayoutPaths(resolveAgentShimHome());
11101
- }
11102
- var import_node_fs9, import_node_os4, import_node_path36;
11103
- var init_paths = __esm({
11104
- "src/paths.ts"() {
11105
- "use strict";
11106
- import_node_fs9 = __toESM(require("node:fs"), 1);
11107
- import_node_os4 = __toESM(require("node:os"), 1);
11108
- import_node_path36 = __toESM(require("node:path"), 1);
11109
- init_legacy();
11110
- }
11111
- });
11112
-
11113
11130
  // src/providerAliases.ts
11114
11131
  function parseAliases(file, raw) {
11115
11132
  const parsed = ProviderAliasesSchema.safeParse(raw);
@@ -11366,7 +11383,7 @@ function providerJsonPath(paths, name) {
11366
11383
  return providerFilePath(paths.providersDir, name);
11367
11384
  }
11368
11385
  function providerExists(paths, name) {
11369
- return import_node_fs10.default.existsSync(providerJsonPath(paths, name));
11386
+ return import_node_fs9.default.existsSync(providerJsonPath(paths, name));
11370
11387
  }
11371
11388
  function requireProviderExists(paths, name) {
11372
11389
  const canonical = canonicalProviderName(name, (candidate) => providerExists(paths, candidate), () => readProviderAliases(paths));
@@ -11423,12 +11440,12 @@ function parseProviderFile(filePath, raw) {
11423
11440
  }
11424
11441
  function readProvider(paths, name) {
11425
11442
  const filePath = providerJsonPath(paths, name);
11426
- if (!import_node_fs10.default.existsSync(filePath)) {
11443
+ if (!import_node_fs9.default.existsSync(filePath)) {
11427
11444
  return void 0;
11428
11445
  }
11429
11446
  let raw;
11430
11447
  try {
11431
- raw = JSON.parse(import_node_fs10.default.readFileSync(filePath, "utf8"));
11448
+ raw = JSON.parse(import_node_fs9.default.readFileSync(filePath, "utf8"));
11432
11449
  } catch (error) {
11433
11450
  throw error instanceof SyntaxError ? new ConfigFileNotJsonError(filePath) : error;
11434
11451
  }
@@ -11444,7 +11461,7 @@ function reportInvalidProvider(name, message) {
11444
11461
  }
11445
11462
  function listProviders(paths, onInvalid = reportInvalidProvider) {
11446
11463
  const names = listProviderNames(
11447
- (dir) => import_node_fs10.default.readdirSync(dir),
11464
+ (dir) => import_node_fs9.default.readdirSync(dir),
11448
11465
  paths.providersDir
11449
11466
  );
11450
11467
  const result = [];
@@ -11513,6 +11530,9 @@ function addProvider(paths, name, input) {
11513
11530
  if (kind !== "http" && kind !== "router" && input.catalogue !== void 0) {
11514
11531
  throw new ProviderKindMismatchError("A model catalogue applies only to an http provider.");
11515
11532
  }
11533
+ if (kind !== "http" && input.connectTimeoutMs !== void 0) {
11534
+ throw new ProviderKindMismatchError("A connect timeout applies only to an http provider, the one kind that dials a base URL.");
11535
+ }
11516
11536
  if (kind !== "codex" && !isEmptyCodexConfig(input.codex)) {
11517
11537
  throw new ProviderKindMismatchError("Codex settings apply only to a codex provider (--kind codex).");
11518
11538
  }
@@ -11526,7 +11546,7 @@ function addProvider(paths, name, input) {
11526
11546
  ...input.pickerModels === void 0 || input.pickerModels.length === 0 ? {} : { pickerModels: input.pickerModels }
11527
11547
  };
11528
11548
  const parsed = ProviderSchema.safeParse(
11529
- kind === "router" ? { kind, displayName: input.displayName } : kind === "codex" ? { kind, ...shared, ...isEmptyCodexConfig(input.codex) ? {} : { codex: input.codex } } : kind === "antigravity" ? { kind, ...shared, ...isEmptyAntigravityConfig(input.antigravity) ? {} : { antigravity: input.antigravity } } : { ...shared, baseUrl: input.baseUrl, ...input.catalogue === void 0 ? {} : { catalogue: input.catalogue } }
11549
+ kind === "router" ? { kind, displayName: input.displayName } : kind === "codex" ? { kind, ...shared, ...isEmptyCodexConfig(input.codex) ? {} : { codex: input.codex } } : kind === "antigravity" ? { kind, ...shared, ...isEmptyAntigravityConfig(input.antigravity) ? {} : { antigravity: input.antigravity } } : { ...shared, baseUrl: input.baseUrl, ...input.connectTimeoutMs === void 0 ? {} : { connectTimeoutMs: input.connectTimeoutMs }, ...input.catalogue === void 0 ? {} : { catalogue: input.catalogue } }
11530
11550
  );
11531
11551
  if (!parsed.success) {
11532
11552
  throw new ConfigValidationError(providerJsonPath(paths, name), parsed.error.issues);
@@ -11558,6 +11578,9 @@ function updateProvider(paths, name, input) {
11558
11578
  if (isAntigravityProvider(existing) && input.baseUrl !== void 0) {
11559
11579
  throw new ProviderKindMismatchError(`Provider "${name}" is an antigravity provider, which has no base URL.`);
11560
11580
  }
11581
+ if (!isHttpProvider(existing) && input.connectTimeoutMs !== void 0) {
11582
+ throw new ProviderKindMismatchError(`Provider "${name}" is not an http provider; a connect timeout applies only to an http provider, the one kind that dials a base URL.`);
11583
+ }
11561
11584
  if ((isCodexProvider(existing) || isAntigravityProvider(existing)) && input.catalogue !== void 0 && input.catalogue !== false) {
11562
11585
  throw new ProviderKindMismatchError(`Provider "${name}" is not an http provider; a model catalogue applies only to an http provider.`);
11563
11586
  }
@@ -11598,7 +11621,8 @@ function updateProvider(paths, name, input) {
11598
11621
  candidate = { kind: "router", ...shared };
11599
11622
  } else {
11600
11623
  const catalogue = input.catalogue === void 0 ? existing.catalogue : input.catalogue === false ? void 0 : input.catalogue;
11601
- candidate = { ...existing, ...shared, catalogue, ...input.baseUrl === void 0 ? {} : { baseUrl: input.baseUrl } };
11624
+ const connectTimeoutMs = input.connectTimeoutMs === void 0 ? existing.connectTimeoutMs : input.connectTimeoutMs === false ? void 0 : input.connectTimeoutMs;
11625
+ candidate = { ...existing, ...shared, catalogue, connectTimeoutMs, ...input.baseUrl === void 0 ? {} : { baseUrl: input.baseUrl } };
11602
11626
  }
11603
11627
  const parsed = ProviderSchema.safeParse(candidate);
11604
11628
  if (!parsed.success) {
@@ -11611,7 +11635,7 @@ function removeProvider(paths, name) {
11611
11635
  if (!providerExists(paths, name)) {
11612
11636
  throw new ProviderNotFoundError(name);
11613
11637
  }
11614
- import_node_fs10.default.rmSync(providerJsonPath(paths, name));
11638
+ import_node_fs9.default.rmSync(providerJsonPath(paths, name));
11615
11639
  createRealCredentialCache(paths.root).remove("file", `provider ${name}`);
11616
11640
  }
11617
11641
  function cascadeProviderName(cascade, identityProvider) {
@@ -11623,13 +11647,19 @@ function cascadeProviderName(cascade, identityProvider) {
11623
11647
  }
11624
11648
  return name ?? identityProvider;
11625
11649
  }
11626
- function selectProvider(params) {
11650
+ function selectedProviderName(params) {
11627
11651
  const cliName = params.cliProvider !== void 0 && params.cliProvider !== "" ? params.cliProvider : void 0;
11628
11652
  const named = cliName ?? (params.cascade === void 0 ? params.identityProvider : cascadeProviderName(params.cascade, params.identityProvider));
11629
11653
  if (named === void 0) {
11630
11654
  return void 0;
11631
11655
  }
11632
- const name = canonicalProviderName(named, (candidate) => loadProvider(params.paths.providersDir, candidate, params.port) !== void 0, () => loadProviderAliases(params.paths.providerAliasesFile, params.port));
11656
+ return canonicalProviderName(named, (candidate) => loadProvider(params.paths.providersDir, candidate, params.port) !== void 0, () => loadProviderAliases(params.paths.providerAliasesFile, params.port));
11657
+ }
11658
+ function selectProvider(params) {
11659
+ const name = selectedProviderName(params);
11660
+ if (name === void 0) {
11661
+ return void 0;
11662
+ }
11633
11663
  const definition = loadProvider(params.paths.providersDir, name, params.port);
11634
11664
  if (definition === void 0) {
11635
11665
  const known = listProviderNames(params.port.readdir, params.paths.providersDir);
@@ -11718,59 +11748,400 @@ function resolveRoutedProviderCredentials(params) {
11718
11748
  }
11719
11749
  return { ok: true, checked: [...providerNames].sort() };
11720
11750
  }
11721
- var import_node_fs10, ProviderNotFoundError, ProviderAlreadyExistsError, LEGACY_PROVIDER_FIELDS, LEGACY_ENV_CREDENTIAL_KEYS, LEGACY_LITERAL_PLACEHOLDER, LegacyProviderFileError, ProviderKindMismatchError;
11722
- var init_providersStore = __esm({
11723
- "src/providersStore.ts"() {
11751
+ var import_node_fs9, ProviderNotFoundError, ProviderAlreadyExistsError, LEGACY_PROVIDER_FIELDS, LEGACY_ENV_CREDENTIAL_KEYS, LEGACY_LITERAL_PLACEHOLDER, LegacyProviderFileError, ProviderKindMismatchError;
11752
+ var init_providersStore = __esm({
11753
+ "src/providersStore.ts"() {
11754
+ "use strict";
11755
+ import_node_fs9 = __toESM(require("node:fs"), 1);
11756
+ init_load();
11757
+ init_store();
11758
+ init_unrecognisedKeys();
11759
+ init_schema();
11760
+ init_cliError();
11761
+ init_providerAliases();
11762
+ init_credential();
11763
+ init_realCredentialCache();
11764
+ init_walk();
11765
+ init_families();
11766
+ init_names();
11767
+ ProviderNotFoundError = class extends CliError {
11768
+ constructor(name) {
11769
+ super(`No provider named "${name}". Run \`agent-shim provider add ${name}\` first.`);
11770
+ this.name = name;
11771
+ this.name = "ProviderNotFoundError";
11772
+ }
11773
+ name;
11774
+ };
11775
+ ProviderAlreadyExistsError = class extends CliError {
11776
+ constructor(providerName) {
11777
+ super(`A provider named "${providerName}" already exists.`);
11778
+ this.providerName = providerName;
11779
+ this.name = "ProviderAlreadyExistsError";
11780
+ }
11781
+ providerName;
11782
+ };
11783
+ LEGACY_PROVIDER_FIELDS = ["tokenEnv", "tokenCommand", "authScheme"];
11784
+ LEGACY_ENV_CREDENTIAL_KEYS = Object.values(CREDENTIAL_TARGET_VARS);
11785
+ LEGACY_LITERAL_PLACEHOLDER = "<the value of env.ANTHROPIC_AUTH_TOKEN>";
11786
+ LegacyProviderFileError = class extends CliError {
11787
+ constructor(filePath, conversion) {
11788
+ super(
11789
+ `${filePath} uses ${conversion.fields.join(", ")}, which a credential block replaced. Rewrite it as:
11790
+ ` + JSON.stringify(conversion.replacement, null, 2)
11791
+ );
11792
+ this.filePath = filePath;
11793
+ this.conversion = conversion;
11794
+ this.name = "LegacyProviderFileError";
11795
+ }
11796
+ filePath;
11797
+ conversion;
11798
+ };
11799
+ ProviderKindMismatchError = class extends UsageError {
11800
+ constructor(message) {
11801
+ super(message);
11802
+ this.name = "ProviderKindMismatchError";
11803
+ }
11804
+ };
11805
+ }
11806
+ });
11807
+
11808
+ // src/launcher/memberProvider.ts
11809
+ function unreadableFileReason(error) {
11810
+ if (error instanceof ConfigValidationError) {
11811
+ return `${error.filepath} is invalid`;
11812
+ }
11813
+ if (error instanceof ConfigFileNotJsonError) {
11814
+ return error.message.replace(/\.$/, "");
11815
+ }
11816
+ if (error instanceof LegacyProviderFileError) {
11817
+ return `${error.filePath} uses ${error.conversion.fields.join(", ")}, which a credential block replaced`;
11818
+ }
11819
+ return void 0;
11820
+ }
11821
+ function memberProviderResolver(params) {
11822
+ if (params.cliProvider === false) {
11823
+ return () => void 0;
11824
+ }
11825
+ const cliProvider = params.cliProvider;
11826
+ const identities = identityReader(params.paths.identitiesDir, params.fs);
11827
+ const cascades = /* @__PURE__ */ new Map();
11828
+ const cascadeOver = (baseConfigProfile) => {
11829
+ const cached = cascades.get(baseConfigProfile);
11830
+ if (cached !== void 0) {
11831
+ return cached;
11832
+ }
11833
+ const loaded = params.loadCascade(baseConfigProfile);
11834
+ cascades.set(baseConfigProfile, loaded);
11835
+ return loaded;
11836
+ };
11837
+ return (name) => {
11838
+ let declared;
11839
+ try {
11840
+ declared = identities.load(name);
11841
+ } catch (error) {
11842
+ if (!(error instanceof ConfigValidationError)) {
11843
+ throw error;
11844
+ }
11845
+ }
11846
+ const profile = decideConfigProfile({
11847
+ env: params.env,
11848
+ ...params.cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile: params.cliFlagConfigProfile },
11849
+ ...params.directoryRuleConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: params.directoryRuleConfigProfile },
11850
+ ...declared?.defaultConfigProfile === void 0 ? {} : { identityDefaultConfigProfile: declared.defaultConfigProfile },
11851
+ ...params.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: params.globalDefaultConfigProfile }
11852
+ });
11853
+ const flagged = cliProvider !== void 0 && cliProvider !== "" ? cliProvider : void 0;
11854
+ let named = flagged ?? declared?.provider;
11855
+ try {
11856
+ const cascade = cascadeOver(profile.name);
11857
+ named = flagged ?? cascadeProviderName(cascade, declared?.provider);
11858
+ return selectedProviderName({
11859
+ paths: params.paths,
11860
+ port: params.fs,
11861
+ ...cliProvider === void 0 ? {} : { cliProvider },
11862
+ cascade,
11863
+ ...declared?.provider === void 0 ? {} : { identityProvider: declared.provider }
11864
+ });
11865
+ } catch (error) {
11866
+ const reason = unreadableFileReason(error);
11867
+ if (reason === void 0) {
11868
+ throw error;
11869
+ }
11870
+ return { ...named === void 0 ? {} : { named }, reason };
11871
+ }
11872
+ };
11873
+ }
11874
+ var init_memberProvider = __esm({
11875
+ "src/launcher/memberProvider.ts"() {
11876
+ "use strict";
11877
+ init_load();
11878
+ init_providersStore();
11879
+ init_identity();
11880
+ }
11881
+ });
11882
+
11883
+ // src/paths.ts
11884
+ function resolveAgentShimHome(env = process.env, home = import_node_os5.default.homedir(), isDirectory = isExistingDirectory) {
11885
+ const fromEnv = env.AGENT_SHIM_HOME;
11886
+ if (fromEnv !== void 0 && fromEnv !== "") {
11887
+ return fromEnv;
11888
+ }
11889
+ const current = import_node_path36.default.join(home, HOME_DIRNAME);
11890
+ const legacy = import_node_path36.default.join(home, LEGACY_HOME_DIRNAME);
11891
+ return !isDirectory(current) && isDirectory(legacy) ? legacy : current;
11892
+ }
11893
+ function isExistingDirectory(candidate) {
11894
+ return import_node_fs10.default.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() ?? false;
11895
+ }
11896
+ function resolveClaudeHome() {
11897
+ const fromEnv = process.env.AGENT_SHIM_CLAUDE_HOME;
11898
+ if (fromEnv !== void 0 && fromEnv !== "") {
11899
+ return fromEnv;
11900
+ }
11901
+ return import_node_path36.default.join(import_node_os5.default.homedir(), ".claude");
11902
+ }
11903
+ function buildLayoutPaths(root) {
11904
+ return {
11905
+ root,
11906
+ identitiesDir: import_node_path36.default.join(root, "identities"),
11907
+ configProfilesDir: import_node_path36.default.join(root, "config-profiles"),
11908
+ providersDir: import_node_path36.default.join(root, "providers"),
11909
+ providerAliasesFile: import_node_path36.default.join(root, "provider-aliases.json"),
11910
+ directoryRulesFile: import_node_path36.default.join(root, "directory-rules.json"),
11911
+ activeIdentityFile: import_node_path36.default.join(root, "active-identity"),
11912
+ globalConfigFile: import_node_path36.default.join(root, "config.json"),
11913
+ categoriesLocalFile: import_node_path36.default.join(root, "categories.local.json"),
11914
+ claudeShimFile: import_node_path36.default.join(root, "claude-shim.json"),
11915
+ headroomDir: import_node_path36.default.join(root, "headroom"),
11916
+ headroomStateFile: import_node_path36.default.join(root, "headroom", "state.json"),
11917
+ headroomRoutingFile: import_node_path36.default.join(root, "headroom", "routing.json"),
11918
+ headroomLegacyStateFile: import_node_path36.default.join(root, "headroom", "state.v2.json"),
11919
+ headroomAllowlistFile: import_node_path36.default.join(root, "headroom", "run", "allowlist.txt"),
11920
+ headroomSocketDir: import_node_path36.default.join(root, "headroom", "run"),
11921
+ headroomLockFile: import_node_path36.default.join(root, "headroom", "start.lock"),
11922
+ headroomSessionsDir: import_node_path36.default.join(root, "headroom", "sessions"),
11923
+ logsDir: import_node_path36.default.join(root, "logs"),
11924
+ headroomLogPath: import_node_path36.default.join(root, "logs", "headroom.log"),
11925
+ frontdoorDir: import_node_path36.default.join(root, "frontdoor"),
11926
+ frontdoorCaDir: import_node_path36.default.join(root, "frontdoor", "ca"),
11927
+ frontdoorCaCertFile: import_node_path36.default.join(root, "frontdoor", "ca", "ca.pem"),
11928
+ frontdoorCaKeyFile: import_node_path36.default.join(root, "frontdoor", "ca", "ca.key"),
11929
+ frontdoorCaBundlesDir: import_node_path36.default.join(root, "frontdoor", "ca", "bundles"),
11930
+ chatgptSignInFile: import_node_path36.default.join(root, "codex", "chatgpt-sign-in.json"),
11931
+ frontdoorStateFile: import_node_path36.default.join(root, "frontdoor", "state.json"),
11932
+ frontdoorLockFile: import_node_path36.default.join(root, "frontdoor", "start.lock"),
11933
+ frontdoorControlTokenFile: import_node_path36.default.join(root, "frontdoor", "control-token"),
11934
+ frontdoorSessionsDir: import_node_path36.default.join(root, "frontdoor", "sessions"),
11935
+ frontdoorDirectRecordsDir: import_node_path36.default.join(root, "frontdoor", "direct"),
11936
+ frontdoorDrainingDir: import_node_path36.default.join(root, "frontdoor", "draining"),
11937
+ frontdoorRcCredentialsDir: import_node_path36.default.join(root, "frontdoor", "rc-credentials"),
11938
+ frontdoorLogPath: import_node_path36.default.join(root, "logs", "frontdoor.log"),
11939
+ usageDir: import_node_path36.default.join(root, "usage"),
11940
+ usageLogDir: import_node_path36.default.join(root, "usage", "log"),
11941
+ usageSnapshotsDir: import_node_path36.default.join(root, "usage", "snapshots"),
11942
+ statuslineDir: import_node_path36.default.join(root, "statusline"),
11943
+ catalogueDir: import_node_path36.default.join(root, "catalogues"),
11944
+ usagePicksFile: import_node_path36.default.join(root, "usage", "picks.json"),
11945
+ usageAnchorsFile: import_node_path36.default.join(root, "usage", "anchors.json"),
11946
+ usageJobsFile: import_node_path36.default.join(root, "usage", "jobs.json"),
11947
+ jobLogsDir: import_node_path36.default.join(root, "logs", "jobs"),
11948
+ identityRenamesDir: import_node_path36.default.join(root, "identity-renames"),
11949
+ identityNameRenamesDir: import_node_path36.default.join(root, "identity-name-renames"),
11950
+ launchesDir: import_node_path36.default.join(root, "launches"),
11951
+ superviseDir: import_node_path36.default.join(root, "supervise"),
11952
+ modelMovesDir: import_node_path36.default.join(root, "model-moves"),
11953
+ mcpPermissionsFile: import_node_path36.default.join(root, "mcp", "permissions.json")
11954
+ };
11955
+ }
11956
+ function resolveLayoutPaths() {
11957
+ return buildLayoutPaths(resolveAgentShimHome());
11958
+ }
11959
+ var import_node_fs10, import_node_os5, import_node_path36;
11960
+ var init_paths = __esm({
11961
+ "src/paths.ts"() {
11962
+ "use strict";
11963
+ import_node_fs10 = __toESM(require("node:fs"), 1);
11964
+ import_node_os5 = __toESM(require("node:os"), 1);
11965
+ import_node_path36 = __toESM(require("node:path"), 1);
11966
+ init_legacy();
11967
+ }
11968
+ });
11969
+
11970
+ // src/frontdoor/probe.ts
11971
+ function requestCatalogueRefreshSync(port, caPem, token, timeoutMs = PROBE_TIMEOUT_MS) {
11972
+ refuseToBlockInRole("a synchronous catalogue refresh request");
11973
+ return runProbeWorker(CATALOGUE_REQUEST_SOURCE, { port, ca: caPem, token }, timeoutMs);
11974
+ }
11975
+ function probeFrontDoorSync(port, caPem, timeoutMs = PROBE_TIMEOUT_MS) {
11976
+ refuseToBlockInRole("a synchronous probe of the front door");
11977
+ return runProbeWorker(PROBE_SOURCE, { port, ca: caPem }, timeoutMs);
11978
+ }
11979
+ function probeListenerAcceptSync(port, timeoutMs = PROBE_TIMEOUT_MS) {
11980
+ refuseToBlockInRole("a synchronous probe of a front door listener");
11981
+ return runProbeWorker(ACCEPT_PROBE_SOURCE, { host: "127.0.0.1", port }, timeoutMs);
11982
+ }
11983
+ function probeAddressAcceptSync(host, port, timeoutMs) {
11984
+ refuseToBlockInRole("a synchronous probe of a provider's address");
11985
+ return runProbeWorker(ACCEPT_PROBE_SOURCE, { host, port }, timeoutMs);
11986
+ }
11987
+ function runProbeWorker(source, data, timeoutMs) {
11988
+ const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
11989
+ const header = new Int32Array(shared, 0, HEADER_SLOTS);
11990
+ const worker = new import_node_worker_threads.Worker(source, {
11991
+ eval: true,
11992
+ workerData: { ...data, timeoutMs, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS }
11993
+ });
11994
+ worker.unref();
11995
+ try {
11996
+ const waited = Atomics.wait(header, 0, VERDICT_PENDING, timeoutMs + PROBE_WAIT_MARGIN_MS);
11997
+ const verdict = Atomics.load(header, 0);
11998
+ if (waited === "timed-out" || verdict === VERDICT_PENDING) {
11999
+ return { ok: false, reason: `the probe did not finish within ${String(timeoutMs + PROBE_WAIT_MARGIN_MS)}ms` };
12000
+ }
12001
+ if (verdict === VERDICT_OK) {
12002
+ return { ok: true };
12003
+ }
12004
+ const length = Atomics.load(header, 1);
12005
+ return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
12006
+ } finally {
12007
+ void worker.terminate();
12008
+ }
12009
+ }
12010
+ var import_node_worker_threads, PROBE_TIMEOUT_MS, PROBE_WAIT_MARGIN_MS, REASON_BYTES, HEADER_SLOTS, INT32_BYTES, VERDICT_PENDING, VERDICT_OK, VERDICT_FAILED, PROBE_SOURCE, CATALOGUE_REQUEST_SOURCE, ACCEPT_PROBE_SOURCE;
12011
+ var init_probe = __esm({
12012
+ "src/frontdoor/probe.ts"() {
12013
+ "use strict";
12014
+ init_processRole();
12015
+ import_node_worker_threads = require("node:worker_threads");
12016
+ PROBE_TIMEOUT_MS = 2e3;
12017
+ PROBE_WAIT_MARGIN_MS = 1e3;
12018
+ REASON_BYTES = 1024;
12019
+ HEADER_SLOTS = 2;
12020
+ INT32_BYTES = 4;
12021
+ VERDICT_PENDING = 0;
12022
+ VERDICT_OK = 1;
12023
+ VERDICT_FAILED = 2;
12024
+ PROBE_SOURCE = `
12025
+ const { workerData } = require("node:worker_threads");
12026
+ const https = require("node:https");
12027
+ const { port, ca, timeoutMs, shared, ok, failed, headerSlots } = workerData;
12028
+ const header = new Int32Array(shared, 0, headerSlots);
12029
+ const reason = new Uint8Array(shared, headerSlots * 4);
12030
+ let done = false;
12031
+ const finish = (verdict, message) => {
12032
+ if (done) return;
12033
+ done = true;
12034
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
12035
+ reason.set(bytes);
12036
+ Atomics.store(header, 1, bytes.length);
12037
+ Atomics.store(header, 0, verdict);
12038
+ Atomics.notify(header, 0);
12039
+ };
12040
+ const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
12041
+ let body = "";
12042
+ response.setEncoding("utf8");
12043
+ response.on("data", (chunk) => { body += chunk; });
12044
+ response.on("end", () => {
12045
+ if (response.statusCode === 200 && body === "ok") finish(ok, "");
12046
+ else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
12047
+ });
12048
+ response.on("error", (error) => finish(failed, error.message));
12049
+ });
12050
+ // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
12051
+ setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
12052
+ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
12053
+ `;
12054
+ CATALOGUE_REQUEST_SOURCE = `
12055
+ const { workerData } = require("node:worker_threads");
12056
+ const https = require("node:https");
12057
+ const { port, ca, token, timeoutMs, shared, ok, failed, headerSlots } = workerData;
12058
+ const header = new Int32Array(shared, 0, headerSlots);
12059
+ const reason = new Uint8Array(shared, headerSlots * 4);
12060
+ let done = false;
12061
+ const finish = (verdict, message) => {
12062
+ if (done) return;
12063
+ done = true;
12064
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
12065
+ reason.set(bytes);
12066
+ Atomics.store(header, 1, bytes.length);
12067
+ Atomics.store(header, 0, verdict);
12068
+ Atomics.notify(header, 0);
12069
+ };
12070
+ const request = https.request({ host: "127.0.0.1", port, path: "/__agent-shim/orpc/rest/frontdoor/catalogues/refresh", method: "POST", headers: { authorization: "Bearer " + token }, ca: [ca], agent: false }, (response) => {
12071
+ response.resume();
12072
+ response.on("end", () => response.statusCode === 200 ? finish(ok, "") : finish(failed, "catalogue refresh request returned HTTP " + String(response.statusCode)));
12073
+ response.on("error", (error) => finish(failed, error.message));
12074
+ });
12075
+ setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
12076
+ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
12077
+ request.end();
12078
+ `;
12079
+ ACCEPT_PROBE_SOURCE = `
12080
+ const { workerData } = require("node:worker_threads");
12081
+ const net = require("node:net");
12082
+ const { host, port, timeoutMs, shared, ok, failed, headerSlots } = workerData;
12083
+ const header = new Int32Array(shared, 0, headerSlots);
12084
+ const reason = new Uint8Array(shared, headerSlots * 4);
12085
+ let done = false;
12086
+ const finish = (verdict, message) => {
12087
+ if (done) return;
12088
+ done = true;
12089
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
12090
+ reason.set(bytes);
12091
+ Atomics.store(header, 1, bytes.length);
12092
+ Atomics.store(header, 0, verdict);
12093
+ Atomics.notify(header, 0);
12094
+ };
12095
+ const socket = net.connect({ host, port });
12096
+ socket.once("connect", () => { socket.destroy(); finish(ok, ""); });
12097
+ socket.once("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
12098
+ setTimeout(() => { socket.destroy(); finish(failed, "no connection accepted within " + String(timeoutMs) + "ms"); }, timeoutMs);
12099
+ `;
12100
+ }
12101
+ });
12102
+
12103
+ // src/providerReachability.ts
12104
+ function providerConnectTimeoutMs(provider) {
12105
+ return provider.connectTimeoutMs ?? DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS;
12106
+ }
12107
+ function dialTargetOf(baseUrl) {
12108
+ const url = new URL(baseUrl);
12109
+ const defaultPort = DEFAULT_PORTS[url.protocol];
12110
+ if (defaultPort === void 0) {
12111
+ return void 0;
12112
+ }
12113
+ return { host: url.hostname.replace(/^\[(.*)\]$/, "$1"), port: url.port === "" ? defaultPort : Number(url.port) };
12114
+ }
12115
+ function couldNotConnectMessage(subject, baseUrl, reason) {
12116
+ return `${subject} could not connect to ${baseUrl}: ${reason}`;
12117
+ }
12118
+ function probeProviderReachability(name, provider, probe) {
12119
+ const verdict = probe(provider.baseUrl, providerConnectTimeoutMs(provider));
12120
+ return verdict.ok ? { ok: true } : { ok: false, message: couldNotConnectMessage(`provider ${name}`, provider.baseUrl, verdict.reason) };
12121
+ }
12122
+ function unreachableProviderLine(name, provider, probe) {
12123
+ if (probe === void 0 || !isHttpProvider(provider)) {
12124
+ return void 0;
12125
+ }
12126
+ const reachability = probeProviderReachability(name, provider, probe);
12127
+ return reachability.ok ? void 0 : reachability.message;
12128
+ }
12129
+ var TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS, CONNECT_SYN_RETRANSMISSIONS_TOLERATED, DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS, DEFAULT_PORTS, realBaseUrlProbe;
12130
+ var init_providerReachability = __esm({
12131
+ "src/providerReachability.ts"() {
11724
12132
  "use strict";
11725
- import_node_fs10 = __toESM(require("node:fs"), 1);
11726
- init_load();
11727
- init_store();
11728
- init_unrecognisedKeys();
11729
12133
  init_schema();
11730
- init_cliError();
11731
- init_providerAliases();
11732
- init_credential();
11733
- init_realCredentialCache();
11734
- init_walk();
11735
- init_families();
11736
- init_names();
11737
- ProviderNotFoundError = class extends CliError {
11738
- constructor(name) {
11739
- super(`No provider named "${name}". Run \`agent-shim provider add ${name}\` first.`);
11740
- this.name = name;
11741
- this.name = "ProviderNotFoundError";
11742
- }
11743
- name;
11744
- };
11745
- ProviderAlreadyExistsError = class extends CliError {
11746
- constructor(providerName) {
11747
- super(`A provider named "${providerName}" already exists.`);
11748
- this.providerName = providerName;
11749
- this.name = "ProviderAlreadyExistsError";
11750
- }
11751
- providerName;
11752
- };
11753
- LEGACY_PROVIDER_FIELDS = ["tokenEnv", "tokenCommand", "authScheme"];
11754
- LEGACY_ENV_CREDENTIAL_KEYS = Object.values(CREDENTIAL_TARGET_VARS);
11755
- LEGACY_LITERAL_PLACEHOLDER = "<the value of env.ANTHROPIC_AUTH_TOKEN>";
11756
- LegacyProviderFileError = class extends CliError {
11757
- constructor(filePath, conversion) {
11758
- super(
11759
- `${filePath} uses ${conversion.fields.join(", ")}, which a credential block replaced. Rewrite it as:
11760
- ` + JSON.stringify(conversion.replacement, null, 2)
11761
- );
11762
- this.filePath = filePath;
11763
- this.conversion = conversion;
11764
- this.name = "LegacyProviderFileError";
11765
- }
11766
- filePath;
11767
- conversion;
11768
- };
11769
- ProviderKindMismatchError = class extends UsageError {
11770
- constructor(message) {
11771
- super(message);
11772
- this.name = "ProviderKindMismatchError";
11773
- }
12134
+ init_probe();
12135
+ TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS = 1e3;
12136
+ CONNECT_SYN_RETRANSMISSIONS_TOLERATED = 2;
12137
+ DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS = TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS * (2 ** (CONNECT_SYN_RETRANSMISSIONS_TOLERATED + 1) - 1);
12138
+ DEFAULT_PORTS = { "http:": 80, "https:": 443 };
12139
+ realBaseUrlProbe = (baseUrl, timeoutMs) => {
12140
+ const target = dialTargetOf(baseUrl);
12141
+ if (target === void 0) {
12142
+ return { ok: false, reason: "the base URL is neither http nor https" };
12143
+ }
12144
+ return probeAddressAcceptSync(target.host, target.port, timeoutMs);
11774
12145
  };
11775
12146
  }
11776
12147
  });
@@ -11817,7 +12188,7 @@ function formatPeriod(window) {
11817
12188
  if (window.periodMs === void 0) {
11818
12189
  return window.period ?? "unknown period";
11819
12190
  }
11820
- const hours = window.periodMs / MS_PER_HOUR4;
12191
+ const hours = window.periodMs / MS_PER_HOUR5;
11821
12192
  return hours >= HOURS_PER_DAY4 && Number.isInteger(hours / HOURS_PER_DAY4) ? `${String(hours / HOURS_PER_DAY4)}d` : `${String(hours)}h`;
11822
12193
  }
11823
12194
  function groupOf(row) {
@@ -11857,13 +12228,13 @@ function collectResets(snapshots, nowMs) {
11857
12228
  );
11858
12229
  return { resets: rows.sort(compareRows) };
11859
12230
  }
11860
- var MS_PER_HOUR4, HOURS_PER_DAY4;
12231
+ var MS_PER_HOUR5, HOURS_PER_DAY4;
11861
12232
  var init_resets = __esm({
11862
12233
  "src/usage/resets.ts"() {
11863
12234
  "use strict";
11864
12235
  init_preflight();
11865
12236
  init_rateLimit();
11866
- MS_PER_HOUR4 = 36e5;
12237
+ MS_PER_HOUR5 = 36e5;
11867
12238
  HOURS_PER_DAY4 = 24;
11868
12239
  }
11869
12240
  });
@@ -12477,7 +12848,7 @@ function providerModels(paths) {
12477
12848
  if (entry.provider.kind === "codex") {
12478
12849
  if (catalogue !== void 0 && catalogue.supervisorPid !== supervisorPid) return [];
12479
12850
  const env = doorHome === void 0 ? process.env : { ...process.env, CODEX_HOME: doorHome };
12480
- const fingerprint = savedCatalogueFingerprint(entry.provider, paths, env, import_node_os6.default.homedir(), realFsPort.readFileUtf8);
12851
+ const fingerprint = savedCatalogueFingerprint(entry.provider, paths, env, import_node_os7.default.homedir(), realFsPort.readFileUtf8);
12481
12852
  if (fingerprint === void 0 || catalogue?.credentialFingerprint !== fingerprint) return [];
12482
12853
  }
12483
12854
  return providerModelRows(entry.provider, catalogue?.models).map((row) => ({ provider: entry.name, model: row.model }));
@@ -12486,11 +12857,11 @@ function providerModels(paths) {
12486
12857
  function targetRefs(paths) {
12487
12858
  return providerModels(paths).map((entry) => `${entry.provider}/${entry.model}`);
12488
12859
  }
12489
- var import_node_os6;
12860
+ var import_node_os7;
12490
12861
  var init_targets = __esm({
12491
12862
  "src/models/targets.ts"() {
12492
12863
  "use strict";
12493
- import_node_os6 = __toESM(require("node:os"), 1);
12864
+ import_node_os7 = __toESM(require("node:os"), 1);
12494
12865
  init_catalogueCredential();
12495
12866
  init_state();
12496
12867
  init_modelPicker();
@@ -12500,135 +12871,6 @@ var init_targets = __esm({
12500
12871
  }
12501
12872
  });
12502
12873
 
12503
- // src/frontdoor/probe.ts
12504
- function requestCatalogueRefreshSync(port, caPem, token, timeoutMs = PROBE_TIMEOUT_MS) {
12505
- refuseToBlockInRole("a synchronous catalogue refresh request");
12506
- return runProbeWorker(CATALOGUE_REQUEST_SOURCE, { port, ca: caPem, token }, timeoutMs);
12507
- }
12508
- function probeFrontDoorSync(port, caPem, timeoutMs = PROBE_TIMEOUT_MS) {
12509
- refuseToBlockInRole("a synchronous probe of the front door");
12510
- return runProbeWorker(PROBE_SOURCE, { port, ca: caPem }, timeoutMs);
12511
- }
12512
- function probeListenerAcceptSync(port, timeoutMs = PROBE_TIMEOUT_MS) {
12513
- refuseToBlockInRole("a synchronous probe of a front door listener");
12514
- return runProbeWorker(ACCEPT_PROBE_SOURCE, { port }, timeoutMs);
12515
- }
12516
- function runProbeWorker(source, data, timeoutMs) {
12517
- const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
12518
- const header = new Int32Array(shared, 0, HEADER_SLOTS);
12519
- const worker = new import_node_worker_threads.Worker(source, {
12520
- eval: true,
12521
- workerData: { ...data, timeoutMs, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS }
12522
- });
12523
- worker.unref();
12524
- try {
12525
- const waited = Atomics.wait(header, 0, VERDICT_PENDING, timeoutMs + PROBE_WAIT_MARGIN_MS);
12526
- const verdict = Atomics.load(header, 0);
12527
- if (waited === "timed-out" || verdict === VERDICT_PENDING) {
12528
- return { ok: false, reason: `the probe did not finish within ${String(timeoutMs + PROBE_WAIT_MARGIN_MS)}ms` };
12529
- }
12530
- if (verdict === VERDICT_OK) {
12531
- return { ok: true };
12532
- }
12533
- const length = Atomics.load(header, 1);
12534
- return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
12535
- } finally {
12536
- void worker.terminate();
12537
- }
12538
- }
12539
- var import_node_worker_threads, PROBE_TIMEOUT_MS, PROBE_WAIT_MARGIN_MS, REASON_BYTES, HEADER_SLOTS, INT32_BYTES, VERDICT_PENDING, VERDICT_OK, VERDICT_FAILED, PROBE_SOURCE, CATALOGUE_REQUEST_SOURCE, ACCEPT_PROBE_SOURCE;
12540
- var init_probe = __esm({
12541
- "src/frontdoor/probe.ts"() {
12542
- "use strict";
12543
- init_processRole();
12544
- import_node_worker_threads = require("node:worker_threads");
12545
- PROBE_TIMEOUT_MS = 2e3;
12546
- PROBE_WAIT_MARGIN_MS = 1e3;
12547
- REASON_BYTES = 1024;
12548
- HEADER_SLOTS = 2;
12549
- INT32_BYTES = 4;
12550
- VERDICT_PENDING = 0;
12551
- VERDICT_OK = 1;
12552
- VERDICT_FAILED = 2;
12553
- PROBE_SOURCE = `
12554
- const { workerData } = require("node:worker_threads");
12555
- const https = require("node:https");
12556
- const { port, ca, timeoutMs, shared, ok, failed, headerSlots } = workerData;
12557
- const header = new Int32Array(shared, 0, headerSlots);
12558
- const reason = new Uint8Array(shared, headerSlots * 4);
12559
- let done = false;
12560
- const finish = (verdict, message) => {
12561
- if (done) return;
12562
- done = true;
12563
- const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
12564
- reason.set(bytes);
12565
- Atomics.store(header, 1, bytes.length);
12566
- Atomics.store(header, 0, verdict);
12567
- Atomics.notify(header, 0);
12568
- };
12569
- const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
12570
- let body = "";
12571
- response.setEncoding("utf8");
12572
- response.on("data", (chunk) => { body += chunk; });
12573
- response.on("end", () => {
12574
- if (response.statusCode === 200 && body === "ok") finish(ok, "");
12575
- else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
12576
- });
12577
- response.on("error", (error) => finish(failed, error.message));
12578
- });
12579
- // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
12580
- setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
12581
- request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
12582
- `;
12583
- CATALOGUE_REQUEST_SOURCE = `
12584
- const { workerData } = require("node:worker_threads");
12585
- const https = require("node:https");
12586
- const { port, ca, token, timeoutMs, shared, ok, failed, headerSlots } = workerData;
12587
- const header = new Int32Array(shared, 0, headerSlots);
12588
- const reason = new Uint8Array(shared, headerSlots * 4);
12589
- let done = false;
12590
- const finish = (verdict, message) => {
12591
- if (done) return;
12592
- done = true;
12593
- const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
12594
- reason.set(bytes);
12595
- Atomics.store(header, 1, bytes.length);
12596
- Atomics.store(header, 0, verdict);
12597
- Atomics.notify(header, 0);
12598
- };
12599
- const request = https.request({ host: "127.0.0.1", port, path: "/__agent-shim/orpc/rest/frontdoor/catalogues/refresh", method: "POST", headers: { authorization: "Bearer " + token }, ca: [ca], agent: false }, (response) => {
12600
- response.resume();
12601
- response.on("end", () => response.statusCode === 200 ? finish(ok, "") : finish(failed, "catalogue refresh request returned HTTP " + String(response.statusCode)));
12602
- response.on("error", (error) => finish(failed, error.message));
12603
- });
12604
- setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
12605
- request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
12606
- request.end();
12607
- `;
12608
- ACCEPT_PROBE_SOURCE = `
12609
- const { workerData } = require("node:worker_threads");
12610
- const net = require("node:net");
12611
- const { port, timeoutMs, shared, ok, failed, headerSlots } = workerData;
12612
- const header = new Int32Array(shared, 0, headerSlots);
12613
- const reason = new Uint8Array(shared, headerSlots * 4);
12614
- let done = false;
12615
- const finish = (verdict, message) => {
12616
- if (done) return;
12617
- done = true;
12618
- const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
12619
- reason.set(bytes);
12620
- Atomics.store(header, 1, bytes.length);
12621
- Atomics.store(header, 0, verdict);
12622
- Atomics.notify(header, 0);
12623
- };
12624
- const socket = net.connect({ host: "127.0.0.1", port });
12625
- socket.once("connect", () => { socket.destroy(); finish(ok, ""); });
12626
- socket.once("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
12627
- setTimeout(() => { socket.destroy(); finish(failed, "no connection accepted within " + String(timeoutMs) + "ms"); }, timeoutMs);
12628
- `;
12629
- }
12630
- });
12631
-
12632
12874
  // src/launcher/proxyBypass.ts
12633
12875
  function checkedProxyBypass(entries, source) {
12634
12876
  const seen = /* @__PURE__ */ new Set();
@@ -13787,7 +14029,10 @@ var init_hold = __esm({
13787
14029
  // src/launcher/launchReport.ts
13788
14030
  function poolDetail(pool) {
13789
14031
  const [reason] = pool.reasons;
13790
- return reason === void 0 ? {} : { detail: reason };
14032
+ if (reason === void 0) {
14033
+ return {};
14034
+ }
14035
+ return { detail: pool.provider === void 0 ? reason : `${reason} (ranked on provider ${pool.provider})` };
13791
14036
  }
13792
14037
  function rankingNotes(ranking, picked) {
13793
14038
  return ranking.flatMap((candidate, index) => [
@@ -13949,6 +14194,7 @@ function resolvePoolLaunch(params) {
13949
14194
  resuming,
13950
14195
  ...params.resumeContextTokens === void 0 ? {} : { resumeContextTokens: params.resumeContextTokens },
13951
14196
  ...params.committedContextTokens === void 0 ? {} : { committedContextTokens: params.committedContextTokens },
14197
+ ...params.providerOf === void 0 ? {} : { providerOf: params.providerOf },
13952
14198
  identityIdOf: identityIdResolver(params.paths.identitiesDir, params.fs),
13953
14199
  ...stickyRead.sticky === void 0 ? {} : { sticky: stickyRead.sticky }
13954
14200
  });
@@ -13990,6 +14236,7 @@ function resolvePoolLaunch(params) {
13990
14236
  explanation: `pool ${poolName}: ${move}${pick.reasons.slice(0, REASONS_LOGGED).join("; ")}`,
13991
14237
  reasons: pick.reasons,
13992
14238
  candidates: graph.ranking.candidates,
14239
+ ...pick.provider === void 0 ? {} : { provider: pick.provider },
13993
14240
  ...movedOff === void 0 ? {} : { movedOff },
13994
14241
  ...stickyRead.sticky === void 0 ? {} : { lastRanAs: stickyRead.sticky }
13995
14242
  };
@@ -14027,7 +14274,7 @@ function childExitCode(result) {
14027
14274
  return result.status;
14028
14275
  }
14029
14276
  if (result.signal !== null) {
14030
- return SIGNAL_EXIT_CODE_OFFSET + import_node_os7.default.constants.signals[result.signal];
14277
+ return SIGNAL_EXIT_CODE_OFFSET + import_node_os8.default.constants.signals[result.signal];
14031
14278
  }
14032
14279
  return 1;
14033
14280
  }
@@ -14041,11 +14288,11 @@ function spawnClaude(params) {
14041
14288
  }
14042
14289
  return params.proc.exit(childExitCode(result));
14043
14290
  }
14044
- var import_node_os7, SIGNAL_EXIT_CODE_OFFSET;
14291
+ var import_node_os8, SIGNAL_EXIT_CODE_OFFSET;
14045
14292
  var init_spawn = __esm({
14046
14293
  "src/launcher/spawn.ts"() {
14047
14294
  "use strict";
14048
- import_node_os7 = __toESM(require("node:os"), 1);
14295
+ import_node_os8 = __toESM(require("node:os"), 1);
14049
14296
  SIGNAL_EXIT_CODE_OFFSET = 128;
14050
14297
  }
14051
14298
  });
@@ -14127,7 +14374,7 @@ function resolveIdentityCredential(identity, credential, env, port) {
14127
14374
  const resolution = resolveCredential({ credential, env, port, subject: `identity ${identity.name}`, cacheKey: identityCacheKey(identity.id) });
14128
14375
  return resolution.ok ? resolution : { ok: false, status: CREDENTIAL_UNAVAILABLE_EXIT, message: `agent-shim: ${resolution.message}` };
14129
14376
  }
14130
- function pickFromPool(decided, params, parsedArgv, readOnly) {
14377
+ function pickFromPool(decided, params, parsedArgv, readOnly, providerSelections) {
14131
14378
  const { paths, fs: fs17, proc, log } = params;
14132
14379
  if (decided.pool === void 0) {
14133
14380
  return { identityDecision: decided };
@@ -14142,6 +14389,17 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
14142
14389
  return proc.exit(1);
14143
14390
  }
14144
14391
  const resumeContextTokens = resumedContextTokens(farmRuntime.fs, { claudeHome: farmRuntime.claudeHome, cwd: farmRuntime.cwd, passthrough: parsedArgv.rest });
14392
+ const cliFlagConfigProfile = params.cliFlagConfigProfile ?? parsedArgv.configProfile;
14393
+ const providerOf = memberProviderResolver({
14394
+ paths,
14395
+ fs: fs17,
14396
+ env: providerSelections.env,
14397
+ cliProvider: parsedArgv.provider,
14398
+ ...cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile },
14399
+ ...params.directoryRuleConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: params.directoryRuleConfigProfile },
14400
+ ...params.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: params.globalDefaultConfigProfile },
14401
+ loadCascade: (baseConfigProfile) => farmRuntime.loadCascade(baseConfigProfile, providerSelections.cliOverride)
14402
+ });
14145
14403
  const resolution = resolvePoolLaunch({
14146
14404
  poolName: decided.pool,
14147
14405
  selectedVia: decided.source,
@@ -14153,6 +14411,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
14153
14411
  now: farmRuntime.now,
14154
14412
  sleep: farmRuntime.lock.sleep,
14155
14413
  passthrough: parsedArgv.rest,
14414
+ providerOf,
14156
14415
  ...resumeContextTokens === void 0 ? {} : { resumeContextTokens },
14157
14416
  // A read-only decision never sleeps for a refused pool and never records its pick, so asking what a launch would pick leaves the next real launch's keep-warm preference as it was.
14158
14417
  wait: !readOnly && parsedArgv.wait === true,
@@ -14165,7 +14424,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
14165
14424
  }
14166
14425
  return {
14167
14426
  identityDecision: { ...decided, name: resolution.identity },
14168
- poolPick: { name: decided.pool, reasons: resolution.reasons, ...resolution.movedOff === void 0 ? {} : { movedOff: resolution.movedOff } },
14427
+ poolPick: { name: decided.pool, reasons: resolution.reasons, ...resolution.provider === void 0 ? {} : { provider: resolution.provider }, ...resolution.movedOff === void 0 ? {} : { movedOff: resolution.movedOff } },
14169
14428
  poolRanking: resolution.candidates,
14170
14429
  ...resolution.lastRanAs === void 0 ? {} : { lastRanAs: { identity: resolution.lastRanAs.identity, agoMs: farmRuntime.now() - Date.parse(resolution.lastRanAs.at) } }
14171
14430
  };
@@ -14201,7 +14460,7 @@ function decideLaunch(params, readOnly, onRecorded) {
14201
14460
  shareFlags: parsedArgv.shareFlags,
14202
14461
  hideFlags: parsedArgv.hideFlags
14203
14462
  });
14204
- const { identityDecision, poolPick, poolRanking, lastRanAs } = pickFromPool(decidedIdentity, params, parsedArgv, readOnly);
14463
+ const { identityDecision, poolPick, poolRanking, lastRanAs } = pickFromPool(decidedIdentity, params, parsedArgv, readOnly, { env, cliOverride });
14205
14464
  const lockFarm = !readOnly && !configDirEscapeHatchApplies && identityDecision.name !== void 0 ? params.farm : void 0;
14206
14465
  const lockPorts = params.namesLock ?? (lockFarm === void 0 ? realIdentityNamesLockPorts : { fs: lockFarm.fs, nowMs: lockFarm.now, ...lockFarm.lock });
14207
14466
  const namesLock = readOnly || configDirEscapeHatchApplies || identityDecision.name === void 0 ? void 0 : acquireIdentityNamesLock(paths, lockPorts);
@@ -14402,12 +14661,12 @@ function decideLaunch(params, readOnly, onRecorded) {
14402
14661
  if (definition.kind === "codex" && readOnly && cache !== void 0) {
14403
14662
  const binding = parseCatalogueBinding(params.fs.readFileUtf8(catalogueBindingPath(paths, name, catalogueOwner, generation)));
14404
14663
  const configuredHome = catalogueEnv.CODEX_HOME;
14405
- const home = configuredHome === void 0 || configuredHome === "" ? import_node_path51.default.join(import_node_os8.default.homedir(), ".codex") : configuredHome;
14664
+ const home = configuredHome === void 0 || configuredHome === "" ? import_node_path51.default.join(import_node_os9.default.homedir(), ".codex") : configuredHome;
14406
14665
  const source = definition.codex?.login === "chatgpt-sign-in" ? paths.chatgptSignInFile : import_node_path51.default.resolve(home, "auth.json");
14407
14666
  const revision = params.fs.fileRevision?.(source);
14408
14667
  if (binding === void 0 || binding.fingerprint !== cache.credentialFingerprint || binding.source !== source || revision === void 0 || revision !== binding.revision) return [];
14409
14668
  }
14410
- const fingerprint = definition.kind === "codex" && !readOnly ? savedCatalogueFingerprint(definition, paths, catalogueEnv, import_node_os8.default.homedir(), params.fs.readFileUtf8) : void 0;
14669
+ const fingerprint = definition.kind === "codex" && !readOnly ? savedCatalogueFingerprint(definition, paths, catalogueEnv, import_node_os9.default.homedir(), params.fs.readFileUtf8) : void 0;
14411
14670
  if (definition.kind === "codex" && !readOnly && cache !== void 0 && (fingerprint === void 0 || cache.credentialFingerprint !== fingerprint)) return [];
14412
14671
  return [[name, definition, cache?.models ?? []]];
14413
14672
  } catch {
@@ -14561,6 +14820,11 @@ function prepareRegisteredLaunch(params, onRecorded) {
14561
14820
  proc.exit(check.status);
14562
14821
  }
14563
14822
  }
14823
+ const unreachable = resolvedProvider === void 0 ? void 0 : unreachableProviderLine(resolvedProvider.name, resolvedProvider.definition, params.probeBaseUrl);
14824
+ if (unreachable !== void 0) {
14825
+ log.error(`agent-shim: ${unreachable}`);
14826
+ proc.exit(1);
14827
+ }
14564
14828
  const frontDoorPort = params.frontdoor;
14565
14829
  const frontDoorEngaged = resolvedProvider !== void 0 || resolvedFlags.headroom || resolvedFlags.trackUsage;
14566
14830
  if (frontDoorEngaged && frontDoorPort === void 0) {
@@ -14675,12 +14939,12 @@ function runLaunchPlan(plan, spawn3) {
14675
14939
  function runLauncher(params) {
14676
14940
  params.proc.exit(runLaunchPlan(prepareLaunch(params), params.spawn));
14677
14941
  }
14678
- var import_node_crypto17, import_node_os8, import_node_util2, import_node_path51;
14942
+ var import_node_crypto17, import_node_os9, import_node_util2, import_node_path51;
14679
14943
  var init_launcher = __esm({
14680
14944
  "src/launcher.ts"() {
14681
14945
  "use strict";
14682
14946
  import_node_crypto17 = require("node:crypto");
14683
- import_node_os8 = __toESM(require("node:os"), 1);
14947
+ import_node_os9 = __toESM(require("node:os"), 1);
14684
14948
  init_catalogueCredential();
14685
14949
  import_node_util2 = require("node:util");
14686
14950
  import_node_path51 = __toESM(require("node:path"), 1);
@@ -14706,6 +14970,7 @@ var init_launcher = __esm({
14706
14970
  init_state();
14707
14971
  init_providerCatalogue();
14708
14972
  init_providersStore();
14973
+ init_memberProvider();
14709
14974
  init_pool();
14710
14975
  init_resumeContext();
14711
14976
  init_lock();
@@ -14715,6 +14980,7 @@ var init_launcher = __esm({
14715
14980
  init_flatten();
14716
14981
  init_walk();
14717
14982
  init_schema();
14983
+ init_providerReachability();
14718
14984
  init_schema();
14719
14985
  init_credential();
14720
14986
  init_middleware();
@@ -14875,7 +15141,7 @@ function realFrontDoorPort(paths, spawnDaemon) {
14875
15141
  const cache2 = parseCatalogueCache(realFarmFs.readFileUtf8(catalogueCachePath(paths, name, supervisorPid, owner.generation)));
14876
15142
  let fingerprint;
14877
15143
  try {
14878
- fingerprint = savedCatalogueFingerprint(provider, paths, { ...process.env, CODEX_HOME: owner.codexHome }, import_node_os9.default.homedir(), realFarmFs.readFileUtf8);
15144
+ fingerprint = savedCatalogueFingerprint(provider, paths, { ...process.env, CODEX_HOME: owner.codexHome }, import_node_os10.default.homedir(), realFarmFs.readFileUtf8);
14879
15145
  } catch (error) {
14880
15146
  warnings.add(`Cannot read catalogue credentials for ${name}: ${error instanceof Error ? error.message : String(error)}`);
14881
15147
  return false;
@@ -14925,12 +15191,12 @@ function realFrontDoorPort(paths, spawnDaemon) {
14925
15191
  }
14926
15192
  };
14927
15193
  }
14928
- var import_node_fs17, import_node_os9, realTrustBundleFs;
15194
+ var import_node_fs17, import_node_os10, realTrustBundleFs;
14929
15195
  var init_realFrontDoorPort = __esm({
14930
15196
  "src/frontdoor/realFrontDoorPort.ts"() {
14931
15197
  "use strict";
14932
15198
  import_node_fs17 = __toESM(require("node:fs"), 1);
14933
- import_node_os9 = __toESM(require("node:os"), 1);
15199
+ import_node_os10 = __toESM(require("node:os"), 1);
14934
15200
  init_providersStore();
14935
15201
  init_providerCatalogue();
14936
15202
  init_catalogueCredential();
@@ -14957,7 +15223,7 @@ var init_realFrontDoorPort = __esm({
14957
15223
 
14958
15224
  // src/launchWiring.ts
14959
15225
  function buildFarmRuntime(paths, cwd, run = realRunPort) {
14960
- const home = import_node_os10.default.homedir();
15226
+ const home = import_node_os11.default.homedir();
14961
15227
  const read = cosmiconfigReader();
14962
15228
  const classification = loadClassification(paths);
14963
15229
  const loaded = loadCascadeInput({ paths, home, cwd, read });
@@ -15008,6 +15274,7 @@ function realPrepareLaunchParams(paths, options) {
15008
15274
  headroom: realHeadroomPort(paths, { spawnDaemon: options.spawnDaemon, cwd: farm.runtime.cwd }),
15009
15275
  frontdoor: realFrontDoorPort(paths, options.spawnDaemon),
15010
15276
  credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
15277
+ probeBaseUrl: realBaseUrlProbe,
15011
15278
  hold: realHoldPort,
15012
15279
  hasStoredLogin: (identity) => identitySignIn(realFarmFs, { platform: process.platform, run: options.run ?? realRunPort }, { farmRoot: import_node_path54.default.join(paths.identitiesDir, identity), hasCredentialBlock: false, provider: void 0 }).state !== "signed-out",
15013
15280
  hasUsableLogin: (identity, claudeBin) => storedLoginUsable(options.run ?? realRunPort, claudeBin, import_node_path54.default.join(paths.identitiesDir, identity), options.proc.env),
@@ -15071,11 +15338,11 @@ function resolveClaudeLaunch(options, run = realRunPort) {
15071
15338
  };
15072
15339
  return { resolution: resolveLaunch(realPrepareLaunchParams(paths, { proc, log, spawnDaemon, run, farm: buildFarmRuntime(paths, options.cwd, run) })), warnings };
15073
15340
  }
15074
- var import_node_os10, import_node_path54, import_node_crypto19, LaunchRefusedError;
15341
+ var import_node_os11, import_node_path54, import_node_crypto19, LaunchRefusedError;
15075
15342
  var init_launchWiring = __esm({
15076
15343
  "src/launchWiring.ts"() {
15077
15344
  "use strict";
15078
- import_node_os10 = __toESM(require("node:os"), 1);
15345
+ import_node_os11 = __toESM(require("node:os"), 1);
15079
15346
  import_node_path54 = __toESM(require("node:path"), 1);
15080
15347
  import_node_crypto19 = require("node:crypto");
15081
15348
  init_cliError();
@@ -15091,6 +15358,7 @@ var init_launchWiring = __esm({
15091
15358
  init_replayRun();
15092
15359
  init_paths();
15093
15360
  init_signIn();
15361
+ init_providerReachability();
15094
15362
  init_realPorts();
15095
15363
  LaunchRefusedError = class extends CliError {
15096
15364
  exitCode;
@@ -15233,7 +15501,7 @@ var init_anthropicUsageRefresh = __esm({
15233
15501
  init_schema();
15234
15502
  init_identity();
15235
15503
  init_middleware();
15236
- init_pick();
15504
+ init_windowLengths();
15237
15505
  init_plan2();
15238
15506
  PERCENT2 = 100;
15239
15507
  ANTHROPIC_USAGE_FRESHNESS_MS = FIVE_HOUR_WINDOW_MS / PERCENT2;
@@ -15439,14 +15707,14 @@ function createRealAnthropicUsageRefresher(params) {
15439
15707
  },
15440
15708
  now: () => Date.now(),
15441
15709
  log: params.log,
15442
- concurrency: (0, import_node_os11.availableParallelism)()
15710
+ concurrency: (0, import_node_os12.availableParallelism)()
15443
15711
  });
15444
15712
  }
15445
- var import_node_os11, PROBE_LAUNCH_FLAGS;
15713
+ var import_node_os12, PROBE_LAUNCH_FLAGS;
15446
15714
  var init_realAnthropicUsageProbe = __esm({
15447
15715
  "src/usage/realAnthropicUsageProbe.ts"() {
15448
15716
  "use strict";
15449
- import_node_os11 = require("node:os");
15717
+ import_node_os12 = require("node:os");
15450
15718
  init_identityStore();
15451
15719
  init_anthropicUsageRefresh();
15452
15720
  init_identityClaude();
@@ -15812,6 +16080,7 @@ __export(index_exports, {
15812
16080
  realCodexAppServerPort: () => realCodexAppServerPort,
15813
16081
  realConnectCertStore: () => realConnectCertStore,
15814
16082
  realConnectEffects: () => realConnectEffects,
16083
+ realMemberProviderResolver: () => realMemberProviderResolver,
15815
16084
  realRcControlTransport: () => realRcControlTransport,
15816
16085
  realRcEventDial: () => realRcEventDial,
15817
16086
  realRcStreamDial: () => realRcStreamDial,
@@ -19575,7 +19844,7 @@ var import_client8 = require("@orpc/client");
19575
19844
  var import_openapi9 = require("@orpc/openapi");
19576
19845
 
19577
19846
  // src/checkReport.ts
19578
- var import_node_os5 = __toESM(require("node:os"), 1);
19847
+ var import_node_os6 = __toESM(require("node:os"), 1);
19579
19848
  init_cliError();
19580
19849
 
19581
19850
  // src/codex/categories.ts
@@ -19605,7 +19874,7 @@ init_classify();
19605
19874
  init_load();
19606
19875
 
19607
19876
  // src/launchSelection.ts
19608
- var import_node_os3 = __toESM(require("node:os"), 1);
19877
+ var import_node_os4 = __toESM(require("node:os"), 1);
19609
19878
  init_load();
19610
19879
  init_cascade();
19611
19880
  init_identity();
@@ -19622,6 +19891,7 @@ function candidateView(candidate) {
19622
19891
  feasible: candidate.feasible,
19623
19892
  ...candidate.blockedUntilMs === void 0 ? {} : { blockedUntil: new Date(candidate.blockedUntilMs).toISOString() },
19624
19893
  plan: candidate.plan,
19894
+ ...candidate.provider === void 0 ? {} : { provider: candidate.provider },
19625
19895
  reasons: [...candidate.reasons]
19626
19896
  };
19627
19897
  }
@@ -19635,6 +19905,7 @@ function collectPoolPick(params) {
19635
19905
  nowMs: params.nowMs,
19636
19906
  resuming: false,
19637
19907
  identityIdOf: identityIdResolver(params.paths.identitiesDir, params.fs),
19908
+ ...params.providerOf === void 0 ? {} : { providerOf: params.providerOf },
19638
19909
  ...sticky.sticky === void 0 ? {} : { sticky: sticky.sticky }
19639
19910
  });
19640
19911
  return {
@@ -19649,6 +19920,29 @@ function collectPoolPick(params) {
19649
19920
  };
19650
19921
  }
19651
19922
 
19923
+ // src/poolProviderWiring.ts
19924
+ var import_node_os3 = __toESM(require("node:os"), 1);
19925
+ init_load();
19926
+ init_cascade();
19927
+ init_memberProvider();
19928
+ init_realPorts();
19929
+ function realMemberProviderResolver(params) {
19930
+ const home = import_node_os3.default.homedir();
19931
+ const read = cosmiconfigReader();
19932
+ const loaded = params.loaded ?? loadCascadeInput({ paths: params.paths, home, cwd: params.cwd, read });
19933
+ const selections = readDirectorySelections(loaded);
19934
+ return memberProviderResolver({
19935
+ paths: params.paths,
19936
+ fs: realFsPort,
19937
+ env: params.env,
19938
+ cliProvider: params.cliProvider,
19939
+ ...params.cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile: params.cliFlagConfigProfile },
19940
+ ...selections.configProfile === void 0 ? {} : { directoryRuleConfigProfile: selections.configProfile },
19941
+ ...loaded.globalConfig?.defaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: loaded.globalConfig.defaultConfigProfile },
19942
+ loadCascade: (baseConfigProfile) => loadCascadeInput({ paths: params.paths, home, cwd: params.cwd, read, ...baseConfigProfile === void 0 ? {} : { baseConfigProfile } }).input
19943
+ });
19944
+ }
19945
+
19652
19946
  // src/launchSelection.ts
19653
19947
  init_poolStore();
19654
19948
  init_realPorts();
@@ -19674,7 +19968,8 @@ function selectLaunch(params, loaded) {
19674
19968
  if (pools[decidedIdentity.pool] === void 0) {
19675
19969
  throw new PoolNotFoundError(decidedIdentity.pool);
19676
19970
  }
19677
- poolPick = collectPoolPick({ paths, fs: realFsPort, usageFs: realFarmFs, poolName: decidedIdentity.pool, pools, directory: cwd, nowMs: Date.now() });
19971
+ const providerOf = realMemberProviderResolver({ paths, cwd, env: params.env, ...params.configProfile === void 0 ? {} : { cliFlagConfigProfile: params.configProfile }, loaded });
19972
+ poolPick = collectPoolPick({ paths, fs: realFsPort, usageFs: realFarmFs, poolName: decidedIdentity.pool, pools, directory: cwd, nowMs: Date.now(), providerOf });
19678
19973
  }
19679
19974
  const identity = poolPick?.pick === void 0 ? decidedIdentity : { ...decidedIdentity, name: poolPick.pick };
19680
19975
  const loadedIdentity = identity.name === void 0 ? void 0 : loadIdentity(paths.identitiesDir, identity.name, realFsPort);
@@ -19691,7 +19986,7 @@ function selectLaunch(params, loaded) {
19691
19986
  };
19692
19987
  }
19693
19988
  function resolveLaunchSelection(params) {
19694
- const loaded = loadCascadeInput({ paths: params.paths, home: import_node_os3.default.homedir(), cwd: params.cwd, read: cosmiconfigReader() });
19989
+ const loaded = loadCascadeInput({ paths: params.paths, home: import_node_os4.default.homedir(), cwd: params.cwd, read: cosmiconfigReader() });
19695
19990
  return selectLaunch(params, loaded).selection;
19696
19991
  }
19697
19992
 
@@ -19707,6 +20002,7 @@ var import_zod27 = require("zod");
19707
20002
  init_envBool();
19708
20003
  init_load();
19709
20004
  init_schema();
20005
+ init_providerReachability();
19710
20006
  init_identityStore();
19711
20007
  init_credential();
19712
20008
  init_claudeVersion();
@@ -19899,6 +20195,7 @@ function runCheck(params) {
19899
20195
  const settingsExposure = inspectSettingsExposure({ settingsShared, files: params.settingsFiles });
19900
20196
  const keychain = !isCodex && params.platform === "darwin" && params.run !== void 0 && params.farmRoot !== void 0 ? lookupKeychainService(params.run, params.farmRoot) : void 0;
19901
20197
  const claudeVersion = isCodex ? void 0 : buildClaudeVersionReport(params, resolved.flattened.launch.claudeVersion);
20198
+ const providerReachability = buildProviderReachability(params.provider, params.probeBaseUrl);
19902
20199
  return {
19903
20200
  ...params.identityName === void 0 ? {} : { identityName: params.identityName },
19904
20201
  identitySource: params.identitySource,
@@ -19912,9 +20209,18 @@ function runCheck(params) {
19912
20209
  ...keychain === void 0 ? {} : { keychain },
19913
20210
  settingsExposure,
19914
20211
  credential: buildCredentialReport(params.provider, params.identity, params.identityId, params.credentialCache),
19915
- ...claudeVersion === void 0 ? {} : { claudeVersion }
20212
+ ...claudeVersion === void 0 ? {} : { claudeVersion },
20213
+ ...providerReachability === void 0 ? {} : { providerReachability }
19916
20214
  };
19917
20215
  }
20216
+ function buildProviderReachability(provider, probe) {
20217
+ if (provider?.definition === void 0 || probe === void 0 || !isHttpProvider(provider.definition)) {
20218
+ return void 0;
20219
+ }
20220
+ const { baseUrl } = provider.definition;
20221
+ const reachability = probeProviderReachability(provider.name, provider.definition, probe);
20222
+ return reachability.ok ? { name: provider.name, baseUrl, ok: true } : { name: provider.name, baseUrl, ok: false, message: reachability.message };
20223
+ }
19918
20224
  function formatCheckReport(report) {
19919
20225
  const lines = [];
19920
20226
  lines.push(`Identity: ${report.identityName ?? "(none)"} (${report.identitySource})`);
@@ -19961,6 +20267,11 @@ function formatCheckReport(report) {
19961
20267
  if (credential.applies === "stored-login") {
19962
20268
  lines.push(" The identity's stored login (no credential block applies).");
19963
20269
  }
20270
+ if (report.providerReachability !== void 0) {
20271
+ lines.push("", "Provider reachability:");
20272
+ const reachability = report.providerReachability;
20273
+ lines.push(reachability.ok ? ` Provider ${reachability.name}: ${reachability.baseUrl} accepts connections` : ` [FAIL] ${reachability.message}`);
20274
+ }
19964
20275
  if (report.claudeVersion !== void 0) {
19965
20276
  lines.push("", "Claude Code version:");
19966
20277
  const { pinned, highestInstalled, installed } = report.claudeVersion;
@@ -20011,11 +20322,12 @@ function checkReportToJson(report) {
20011
20322
  ...report.keychain === void 0 ? {} : { keychain: report.keychain },
20012
20323
  settingsExposure: report.settingsExposure,
20013
20324
  credential: report.credential,
20014
- ...report.claudeVersion === void 0 ? {} : { claudeVersion: report.claudeVersion }
20325
+ ...report.claudeVersion === void 0 ? {} : { claudeVersion: report.claudeVersion },
20326
+ ...report.providerReachability === void 0 ? {} : { providerReachability: report.providerReachability }
20015
20327
  };
20016
20328
  }
20017
20329
  function checkReportHasWarnings(report) {
20018
- return report.resolved.diagnostics.some((diagnostic) => diagnostic.severity !== "info") || report.projectEncodingAmbiguities.length > 0 || !report.ambientCredential.ok || report.credential.provider?.problem !== void 0 || report.claudeVersion?.pinned?.installed === false;
20330
+ return report.resolved.diagnostics.some((diagnostic) => diagnostic.severity !== "info") || report.projectEncodingAmbiguities.length > 0 || !report.ambientCredential.ok || report.credential.provider?.problem !== void 0 || report.providerReachability?.ok === false || report.claudeVersion?.pinned?.installed === false;
20019
20331
  }
20020
20332
  function loadCheckProvider(paths, name) {
20021
20333
  let definition;
@@ -20031,7 +20343,7 @@ function loadCheckProvider(paths, name) {
20031
20343
  }
20032
20344
  function collectCheckReport(params) {
20033
20345
  const { paths, cwd } = params;
20034
- const home = import_node_os5.default.homedir();
20346
+ const home = import_node_os6.default.homedir();
20035
20347
  const read = cosmiconfigReader();
20036
20348
  const loaded = loadCascadeInput({ paths, home, cwd, read });
20037
20349
  const git = resolveGitBranch(realRunPort, cwd);
@@ -20082,7 +20394,8 @@ function collectCheckReport(params) {
20082
20394
  ...isCodex ? {} : { installedClaudeVersions: realInstalledClaudeVersions() },
20083
20395
  ...farmRoot === void 0 ? {} : { farmRoot },
20084
20396
  platform: process.platform,
20085
- ...provider === void 0 ? {} : { provider }
20397
+ ...provider === void 0 ? {} : { provider },
20398
+ probeBaseUrl: realBaseUrlProbe
20086
20399
  });
20087
20400
  return report;
20088
20401
  }
@@ -20167,6 +20480,8 @@ var PoolPickCandidateViewSchema = import_zod28.z.strictObject({
20167
20480
  /** When an `ineligible` member can be used again, as an ISO instant. */
20168
20481
  blockedUntil: import_zod28.z.iso.datetime().optional(),
20169
20482
  plan: PlanClassSchema,
20483
+ /** The provider the member was ranked on, when its launch spends one in place of its Claude account: its windows, refusals and plan are the provider's own. Absent when ranked on the Claude account. */
20484
+ provider: import_zod28.z.string().optional(),
20170
20485
  /** The facts behind the class and score, in the order they matter. */
20171
20486
  reasons: import_zod28.z.array(import_zod28.z.string())
20172
20487
  });
@@ -20245,6 +20560,10 @@ var CheckCredentialProviderSchema = import_zod29.z.union([
20245
20560
  import_zod29.z.strictObject({ name: import_zod29.z.string(), credential: CredentialSummarySchema.optional(), cached: CachedCredentialStateSchema.optional() }),
20246
20561
  import_zod29.z.strictObject({ name: import_zod29.z.string(), problem: import_zod29.z.string() })
20247
20562
  ]);
20563
+ var CheckProviderReachabilitySchema = import_zod29.z.union([
20564
+ import_zod29.z.strictObject({ name: import_zod29.z.string(), baseUrl: import_zod29.z.string(), ok: import_zod29.z.literal(true) }),
20565
+ import_zod29.z.strictObject({ name: import_zod29.z.string(), baseUrl: import_zod29.z.string(), ok: import_zod29.z.literal(false), message: import_zod29.z.string() })
20566
+ ]);
20248
20567
  var CheckCredentialSchema = import_zod29.z.strictObject({
20249
20568
  applies: import_zod29.z.enum(CHECK_CREDENTIAL_APPLIES),
20250
20569
  provider: CheckCredentialProviderSchema.optional(),
@@ -20271,7 +20590,8 @@ var CheckReportJsonSchema = import_zod29.z.strictObject({
20271
20590
  keychain: CheckKeychainSchema.optional(),
20272
20591
  settingsExposure: import_zod29.z.readonly(import_zod29.z.array(CheckSettingsExposureSchema)),
20273
20592
  credential: CheckCredentialSchema,
20274
- claudeVersion: CheckClaudeVersionSchema.optional()
20593
+ claudeVersion: CheckClaudeVersionSchema.optional(),
20594
+ providerReachability: CheckProviderReachabilitySchema.optional()
20275
20595
  });
20276
20596
 
20277
20597
  // src/frontdoor/controlApi.ts
@@ -20315,7 +20635,6 @@ function codexIdentityFindings(entry, identity) {
20315
20635
  // src/doctorReport.ts
20316
20636
  init_claudeShim();
20317
20637
  init_readableConfig();
20318
- init_names();
20319
20638
  init_store();
20320
20639
  init_identityStore();
20321
20640
  init_identityRecords();
@@ -20390,6 +20709,28 @@ var import_node_path42 = __toESM(require("node:path"), 1);
20390
20709
  init_signIn();
20391
20710
  init_identityAccounts();
20392
20711
  init_read();
20712
+ init_providerReachability();
20713
+
20714
+ // src/doctorNameFinding.ts
20715
+ init_names();
20716
+ function pushNameFinding(push, section, kind, entry) {
20717
+ if (isFileName(entry.name)) {
20718
+ return true;
20719
+ }
20720
+ if (!isStoredName(entry.name)) {
20721
+ push(section, "fail", `${entry.path} cannot be used as a ${kind}: its name is ${JSON.stringify(entry.name)}, and a name ${FILE_NAME_RULE}. Rename or remove the file.`, entry.name);
20722
+ return false;
20723
+ }
20724
+ push(
20725
+ section,
20726
+ "warn",
20727
+ `The ${kind} ${JSON.stringify(entry.name)} is stored under a name that does not fit the shape names are given now (a name ${FILE_NAME_RULE}). It still works from your own configuration, but a project file cannot name it. Rename ${entry.path} to a name that fits, and change what names it.`,
20728
+ entry.name
20729
+ );
20730
+ return true;
20731
+ }
20732
+
20733
+ // src/doctorReport.ts
20393
20734
  init_siwcStore();
20394
20735
  init_siwc();
20395
20736
  init_load();
@@ -20884,23 +21225,7 @@ function signInProblem(signIn) {
20884
21225
  return error instanceof Error ? error.message : String(error);
20885
21226
  }
20886
21227
  }
20887
- function pushNameFinding(push, section, kind, entry) {
20888
- if (isFileName(entry.name)) {
20889
- return true;
20890
- }
20891
- if (!isStoredName(entry.name)) {
20892
- push(section, "fail", `${entry.path} cannot be used as a ${kind}: its name is ${JSON.stringify(entry.name)}, and a name ${FILE_NAME_RULE}. Rename or remove the file.`, entry.name);
20893
- return false;
20894
- }
20895
- push(
20896
- section,
20897
- "warn",
20898
- `The ${kind} ${JSON.stringify(entry.name)} is stored under a name that does not fit the shape names are given now (a name ${FILE_NAME_RULE}). It still works from your own configuration, but a project file cannot name it. Rename ${entry.path} to a name that fits, and change what names it.`,
20899
- entry.name
20900
- );
20901
- return true;
20902
- }
20903
- function pushProvider(push, entry, cacheEnv, signIn) {
21228
+ function pushProvider(push, entry, cacheEnv, signIn, probeBaseUrl) {
20904
21229
  if (entry.raw === void 0) {
20905
21230
  push("provider", "fail", `${entry.path} is missing.`, entry.name);
20906
21231
  return;
@@ -20932,6 +21257,10 @@ function pushProvider(push, entry, cacheEnv, signIn) {
20932
21257
  if (!router && validated3.data.env?.ENABLE_TOOL_SEARCH === void 0) {
20933
21258
  push("provider", "warn", `${entry.name} does not set ENABLE_TOOL_SEARCH: a session on this provider keeps Claude Code's own API as its base URL, so it defers MCP tool loading and sends tool_reference payloads the upstream backend must understand. Set ENABLE_TOOL_SEARCH=false in the provider's env block to load tools upfront instead, when the backend does not support them.`, entry.name);
20934
21259
  }
21260
+ const unreachable = unreachableProviderLine(entry.name, validated3.data, probeBaseUrl);
21261
+ if (unreachable !== void 0) {
21262
+ push("provider", "fail", unreachable, entry.name);
21263
+ }
20935
21264
  if (signIn !== void 0 && isCodexProvider(validated3.data) && validated3.data.codex?.login === "chatgpt-sign-in") {
20936
21265
  const problem = signInProblem(signIn);
20937
21266
  if (problem !== void 0) {
@@ -21162,7 +21491,7 @@ function runDoctor(params) {
21162
21491
  if (!pushNameFinding(push, "provider", "provider", entry)) {
21163
21492
  continue;
21164
21493
  }
21165
- pushProvider(push, entry, params.credentialCache, params.chatgptSignIn);
21494
+ pushProvider(push, entry, params.credentialCache, params.chatgptSignIn, params.probeBaseUrl);
21166
21495
  }
21167
21496
  const providerNames = new Set(params.providers.map((entry) => entry.name));
21168
21497
  for (const finding of aliasFindings(params.providerAliases ?? {}, providerNames)) {
@@ -21469,6 +21798,7 @@ function collectDoctorReport(params) {
21469
21798
  configProfiles,
21470
21799
  providers,
21471
21800
  providerAliases: readProviderAliases(paths),
21801
+ probeBaseUrl: realBaseUrlProbe,
21472
21802
  renameJournals: listRenameJournals(realFarmFs, paths.identityRenamesDir),
21473
21803
  unreachableIdentities,
21474
21804
  identityRecords: { all: records, displaced: displacedIdentities.map((record) => ({ ...record, directoryPresent: import_node_fs14.default.existsSync(import_node_path42.default.join(paths.identitiesDir, record.id)) })), nameRenames: unfinishedNameRenames(paths).map((record) => ({ from: record.from, description: describeInterruptedNameRename(paths, record) })), strayNameRenameFiles: strayNameRenameRecordFiles(paths) },
@@ -22334,6 +22664,8 @@ var LaunchResolveInputSchema = import_zod41.z.strictObject({
22334
22664
  var LaunchPoolDecisionSchema = import_zod41.z.strictObject({
22335
22665
  name: import_zod41.z.string(),
22336
22666
  reasons: import_zod41.z.readonly(import_zod41.z.array(import_zod41.z.string())),
22667
+ /** The provider the ranking read for the chosen member, when the launch spends one in place of the member's Claude account. */
22668
+ provider: import_zod41.z.string().optional(),
22337
22669
  movedOff: import_zod41.z.strictObject({ identity: import_zod41.z.string(), reason: import_zod41.z.string() }).optional()
22338
22670
  });
22339
22671
  var LaunchDecisionSchema = import_zod41.z.strictObject({
@@ -23084,7 +23416,7 @@ function createDoorHealthPublisher(hub, now, pid) {
23084
23416
  }
23085
23417
 
23086
23418
  // src/frontdoor/quotaExpiringEvents.ts
23087
- init_pick();
23419
+ init_windowLengths();
23088
23420
  var FINAL_SPAN_DENOMINATOR = 30;
23089
23421
  var QUOTA_EXPIRING_WINDOW_FRACTION = 1 / FINAL_SPAN_DENOMINATOR;
23090
23422
  function createQuotaExpiringPublisher(hub, deps) {
@@ -25385,7 +25717,7 @@ init_launcher();
25385
25717
  init_launchWiring();
25386
25718
 
25387
25719
  // src/poolUsageRefresh.ts
25388
- var import_node_os12 = __toESM(require("node:os"), 1);
25720
+ var import_node_os13 = __toESM(require("node:os"), 1);
25389
25721
  init_load();
25390
25722
  init_launchWiring();
25391
25723
  init_argv();
@@ -25399,7 +25731,8 @@ async function refreshStalePoolMembers(params) {
25399
25731
  if (identities.size === 0) {
25400
25732
  return;
25401
25733
  }
25402
- await params.refresher.refreshStale(params.loadMembers([...identities]));
25734
+ const members = params.loadMembers([...identities]).filter((member) => member.provider === void 0 && member.providerError === void 0);
25735
+ await params.refresher.refreshStale(members);
25403
25736
  }
25404
25737
 
25405
25738
  // src/poolUsageRefresh.ts
@@ -25419,7 +25752,7 @@ async function refreshPools(params) {
25419
25752
  await refreshStalePoolMembers({
25420
25753
  poolNames: params.poolNames,
25421
25754
  pools: readPools(paths),
25422
- loadMembers: (identities) => loadPoolMembers(realFarmFs, paths, identities, Date.now(), (name) => identityIdOf(paths, name)),
25755
+ loadMembers: (identities) => loadPoolMembers(realFarmFs, paths, identities, Date.now(), (name) => identityIdOf(paths, name), params.providerOf),
25423
25756
  refresher
25424
25757
  });
25425
25758
  }
@@ -25441,12 +25774,13 @@ async function refreshPoolUsage(params) {
25441
25774
  poolNames: params.poolNames,
25442
25775
  spawnDaemon: daemonSpawnerFor(params.agentShim),
25443
25776
  log: params.log ?? (() => void 0),
25444
- ...params.refresher === void 0 ? {} : { refresher: params.refresher }
25777
+ ...params.refresher === void 0 ? {} : { refresher: params.refresher },
25778
+ ...params.providerOf === void 0 ? {} : { providerOf: params.providerOf }
25445
25779
  });
25446
25780
  }
25447
25781
  function poolSelectedByLaunch(options) {
25448
25782
  const paths = options.paths ?? resolveLayoutPaths();
25449
- const loaded = loadCascadeInput({ paths, home: import_node_os12.default.homedir(), cwd: options.cwd, read: cosmiconfigReader() });
25783
+ const loaded = loadCascadeInput({ paths, home: import_node_os13.default.homedir(), cwd: options.cwd, read: cosmiconfigReader() });
25450
25784
  return decideIdentity({
25451
25785
  env: options.env,
25452
25786
  argv0Identity: parseLauncherArgv(options.argv).identity,
@@ -25456,8 +25790,12 @@ function poolSelectedByLaunch(options) {
25456
25790
  }
25457
25791
  async function refreshLaunchPoolUsage(options) {
25458
25792
  const pool = poolSelectedByLaunch(options);
25793
+ const paths = options.paths ?? resolveLayoutPaths();
25794
+ const parsed = parseLauncherArgv(options.argv);
25459
25795
  await refreshPoolUsage({
25460
- ...options.paths === void 0 ? {} : { paths: options.paths },
25796
+ paths,
25797
+ // The provider each member's launch will spend, resolved as the launch resolves it, so a launch through a provider probes no Claude account.
25798
+ ...pool === void 0 ? {} : { providerOf: realMemberProviderResolver({ paths, cwd: options.cwd, env: options.env, ...parsed.provider === void 0 ? {} : { cliProvider: parsed.provider }, ...parsed.configProfile === void 0 ? {} : { cliFlagConfigProfile: parsed.configProfile } }) },
25461
25799
  cwd: options.cwd,
25462
25800
  poolNames: pool === void 0 ? [] : [pool],
25463
25801
  ...options.agentShim === void 0 ? {} : { agentShim: options.agentShim },
@@ -25830,6 +26168,7 @@ init_ownCli();
25830
26168
  realCodexAppServerPort,
25831
26169
  realConnectCertStore,
25832
26170
  realConnectEffects,
26171
+ realMemberProviderResolver,
25833
26172
  realRcControlTransport,
25834
26173
  realRcEventDial,
25835
26174
  realRcStreamDial,