claude-use 12.0.0 → 12.1.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.mjs CHANGED
@@ -5245,6 +5245,23 @@ function identityIdResolver(identitiesDir, fs17) {
5245
5245
  return identityIdIn(records, name);
5246
5246
  };
5247
5247
  }
5248
+ function identityReader(identitiesDir, fs17) {
5249
+ const read = /* @__PURE__ */ new Map();
5250
+ const readOnce = (file) => {
5251
+ if (!read.has(file)) {
5252
+ read.set(file, fs17.readConfigFile(file));
5253
+ }
5254
+ return read.get(file);
5255
+ };
5256
+ const idOf = identityIdResolver(identitiesDir, { readdir: fs17.readdir, readConfigFile: readOnce });
5257
+ return {
5258
+ idOf,
5259
+ load: (name) => {
5260
+ const id = idOf(name);
5261
+ return id === void 0 ? void 0 : loadConfigFile(path15.join(identitiesDir, id, IDENTITY_FILE), IdentitySchema, readOnce)?.config;
5262
+ }
5263
+ };
5264
+ }
5248
5265
  function loadIdentity(identitiesDir, name, fs17) {
5249
5266
  if (!isFileName(name)) {
5250
5267
  throw new UnsafeNameError(name, "identity", FILE_NAME_RULE);
@@ -6663,11 +6680,226 @@ var init_blockingSpawn = __esm({
6663
6680
  }
6664
6681
  });
6665
6682
 
6666
- // src/usage/signIn.ts
6683
+ // src/headroom/headers.ts
6684
+ function mergeAnthropicCustomHeaders(existing, additions) {
6685
+ const merged = /* @__PURE__ */ new Map();
6686
+ for (const block of existing) {
6687
+ if (block === void 0) {
6688
+ continue;
6689
+ }
6690
+ for (const line of block.split("\n")) {
6691
+ const entry = parseCustomHeaderLine(line);
6692
+ if (entry === void 0) {
6693
+ continue;
6694
+ }
6695
+ merged.set(entry.name, entry.value);
6696
+ }
6697
+ }
6698
+ for (const entry of additions) {
6699
+ merged.set(entry.name, entry.value);
6700
+ }
6701
+ return [...merged].map(([name, value]) => `${name}: ${value}`).join("\n");
6702
+ }
6703
+ function parseAnthropicCustomHeaders(block) {
6704
+ return block.split("\n").flatMap((line) => {
6705
+ const entry = parseCustomHeaderLine(line);
6706
+ return entry === void 0 ? [] : [entry];
6707
+ });
6708
+ }
6709
+ function withoutAnthropicCustomHeaders(block, remove) {
6710
+ const lines = block.split("\n");
6711
+ const kept = lines.filter((line) => {
6712
+ const entry = parseCustomHeaderLine(line);
6713
+ return entry === void 0 || !remove(entry);
6714
+ });
6715
+ return kept.length === lines.length ? block : kept.join("\n");
6716
+ }
6717
+ function parseCustomHeaderLine(line) {
6718
+ const trimmed = line.trim();
6719
+ if (trimmed === "") {
6720
+ return void 0;
6721
+ }
6722
+ const colon = trimmed.indexOf(":");
6723
+ if (colon <= 0) {
6724
+ return void 0;
6725
+ }
6726
+ return { name: trimmed.slice(0, colon).trim(), value: trimmed.slice(colon + 1).trim() };
6727
+ }
6728
+ var init_headers = __esm({
6729
+ "src/headroom/headers.ts"() {
6730
+ "use strict";
6731
+ }
6732
+ });
6733
+
6734
+ // src/launcher/injected.ts
6667
6735
  import { createHash as createHash4 } from "node:crypto";
6736
+ import { z as z14 } from "zod";
6737
+ function listKey(list) {
6738
+ return `${list},appended`;
6739
+ }
6740
+ function digest2(value) {
6741
+ return createHash4("sha256").update(value).digest("hex");
6742
+ }
6743
+ function recordedDigests(env) {
6744
+ const raw = env[INJECTED_ENV];
6745
+ if (raw === void 0 || raw === "") {
6746
+ return {};
6747
+ }
6748
+ let parsed;
6749
+ try {
6750
+ parsed = JSON.parse(raw);
6751
+ } catch {
6752
+ return {};
6753
+ }
6754
+ const result = InjectedSchema.safeParse(parsed);
6755
+ return result.success ? result.data : {};
6756
+ }
6757
+ function recordInjections(base) {
6758
+ const env = { ...base };
6759
+ const digests = new Map(Object.entries(recordedDigests(env)));
6760
+ return {
6761
+ env,
6762
+ set: (name, value) => {
6763
+ env[name] = value;
6764
+ digests.set(name, digest2(value));
6765
+ },
6766
+ unset: (name) => {
6767
+ env[name] = void 0;
6768
+ digests.delete(name);
6769
+ },
6770
+ recordHeaders: (names) => {
6771
+ const block = env[CUSTOM_HEADERS_ENV];
6772
+ for (const entry of block === void 0 ? [] : parseAnthropicCustomHeaders(block)) {
6773
+ if (names.includes(entry.name)) {
6774
+ digests.set(`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`, digest2(entry.value));
6775
+ }
6776
+ }
6777
+ },
6778
+ recordBypassHosts: (list, hosts) => {
6779
+ const recordedHosts = [.../* @__PURE__ */ new Set([...digests.get(listKey(list))?.split(",") ?? [], ...hosts.map((host) => host.trim().toLowerCase()).filter((host) => host !== "")])];
6780
+ if (recordedHosts.length > 0) {
6781
+ digests.set(listKey(list), recordedHosts.join(","));
6782
+ }
6783
+ },
6784
+ finish: () => {
6785
+ if (digests.size > 0) {
6786
+ env[INJECTED_ENV] = JSON.stringify(Object.fromEntries(digests));
6787
+ }
6788
+ }
6789
+ };
6790
+ }
6791
+ function withoutRecordedHosts(list, value, digests) {
6792
+ const recordedHosts = new Set(digests[listKey(list)]?.split(","));
6793
+ const entries = value.split(",");
6794
+ const kept = entries.filter((entry) => !recordedHosts.has(entry.trim().toLowerCase()));
6795
+ return kept.length === entries.length ? value : kept.join(",");
6796
+ }
6797
+ function launchEnvironment(env, configDirEscapeHatch) {
6798
+ return configDirEscapeHatch ? env : withoutInjected(env);
6799
+ }
6800
+ function withoutInjected(env) {
6801
+ const digests = recordedDigests(env);
6802
+ const entries = Object.entries(env).flatMap(([name, value]) => {
6803
+ if (name === INJECTED_ENV) {
6804
+ return [];
6805
+ }
6806
+ if (value === void 0) {
6807
+ return [[name, value]];
6808
+ }
6809
+ if (name === CUSTOM_HEADERS_ENV) {
6810
+ const remaining = withoutAnthropicCustomHeaders(value, (entry) => digests[`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`] === digest2(entry.value));
6811
+ return remaining !== value && remaining.trim() === "" ? [] : [[name, remaining]];
6812
+ }
6813
+ if (name === "NO_PROXY" || name === "no_proxy") {
6814
+ const remaining = withoutRecordedHosts(name, value, digests);
6815
+ return remaining !== value && remaining.split(",").every((entry) => entry.trim() === "") ? [] : [[name, remaining]];
6816
+ }
6817
+ return digests[name] === digest2(value) ? [] : [[name, value]];
6818
+ });
6819
+ return Object.fromEntries(entries);
6820
+ }
6821
+ var INJECTED_ENV, CUSTOM_HEADERS_ENV, HEADER_KEY_PREFIX, InjectedSchema;
6822
+ var init_injected = __esm({
6823
+ "src/launcher/injected.ts"() {
6824
+ "use strict";
6825
+ init_headers();
6826
+ INJECTED_ENV = "AGENT_SHIM_INJECTED";
6827
+ CUSTOM_HEADERS_ENV = "ANTHROPIC_CUSTOM_HEADERS";
6828
+ HEADER_KEY_PREFIX = `${CUSTOM_HEADERS_ENV}:`;
6829
+ InjectedSchema = z14.record(z14.string(), z14.string());
6830
+ }
6831
+ });
6832
+
6833
+ // src/launcher/guard.ts
6834
+ function detectAmbientCredential(env, injected) {
6835
+ for (const variable of AMBIENT_CREDENTIAL_VARS) {
6836
+ const value = env[variable];
6837
+ if (value === void 0 || value === "") {
6838
+ continue;
6839
+ }
6840
+ if (injected?.variable === variable && value === injected.token) {
6841
+ continue;
6842
+ }
6843
+ return { variable };
6844
+ }
6845
+ return void 0;
6846
+ }
6847
+ function formatAmbientCredentialGuardMessage(variable, identityName) {
6848
+ const identitySetCommand = identityName === void 0 ? "agent-shim identity set <name> --allow-ambient-credential" : `agent-shim identity set ${identityName} --allow-ambient-credential`;
6849
+ return [
6850
+ `error: ${variable} is set in the environment. This identity's isolated`,
6851
+ "credential would be bypassed \u2014 every identity authenticates as this same key",
6852
+ "while it's set. Unset it, or if this is deliberate, opt in per-launch with",
6853
+ "AGENT_SHIM_ALLOW_AMBIENT_CREDENTIAL=1, or persistently for this identity with",
6854
+ `\`${identitySetCommand}\`.`
6855
+ ].join("\n");
6856
+ }
6857
+ function evaluateAmbientCredentialGuard(params) {
6858
+ const detected = detectAmbientCredential(params.env, params.injectedCredential);
6859
+ if (detected === void 0) {
6860
+ return { ok: true };
6861
+ }
6862
+ if (params.allowAmbientCredentialOverride || params.allowAmbientCredential || params.providerSelected === true) {
6863
+ return { ok: true };
6864
+ }
6865
+ return {
6866
+ ok: false,
6867
+ variable: detected.variable,
6868
+ message: formatAmbientCredentialGuardMessage(detected.variable, params.identityName)
6869
+ };
6870
+ }
6871
+ function ambientCredentialFinding(env) {
6872
+ const named = detectAmbientCredential(launchEnvironment(env, false));
6873
+ if (named !== void 0) {
6874
+ return { severity: "warn", message: formatAmbientCredentialGuardMessage(named.variable) };
6875
+ }
6876
+ const bare = env.CLAUDE_CONFIG_DIR === void 0 || env.CLAUDE_CONFIG_DIR === "" ? void 0 : detectAmbientCredential(env);
6877
+ if (bare !== void 0) {
6878
+ return { severity: "warn", message: `${bare.variable} was set in this session by the launcher that started it. A launch that names an identity drops it, but a launch naming none keeps the session's CLAUDE_CONFIG_DIR and environment and is refused. Name an identity, as in \`claude @<name>\`.` };
6879
+ }
6880
+ return { severity: "pass", message: "No ambient-credential environment variable is set." };
6881
+ }
6882
+ var AMBIENT_CREDENTIAL_VARS;
6883
+ var init_guard = __esm({
6884
+ "src/launcher/guard.ts"() {
6885
+ "use strict";
6886
+ init_injected();
6887
+ AMBIENT_CREDENTIAL_VARS = [
6888
+ "ANTHROPIC_API_KEY",
6889
+ "ANTHROPIC_AUTH_TOKEN",
6890
+ "CLAUDE_CODE_OAUTH_TOKEN",
6891
+ "CLAUDE_CODE_USE_BEDROCK",
6892
+ "CLAUDE_CODE_USE_VERTEX",
6893
+ "CLAUDE_CODE_USE_FOUNDRY"
6894
+ ];
6895
+ }
6896
+ });
6897
+
6898
+ // src/usage/signIn.ts
6899
+ import { createHash as createHash5 } from "node:crypto";
6668
6900
  import path19 from "node:path";
6669
6901
  function claudeCodeKeychainService(configDir) {
6670
- return `${KEYCHAIN_SERVICE_PREFIX}-${createHash4("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
6902
+ return `${KEYCHAIN_SERVICE_PREFIX}-${createHash5("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
6671
6903
  }
6672
6904
  function keychainHasItem(run, configDir) {
6673
6905
  return run.run("security", ["find-generic-password", "-s", claudeCodeKeychainService(configDir)]).status === 0;
@@ -6700,13 +6932,33 @@ function identitySignIn(fs17, probe, identity) {
6700
6932
  platform: probe.platform
6701
6933
  });
6702
6934
  }
6703
- var CREDENTIALS_FILE, KEYCHAIN_SERVICE_PREFIX, KEYCHAIN_SERVICE_HASH_DIGITS;
6935
+ function storedLoginUsable(run, claudeBin, configDir, env) {
6936
+ const childEnv = { ...env, CLAUDE_CONFIG_DIR: configDir };
6937
+ for (const variable of AMBIENT_CREDENTIAL_VARS) {
6938
+ childEnv[variable] = void 0;
6939
+ }
6940
+ const result = run.run(claudeBin, ["auth", "status"], void 0, { env: childEnv, timeoutMs: AUTH_STATUS_TIMEOUT_MS });
6941
+ if (result.status === null) {
6942
+ return void 0;
6943
+ }
6944
+ try {
6945
+ const status = JSON.parse(result.stdout);
6946
+ if (typeof status === "object" && status !== null && "loggedIn" in status && typeof status.loggedIn === "boolean") {
6947
+ return status.loggedIn;
6948
+ }
6949
+ } catch {
6950
+ }
6951
+ return void 0;
6952
+ }
6953
+ var CREDENTIALS_FILE, KEYCHAIN_SERVICE_PREFIX, KEYCHAIN_SERVICE_HASH_DIGITS, AUTH_STATUS_TIMEOUT_MS;
6704
6954
  var init_signIn = __esm({
6705
6955
  "src/usage/signIn.ts"() {
6706
6956
  "use strict";
6957
+ init_guard();
6707
6958
  CREDENTIALS_FILE = ".credentials.json";
6708
6959
  KEYCHAIN_SERVICE_PREFIX = "Claude Code-credentials";
6709
6960
  KEYCHAIN_SERVICE_HASH_DIGITS = 8;
6961
+ AUTH_STATUS_TIMEOUT_MS = 1e4;
6710
6962
  }
6711
6963
  });
6712
6964
 
@@ -7071,9 +7323,9 @@ var init_supervisorProcesses = __esm({
7071
7323
  });
7072
7324
 
7073
7325
  // src/headroom/state.ts
7074
- import { createHash as createHash5 } from "node:crypto";
7326
+ import { createHash as createHash6 } from "node:crypto";
7075
7327
  import path21 from "node:path";
7076
- import { z as z14 } from "zod";
7328
+ import { z as z15 } from "zod";
7077
7329
  function parseJson(raw, schema) {
7078
7330
  if (raw === void 0 || raw.trim() === "") {
7079
7331
  return void 0;
@@ -7120,7 +7372,7 @@ function migrateHeadroomState(fs17, files, isRunning) {
7120
7372
  fs17.removeRecursive(files.legacyStateFile);
7121
7373
  }
7122
7374
  function hashAllowlist(allowlist) {
7123
- return createHash5("sha256").update(allowlist.join("\n")).digest("hex");
7375
+ return createHash6("sha256").update(allowlist.join("\n")).digest("hex");
7124
7376
  }
7125
7377
  function formatAllowlistFile(allowlist) {
7126
7378
  return allowlist.map((entry) => `${entry}
@@ -7230,32 +7482,32 @@ var init_state2 = __esm({
7230
7482
  "src/headroom/state.ts"() {
7231
7483
  "use strict";
7232
7484
  init_schema();
7233
- HeadroomStateSchema = z14.strictObject({
7485
+ HeadroomStateSchema = z15.strictObject({
7234
7486
  /** The supervisor process owning the daemon. Alive means someone is keeping headroom running. */
7235
- supervisorPid: z14.number().int().positive().optional(),
7487
+ supervisorPid: z15.number().int().positive().optional(),
7236
7488
  /** The headroom proxy process itself, recorded as soon as it is spawned (before it is ready, which `socketPath` signals) so a successor can find a daemon whose supervisor died during its start. Absent while the supervisor is between restarts. */
7237
- headroomPid: z14.number().int().positive().optional(),
7489
+ headroomPid: z15.number().int().positive().optional(),
7238
7490
  /**
7239
7491
  * The unix socket the proxy serves on, inside the owner-only socket directory. Absent until the proxy has passed its readiness check, so "socketPath is set" is itself the ready signal a launcher polls for. The front door reads it on every hop, so a restart (which keeps the generation's path) is followed without anything being relaunched.
7240
7492
  */
7241
- socketPath: z14.string().min(1).optional(),
7493
+ socketPath: z15.string().min(1).optional(),
7242
7494
  /** The `headroom --version` output of the running install. */
7243
- version: z14.string().optional(),
7495
+ version: z15.string().optional(),
7244
7496
  /**
7245
7497
  * Hash of the allowlist the running proxy serves. The supervisor records it in the same tick it writes that allowlist to `LayoutPaths.headroomAllowlistFile`, which the proxy re-reads on its next request, so a provider launch, whose requests come back through its front door's direct origin, waits until this names an allowlist holding that origin. A supervisor from an earlier release records here the hash of the allowlist its daemon was started with instead (see `earlierRelease.ts`).
7246
7498
  */
7247
- allowlistHash: z14.string().optional(),
7499
+ allowlistHash: z15.string().optional(),
7248
7500
  /** Hash of the token-saving settings the running proxy was started with, so a settings change is detected as drift. */
7249
- settingsHash: z14.string().optional(),
7501
+ settingsHash: z15.string().optional(),
7250
7502
  /** The install spec the running install was last installed from, so a `source` config change is detected as drift. */
7251
- installedSource: z14.string().optional(),
7503
+ installedSource: z15.string().optional(),
7252
7504
  /** The install spec the supervisor is installing right now, present only while `uv tool install` runs, so a launcher that finds a live supervisor with no daemon yet keeps waiting for the install instead of counting it against its start bound. Cleared by the write that follows the install, whatever its outcome. */
7253
- installing: z14.string().optional(),
7505
+ installing: z15.string().optional(),
7254
7506
  /** The last fatal error, kept across shutdowns so `headroom status` can explain a daemon that is not running. */
7255
- lastError: z14.string().optional()
7507
+ lastError: z15.string().optional()
7256
7508
  });
7257
- HeadroomSessionSchema = z14.strictObject({ pid: z14.number().int().positive(), startedAt: z14.number(), supervisorPid: z14.number().int().positive() });
7258
- HeadroomLockSchema = z14.strictObject({ pid: z14.number().int().positive(), at: z14.number() });
7509
+ HeadroomSessionSchema = z15.strictObject({ pid: z15.number().int().positive(), startedAt: z15.number(), supervisorPid: z15.number().int().positive() });
7510
+ HeadroomLockSchema = z15.strictObject({ pid: z15.number().int().positive(), at: z15.number() });
7259
7511
  HEADROOM_ALLOWLIST_FILE_FLAG = "--allowed-base-urls-file";
7260
7512
  ALLOWLIST_LINE_BREAKS = "\\n\\r\\u000b\\u000c\\u001c\\u001d\\u001e\\u0085\\u2028\\u2029";
7261
7513
  ALLOWLIST_WHITESPACE = "\\t\\n\\u000b\\u000c\\r\\u001c-\\u001f \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
@@ -7445,7 +7697,7 @@ var init_ensure = __esm({
7445
7697
  });
7446
7698
 
7447
7699
  // src/headroom/settings.ts
7448
- import { createHash as createHash6 } from "node:crypto";
7700
+ import { createHash as createHash7 } from "node:crypto";
7449
7701
  function settingsOf(config) {
7450
7702
  return {
7451
7703
  ...config.mode === void 0 ? {} : { mode: config.mode },
@@ -7470,7 +7722,7 @@ function settingsEnv(settings) {
7470
7722
  return settings.rolloutChannel === void 0 ? {} : { HEADROOM_ROLLOUT_CHANNEL: settings.rolloutChannel };
7471
7723
  }
7472
7724
  function hashSettings(settings) {
7473
- return createHash6("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
7725
+ return createHash7("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
7474
7726
  }
7475
7727
  var init_settings = __esm({
7476
7728
  "src/headroom/settings.ts"() {
@@ -7662,7 +7914,7 @@ var init_socket = __esm({
7662
7914
  });
7663
7915
 
7664
7916
  // src/headroom/source.ts
7665
- import { z as z15 } from "zod";
7917
+ import { z as z16 } from "zod";
7666
7918
  function isMovingGitSource(spec) {
7667
7919
  const match = GIT_SPEC_RE.exec(spec);
7668
7920
  if (match === null) {
@@ -7681,7 +7933,7 @@ var init_source = __esm({
7681
7933
  "use strict";
7682
7934
  GIT_SPEC_RE = /git\+[^@\s]+(?:@([^\s#]+))?/;
7683
7935
  COMMIT_SHA_RE = /^[0-9a-f]{40}$/i;
7684
- DirectUrlSchema = z15.object({ vcs_info: z15.object({ commit_id: z15.string() }) });
7936
+ DirectUrlSchema = z16.object({ vcs_info: z16.object({ commit_id: z16.string() }) });
7685
7937
  }
7686
7938
  });
7687
7939
 
@@ -8126,7 +8378,7 @@ var init_logStyle = __esm({
8126
8378
 
8127
8379
  // src/realPorts.ts
8128
8380
  import { execFile, spawn } from "node:child_process";
8129
- import { createHash as createHash7 } from "node:crypto";
8381
+ import { createHash as createHash8 } from "node:crypto";
8130
8382
  import fs6 from "node:fs";
8131
8383
  import os2 from "node:os";
8132
8384
  import path24 from "node:path";
@@ -8193,6 +8445,9 @@ function realFrontDoorLiveness(pids) {
8193
8445
  return { status: result.status, stdout: result.stdout, stderr: result.stderr, ...result.error === void 0 ? {} : { error: result.error } };
8194
8446
  });
8195
8447
  }
8448
+ function definedEntries(env) {
8449
+ return Object.fromEntries(Object.entries(env).filter((entry) => entry[1] !== void 0));
8450
+ }
8196
8451
  function realRunAsyncWithin(timeoutMs) {
8197
8452
  return async (command, args) => await new Promise((resolve) => {
8198
8453
  execFile(command, [...args], { encoding: "utf8", timeout: timeoutMs }, (error, stdout, stderr) => {
@@ -8553,7 +8808,7 @@ var init_realPorts = __esm({
8553
8808
  },
8554
8809
  hashFile(filePath) {
8555
8810
  try {
8556
- return createHash7("sha256").update(fs6.readFileSync(filePath)).digest("hex");
8811
+ return createHash8("sha256").update(fs6.readFileSync(filePath)).digest("hex");
8557
8812
  } catch (error) {
8558
8813
  if (isEnoent3(error) || isErrorWithCode(error, "EISDIR")) {
8559
8814
  return void 0;
@@ -8593,8 +8848,14 @@ var init_realPorts = __esm({
8593
8848
  BYTES_PER_MIB2 = 1048576;
8594
8849
  RUN_OUTPUT_LIMIT_BYTES = RUN_OUTPUT_LIMIT_MIB * BYTES_PER_MIB2;
8595
8850
  realRunPort = {
8596
- run(command, args, input) {
8597
- const result = spawnSyncBlocking("an external command", command, args, { encoding: "utf8", maxBuffer: RUN_OUTPUT_LIMIT_BYTES, ...input === void 0 ? {} : { input } });
8851
+ run(command, args, input, options) {
8852
+ const result = spawnSyncBlocking("an external command", command, args, {
8853
+ encoding: "utf8",
8854
+ maxBuffer: RUN_OUTPUT_LIMIT_BYTES,
8855
+ ...input === void 0 ? {} : { input },
8856
+ ...options?.env === void 0 ? {} : { env: definedEntries(options.env) },
8857
+ ...options?.timeoutMs === void 0 ? {} : { timeout: options.timeoutMs }
8858
+ });
8598
8859
  return { status: result.status, stdout: result.stdout, stderr: result.stderr };
8599
8860
  }
8600
8861
  };
@@ -8972,7 +9233,8 @@ var init_identityAccounts = __esm({
8972
9233
  function candidateHeading(candidate) {
8973
9234
  const score = candidate.score === void 0 ? "" : ` score ${candidate.score.toFixed(2)}${candidate.scoreWindow === "fiveHour" ? " by 5h reset" : " by 7d reset"}`;
8974
9235
  const dry = candidate.feasible ? "" : " (5h would run dry)";
8975
- return `[${candidate.class}${score}]${dry}`;
9236
+ const onProvider = candidate.provider === void 0 ? "" : ` on provider ${candidate.provider}`;
9237
+ return `[${candidate.class}${score}]${dry}${onProvider}`;
8976
9238
  }
8977
9239
  function percent(fraction) {
8978
9240
  return `${String(Math.round(fraction * PERCENT))}%`;
@@ -8995,7 +9257,7 @@ var init_candidateText = __esm({
8995
9257
  });
8996
9258
 
8997
9259
  // src/usage/plan.ts
8998
- import { z as z16 } from "zod";
9260
+ import { z as z17 } from "zod";
8999
9261
  function planOf(account) {
9000
9262
  const userTier = account?.userRateLimitTier;
9001
9263
  if (userTier !== void 0 && ZERO_TIER.test(userTier)) {
@@ -9015,23 +9277,26 @@ function planOf(account) {
9015
9277
  }
9016
9278
  return { kind: "subscription", capacity: 1, recognised: BASE_TIER.test(tier), ...tierField };
9017
9279
  }
9280
+ function planOfProviderQuota(quota) {
9281
+ return planOf(quota?.level === void 0 ? void 0 : { organizationRateLimitTier: quota.level });
9282
+ }
9018
9283
  var PlanClassSchema, TIER_MULTIPLIER, ZERO_TIER, BASE_TIER;
9019
9284
  var init_plan2 = __esm({
9020
9285
  "src/usage/plan.ts"() {
9021
9286
  "use strict";
9022
- PlanClassSchema = z16.union([
9023
- z16.strictObject({
9024
- kind: z16.literal("subscription"),
9287
+ PlanClassSchema = z17.union([
9288
+ z17.strictObject({
9289
+ kind: z17.literal("subscription"),
9025
9290
  /** The plan's size as a multiple of the smallest subscription tier (Max is 5, Ultra is 20). */
9026
- capacity: z16.number().positive(),
9291
+ capacity: z17.number().positive(),
9027
9292
  /** False when the tier string named no multiplier and no tier this project knows, so `capacity` is the neutral 1 rather than a reading. */
9028
- recognised: z16.boolean(),
9293
+ recognised: z17.boolean(),
9029
9294
  /** The tier string the classification rests on, when the account had one. */
9030
- tier: z16.string().optional()
9295
+ tier: z17.string().optional()
9031
9296
  }),
9032
- z16.strictObject({
9033
- kind: z16.literal("pay-per-use"),
9034
- tier: z16.string().optional()
9297
+ z17.strictObject({
9298
+ kind: z17.literal("pay-per-use"),
9299
+ tier: z17.string().optional()
9035
9300
  })
9036
9301
  ]);
9037
9302
  TIER_MULTIPLIER = /(?:^|_)(\d+)x$/;
@@ -9041,21 +9306,21 @@ var init_plan2 = __esm({
9041
9306
  });
9042
9307
 
9043
9308
  // src/usage/scan.ts
9044
- import { z as z17 } from "zod";
9309
+ import { z as z18 } from "zod";
9045
9310
  var AnthropicUsageSchema, ErrorObjectSchema;
9046
9311
  var init_scan = __esm({
9047
9312
  "src/usage/scan.ts"() {
9048
9313
  "use strict";
9049
- AnthropicUsageSchema = z17.looseObject({
9050
- input_tokens: z17.number().int().nonnegative().nullish(),
9051
- output_tokens: z17.number().int().nonnegative().nullish(),
9052
- cache_creation_input_tokens: z17.number().int().nonnegative().nullish(),
9053
- cache_read_input_tokens: z17.number().int().nonnegative().nullish()
9314
+ AnthropicUsageSchema = z18.looseObject({
9315
+ input_tokens: z18.number().int().nonnegative().nullish(),
9316
+ output_tokens: z18.number().int().nonnegative().nullish(),
9317
+ cache_creation_input_tokens: z18.number().int().nonnegative().nullish(),
9318
+ cache_read_input_tokens: z18.number().int().nonnegative().nullish()
9054
9319
  });
9055
- ErrorObjectSchema = z17.looseObject({
9056
- type: z17.string().optional(),
9057
- code: z17.union([z17.string(), z17.number()]).optional(),
9058
- message: z17.string().optional()
9320
+ ErrorObjectSchema = z18.looseObject({
9321
+ type: z18.string().optional(),
9322
+ code: z18.union([z18.string(), z18.number()]).optional(),
9323
+ message: z18.string().optional()
9059
9324
  });
9060
9325
  }
9061
9326
  });
@@ -9073,12 +9338,58 @@ var init_middleware = __esm({
9073
9338
  }
9074
9339
  });
9075
9340
 
9076
- // src/usage/quotaFacts.ts
9077
- function windowFacts(window, nowMs) {
9078
- if (window?.utilization === void 0 || window.resetsAt === void 0) {
9079
- return void 0;
9080
- }
9081
- return { remaining: Math.max(0, 1 - window.utilization), utilization: window.utilization, hoursUntilReset: Math.max(0, (Date.parse(window.resetsAt) - nowMs) / MS_PER_HOUR2) };
9341
+ // src/usage/windowLengths.ts
9342
+ var MS_PER_HOUR2, HOURS_PER_DAY3, FIVE_HOURS, SEVEN_DAYS, FIVE_HOUR_WINDOW_MS, SEVEN_DAY_WINDOW_MS;
9343
+ var init_windowLengths = __esm({
9344
+ "src/usage/windowLengths.ts"() {
9345
+ "use strict";
9346
+ MS_PER_HOUR2 = 36e5;
9347
+ HOURS_PER_DAY3 = 24;
9348
+ FIVE_HOURS = 5;
9349
+ SEVEN_DAYS = 7;
9350
+ FIVE_HOUR_WINDOW_MS = FIVE_HOURS * MS_PER_HOUR2;
9351
+ SEVEN_DAY_WINDOW_MS = SEVEN_DAYS * HOURS_PER_DAY3 * MS_PER_HOUR2;
9352
+ }
9353
+ });
9354
+
9355
+ // src/usage/providerWindows.ts
9356
+ function bindingWindow(quota, periodMs) {
9357
+ const same = quota.windows.filter((window) => window.periodMs === periodMs);
9358
+ const tightest = same.reduce((binding, window) => binding === void 0 || window.utilization > binding.utilization ? window : binding, void 0);
9359
+ if (tightest === void 0) {
9360
+ return void 0;
9361
+ }
9362
+ return { utilization: tightest.utilization, ...tightest.resetsAt === void 0 ? {} : { resetsAt: tightest.resetsAt }, status: tightest.utilization >= 1 ? "rejected" : "allowed" };
9363
+ }
9364
+ function unifiedFromQuota(quota) {
9365
+ const fiveHour = bindingWindow(quota, FIVE_HOUR_WINDOW_MS);
9366
+ const sevenDay = bindingWindow(quota, SEVEN_DAY_WINDOW_MS);
9367
+ return fiveHour === void 0 && sevenDay === void 0 ? void 0 : { ...fiveHour === void 0 ? {} : { fiveHour }, ...sevenDay === void 0 ? {} : { sevenDay } };
9368
+ }
9369
+ function rankingWindowsOf(provider, state) {
9370
+ const recorded = state?.rateLimit;
9371
+ if (provider === void 0) {
9372
+ return recorded?.unified === void 0 ? void 0 : { unified: recorded.unified, observedAt: recorded.observedAt };
9373
+ }
9374
+ if (recorded?.unified !== void 0 && (recorded.unified.fiveHour !== void 0 || recorded.unified.sevenDay !== void 0)) {
9375
+ return { unified: recorded.unified, observedAt: recorded.observedAt };
9376
+ }
9377
+ const pulled = state?.quota === void 0 ? void 0 : unifiedFromQuota(state.quota);
9378
+ return state?.quota === void 0 || pulled === void 0 ? void 0 : { unified: pulled, observedAt: state.quota.observedAt };
9379
+ }
9380
+ var init_providerWindows = __esm({
9381
+ "src/usage/providerWindows.ts"() {
9382
+ "use strict";
9383
+ init_windowLengths();
9384
+ }
9385
+ });
9386
+
9387
+ // src/usage/quotaFacts.ts
9388
+ function windowFacts(window, nowMs) {
9389
+ if (window?.utilization === void 0 || window.resetsAt === void 0) {
9390
+ return void 0;
9391
+ }
9392
+ return { remaining: Math.max(0, 1 - window.utilization), utilization: window.utilization, hoursUntilReset: Math.max(0, (Date.parse(window.resetsAt) - nowMs) / MS_PER_HOUR3) };
9082
9393
  }
9083
9394
  function quotaFactsOf(unified, nowMs) {
9084
9395
  const fiveHour = windowFacts(unified?.fiveHour, nowMs);
@@ -9086,19 +9397,16 @@ function quotaFactsOf(unified, nowMs) {
9086
9397
  const extraUsage = windowFacts(unified === void 0 ? void 0 : soleOverageWindow(unified), nowMs);
9087
9398
  return { ...fiveHour === void 0 ? {} : { fiveHour }, ...sevenDay === void 0 ? {} : { sevenDay }, ...extraUsage === void 0 ? {} : { extraUsage } };
9088
9399
  }
9089
- var MS_PER_HOUR2;
9400
+ var MS_PER_HOUR3;
9090
9401
  var init_quotaFacts = __esm({
9091
9402
  "src/usage/quotaFacts.ts"() {
9092
9403
  "use strict";
9093
9404
  init_rateLimit();
9094
- MS_PER_HOUR2 = 36e5;
9405
+ MS_PER_HOUR3 = 36e5;
9095
9406
  }
9096
9407
  });
9097
9408
 
9098
9409
  // src/usage/pick.ts
9099
- function unifiedOf(state) {
9100
- return state?.rateLimit?.unified;
9101
- }
9102
9410
  function limitBlockedUntil(state, nowMs) {
9103
9411
  const limit = state?.lastLimit;
9104
9412
  if (state === void 0 || limit === void 0) {
@@ -9188,6 +9496,10 @@ function assessRefusedNested(member, nested, nowMs) {
9188
9496
  };
9189
9497
  }
9190
9498
  function assess(member, nowMs) {
9499
+ const assessment = assessMember(member, nowMs);
9500
+ return member.provider === void 0 ? assessment : { ...assessment, candidate: { ...assessment.candidate, provider: member.provider } };
9501
+ }
9502
+ function assessMember(member, nowMs) {
9191
9503
  if (member.sameLoginAs !== void 0) {
9192
9504
  return { candidate: { identity: member.identity, class: "ineligible", plan: planOf(member.account), reasons: [`same login as ${member.sameLoginAs}`] } };
9193
9505
  }
@@ -9201,22 +9513,43 @@ function assess(member, nowMs) {
9201
9513
  const assessment = assessIdentity(member, nowMs);
9202
9514
  return { ...assessment, candidate: { ...assessment.candidate, reasons: [`picked by pool "${nested.pool}"`, ...nested.reasons] } };
9203
9515
  }
9516
+ function sliceOf(member) {
9517
+ return member.snapshot?.providers[member.provider ?? ANTHROPIC_PROVIDER];
9518
+ }
9519
+ function assessProviderWithoutWindows(member, provider, state, base, planReasons, nowMs) {
9520
+ const blockedUntil = limitBlockedUntil(state, nowMs);
9521
+ if (blockedUntil !== void 0) {
9522
+ return { candidate: { ...base, class: "ineligible", blockedUntilMs: blockedUntil, reasons: [`refused until ${new Date(blockedUntil).toISOString()} (in ${formatAge(blockedUntil - nowMs)})`, ...planReasons] } };
9523
+ }
9524
+ if (base.plan.kind === "pay-per-use") {
9525
+ return { candidate: { ...base, class: "pay-per-use", usageUnrecorded: true, reasons: [...planReasons, `provider ${provider} reports no plan windows, so its spend is not tracked`] } };
9526
+ }
9527
+ 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`;
9528
+ return { candidate: { ...base, class: "unknown", reasons: [why, ...planReasons] } };
9529
+ }
9204
9530
  function assessIdentity(member, nowMs) {
9205
- const plan = planOf(member.account);
9531
+ const state = sliceOf(member);
9532
+ const plan = member.provider === void 0 ? planOf(member.account) : planOfProviderQuota(state?.quota);
9206
9533
  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`];
9207
9534
  const base = { identity: member.identity, plan };
9208
9535
  if (member.readError !== void 0) {
9209
9536
  return { candidate: { ...base, class: "unknown", reasons: [`usage state unreadable: ${member.readError}`, ...planReasons] } };
9210
9537
  }
9211
- const state = member.snapshot?.providers[ANTHROPIC_PROVIDER];
9212
- const unified = unifiedOf(state);
9213
- if (member.snapshot === void 0 || state === void 0 || unified === void 0) {
9538
+ if (member.providerError !== void 0) {
9539
+ return { candidate: { ...base, class: "unknown", reasons: [`provider configuration unreadable: ${member.providerError}`, ...planReasons] } };
9540
+ }
9541
+ const windows = rankingWindowsOf(member.provider, state);
9542
+ if (member.snapshot === void 0 || state === void 0 || windows === void 0) {
9543
+ if (member.provider !== void 0) {
9544
+ return assessProviderWithoutWindows(member, member.provider, state, base, planReasons, nowMs);
9545
+ }
9214
9546
  if (plan.kind === "pay-per-use") {
9215
9547
  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)"] } };
9216
9548
  }
9217
9549
  return { candidate: { ...base, class: "unknown", reasons: ["no usage recorded yet, so its quota is unknown (turn on trackUsage for it)", ...planReasons] } };
9218
9550
  }
9219
- const observedAgo = state.rateLimit === void 0 ? "" : ` (last seen ${formatAge(nowMs - Date.parse(state.rateLimit.observedAt))} ago)`;
9551
+ const { unified } = windows;
9552
+ const observedAgo = ` (last seen ${formatAge(nowMs - Date.parse(windows.observedAt))} ago)`;
9220
9553
  const fiveHourWindow = unified.fiveHour;
9221
9554
  const sevenDayWindow = unified.sevenDay;
9222
9555
  const five = fiveHourWindow === void 0 ? void 0 : effectiveWindow(fiveHourWindow, nowMs);
@@ -9228,6 +9561,15 @@ function assessIdentity(member, nowMs) {
9228
9561
  const overageWindow = soleOverageWindow(unified);
9229
9562
  const overage = overageWindow === void 0 ? void 0 : effectiveWindow(overageWindow, nowMs);
9230
9563
  const overageReasons = overageWindow === void 0 || overage === void 0 ? [] : [describeWindow("extra usage", overageWindow, overage, nowMs)];
9564
+ if (member.provider !== void 0) {
9565
+ const spent = [
9566
+ { name: "5h", window: five },
9567
+ { name: "7d", window: seven }
9568
+ ].filter(({ window }) => window?.status === "rejected" && window.resetsAtMs === void 0).map(({ name }) => name);
9569
+ if (spent.length > 0) {
9570
+ 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] } };
9571
+ }
9572
+ }
9231
9573
  const blockedUntil = Math.max(
9232
9574
  windowBlockedUntil([five, seven, overage].flatMap((window) => window === void 0 ? [] : [window])) ?? 0,
9233
9575
  limitBlockedUntil(state, nowMs) ?? 0
@@ -9248,11 +9590,11 @@ function assessIdentity(member, nowMs) {
9248
9590
  }
9249
9591
  const remaining = Math.max(0, 1 - basis.window.utilization);
9250
9592
  const untilResetMs = basis.window.resetsAtMs === void 0 ? basis.windowMs : Math.max(basis.window.resetsAtMs - nowMs, MS_PER_SECOND5);
9251
- const weeklyScore = remaining * plan.capacity / (untilResetMs / MS_PER_HOUR3);
9593
+ const weeklyScore = remaining * plan.capacity / (untilResetMs / MS_PER_HOUR4);
9252
9594
  const fiveRemaining = five?.utilization === void 0 ? void 0 : Math.max(0, 1 - five.utilization);
9253
9595
  const fiveUntil = five?.resetsAtMs === void 0 ? FIVE_HOUR_WINDOW_MS : Math.max(five.resetsAtMs - nowMs, MS_PER_SECOND5);
9254
9596
  const ratio = windowRatio(member.records);
9255
- const fiveHourScore = basis.name === "sevenDay" && fiveRemaining !== void 0 && ratio !== void 0 ? Math.min(fiveRemaining * ratio, remaining) * plan.capacity / (fiveUntil / MS_PER_HOUR3) : void 0;
9597
+ const fiveHourScore = basis.name === "sevenDay" && fiveRemaining !== void 0 && ratio !== void 0 ? Math.min(fiveRemaining * ratio, remaining) * plan.capacity / (fiveUntil / MS_PER_HOUR4) : void 0;
9256
9598
  const fiveHourLeads = fiveHourScore !== void 0 && fiveHourScore > weeklyScore;
9257
9599
  const score = fiveHourLeads ? fiveHourScore : weeklyScore;
9258
9600
  const scoreWindow = fiveHourLeads ? "fiveHour" : basis.name;
@@ -9270,15 +9612,15 @@ function assessIdentity(member, nowMs) {
9270
9612
  };
9271
9613
  }
9272
9614
  function poolFactsOf(member, nowMs, resuming, sticky) {
9273
- const { fiveHour, sevenDay, extraUsage } = quotaFactsOf(member.snapshot?.providers[ANTHROPIC_PROVIDER]?.rateLimit?.unified, nowMs);
9615
+ const { fiveHour, sevenDay, extraUsage } = quotaFactsOf(rankingWindowsOf(member.provider, sliceOf(member))?.unified, nowMs);
9274
9616
  const burn = windowBurn(member.records, "fiveHour");
9275
9617
  return {
9276
9618
  ...fiveHour === void 0 ? {} : { fiveHour },
9277
9619
  ...sevenDay === void 0 ? {} : { sevenDay },
9278
9620
  ...extraUsage === void 0 ? {} : { extraUsage },
9279
- ...burn === void 0 ? {} : { burnPerHour: burn * MS_PER_HOUR3 },
9621
+ ...burn === void 0 ? {} : { burnPerHour: burn * MS_PER_HOUR4 },
9280
9622
  resuming,
9281
- ...sticky?.identity === member.identity ? { lastPickHoursAgo: Math.max(0, (nowMs - Date.parse(sticky.at)) / MS_PER_HOUR3) } : {}
9623
+ ...sticky?.identity === member.identity ? { lastPickHoursAgo: Math.max(0, (nowMs - Date.parse(sticky.at)) / MS_PER_HOUR4) } : {}
9282
9624
  };
9283
9625
  }
9284
9626
  function rankPool(input) {
@@ -9373,7 +9715,7 @@ function rankPool(input) {
9373
9715
  ...holdForReturn === void 0 ? {} : { holdForReturn }
9374
9716
  };
9375
9717
  }
9376
- 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;
9718
+ var MS_PER_SECOND5, MS_PER_HOUR4, PROMPT_CACHE_TTL_HOURS, PROMPT_CACHE_TTL_MS, CLASS_ORDER;
9377
9719
  var init_pick = __esm({
9378
9720
  "src/usage/pick.ts"() {
9379
9721
  "use strict";
@@ -9382,17 +9724,14 @@ var init_pick = __esm({
9382
9724
  init_plan2();
9383
9725
  init_middleware();
9384
9726
  init_preflight();
9727
+ init_providerWindows();
9385
9728
  init_quotaFacts();
9729
+ init_windowLengths();
9386
9730
  init_rateLimit();
9387
9731
  MS_PER_SECOND5 = 1e3;
9388
- MS_PER_HOUR3 = 36e5;
9389
- HOURS_PER_DAY3 = 24;
9390
- FIVE_HOURS = 5;
9732
+ MS_PER_HOUR4 = 36e5;
9391
9733
  PROMPT_CACHE_TTL_HOURS = 1;
9392
- SEVEN_DAYS = 7;
9393
- FIVE_HOUR_WINDOW_MS = FIVE_HOURS * MS_PER_HOUR3;
9394
- SEVEN_DAY_WINDOW_MS = SEVEN_DAYS * HOURS_PER_DAY3 * MS_PER_HOUR3;
9395
- PROMPT_CACHE_TTL_MS = PROMPT_CACHE_TTL_HOURS * MS_PER_HOUR3;
9734
+ PROMPT_CACHE_TTL_MS = PROMPT_CACHE_TTL_HOURS * MS_PER_HOUR4;
9396
9735
  CLASS_ORDER = { scored: 0, unknown: 1, "pay-per-use": 2, ineligible: 3 };
9397
9736
  }
9398
9737
  });
@@ -9525,11 +9864,11 @@ var init_store2 = __esm({
9525
9864
 
9526
9865
  // src/usage/poolPick.ts
9527
9866
  import path26 from "node:path";
9528
- import { z as z18 } from "zod";
9867
+ import { z as z19 } from "zod";
9529
9868
  function errorMessage(error) {
9530
9869
  return error instanceof Error ? error.message : String(error);
9531
9870
  }
9532
- function loadPoolMembers(fs17, paths, identities, nowMs, idOf) {
9871
+ function loadPoolMembers(fs17, paths, identities, nowMs, idOf, providerOf) {
9533
9872
  const windowStartMs = nowMs - FIVE_HOUR_WINDOW_MS;
9534
9873
  const log = readUsageLog(fs17, paths.usageLogDir, { sinceMs: windowStartMs });
9535
9874
  return identities.map((identity) => {
@@ -9537,14 +9876,20 @@ function loadPoolMembers(fs17, paths, identities, nowMs, idOf) {
9537
9876
  if (id === void 0) {
9538
9877
  return { identity, records: [] };
9539
9878
  }
9540
- const records = log.records.filter((record) => record.identity === id && record.provider === ANTHROPIC_PROVIDER && Date.parse(record.at) >= windowStartMs);
9879
+ const resolved = providerOf?.(identity);
9880
+ const provider = typeof resolved === "object" ? resolved.named : resolved;
9881
+ const providerField = {
9882
+ ...provider === void 0 ? {} : { provider },
9883
+ ...typeof resolved === "object" ? { providerError: resolved.reason } : {}
9884
+ };
9885
+ const records = log.records.filter((record) => record.identity === id && record.provider === (provider ?? ANTHROPIC_PROVIDER) && Date.parse(record.at) >= windowStartMs);
9541
9886
  try {
9542
9887
  const snapshot = readUsageSnapshot(fs17, paths.usageSnapshotsDir, id);
9543
9888
  const account = readAccountMetadata(fs17, paths.identitiesDir, id) ?? snapshot?.account;
9544
- return { identity, records, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
9889
+ return { identity, records, ...providerField, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
9545
9890
  } catch (error) {
9546
9891
  if (error instanceof UsageSnapshotError || error instanceof AccountMetadataError) {
9547
- return { identity, records, readError: errorMessage(error) };
9892
+ return { identity, records, ...providerField, readError: errorMessage(error) };
9548
9893
  }
9549
9894
  throw error;
9550
9895
  }
@@ -9554,7 +9899,7 @@ function snapshotAgeKey(member) {
9554
9899
  return member.snapshot === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(member.snapshot.updatedAt);
9555
9900
  }
9556
9901
  function collapseSharedLogins(members) {
9557
- const groups = groupSharedLogins(members, (member) => member.nested === void 0 && member.account !== void 0 ? loginKeyOf(member.account) : void 0);
9902
+ const groups = groupSharedLogins(members, (member) => member.nested === void 0 && member.provider === void 0 && member.account !== void 0 ? loginKeyOf(member.account) : void 0);
9558
9903
  const representativeOf = /* @__PURE__ */ new Map();
9559
9904
  for (const group of groups) {
9560
9905
  const representative = group.reduce((freshest, member) => snapshotAgeKey(member) > snapshotAgeKey(freshest) ? member : freshest);
@@ -9584,7 +9929,7 @@ function rankNamedPool(input, poolName, stack, sticky) {
9584
9929
  const childStack = [...stack, poolName];
9585
9930
  const direct = pool.identities.filter((entry) => poolNameOf(poolMemberIdentity(entry)) === void 0);
9586
9931
  const missing = direct.filter((entry) => input.identityIdOf(poolMemberIdentity(entry)) === void 0).map((entry) => ({ pool: poolName, identity: poolMemberIdentity(entry) }));
9587
- 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]));
9932
+ 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]));
9588
9933
  const members = [];
9589
9934
  for (const entry of pool.identities) {
9590
9935
  const nestedName = poolNameOf(poolMemberIdentity(entry));
@@ -9625,7 +9970,7 @@ function nestedMember(input, nestedName, childStack, sticky) {
9625
9970
  const nested = rankNamedPool(input, nestedName, childStack, sticky);
9626
9971
  const pick = nested.ranking.pick;
9627
9972
  if (pick !== void 0) {
9628
- const [member] = loadPoolMembers(input.fs, input.paths, [pick.identity], input.nowMs, input.identityIdOf);
9973
+ const [member] = loadPoolMembers(input.fs, input.paths, [pick.identity], input.nowMs, input.identityIdOf, input.providerOf);
9629
9974
  return { member: { ...member ?? { identity: pick.identity, records: [] }, nested: { kind: "pick", pool: nestedName, reasons: pick.reasons } }, missing: nested.missing };
9630
9975
  }
9631
9976
  const earliestReturn = nested.ranking.earliestReturn;
@@ -9720,6 +10065,7 @@ var init_poolPick = __esm({
9720
10065
  init_read();
9721
10066
  init_middleware();
9722
10067
  init_store2();
10068
+ init_windowLengths();
9723
10069
  PoolGraphError = class extends CliError {
9724
10070
  constructor(message) {
9725
10071
  super(message);
@@ -9727,20 +10073,20 @@ var init_poolPick = __esm({
9727
10073
  }
9728
10074
  };
9729
10075
  SCHEMA_VERSION = 1;
9730
- PickEntrySchema = z18.strictObject({ identity: z18.string().min(1), at: z18.iso.datetime() });
9731
- PicksFileSchema = z18.strictObject({
9732
- schemaVersion: z18.literal(SCHEMA_VERSION),
9733
- picks: z18.record(z18.string().min(1), PickEntrySchema)
10076
+ PickEntrySchema = z19.strictObject({ identity: z19.string().min(1), at: z19.iso.datetime() });
10077
+ PicksFileSchema = z19.strictObject({
10078
+ schemaVersion: z19.literal(SCHEMA_VERSION),
10079
+ picks: z19.record(z19.string().min(1), PickEntrySchema)
9734
10080
  });
9735
10081
  }
9736
10082
  });
9737
10083
 
9738
10084
  // src/identityRenameJournal.ts
9739
- import { createHash as createHash8 } from "node:crypto";
10085
+ import { createHash as createHash9 } from "node:crypto";
9740
10086
  import path27 from "node:path";
9741
- import { z as z19 } from "zod";
10087
+ import { z as z20 } from "zod";
9742
10088
  function renamePairFileName(from, to, suffix) {
9743
- return `${createHash8("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
10089
+ return `${createHash9("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
9744
10090
  }
9745
10091
  function readRenameJournal(fs17, file) {
9746
10092
  const raw = fs17.readFileUtf8(file);
@@ -9816,20 +10162,20 @@ var init_identityRenameJournal = __esm({
9816
10162
  "src/identityRenameJournal.ts"() {
9817
10163
  "use strict";
9818
10164
  init_cliError();
9819
- RenameJournalSchema = z19.strictObject({
9820
- version: z19.literal(1),
9821
- from: z19.string().min(1),
9822
- to: z19.string().min(1),
9823
- startedAt: z19.iso.datetime(),
10165
+ RenameJournalSchema = z20.strictObject({
10166
+ version: z20.literal(1),
10167
+ from: z20.string().min(1),
10168
+ to: z20.string().min(1),
10169
+ startedAt: z20.iso.datetime(),
9824
10170
  /** The process that began the rename, for a person reading the file. Whether it is still running is told by the locks, not by this. */
9825
- pid: z19.number().int().positive(),
9826
- steps: z19.array(
9827
- z19.strictObject({
9828
- description: z19.string().min(1),
10171
+ pid: z20.number().int().positive(),
10172
+ steps: z20.array(
10173
+ z20.strictObject({
10174
+ description: z20.string().min(1),
9829
10175
  /** Whether the step has been applied and marked so. */
9830
- done: z19.boolean(),
10176
+ done: z20.boolean(),
9831
10177
  /** Whether the step was begun: written ahead of the step, before it runs, so a process that dies after the step took effect and before `done` was written still leaves a record that it may have. */
9832
- started: z19.boolean()
10178
+ started: z20.boolean()
9833
10179
  })
9834
10180
  )
9835
10181
  });
@@ -9855,7 +10201,7 @@ var init_identityRenameJournal = __esm({
9855
10201
  // src/identityNameRenameRecord.ts
9856
10202
  import fs7 from "node:fs";
9857
10203
  import path28 from "node:path";
9858
- import { z as z20 } from "zod";
10204
+ import { z as z21 } from "zod";
9859
10205
  function readRecordFiles(paths) {
9860
10206
  if (!fs7.existsSync(paths.identityNameRenamesDir)) {
9861
10207
  return [];
@@ -9950,12 +10296,12 @@ var init_identityNameRenameRecord = __esm({
9950
10296
  init_poolPick();
9951
10297
  init_identityRecords();
9952
10298
  init_identityRenameJournal();
9953
- NameRenameRecordSchema = z20.strictObject({
9954
- version: z20.literal(1),
9955
- id: z20.string().min(1),
9956
- from: z20.string().min(1),
9957
- to: z20.string().min(1),
9958
- startedAt: z20.iso.datetime()
10299
+ NameRenameRecordSchema = z21.strictObject({
10300
+ version: z21.literal(1),
10301
+ id: z21.string().min(1),
10302
+ from: z21.string().min(1),
10303
+ to: z21.string().min(1),
10304
+ startedAt: z21.iso.datetime()
9959
10305
  });
9960
10306
  RECORD_SUFFIX = ".json";
9961
10307
  InterruptedNameRenameError = class extends CliError {
@@ -9970,7 +10316,7 @@ var init_identityNameRenameRecord = __esm({
9970
10316
  // src/launcher/launchRecords.ts
9971
10317
  import path29 from "node:path";
9972
10318
  import { randomUUID as randomUUID4 } from "node:crypto";
9973
- import { z as z21 } from "zod";
10319
+ import { z as z22 } from "zod";
9974
10320
  function recordFile(directory, pid) {
9975
10321
  return path29.join(directory, `${String(pid)}.${randomUUID4()}${RECORD_SUFFIX2}`);
9976
10322
  }
@@ -10017,11 +10363,11 @@ var LaunchRecordSchema, RECORD_SUFFIX2;
10017
10363
  var init_launchRecords = __esm({
10018
10364
  "src/launcher/launchRecords.ts"() {
10019
10365
  "use strict";
10020
- LaunchRecordSchema = z21.strictObject({
10366
+ LaunchRecordSchema = z22.strictObject({
10021
10367
  /** The launcher's process id, which is what tells a launch in progress from a record a crashed launcher left behind. */
10022
- pid: z21.number().int().positive(),
10023
- identity: z21.string().min(1),
10024
- startedAt: z21.iso.datetime()
10368
+ pid: z22.number().int().positive(),
10369
+ identity: z22.string().min(1),
10370
+ startedAt: z22.iso.datetime()
10025
10371
  });
10026
10372
  RECORD_SUFFIX2 = ".json";
10027
10373
  }
@@ -10492,7 +10838,7 @@ var init_package = __esm({
10492
10838
  "package.json"() {
10493
10839
  package_default = {
10494
10840
  name: "claude-use",
10495
- version: "12.0.0",
10841
+ version: "12.1.0",
10496
10842
  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.",
10497
10843
  license: "MIT",
10498
10844
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -10751,94 +11097,8 @@ var init_cascade = __esm({
10751
11097
  }
10752
11098
  });
10753
11099
 
10754
- // src/paths.ts
10755
- import fs9 from "node:fs";
10756
- import os5 from "node:os";
10757
- import path36 from "node:path";
10758
- function resolveAgentShimHome(env = process.env, home = os5.homedir(), isDirectory = isExistingDirectory) {
10759
- const fromEnv = env.AGENT_SHIM_HOME;
10760
- if (fromEnv !== void 0 && fromEnv !== "") {
10761
- return fromEnv;
10762
- }
10763
- const current = path36.join(home, HOME_DIRNAME);
10764
- const legacy = path36.join(home, LEGACY_HOME_DIRNAME);
10765
- return !isDirectory(current) && isDirectory(legacy) ? legacy : current;
10766
- }
10767
- function isExistingDirectory(candidate) {
10768
- return fs9.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() ?? false;
10769
- }
10770
- function resolveClaudeHome() {
10771
- const fromEnv = process.env.AGENT_SHIM_CLAUDE_HOME;
10772
- if (fromEnv !== void 0 && fromEnv !== "") {
10773
- return fromEnv;
10774
- }
10775
- return path36.join(os5.homedir(), ".claude");
10776
- }
10777
- function buildLayoutPaths(root) {
10778
- return {
10779
- root,
10780
- identitiesDir: path36.join(root, "identities"),
10781
- configProfilesDir: path36.join(root, "config-profiles"),
10782
- providersDir: path36.join(root, "providers"),
10783
- providerAliasesFile: path36.join(root, "provider-aliases.json"),
10784
- directoryRulesFile: path36.join(root, "directory-rules.json"),
10785
- activeIdentityFile: path36.join(root, "active-identity"),
10786
- globalConfigFile: path36.join(root, "config.json"),
10787
- categoriesLocalFile: path36.join(root, "categories.local.json"),
10788
- claudeShimFile: path36.join(root, "claude-shim.json"),
10789
- headroomDir: path36.join(root, "headroom"),
10790
- headroomStateFile: path36.join(root, "headroom", "state.json"),
10791
- headroomRoutingFile: path36.join(root, "headroom", "routing.json"),
10792
- headroomLegacyStateFile: path36.join(root, "headroom", "state.v2.json"),
10793
- headroomAllowlistFile: path36.join(root, "headroom", "run", "allowlist.txt"),
10794
- headroomSocketDir: path36.join(root, "headroom", "run"),
10795
- headroomLockFile: path36.join(root, "headroom", "start.lock"),
10796
- headroomSessionsDir: path36.join(root, "headroom", "sessions"),
10797
- logsDir: path36.join(root, "logs"),
10798
- headroomLogPath: path36.join(root, "logs", "headroom.log"),
10799
- frontdoorDir: path36.join(root, "frontdoor"),
10800
- frontdoorCaDir: path36.join(root, "frontdoor", "ca"),
10801
- frontdoorCaCertFile: path36.join(root, "frontdoor", "ca", "ca.pem"),
10802
- frontdoorCaKeyFile: path36.join(root, "frontdoor", "ca", "ca.key"),
10803
- frontdoorCaBundlesDir: path36.join(root, "frontdoor", "ca", "bundles"),
10804
- chatgptSignInFile: path36.join(root, "codex", "chatgpt-sign-in.json"),
10805
- frontdoorStateFile: path36.join(root, "frontdoor", "state.json"),
10806
- frontdoorLockFile: path36.join(root, "frontdoor", "start.lock"),
10807
- frontdoorControlTokenFile: path36.join(root, "frontdoor", "control-token"),
10808
- frontdoorSessionsDir: path36.join(root, "frontdoor", "sessions"),
10809
- frontdoorDirectRecordsDir: path36.join(root, "frontdoor", "direct"),
10810
- frontdoorDrainingDir: path36.join(root, "frontdoor", "draining"),
10811
- frontdoorRcCredentialsDir: path36.join(root, "frontdoor", "rc-credentials"),
10812
- frontdoorLogPath: path36.join(root, "logs", "frontdoor.log"),
10813
- usageDir: path36.join(root, "usage"),
10814
- usageLogDir: path36.join(root, "usage", "log"),
10815
- usageSnapshotsDir: path36.join(root, "usage", "snapshots"),
10816
- statuslineDir: path36.join(root, "statusline"),
10817
- catalogueDir: path36.join(root, "catalogues"),
10818
- usagePicksFile: path36.join(root, "usage", "picks.json"),
10819
- usageAnchorsFile: path36.join(root, "usage", "anchors.json"),
10820
- usageJobsFile: path36.join(root, "usage", "jobs.json"),
10821
- jobLogsDir: path36.join(root, "logs", "jobs"),
10822
- identityRenamesDir: path36.join(root, "identity-renames"),
10823
- identityNameRenamesDir: path36.join(root, "identity-name-renames"),
10824
- launchesDir: path36.join(root, "launches"),
10825
- superviseDir: path36.join(root, "supervise"),
10826
- modelMovesDir: path36.join(root, "model-moves"),
10827
- mcpPermissionsFile: path36.join(root, "mcp", "permissions.json")
10828
- };
10829
- }
10830
- function resolveLayoutPaths() {
10831
- return buildLayoutPaths(resolveAgentShimHome());
10832
- }
10833
- var init_paths = __esm({
10834
- "src/paths.ts"() {
10835
- "use strict";
10836
- init_legacy();
10837
- }
10838
- });
10839
-
10840
11100
  // src/providerAliases.ts
10841
- import { z as z25 } from "zod";
11101
+ import { z as z26 } from "zod";
10842
11102
  function parseAliases(file, raw) {
10843
11103
  const parsed = ProviderAliasesSchema.safeParse(raw);
10844
11104
  if (!parsed.success) {
@@ -10877,7 +11137,7 @@ var init_providerAliases = __esm({
10877
11137
  init_cliError();
10878
11138
  init_load();
10879
11139
  init_store();
10880
- ProviderAliasesSchema = z25.record(z25.string().min(1), z25.string().min(1));
11140
+ ProviderAliasesSchema = z26.record(z26.string().min(1), z26.string().min(1));
10881
11141
  }
10882
11142
  });
10883
11143
 
@@ -11089,12 +11349,12 @@ var init_families = __esm({
11089
11349
  });
11090
11350
 
11091
11351
  // src/providersStore.ts
11092
- import fs10 from "node:fs";
11352
+ import fs9 from "node:fs";
11093
11353
  function providerJsonPath(paths, name) {
11094
11354
  return providerFilePath(paths.providersDir, name);
11095
11355
  }
11096
11356
  function providerExists(paths, name) {
11097
- return fs10.existsSync(providerJsonPath(paths, name));
11357
+ return fs9.existsSync(providerJsonPath(paths, name));
11098
11358
  }
11099
11359
  function requireProviderExists(paths, name) {
11100
11360
  const canonical = canonicalProviderName(name, (candidate) => providerExists(paths, candidate), () => readProviderAliases(paths));
@@ -11151,12 +11411,12 @@ function parseProviderFile(filePath, raw) {
11151
11411
  }
11152
11412
  function readProvider(paths, name) {
11153
11413
  const filePath = providerJsonPath(paths, name);
11154
- if (!fs10.existsSync(filePath)) {
11414
+ if (!fs9.existsSync(filePath)) {
11155
11415
  return void 0;
11156
11416
  }
11157
11417
  let raw;
11158
11418
  try {
11159
- raw = JSON.parse(fs10.readFileSync(filePath, "utf8"));
11419
+ raw = JSON.parse(fs9.readFileSync(filePath, "utf8"));
11160
11420
  } catch (error) {
11161
11421
  throw error instanceof SyntaxError ? new ConfigFileNotJsonError(filePath) : error;
11162
11422
  }
@@ -11172,7 +11432,7 @@ function reportInvalidProvider(name, message) {
11172
11432
  }
11173
11433
  function listProviders(paths, onInvalid = reportInvalidProvider) {
11174
11434
  const names = listProviderNames(
11175
- (dir) => fs10.readdirSync(dir),
11435
+ (dir) => fs9.readdirSync(dir),
11176
11436
  paths.providersDir
11177
11437
  );
11178
11438
  const result = [];
@@ -11339,7 +11599,7 @@ function removeProvider(paths, name) {
11339
11599
  if (!providerExists(paths, name)) {
11340
11600
  throw new ProviderNotFoundError(name);
11341
11601
  }
11342
- fs10.rmSync(providerJsonPath(paths, name));
11602
+ fs9.rmSync(providerJsonPath(paths, name));
11343
11603
  createRealCredentialCache(paths.root).remove("file", `provider ${name}`);
11344
11604
  }
11345
11605
  function cascadeProviderName(cascade, identityProvider) {
@@ -11351,13 +11611,19 @@ function cascadeProviderName(cascade, identityProvider) {
11351
11611
  }
11352
11612
  return name ?? identityProvider;
11353
11613
  }
11354
- function selectProvider(params) {
11614
+ function selectedProviderName(params) {
11355
11615
  const cliName = params.cliProvider !== void 0 && params.cliProvider !== "" ? params.cliProvider : void 0;
11356
11616
  const named = cliName ?? (params.cascade === void 0 ? params.identityProvider : cascadeProviderName(params.cascade, params.identityProvider));
11357
11617
  if (named === void 0) {
11358
11618
  return void 0;
11359
11619
  }
11360
- const name = canonicalProviderName(named, (candidate) => loadProvider(params.paths.providersDir, candidate, params.port) !== void 0, () => loadProviderAliases(params.paths.providerAliasesFile, params.port));
11620
+ return canonicalProviderName(named, (candidate) => loadProvider(params.paths.providersDir, candidate, params.port) !== void 0, () => loadProviderAliases(params.paths.providerAliasesFile, params.port));
11621
+ }
11622
+ function selectProvider(params) {
11623
+ const name = selectedProviderName(params);
11624
+ if (name === void 0) {
11625
+ return void 0;
11626
+ }
11361
11627
  const definition = loadProvider(params.paths.providersDir, name, params.port);
11362
11628
  if (definition === void 0) {
11363
11629
  const known = listProviderNames(params.port.readdir, params.paths.providersDir);
@@ -11502,255 +11768,201 @@ var init_providersStore = __esm({
11502
11768
  }
11503
11769
  });
11504
11770
 
11505
- // src/launcher/claudeVersion.ts
11506
- function validated2(value, origin) {
11507
- if (!NUMERIC_DOTTED_VERSION_RE.test(value)) {
11508
- throw new InvalidClaudeVersionError(value, origin);
11509
- }
11510
- return value;
11511
- }
11512
- function resolveClaudeVersion(params) {
11513
- if (params.flag !== void 0) {
11514
- return { version: validated2(params.flag, "--claude-version"), source: "flag" };
11515
- }
11516
- const fromEnv = params.env.AGENT_SHIM_CLAUDE_VERSION;
11517
- if (fromEnv !== void 0 && fromEnv !== "") {
11518
- return { version: validated2(fromEnv, "AGENT_SHIM_CLAUDE_VERSION"), source: "environment" };
11519
- }
11520
- return params.cascade === void 0 ? void 0 : { version: params.cascade, source: "cascade" };
11521
- }
11522
- var CLAUDE_VERSION_SOURCES, InvalidClaudeVersionError;
11523
- var init_claudeVersion = __esm({
11524
- "src/launcher/claudeVersion.ts"() {
11525
- "use strict";
11526
- init_cliError();
11527
- init_versionDiscovery();
11528
- CLAUDE_VERSION_SOURCES = ["flag", "environment", "cascade"];
11529
- InvalidClaudeVersionError = class extends UsageError {
11530
- constructor(value, origin) {
11531
- super(`${origin} names Claude Code version "${value}", which is not an exact dotted-numeric version such as 2.1.220.`);
11532
- this.value = value;
11533
- this.origin = origin;
11534
- this.name = "InvalidClaudeVersionError";
11535
- }
11536
- value;
11537
- origin;
11538
- };
11539
- }
11540
- });
11541
-
11542
- // src/headroom/headers.ts
11543
- function mergeAnthropicCustomHeaders(existing, additions) {
11544
- const merged = /* @__PURE__ */ new Map();
11545
- for (const block of existing) {
11546
- if (block === void 0) {
11547
- continue;
11548
- }
11549
- for (const line of block.split("\n")) {
11550
- const entry = parseCustomHeaderLine(line);
11551
- if (entry === void 0) {
11552
- continue;
11553
- }
11554
- merged.set(entry.name, entry.value);
11555
- }
11556
- }
11557
- for (const entry of additions) {
11558
- merged.set(entry.name, entry.value);
11559
- }
11560
- return [...merged].map(([name, value]) => `${name}: ${value}`).join("\n");
11561
- }
11562
- function parseAnthropicCustomHeaders(block) {
11563
- return block.split("\n").flatMap((line) => {
11564
- const entry = parseCustomHeaderLine(line);
11565
- return entry === void 0 ? [] : [entry];
11566
- });
11567
- }
11568
- function withoutAnthropicCustomHeaders(block, remove) {
11569
- const lines = block.split("\n");
11570
- const kept = lines.filter((line) => {
11571
- const entry = parseCustomHeaderLine(line);
11572
- return entry === void 0 || !remove(entry);
11573
- });
11574
- return kept.length === lines.length ? block : kept.join("\n");
11575
- }
11576
- function parseCustomHeaderLine(line) {
11577
- const trimmed = line.trim();
11578
- if (trimmed === "") {
11579
- return void 0;
11580
- }
11581
- const colon = trimmed.indexOf(":");
11582
- if (colon <= 0) {
11583
- return void 0;
11584
- }
11585
- return { name: trimmed.slice(0, colon).trim(), value: trimmed.slice(colon + 1).trim() };
11586
- }
11587
- var init_headers = __esm({
11588
- "src/headroom/headers.ts"() {
11589
- "use strict";
11590
- }
11591
- });
11592
-
11593
- // src/launcher/injected.ts
11594
- import { createHash as createHash9 } from "node:crypto";
11595
- import { z as z26 } from "zod";
11596
- function listKey(list) {
11597
- return `${list},appended`;
11598
- }
11599
- function digest2(value) {
11600
- return createHash9("sha256").update(value).digest("hex");
11601
- }
11602
- function recordedDigests(env) {
11603
- const raw = env[INJECTED_ENV];
11604
- if (raw === void 0 || raw === "") {
11605
- return {};
11606
- }
11607
- let parsed;
11608
- try {
11609
- parsed = JSON.parse(raw);
11610
- } catch {
11611
- return {};
11612
- }
11613
- const result = InjectedSchema.safeParse(parsed);
11614
- return result.success ? result.data : {};
11615
- }
11616
- function recordInjections(base) {
11617
- const env = { ...base };
11618
- const digests = new Map(Object.entries(recordedDigests(env)));
11619
- return {
11620
- env,
11621
- set: (name, value) => {
11622
- env[name] = value;
11623
- digests.set(name, digest2(value));
11624
- },
11625
- unset: (name) => {
11626
- env[name] = void 0;
11627
- digests.delete(name);
11628
- },
11629
- recordHeaders: (names) => {
11630
- const block = env[CUSTOM_HEADERS_ENV];
11631
- for (const entry of block === void 0 ? [] : parseAnthropicCustomHeaders(block)) {
11632
- if (names.includes(entry.name)) {
11633
- digests.set(`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`, digest2(entry.value));
11634
- }
11635
- }
11636
- },
11637
- recordBypassHosts: (list, hosts) => {
11638
- const recordedHosts = [.../* @__PURE__ */ new Set([...digests.get(listKey(list))?.split(",") ?? [], ...hosts.map((host) => host.trim().toLowerCase()).filter((host) => host !== "")])];
11639
- if (recordedHosts.length > 0) {
11640
- digests.set(listKey(list), recordedHosts.join(","));
11641
- }
11642
- },
11643
- finish: () => {
11644
- if (digests.size > 0) {
11645
- env[INJECTED_ENV] = JSON.stringify(Object.fromEntries(digests));
11646
- }
11647
- }
11648
- };
11649
- }
11650
- function withoutRecordedHosts(list, value, digests) {
11651
- const recordedHosts = new Set(digests[listKey(list)]?.split(","));
11652
- const entries = value.split(",");
11653
- const kept = entries.filter((entry) => !recordedHosts.has(entry.trim().toLowerCase()));
11654
- return kept.length === entries.length ? value : kept.join(",");
11655
- }
11656
- function launchEnvironment(env, configDirEscapeHatch) {
11657
- return configDirEscapeHatch ? env : withoutInjected(env);
11771
+ // src/launcher/memberProvider.ts
11772
+ function unreadableFileReason(error) {
11773
+ if (error instanceof ConfigValidationError) {
11774
+ return `${error.filepath} is invalid`;
11775
+ }
11776
+ if (error instanceof ConfigFileNotJsonError) {
11777
+ return error.message.replace(/\.$/, "");
11778
+ }
11779
+ if (error instanceof LegacyProviderFileError) {
11780
+ return `${error.filePath} uses ${error.conversion.fields.join(", ")}, which a credential block replaced`;
11781
+ }
11782
+ return void 0;
11658
11783
  }
11659
- function withoutInjected(env) {
11660
- const digests = recordedDigests(env);
11661
- const entries = Object.entries(env).flatMap(([name, value]) => {
11662
- if (name === INJECTED_ENV) {
11663
- return [];
11664
- }
11665
- if (value === void 0) {
11666
- return [[name, value]];
11784
+ function memberProviderResolver(params) {
11785
+ if (params.cliProvider === false) {
11786
+ return () => void 0;
11787
+ }
11788
+ const cliProvider = params.cliProvider;
11789
+ const identities = identityReader(params.paths.identitiesDir, params.fs);
11790
+ const cascades = /* @__PURE__ */ new Map();
11791
+ const cascadeOver = (baseConfigProfile) => {
11792
+ const cached = cascades.get(baseConfigProfile);
11793
+ if (cached !== void 0) {
11794
+ return cached;
11667
11795
  }
11668
- if (name === CUSTOM_HEADERS_ENV) {
11669
- const remaining = withoutAnthropicCustomHeaders(value, (entry) => digests[`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`] === digest2(entry.value));
11670
- return remaining !== value && remaining.trim() === "" ? [] : [[name, remaining]];
11796
+ const loaded = params.loadCascade(baseConfigProfile);
11797
+ cascades.set(baseConfigProfile, loaded);
11798
+ return loaded;
11799
+ };
11800
+ return (name) => {
11801
+ let declared;
11802
+ try {
11803
+ declared = identities.load(name);
11804
+ } catch (error) {
11805
+ if (!(error instanceof ConfigValidationError)) {
11806
+ throw error;
11807
+ }
11671
11808
  }
11672
- if (name === "NO_PROXY" || name === "no_proxy") {
11673
- const remaining = withoutRecordedHosts(name, value, digests);
11674
- return remaining !== value && remaining.split(",").every((entry) => entry.trim() === "") ? [] : [[name, remaining]];
11809
+ const profile = decideConfigProfile({
11810
+ env: params.env,
11811
+ ...params.cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile: params.cliFlagConfigProfile },
11812
+ ...params.directoryRuleConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: params.directoryRuleConfigProfile },
11813
+ ...declared?.defaultConfigProfile === void 0 ? {} : { identityDefaultConfigProfile: declared.defaultConfigProfile },
11814
+ ...params.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: params.globalDefaultConfigProfile }
11815
+ });
11816
+ const flagged = cliProvider !== void 0 && cliProvider !== "" ? cliProvider : void 0;
11817
+ let named = flagged ?? declared?.provider;
11818
+ try {
11819
+ const cascade = cascadeOver(profile.name);
11820
+ named = flagged ?? cascadeProviderName(cascade, declared?.provider);
11821
+ return selectedProviderName({
11822
+ paths: params.paths,
11823
+ port: params.fs,
11824
+ ...cliProvider === void 0 ? {} : { cliProvider },
11825
+ cascade,
11826
+ ...declared?.provider === void 0 ? {} : { identityProvider: declared.provider }
11827
+ });
11828
+ } catch (error) {
11829
+ const reason = unreadableFileReason(error);
11830
+ if (reason === void 0) {
11831
+ throw error;
11832
+ }
11833
+ return { ...named === void 0 ? {} : { named }, reason };
11675
11834
  }
11676
- return digests[name] === digest2(value) ? [] : [[name, value]];
11677
- });
11678
- return Object.fromEntries(entries);
11835
+ };
11679
11836
  }
11680
- var INJECTED_ENV, CUSTOM_HEADERS_ENV, HEADER_KEY_PREFIX, InjectedSchema;
11681
- var init_injected = __esm({
11682
- "src/launcher/injected.ts"() {
11837
+ var init_memberProvider = __esm({
11838
+ "src/launcher/memberProvider.ts"() {
11683
11839
  "use strict";
11684
- init_headers();
11685
- INJECTED_ENV = "AGENT_SHIM_INJECTED";
11686
- CUSTOM_HEADERS_ENV = "ANTHROPIC_CUSTOM_HEADERS";
11687
- HEADER_KEY_PREFIX = `${CUSTOM_HEADERS_ENV}:`;
11688
- InjectedSchema = z26.record(z26.string(), z26.string());
11840
+ init_load();
11841
+ init_providersStore();
11842
+ init_identity();
11689
11843
  }
11690
11844
  });
11691
11845
 
11692
- // src/launcher/guard.ts
11693
- function detectAmbientCredential(env, injected) {
11694
- for (const variable of AMBIENT_CREDENTIAL_VARS) {
11695
- const value = env[variable];
11696
- if (value === void 0 || value === "") {
11697
- continue;
11698
- }
11699
- if (injected?.variable === variable && value === injected.token) {
11700
- continue;
11701
- }
11702
- return { variable };
11846
+ // src/paths.ts
11847
+ import fs10 from "node:fs";
11848
+ import os6 from "node:os";
11849
+ import path36 from "node:path";
11850
+ function resolveAgentShimHome(env = process.env, home = os6.homedir(), isDirectory = isExistingDirectory) {
11851
+ const fromEnv = env.AGENT_SHIM_HOME;
11852
+ if (fromEnv !== void 0 && fromEnv !== "") {
11853
+ return fromEnv;
11703
11854
  }
11704
- return void 0;
11855
+ const current = path36.join(home, HOME_DIRNAME);
11856
+ const legacy = path36.join(home, LEGACY_HOME_DIRNAME);
11857
+ return !isDirectory(current) && isDirectory(legacy) ? legacy : current;
11705
11858
  }
11706
- function formatAmbientCredentialGuardMessage(variable, identityName) {
11707
- const identitySetCommand = identityName === void 0 ? "agent-shim identity set <name> --allow-ambient-credential" : `agent-shim identity set ${identityName} --allow-ambient-credential`;
11708
- return [
11709
- `error: ${variable} is set in the environment. This identity's isolated`,
11710
- "credential would be bypassed \u2014 every identity authenticates as this same key",
11711
- "while it's set. Unset it, or if this is deliberate, opt in per-launch with",
11712
- "AGENT_SHIM_ALLOW_AMBIENT_CREDENTIAL=1, or persistently for this identity with",
11713
- `\`${identitySetCommand}\`.`
11714
- ].join("\n");
11859
+ function isExistingDirectory(candidate) {
11860
+ return fs10.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() ?? false;
11715
11861
  }
11716
- function evaluateAmbientCredentialGuard(params) {
11717
- const detected = detectAmbientCredential(params.env, params.injectedCredential);
11718
- if (detected === void 0) {
11719
- return { ok: true };
11720
- }
11721
- if (params.allowAmbientCredentialOverride || params.allowAmbientCredential || params.providerSelected === true) {
11722
- return { ok: true };
11862
+ function resolveClaudeHome() {
11863
+ const fromEnv = process.env.AGENT_SHIM_CLAUDE_HOME;
11864
+ if (fromEnv !== void 0 && fromEnv !== "") {
11865
+ return fromEnv;
11723
11866
  }
11867
+ return path36.join(os6.homedir(), ".claude");
11868
+ }
11869
+ function buildLayoutPaths(root) {
11724
11870
  return {
11725
- ok: false,
11726
- variable: detected.variable,
11727
- message: formatAmbientCredentialGuardMessage(detected.variable, params.identityName)
11871
+ root,
11872
+ identitiesDir: path36.join(root, "identities"),
11873
+ configProfilesDir: path36.join(root, "config-profiles"),
11874
+ providersDir: path36.join(root, "providers"),
11875
+ providerAliasesFile: path36.join(root, "provider-aliases.json"),
11876
+ directoryRulesFile: path36.join(root, "directory-rules.json"),
11877
+ activeIdentityFile: path36.join(root, "active-identity"),
11878
+ globalConfigFile: path36.join(root, "config.json"),
11879
+ categoriesLocalFile: path36.join(root, "categories.local.json"),
11880
+ claudeShimFile: path36.join(root, "claude-shim.json"),
11881
+ headroomDir: path36.join(root, "headroom"),
11882
+ headroomStateFile: path36.join(root, "headroom", "state.json"),
11883
+ headroomRoutingFile: path36.join(root, "headroom", "routing.json"),
11884
+ headroomLegacyStateFile: path36.join(root, "headroom", "state.v2.json"),
11885
+ headroomAllowlistFile: path36.join(root, "headroom", "run", "allowlist.txt"),
11886
+ headroomSocketDir: path36.join(root, "headroom", "run"),
11887
+ headroomLockFile: path36.join(root, "headroom", "start.lock"),
11888
+ headroomSessionsDir: path36.join(root, "headroom", "sessions"),
11889
+ logsDir: path36.join(root, "logs"),
11890
+ headroomLogPath: path36.join(root, "logs", "headroom.log"),
11891
+ frontdoorDir: path36.join(root, "frontdoor"),
11892
+ frontdoorCaDir: path36.join(root, "frontdoor", "ca"),
11893
+ frontdoorCaCertFile: path36.join(root, "frontdoor", "ca", "ca.pem"),
11894
+ frontdoorCaKeyFile: path36.join(root, "frontdoor", "ca", "ca.key"),
11895
+ frontdoorCaBundlesDir: path36.join(root, "frontdoor", "ca", "bundles"),
11896
+ chatgptSignInFile: path36.join(root, "codex", "chatgpt-sign-in.json"),
11897
+ frontdoorStateFile: path36.join(root, "frontdoor", "state.json"),
11898
+ frontdoorLockFile: path36.join(root, "frontdoor", "start.lock"),
11899
+ frontdoorControlTokenFile: path36.join(root, "frontdoor", "control-token"),
11900
+ frontdoorSessionsDir: path36.join(root, "frontdoor", "sessions"),
11901
+ frontdoorDirectRecordsDir: path36.join(root, "frontdoor", "direct"),
11902
+ frontdoorDrainingDir: path36.join(root, "frontdoor", "draining"),
11903
+ frontdoorRcCredentialsDir: path36.join(root, "frontdoor", "rc-credentials"),
11904
+ frontdoorLogPath: path36.join(root, "logs", "frontdoor.log"),
11905
+ usageDir: path36.join(root, "usage"),
11906
+ usageLogDir: path36.join(root, "usage", "log"),
11907
+ usageSnapshotsDir: path36.join(root, "usage", "snapshots"),
11908
+ statuslineDir: path36.join(root, "statusline"),
11909
+ catalogueDir: path36.join(root, "catalogues"),
11910
+ usagePicksFile: path36.join(root, "usage", "picks.json"),
11911
+ usageAnchorsFile: path36.join(root, "usage", "anchors.json"),
11912
+ usageJobsFile: path36.join(root, "usage", "jobs.json"),
11913
+ jobLogsDir: path36.join(root, "logs", "jobs"),
11914
+ identityRenamesDir: path36.join(root, "identity-renames"),
11915
+ identityNameRenamesDir: path36.join(root, "identity-name-renames"),
11916
+ launchesDir: path36.join(root, "launches"),
11917
+ superviseDir: path36.join(root, "supervise"),
11918
+ modelMovesDir: path36.join(root, "model-moves"),
11919
+ mcpPermissionsFile: path36.join(root, "mcp", "permissions.json")
11728
11920
  };
11729
11921
  }
11730
- function ambientCredentialFinding(env) {
11731
- const named = detectAmbientCredential(launchEnvironment(env, false));
11732
- if (named !== void 0) {
11733
- return { severity: "warn", message: formatAmbientCredentialGuardMessage(named.variable) };
11922
+ function resolveLayoutPaths() {
11923
+ return buildLayoutPaths(resolveAgentShimHome());
11924
+ }
11925
+ var init_paths = __esm({
11926
+ "src/paths.ts"() {
11927
+ "use strict";
11928
+ init_legacy();
11734
11929
  }
11735
- const bare = env.CLAUDE_CONFIG_DIR === void 0 || env.CLAUDE_CONFIG_DIR === "" ? void 0 : detectAmbientCredential(env);
11736
- if (bare !== void 0) {
11737
- return { severity: "warn", message: `${bare.variable} was set in this session by the launcher that started it. A launch that names an identity drops it, but a launch naming none keeps the session's CLAUDE_CONFIG_DIR and environment and is refused. Name an identity, as in \`claude @<name>\`.` };
11930
+ });
11931
+
11932
+ // src/launcher/claudeVersion.ts
11933
+ function validated2(value, origin) {
11934
+ if (!NUMERIC_DOTTED_VERSION_RE.test(value)) {
11935
+ throw new InvalidClaudeVersionError(value, origin);
11738
11936
  }
11739
- return { severity: "pass", message: "No ambient-credential environment variable is set." };
11937
+ return value;
11740
11938
  }
11741
- var AMBIENT_CREDENTIAL_VARS;
11742
- var init_guard = __esm({
11743
- "src/launcher/guard.ts"() {
11939
+ function resolveClaudeVersion(params) {
11940
+ if (params.flag !== void 0) {
11941
+ return { version: validated2(params.flag, "--claude-version"), source: "flag" };
11942
+ }
11943
+ const fromEnv = params.env.AGENT_SHIM_CLAUDE_VERSION;
11944
+ if (fromEnv !== void 0 && fromEnv !== "") {
11945
+ return { version: validated2(fromEnv, "AGENT_SHIM_CLAUDE_VERSION"), source: "environment" };
11946
+ }
11947
+ return params.cascade === void 0 ? void 0 : { version: params.cascade, source: "cascade" };
11948
+ }
11949
+ var CLAUDE_VERSION_SOURCES, InvalidClaudeVersionError;
11950
+ var init_claudeVersion = __esm({
11951
+ "src/launcher/claudeVersion.ts"() {
11744
11952
  "use strict";
11745
- init_injected();
11746
- AMBIENT_CREDENTIAL_VARS = [
11747
- "ANTHROPIC_API_KEY",
11748
- "ANTHROPIC_AUTH_TOKEN",
11749
- "CLAUDE_CODE_OAUTH_TOKEN",
11750
- "CLAUDE_CODE_USE_BEDROCK",
11751
- "CLAUDE_CODE_USE_VERTEX",
11752
- "CLAUDE_CODE_USE_FOUNDRY"
11753
- ];
11953
+ init_cliError();
11954
+ init_versionDiscovery();
11955
+ CLAUDE_VERSION_SOURCES = ["flag", "environment", "cascade"];
11956
+ InvalidClaudeVersionError = class extends UsageError {
11957
+ constructor(value, origin) {
11958
+ super(`${origin} names Claude Code version "${value}", which is not an exact dotted-numeric version such as 2.1.220.`);
11959
+ this.value = value;
11960
+ this.origin = origin;
11961
+ this.name = "InvalidClaudeVersionError";
11962
+ }
11963
+ value;
11964
+ origin;
11965
+ };
11754
11966
  }
11755
11967
  });
11756
11968
 
@@ -11759,7 +11971,7 @@ function formatPeriod(window) {
11759
11971
  if (window.periodMs === void 0) {
11760
11972
  return window.period ?? "unknown period";
11761
11973
  }
11762
- const hours = window.periodMs / MS_PER_HOUR4;
11974
+ const hours = window.periodMs / MS_PER_HOUR5;
11763
11975
  return hours >= HOURS_PER_DAY4 && Number.isInteger(hours / HOURS_PER_DAY4) ? `${String(hours / HOURS_PER_DAY4)}d` : `${String(hours)}h`;
11764
11976
  }
11765
11977
  function groupOf(row) {
@@ -11799,13 +12011,13 @@ function collectResets(snapshots, nowMs) {
11799
12011
  );
11800
12012
  return { resets: rows.sort(compareRows) };
11801
12013
  }
11802
- var MS_PER_HOUR4, HOURS_PER_DAY4;
12014
+ var MS_PER_HOUR5, HOURS_PER_DAY4;
11803
12015
  var init_resets = __esm({
11804
12016
  "src/usage/resets.ts"() {
11805
12017
  "use strict";
11806
12018
  init_preflight();
11807
12019
  init_rateLimit();
11808
- MS_PER_HOUR4 = 36e5;
12020
+ MS_PER_HOUR5 = 36e5;
11809
12021
  HOURS_PER_DAY4 = 24;
11810
12022
  }
11811
12023
  });
@@ -12407,7 +12619,7 @@ var init_modelPicker = __esm({
12407
12619
  });
12408
12620
 
12409
12621
  // src/models/targets.ts
12410
- import os7 from "node:os";
12622
+ import os8 from "node:os";
12411
12623
  function providerModels(paths) {
12412
12624
  const door = readFrontDoorState(realFarmFs, paths.frontdoorStateFile);
12413
12625
  const recordedPid = door?.port === void 0 ? void 0 : door.supervisorPid;
@@ -12420,7 +12632,7 @@ function providerModels(paths) {
12420
12632
  if (entry.provider.kind === "codex") {
12421
12633
  if (catalogue !== void 0 && catalogue.supervisorPid !== supervisorPid) return [];
12422
12634
  const env = doorHome === void 0 ? process.env : { ...process.env, CODEX_HOME: doorHome };
12423
- const fingerprint = savedCatalogueFingerprint(entry.provider, paths, env, os7.homedir(), realFsPort.readFileUtf8);
12635
+ const fingerprint = savedCatalogueFingerprint(entry.provider, paths, env, os8.homedir(), realFsPort.readFileUtf8);
12424
12636
  if (fingerprint === void 0 || catalogue?.credentialFingerprint !== fingerprint) return [];
12425
12637
  }
12426
12638
  return providerModelRows(entry.provider, catalogue?.models).map((row) => ({ provider: entry.name, model: row.model }));
@@ -13727,7 +13939,10 @@ var init_hold = __esm({
13727
13939
  // src/launcher/launchReport.ts
13728
13940
  function poolDetail(pool) {
13729
13941
  const [reason] = pool.reasons;
13730
- return reason === void 0 ? {} : { detail: reason };
13942
+ if (reason === void 0) {
13943
+ return {};
13944
+ }
13945
+ return { detail: pool.provider === void 0 ? reason : `${reason} (ranked on provider ${pool.provider})` };
13731
13946
  }
13732
13947
  function rankingNotes(ranking, picked) {
13733
13948
  return ranking.flatMap((candidate, index) => [
@@ -13889,6 +14104,7 @@ function resolvePoolLaunch(params) {
13889
14104
  resuming,
13890
14105
  ...params.resumeContextTokens === void 0 ? {} : { resumeContextTokens: params.resumeContextTokens },
13891
14106
  ...params.committedContextTokens === void 0 ? {} : { committedContextTokens: params.committedContextTokens },
14107
+ ...params.providerOf === void 0 ? {} : { providerOf: params.providerOf },
13892
14108
  identityIdOf: identityIdResolver(params.paths.identitiesDir, params.fs),
13893
14109
  ...stickyRead.sticky === void 0 ? {} : { sticky: stickyRead.sticky }
13894
14110
  });
@@ -13930,6 +14146,7 @@ function resolvePoolLaunch(params) {
13930
14146
  explanation: `pool ${poolName}: ${move}${pick.reasons.slice(0, REASONS_LOGGED).join("; ")}`,
13931
14147
  reasons: pick.reasons,
13932
14148
  candidates: graph.ranking.candidates,
14149
+ ...pick.provider === void 0 ? {} : { provider: pick.provider },
13933
14150
  ...movedOff === void 0 ? {} : { movedOff },
13934
14151
  ...stickyRead.sticky === void 0 ? {} : { lastRanAs: stickyRead.sticky }
13935
14152
  };
@@ -13962,13 +14179,13 @@ var init_pool = __esm({
13962
14179
  });
13963
14180
 
13964
14181
  // src/launcher/spawn.ts
13965
- import os8 from "node:os";
14182
+ import os9 from "node:os";
13966
14183
  function childExitCode(result) {
13967
14184
  if (result.status !== null) {
13968
14185
  return result.status;
13969
14186
  }
13970
14187
  if (result.signal !== null) {
13971
- return SIGNAL_EXIT_CODE_OFFSET + os8.constants.signals[result.signal];
14188
+ return SIGNAL_EXIT_CODE_OFFSET + os9.constants.signals[result.signal];
13972
14189
  }
13973
14190
  return 1;
13974
14191
  }
@@ -14061,7 +14278,7 @@ var init_launchHook = __esm({
14061
14278
 
14062
14279
  // src/launcher.ts
14063
14280
  import { randomUUID as randomUUID6 } from "node:crypto";
14064
- import os9 from "node:os";
14281
+ import os10 from "node:os";
14065
14282
  import { isDeepStrictEqual } from "node:util";
14066
14283
  import path51 from "node:path";
14067
14284
  function resolveIdentityCredential(identity, credential, env, port) {
@@ -14071,7 +14288,7 @@ function resolveIdentityCredential(identity, credential, env, port) {
14071
14288
  const resolution = resolveCredential({ credential, env, port, subject: `identity ${identity.name}`, cacheKey: identityCacheKey(identity.id) });
14072
14289
  return resolution.ok ? resolution : { ok: false, status: CREDENTIAL_UNAVAILABLE_EXIT, message: `agent-shim: ${resolution.message}` };
14073
14290
  }
14074
- function pickFromPool(decided, params, parsedArgv, readOnly) {
14291
+ function pickFromPool(decided, params, parsedArgv, readOnly, providerSelections) {
14075
14292
  const { paths, fs: fs17, proc, log } = params;
14076
14293
  if (decided.pool === void 0) {
14077
14294
  return { identityDecision: decided };
@@ -14086,6 +14303,17 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
14086
14303
  return proc.exit(1);
14087
14304
  }
14088
14305
  const resumeContextTokens = resumedContextTokens(farmRuntime.fs, { claudeHome: farmRuntime.claudeHome, cwd: farmRuntime.cwd, passthrough: parsedArgv.rest });
14306
+ const cliFlagConfigProfile = params.cliFlagConfigProfile ?? parsedArgv.configProfile;
14307
+ const providerOf = memberProviderResolver({
14308
+ paths,
14309
+ fs: fs17,
14310
+ env: providerSelections.env,
14311
+ cliProvider: parsedArgv.provider,
14312
+ ...cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile },
14313
+ ...params.directoryRuleConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: params.directoryRuleConfigProfile },
14314
+ ...params.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: params.globalDefaultConfigProfile },
14315
+ loadCascade: (baseConfigProfile) => farmRuntime.loadCascade(baseConfigProfile, providerSelections.cliOverride)
14316
+ });
14089
14317
  const resolution = resolvePoolLaunch({
14090
14318
  poolName: decided.pool,
14091
14319
  selectedVia: decided.source,
@@ -14097,6 +14325,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
14097
14325
  now: farmRuntime.now,
14098
14326
  sleep: farmRuntime.lock.sleep,
14099
14327
  passthrough: parsedArgv.rest,
14328
+ providerOf,
14100
14329
  ...resumeContextTokens === void 0 ? {} : { resumeContextTokens },
14101
14330
  // 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.
14102
14331
  wait: !readOnly && parsedArgv.wait === true,
@@ -14109,7 +14338,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
14109
14338
  }
14110
14339
  return {
14111
14340
  identityDecision: { ...decided, name: resolution.identity },
14112
- poolPick: { name: decided.pool, reasons: resolution.reasons, ...resolution.movedOff === void 0 ? {} : { movedOff: resolution.movedOff } },
14341
+ poolPick: { name: decided.pool, reasons: resolution.reasons, ...resolution.provider === void 0 ? {} : { provider: resolution.provider }, ...resolution.movedOff === void 0 ? {} : { movedOff: resolution.movedOff } },
14113
14342
  poolRanking: resolution.candidates,
14114
14343
  ...resolution.lastRanAs === void 0 ? {} : { lastRanAs: { identity: resolution.lastRanAs.identity, agoMs: farmRuntime.now() - Date.parse(resolution.lastRanAs.at) } }
14115
14344
  };
@@ -14145,7 +14374,7 @@ function decideLaunch(params, readOnly, onRecorded) {
14145
14374
  shareFlags: parsedArgv.shareFlags,
14146
14375
  hideFlags: parsedArgv.hideFlags
14147
14376
  });
14148
- const { identityDecision, poolPick, poolRanking, lastRanAs } = pickFromPool(decidedIdentity, params, parsedArgv, readOnly);
14377
+ const { identityDecision, poolPick, poolRanking, lastRanAs } = pickFromPool(decidedIdentity, params, parsedArgv, readOnly, { env, cliOverride });
14149
14378
  const lockFarm = !readOnly && !configDirEscapeHatchApplies && identityDecision.name !== void 0 ? params.farm : void 0;
14150
14379
  const lockPorts = params.namesLock ?? (lockFarm === void 0 ? realIdentityNamesLockPorts : { fs: lockFarm.fs, nowMs: lockFarm.now, ...lockFarm.lock });
14151
14380
  const namesLock = readOnly || configDirEscapeHatchApplies || identityDecision.name === void 0 ? void 0 : acquireIdentityNamesLock(paths, lockPorts);
@@ -14304,10 +14533,22 @@ function decideLaunch(params, readOnly, onRecorded) {
14304
14533
  ...parsedArgv.delay === void 0 ? {} : { delay: parsedArgv.delay }
14305
14534
  }
14306
14535
  });
14307
- const loginlessProvider = requestedFlags.remoteControl && selectedProvider !== void 0 && farmIdentity !== void 0 && identityDecision.name !== void 0 && params.hasStoredLogin?.(farmIdentity) === false ? { identity: identityDecision.name, provider: selectedProvider.name } : void 0;
14536
+ const loginlessProvider = (() => {
14537
+ if (!requestedFlags.remoteControl || selectedProvider === void 0 || farmIdentity === void 0 || identityDecision.name === void 0) {
14538
+ return void 0;
14539
+ }
14540
+ const stored = params.hasStoredLogin?.(farmIdentity);
14541
+ if (stored === false) {
14542
+ return { identity: identityDecision.name, provider: selectedProvider.name, why: "has no stored login" };
14543
+ }
14544
+ if (stored === true && params.hasUsableLogin?.(farmIdentity, discovered.path) === false) {
14545
+ return { identity: identityDecision.name, provider: selectedProvider.name, why: "has a stored login that is no longer usable" };
14546
+ }
14547
+ return void 0;
14548
+ })();
14308
14549
  const notes = [];
14309
14550
  if (loginlessProvider !== void 0) {
14310
- notes.push(`${loginlessProvider.identity} has no stored login, so Remote Control is off; provider ${loginlessProvider.provider} runs without it`);
14551
+ notes.push(`${loginlessProvider.identity} ${loginlessProvider.why}, so Remote Control is off; provider ${loginlessProvider.provider} runs without it`);
14311
14552
  }
14312
14553
  const flags = loginlessProvider === void 0 ? requestedFlags : { ...requestedFlags, remoteControl: false };
14313
14554
  const globalModels = loadConfigFile(paths.globalConfigFile, GlobalConfigSchema, params.fs.readConfigFile)?.config.models;
@@ -14334,12 +14575,12 @@ function decideLaunch(params, readOnly, onRecorded) {
14334
14575
  if (definition.kind === "codex" && readOnly && cache !== void 0) {
14335
14576
  const binding = parseCatalogueBinding(params.fs.readFileUtf8(catalogueBindingPath(paths, name, catalogueOwner, generation)));
14336
14577
  const configuredHome = catalogueEnv.CODEX_HOME;
14337
- const home = configuredHome === void 0 || configuredHome === "" ? path51.join(os9.homedir(), ".codex") : configuredHome;
14578
+ const home = configuredHome === void 0 || configuredHome === "" ? path51.join(os10.homedir(), ".codex") : configuredHome;
14338
14579
  const source = definition.codex?.login === "chatgpt-sign-in" ? paths.chatgptSignInFile : path51.resolve(home, "auth.json");
14339
14580
  const revision = params.fs.fileRevision?.(source);
14340
14581
  if (binding === void 0 || binding.fingerprint !== cache.credentialFingerprint || binding.source !== source || revision === void 0 || revision !== binding.revision) return [];
14341
14582
  }
14342
- const fingerprint = definition.kind === "codex" && !readOnly ? savedCatalogueFingerprint(definition, paths, catalogueEnv, os9.homedir(), params.fs.readFileUtf8) : void 0;
14583
+ const fingerprint = definition.kind === "codex" && !readOnly ? savedCatalogueFingerprint(definition, paths, catalogueEnv, os10.homedir(), params.fs.readFileUtf8) : void 0;
14343
14584
  if (definition.kind === "codex" && !readOnly && cache !== void 0 && (fingerprint === void 0 || cache.credentialFingerprint !== fingerprint)) return [];
14344
14585
  return [[name, definition, cache?.models ?? []]];
14345
14586
  } catch {
@@ -14633,6 +14874,7 @@ var init_launcher = __esm({
14633
14874
  init_state();
14634
14875
  init_providerCatalogue();
14635
14876
  init_providersStore();
14877
+ init_memberProvider();
14636
14878
  init_pool();
14637
14879
  init_resumeContext();
14638
14880
  init_lock();
@@ -14756,7 +14998,7 @@ var init_trust = __esm({
14756
14998
 
14757
14999
  // src/frontdoor/realFrontDoorPort.ts
14758
15000
  import fs16 from "node:fs";
14759
- import os10 from "node:os";
15001
+ import os11 from "node:os";
14760
15002
  function realEnsurePorts(paths, spawnDaemon) {
14761
15003
  return {
14762
15004
  fs: realFarmFs,
@@ -14803,7 +15045,7 @@ function realFrontDoorPort(paths, spawnDaemon) {
14803
15045
  const cache2 = parseCatalogueCache(realFarmFs.readFileUtf8(catalogueCachePath(paths, name, supervisorPid, owner.generation)));
14804
15046
  let fingerprint;
14805
15047
  try {
14806
- fingerprint = savedCatalogueFingerprint(provider, paths, { ...process.env, CODEX_HOME: owner.codexHome }, os10.homedir(), realFarmFs.readFileUtf8);
15048
+ fingerprint = savedCatalogueFingerprint(provider, paths, { ...process.env, CODEX_HOME: owner.codexHome }, os11.homedir(), realFarmFs.readFileUtf8);
14807
15049
  } catch (error) {
14808
15050
  warnings.add(`Cannot read catalogue credentials for ${name}: ${error instanceof Error ? error.message : String(error)}`);
14809
15051
  return false;
@@ -14882,11 +15124,11 @@ var init_realFrontDoorPort = __esm({
14882
15124
  });
14883
15125
 
14884
15126
  // src/launchWiring.ts
14885
- import os11 from "node:os";
15127
+ import os12 from "node:os";
14886
15128
  import path54 from "node:path";
14887
15129
  import { randomUUID as randomUUID7 } from "node:crypto";
14888
15130
  function buildFarmRuntime(paths, cwd, run = realRunPort) {
14889
- const home = os11.homedir();
15131
+ const home = os12.homedir();
14890
15132
  const read = cosmiconfigReader();
14891
15133
  const classification = loadClassification(paths);
14892
15134
  const loaded = loadCascadeInput({ paths, home, cwd, read });
@@ -14939,6 +15181,7 @@ function realPrepareLaunchParams(paths, options) {
14939
15181
  credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
14940
15182
  hold: realHoldPort,
14941
15183
  hasStoredLogin: (identity) => identitySignIn(realFarmFs, { platform: process.platform, run: options.run ?? realRunPort }, { farmRoot: path54.join(paths.identitiesDir, identity), hasCredentialBlock: false, provider: void 0 }).state !== "signed-out",
15184
+ hasUsableLogin: (identity, claudeBin) => storedLoginUsable(options.run ?? realRunPort, claudeBin, path54.join(paths.identitiesDir, identity), options.proc.env),
14942
15185
  ...farm.directoryIdentity === void 0 ? {} : { directoryPinnedIdentity: farm.directoryIdentity },
14943
15186
  ...farm.directoryConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: farm.directoryConfigProfile },
14944
15187
  ...farm.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: farm.globalDefaultConfigProfile },
@@ -15158,7 +15401,7 @@ var init_anthropicUsageRefresh = __esm({
15158
15401
  init_schema();
15159
15402
  init_identity();
15160
15403
  init_middleware();
15161
- init_pick();
15404
+ init_windowLengths();
15162
15405
  init_plan2();
15163
15406
  PERCENT2 = 100;
15164
15407
  ANTHROPIC_USAGE_FRESHNESS_MS = FIVE_HOUR_WINDOW_MS / PERCENT2;
@@ -17975,19 +18218,19 @@ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
17975
18218
  // src/frontdoor/rcSessionRegistry.ts
17976
18219
  init_identityStore();
17977
18220
  import path31 from "node:path";
17978
- import { z as z22 } from "zod";
18221
+ import { z as z23 } from "zod";
17979
18222
  var REGISTRY_BRIDGE_PREFIX = "session_";
17980
18223
  var DOOR_SESSION_PREFIX = "cse_";
17981
18224
  var REGISTRY_DIR = "sessions";
17982
18225
  var ENTRY_SUFFIX = ".json";
17983
18226
  var RC_REGISTRY_ENTRY_MAX_BYTES = 8192;
17984
- var RegistryEntrySchema = z22.looseObject({
17985
- sessionId: z22.string().min(1),
17986
- pid: z22.int().positive(),
17987
- bridgeSessionId: z22.union([z22.string().startsWith(REGISTRY_BRIDGE_PREFIX), z22.string().startsWith(DOOR_SESSION_PREFIX)]),
17988
- cwd: z22.string().optional(),
17989
- name: z22.string().optional(),
17990
- updatedAt: z22.number().optional()
18227
+ var RegistryEntrySchema = z23.looseObject({
18228
+ sessionId: z23.string().min(1),
18229
+ pid: z23.int().positive(),
18230
+ bridgeSessionId: z23.union([z23.string().startsWith(REGISTRY_BRIDGE_PREFIX), z23.string().startsWith(DOOR_SESSION_PREFIX)]),
18231
+ cwd: z23.string().optional(),
18232
+ name: z23.string().optional(),
18233
+ updatedAt: z23.number().optional()
17991
18234
  });
17992
18235
  function supersedes(candidate, kept) {
17993
18236
  return candidate.updatedAt > kept.updatedAt || candidate.updatedAt === kept.updatedAt && candidate.session.pid > kept.session.pid;
@@ -18194,7 +18437,7 @@ var COMPACT_TIMEOUT_MS = 9e5;
18194
18437
  init_capability();
18195
18438
 
18196
18439
  // src/frontdoor/rcSlashCommandSchemas.ts
18197
- import { z as z23 } from "zod";
18440
+ import { z as z24 } from "zod";
18198
18441
 
18199
18442
  // src/frontdoor/rcSessionCommands.ts
18200
18443
  import { setTimeout as sleep } from "node:timers/promises";
@@ -18582,47 +18825,47 @@ function createRcSessionCommands(deps) {
18582
18825
  }
18583
18826
 
18584
18827
  // src/frontdoor/rcSlashCommandSchemas.ts
18585
- var WaitMsSchema = z23.int().positive().max(RC_SESSION_COMMAND_MAX_WAIT_MS).optional();
18586
- var RcGoalSessionInputSchema = z23.strictObject({
18587
- session: z23.string().min(1),
18828
+ var WaitMsSchema = z24.int().positive().max(RC_SESSION_COMMAND_MAX_WAIT_MS).optional();
18829
+ var RcGoalSessionInputSchema = z24.strictObject({
18830
+ session: z24.string().min(1),
18588
18831
  waitMs: WaitMsSchema
18589
18832
  });
18590
- var RcGoalSetInputSchema = z23.strictObject({
18591
- session: z23.string().min(1),
18592
- condition: z23.string().trim().min(1).max(RC_GOAL_CONDITION_MAX_CHARS).regex(/^[^\r\n]*$/u, "a goal condition is one line"),
18833
+ var RcGoalSetInputSchema = z24.strictObject({
18834
+ session: z24.string().min(1),
18835
+ condition: z24.string().trim().min(1).max(RC_GOAL_CONDITION_MAX_CHARS).regex(/^[^\r\n]*$/u, "a goal condition is one line"),
18593
18836
  waitMs: WaitMsSchema
18594
18837
  });
18595
- var RcCompactInputSchema = z23.strictObject({
18596
- session: z23.string().min(1),
18838
+ var RcCompactInputSchema = z24.strictObject({
18839
+ session: z24.string().min(1),
18597
18840
  waitMs: WaitMsSchema
18598
18841
  });
18599
- var RcCompactWithInstructionsInputSchema = z23.strictObject({
18600
- session: z23.string().min(1),
18601
- instructions: z23.string().trim().min(1).max(RC_COMPACT_INSTRUCTIONS_MAX_CHARS),
18842
+ var RcCompactWithInstructionsInputSchema = z24.strictObject({
18843
+ session: z24.string().min(1),
18844
+ instructions: z24.string().trim().min(1).max(RC_COMPACT_INSTRUCTIONS_MAX_CHARS),
18602
18845
  waitMs: WaitMsSchema
18603
18846
  });
18604
18847
  var commandAnswerShape = {
18605
- session: z23.string(),
18606
- route: z23.enum(["supervised", "self-hosted"])
18848
+ session: z24.string(),
18849
+ route: z24.enum(["supervised", "self-hosted"])
18607
18850
  };
18608
- var RcGoalGetOutputSchema = z23.strictObject({
18851
+ var RcGoalGetOutputSchema = z24.strictObject({
18609
18852
  ...commandAnswerShape,
18610
- goal: z23.strictObject({ condition: z23.string(), iterations: z23.int().nonnegative(), lastCheck: z23.string().optional() }).nullable()
18853
+ goal: z24.strictObject({ condition: z24.string(), iterations: z24.int().nonnegative(), lastCheck: z24.string().optional() }).nullable()
18611
18854
  });
18612
- var RcGoalSetOutputSchema = z23.strictObject({
18855
+ var RcGoalSetOutputSchema = z24.strictObject({
18613
18856
  ...commandAnswerShape,
18614
- condition: z23.string(),
18615
- superseded: z23.string().nullable()
18857
+ condition: z24.string(),
18858
+ superseded: z24.string().nullable()
18616
18859
  });
18617
- var RcGoalClearOutputSchema = z23.strictObject({
18860
+ var RcGoalClearOutputSchema = z24.strictObject({
18618
18861
  ...commandAnswerShape,
18619
- cleared: z23.string().nullable()
18862
+ cleared: z24.string().nullable()
18620
18863
  });
18621
- var RcCompactOutputSchema = z23.strictObject({
18864
+ var RcCompactOutputSchema = z24.strictObject({
18622
18865
  ...commandAnswerShape,
18623
- trigger: z23.string(),
18624
- preTokens: z23.number().optional(),
18625
- postTokens: z23.number().optional()
18866
+ trigger: z24.string(),
18867
+ preTokens: z24.number().optional(),
18868
+ postTokens: z24.number().optional()
18626
18869
  });
18627
18870
 
18628
18871
  // src/frontdoor/rcApi.ts
@@ -18843,48 +19086,48 @@ init_cliError();
18843
19086
  init_package();
18844
19087
 
18845
19088
  // src/codex/appServerSchemas.ts
18846
- import { z as z24 } from "zod";
19089
+ import { z as z25 } from "zod";
18847
19090
  var CODEX_APP_SERVER_GENERATED_AGAINST = "0.160.0";
18848
- var RateLimitWindowSchema = z24.object({
18849
- usedPercent: z24.number(),
18850
- resetsAt: z24.number().nullish(),
18851
- windowDurationMins: z24.number().nullish()
18852
- });
18853
- var RateLimitSnapshotSchema = z24.object({
18854
- limitId: z24.string().nullish(),
18855
- limitName: z24.string().nullish(),
18856
- planType: z24.string().nullish(),
19091
+ var RateLimitWindowSchema = z25.object({
19092
+ usedPercent: z25.number(),
19093
+ resetsAt: z25.number().nullish(),
19094
+ windowDurationMins: z25.number().nullish()
19095
+ });
19096
+ var RateLimitSnapshotSchema = z25.object({
19097
+ limitId: z25.string().nullish(),
19098
+ limitName: z25.string().nullish(),
19099
+ planType: z25.string().nullish(),
18857
19100
  primary: RateLimitWindowSchema.nullish(),
18858
19101
  secondary: RateLimitWindowSchema.nullish(),
18859
- rateLimitReachedType: z24.string().nullish(),
18860
- spendControlReached: z24.boolean().nullish()
18861
- });
18862
- var RateLimitResetCreditSchema = z24.object({
18863
- id: z24.string(),
18864
- grantedAt: z24.number(),
18865
- expiresAt: z24.number().nullish(),
18866
- resetType: z24.string(),
18867
- status: z24.string(),
18868
- title: z24.string().nullish(),
18869
- description: z24.string().nullish()
18870
- });
18871
- var CodexAccountSchema = z24.discriminatedUnion("type", [
18872
- z24.object({ type: z24.literal("apiKey") }),
18873
- z24.object({ type: z24.literal("chatgpt"), email: z24.string().nullable(), planType: z24.string() }),
18874
- z24.object({ type: z24.literal("amazonBedrock"), usesCodexManagedCredentials: z24.boolean().default(false) })
19102
+ rateLimitReachedType: z25.string().nullish(),
19103
+ spendControlReached: z25.boolean().nullish()
19104
+ });
19105
+ var RateLimitResetCreditSchema = z25.object({
19106
+ id: z25.string(),
19107
+ grantedAt: z25.number(),
19108
+ expiresAt: z25.number().nullish(),
19109
+ resetType: z25.string(),
19110
+ status: z25.string(),
19111
+ title: z25.string().nullish(),
19112
+ description: z25.string().nullish()
19113
+ });
19114
+ var CodexAccountSchema = z25.discriminatedUnion("type", [
19115
+ z25.object({ type: z25.literal("apiKey") }),
19116
+ z25.object({ type: z25.literal("chatgpt"), email: z25.string().nullable(), planType: z25.string() }),
19117
+ z25.object({ type: z25.literal("amazonBedrock"), usesCodexManagedCredentials: z25.boolean().default(false) })
18875
19118
  ]);
18876
- var CodexAccountReadSchema = z24.object({
19119
+ var CodexAccountReadSchema = z25.object({
18877
19120
  account: CodexAccountSchema.nullable(),
18878
- requiresOpenaiAuth: z24.boolean()
19121
+ requiresOpenaiAuth: z25.boolean()
18879
19122
  });
18880
- var CodexRateLimitsReadSchema = z24.object({
19123
+ var CodexRateLimitsReadSchema = z25.object({
18881
19124
  rateLimits: RateLimitSnapshotSchema,
18882
- rateLimitsByLimitId: z24.record(z24.string(), RateLimitSnapshotSchema).nullish(),
18883
- rateLimitResetCredits: z24.object({ availableCount: z24.number(), credits: z24.array(RateLimitResetCreditSchema).nullish() }).nullish(),
18884
- accountId: z24.string().nullish(),
18885
- ordinaryUsageAllowed: z24.boolean().nullish()
19125
+ rateLimitsByLimitId: z25.record(z25.string(), RateLimitSnapshotSchema).nullish(),
19126
+ rateLimitResetCredits: z25.object({ availableCount: z25.number(), credits: z25.array(RateLimitResetCreditSchema).nullish() }).nullish(),
19127
+ accountId: z25.string().nullish(),
19128
+ ordinaryUsageAllowed: z25.boolean().nullish()
18886
19129
  });
18887
- var CodexInitializeResultSchema = z24.object({ userAgent: z24.string() });
19130
+ var CodexInitializeResultSchema = z25.object({ userAgent: z25.string() });
18888
19131
 
18889
19132
  // src/codex/appServer.ts
18890
19133
  var CodexAppServerUnavailableError = class extends CliError {
@@ -19084,7 +19327,7 @@ import { openapi as openapi9 } from "@orpc/openapi";
19084
19327
 
19085
19328
  // src/checkReport.ts
19086
19329
  init_cliError();
19087
- import os6 from "node:os";
19330
+ import os7 from "node:os";
19088
19331
 
19089
19332
  // src/codex/categories.ts
19090
19333
  var CODEX_CATEGORIES = {
@@ -19116,7 +19359,7 @@ init_load();
19116
19359
  init_load();
19117
19360
  init_cascade();
19118
19361
  init_identity();
19119
- import os4 from "node:os";
19362
+ import os5 from "node:os";
19120
19363
 
19121
19364
  // src/poolPickReport.ts
19122
19365
  init_identity();
@@ -19130,6 +19373,7 @@ function candidateView(candidate) {
19130
19373
  feasible: candidate.feasible,
19131
19374
  ...candidate.blockedUntilMs === void 0 ? {} : { blockedUntil: new Date(candidate.blockedUntilMs).toISOString() },
19132
19375
  plan: candidate.plan,
19376
+ ...candidate.provider === void 0 ? {} : { provider: candidate.provider },
19133
19377
  reasons: [...candidate.reasons]
19134
19378
  };
19135
19379
  }
@@ -19143,6 +19387,7 @@ function collectPoolPick(params) {
19143
19387
  nowMs: params.nowMs,
19144
19388
  resuming: false,
19145
19389
  identityIdOf: identityIdResolver(params.paths.identitiesDir, params.fs),
19390
+ ...params.providerOf === void 0 ? {} : { providerOf: params.providerOf },
19146
19391
  ...sticky.sticky === void 0 ? {} : { sticky: sticky.sticky }
19147
19392
  });
19148
19393
  return {
@@ -19157,6 +19402,29 @@ function collectPoolPick(params) {
19157
19402
  };
19158
19403
  }
19159
19404
 
19405
+ // src/poolProviderWiring.ts
19406
+ init_load();
19407
+ init_cascade();
19408
+ init_memberProvider();
19409
+ init_realPorts();
19410
+ import os4 from "node:os";
19411
+ function realMemberProviderResolver(params) {
19412
+ const home = os4.homedir();
19413
+ const read = cosmiconfigReader();
19414
+ const loaded = params.loaded ?? loadCascadeInput({ paths: params.paths, home, cwd: params.cwd, read });
19415
+ const selections = readDirectorySelections(loaded);
19416
+ return memberProviderResolver({
19417
+ paths: params.paths,
19418
+ fs: realFsPort,
19419
+ env: params.env,
19420
+ cliProvider: params.cliProvider,
19421
+ ...params.cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile: params.cliFlagConfigProfile },
19422
+ ...selections.configProfile === void 0 ? {} : { directoryRuleConfigProfile: selections.configProfile },
19423
+ ...loaded.globalConfig?.defaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: loaded.globalConfig.defaultConfigProfile },
19424
+ loadCascade: (baseConfigProfile) => loadCascadeInput({ paths: params.paths, home, cwd: params.cwd, read, ...baseConfigProfile === void 0 ? {} : { baseConfigProfile } }).input
19425
+ });
19426
+ }
19427
+
19160
19428
  // src/launchSelection.ts
19161
19429
  init_poolStore();
19162
19430
  init_realPorts();
@@ -19182,7 +19450,8 @@ function selectLaunch(params, loaded) {
19182
19450
  if (pools[decidedIdentity.pool] === void 0) {
19183
19451
  throw new PoolNotFoundError(decidedIdentity.pool);
19184
19452
  }
19185
- poolPick = collectPoolPick({ paths, fs: realFsPort, usageFs: realFarmFs, poolName: decidedIdentity.pool, pools, directory: cwd, nowMs: Date.now() });
19453
+ const providerOf = realMemberProviderResolver({ paths, cwd, env: params.env, ...params.configProfile === void 0 ? {} : { cliFlagConfigProfile: params.configProfile }, loaded });
19454
+ poolPick = collectPoolPick({ paths, fs: realFsPort, usageFs: realFarmFs, poolName: decidedIdentity.pool, pools, directory: cwd, nowMs: Date.now(), providerOf });
19186
19455
  }
19187
19456
  const identity = poolPick?.pick === void 0 ? decidedIdentity : { ...decidedIdentity, name: poolPick.pick };
19188
19457
  const loadedIdentity = identity.name === void 0 ? void 0 : loadIdentity(paths.identitiesDir, identity.name, realFsPort);
@@ -19199,7 +19468,7 @@ function selectLaunch(params, loaded) {
19199
19468
  };
19200
19469
  }
19201
19470
  function resolveLaunchSelection(params) {
19202
- const loaded = loadCascadeInput({ paths: params.paths, home: os4.homedir(), cwd: params.cwd, read: cosmiconfigReader() });
19471
+ const loaded = loadCascadeInput({ paths: params.paths, home: os5.homedir(), cwd: params.cwd, read: cosmiconfigReader() });
19203
19472
  return selectLaunch(params, loaded).selection;
19204
19473
  }
19205
19474
 
@@ -19539,7 +19808,7 @@ function loadCheckProvider(paths, name) {
19539
19808
  }
19540
19809
  function collectCheckReport(params) {
19541
19810
  const { paths, cwd } = params;
19542
- const home = os6.homedir();
19811
+ const home = os7.homedir();
19543
19812
  const read = cosmiconfigReader();
19544
19813
  const loaded = loadCascadeInput({ paths, home, cwd, read });
19545
19814
  const git = resolveGitBranch(realRunPort, cwd);
@@ -19675,6 +19944,8 @@ var PoolPickCandidateViewSchema = z28.strictObject({
19675
19944
  /** When an `ineligible` member can be used again, as an ISO instant. */
19676
19945
  blockedUntil: z28.iso.datetime().optional(),
19677
19946
  plan: PlanClassSchema,
19947
+ /** 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. */
19948
+ provider: z28.string().optional(),
19678
19949
  /** The facts behind the class and score, in the order they matter. */
19679
19950
  reasons: z28.array(z28.string())
19680
19951
  });
@@ -21842,6 +22113,8 @@ var LaunchResolveInputSchema = z41.strictObject({
21842
22113
  var LaunchPoolDecisionSchema = z41.strictObject({
21843
22114
  name: z41.string(),
21844
22115
  reasons: z41.readonly(z41.array(z41.string())),
22116
+ /** The provider the ranking read for the chosen member, when the launch spends one in place of the member's Claude account. */
22117
+ provider: z41.string().optional(),
21845
22118
  movedOff: z41.strictObject({ identity: z41.string(), reason: z41.string() }).optional()
21846
22119
  });
21847
22120
  var LaunchDecisionSchema = z41.strictObject({
@@ -22592,7 +22865,7 @@ function createDoorHealthPublisher(hub, now, pid) {
22592
22865
  }
22593
22866
 
22594
22867
  // src/frontdoor/quotaExpiringEvents.ts
22595
- init_pick();
22868
+ init_windowLengths();
22596
22869
  var FINAL_SPAN_DENOMINATOR = 30;
22597
22870
  var QUOTA_EXPIRING_WINDOW_FRACTION = 1 / FINAL_SPAN_DENOMINATOR;
22598
22871
  function createQuotaExpiringPublisher(hub, deps) {
@@ -24898,7 +25171,7 @@ init_launchWiring();
24898
25171
  init_argv();
24899
25172
  init_cascade();
24900
25173
  init_identity();
24901
- import os12 from "node:os";
25174
+ import os13 from "node:os";
24902
25175
 
24903
25176
  // src/launcher/poolRefresh.ts
24904
25177
  init_anthropicUsageRefresh();
@@ -24907,7 +25180,8 @@ async function refreshStalePoolMembers(params) {
24907
25180
  if (identities.size === 0) {
24908
25181
  return;
24909
25182
  }
24910
- await params.refresher.refreshStale(params.loadMembers([...identities]));
25183
+ const members = params.loadMembers([...identities]).filter((member) => member.provider === void 0 && member.providerError === void 0);
25184
+ await params.refresher.refreshStale(members);
24911
25185
  }
24912
25186
 
24913
25187
  // src/poolUsageRefresh.ts
@@ -24927,7 +25201,7 @@ async function refreshPools(params) {
24927
25201
  await refreshStalePoolMembers({
24928
25202
  poolNames: params.poolNames,
24929
25203
  pools: readPools(paths),
24930
- loadMembers: (identities) => loadPoolMembers(realFarmFs, paths, identities, Date.now(), (name) => identityIdOf(paths, name)),
25204
+ loadMembers: (identities) => loadPoolMembers(realFarmFs, paths, identities, Date.now(), (name) => identityIdOf(paths, name), params.providerOf),
24931
25205
  refresher
24932
25206
  });
24933
25207
  }
@@ -24949,12 +25223,13 @@ async function refreshPoolUsage(params) {
24949
25223
  poolNames: params.poolNames,
24950
25224
  spawnDaemon: daemonSpawnerFor(params.agentShim),
24951
25225
  log: params.log ?? (() => void 0),
24952
- ...params.refresher === void 0 ? {} : { refresher: params.refresher }
25226
+ ...params.refresher === void 0 ? {} : { refresher: params.refresher },
25227
+ ...params.providerOf === void 0 ? {} : { providerOf: params.providerOf }
24953
25228
  });
24954
25229
  }
24955
25230
  function poolSelectedByLaunch(options) {
24956
25231
  const paths = options.paths ?? resolveLayoutPaths();
24957
- const loaded = loadCascadeInput({ paths, home: os12.homedir(), cwd: options.cwd, read: cosmiconfigReader() });
25232
+ const loaded = loadCascadeInput({ paths, home: os13.homedir(), cwd: options.cwd, read: cosmiconfigReader() });
24958
25233
  return decideIdentity({
24959
25234
  env: options.env,
24960
25235
  argv0Identity: parseLauncherArgv(options.argv).identity,
@@ -24964,8 +25239,12 @@ function poolSelectedByLaunch(options) {
24964
25239
  }
24965
25240
  async function refreshLaunchPoolUsage(options) {
24966
25241
  const pool = poolSelectedByLaunch(options);
25242
+ const paths = options.paths ?? resolveLayoutPaths();
25243
+ const parsed = parseLauncherArgv(options.argv);
24967
25244
  await refreshPoolUsage({
24968
- ...options.paths === void 0 ? {} : { paths: options.paths },
25245
+ paths,
25246
+ // The provider each member's launch will spend, resolved as the launch resolves it, so a launch through a provider probes no Claude account.
25247
+ ...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 } }) },
24969
25248
  cwd: options.cwd,
24970
25249
  poolNames: pool === void 0 ? [] : [pool],
24971
25250
  ...options.agentShim === void 0 ? {} : { agentShim: options.agentShim },
@@ -25337,6 +25616,7 @@ export {
25337
25616
  realCodexAppServerPort,
25338
25617
  realConnectCertStore,
25339
25618
  realConnectEffects,
25619
+ realMemberProviderResolver,
25340
25620
  realRcControlTransport,
25341
25621
  realRcEventDial,
25342
25622
  realRcStreamDial,