claude-use 14.2.4 → 14.3.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
@@ -668,6 +668,134 @@ var init_statusline = __esm({
668
668
  }
669
669
  });
670
670
 
671
+ // src/models/identity.ts
672
+ function withoutContextMarker(model) {
673
+ return model.toLowerCase().endsWith(CONTEXT_MARKER_1M) ? model.slice(0, -CONTEXT_MARKER_1M.length) : model;
674
+ }
675
+ function namesAModel(value) {
676
+ return withoutContextMarker(value).trim() !== "";
677
+ }
678
+ function canonicalText(name) {
679
+ return name.trim().toLowerCase().replace(NON_IDENTITY_BRACKET_RE, "").replace(/[\s_]+/g, "-").replace(/([a-z])(\d+(?:\.\d+)+)/g, "$1-$2").replace(/-+/g, "-").replace(/^-|-$/g, "");
680
+ }
681
+ function splitVariants(tokens) {
682
+ const variants = [];
683
+ let end = tokens.length;
684
+ for (; ; ) {
685
+ const token = tokens[end - 1];
686
+ if (token === void 0 || !KNOWN_VARIANTS.has(token)) {
687
+ return { familyTokens: tokens.slice(0, end), variants };
688
+ }
689
+ variants.unshift(token);
690
+ end -= 1;
691
+ }
692
+ }
693
+ function versionOf(tokens) {
694
+ for (let index = 0; index < tokens.length; index += 1) {
695
+ const token = tokens[index];
696
+ const next = tokens[index + 1];
697
+ if (token === void 0) {
698
+ return "";
699
+ }
700
+ if (/^\d+$/.test(token) && next !== void 0 && /^\d+$/.test(next)) {
701
+ return `${token}.${next}`;
702
+ }
703
+ const dotted = /^\d+(?:\.\d+)+$/.exec(token);
704
+ if (dotted !== null) {
705
+ return dotted[0];
706
+ }
707
+ }
708
+ return "";
709
+ }
710
+ function modelIdentity(rawName) {
711
+ const segments = rawName.trim().toLowerCase().split("/");
712
+ const stripped = canonicalText(segments[segments.length - 1] ?? "").split(":")[0] ?? "";
713
+ const withoutDate = stripped.replace(DATE_STAMP_RE, "");
714
+ const tokens = withoutDate.split("-").filter((token) => token !== "");
715
+ const { familyTokens, variants } = splitVariants(tokens);
716
+ const version = versionOf(familyTokens);
717
+ const versionless = familyTokens.filter((token, index) => {
718
+ if (version === "") {
719
+ return true;
720
+ }
721
+ const dotted = /^\d+(?:\.\d+)+$/.test(token);
722
+ const previous = familyTokens[index - 1];
723
+ const next = familyTokens[index + 1];
724
+ const insideVersionRun = dotted || /^\d+$/.test(token) && (previous !== void 0 && /^\d+$/.test(previous) || next !== void 0 && /^\d+$/.test(next));
725
+ return !insideVersionRun;
726
+ });
727
+ const family = versionless.join("-");
728
+ const tokenVendor = familyTokens.find((token) => Object.keys(VENDOR_BY_TOKEN).some((key) => token === key || token.startsWith(key)));
729
+ const namespace = segments.length >= 2 ? (segments[0] ?? "").split(":").pop() ?? "" : "";
730
+ const namespaceVendor = VENDOR_BY_NAMESPACE[namespace] ?? "";
731
+ const tokenVendorName = tokenVendor === void 0 ? "" : VENDOR_BY_TOKEN[Object.keys(VENDOR_BY_TOKEN).find((key) => tokenVendor === key || tokenVendor.startsWith(key)) ?? ""] ?? "";
732
+ return {
733
+ vendor: tokenVendorName === "" ? namespaceVendor : tokenVendorName,
734
+ vendorConflict: tokenVendorName !== "" && namespaceVendor !== "" && tokenVendorName !== namespaceVendor,
735
+ family,
736
+ version,
737
+ variant: variants.join("-"),
738
+ familyAndVersion: version === "" ? family : `${family}-${version.replace(/\./g, "-")}`
739
+ };
740
+ }
741
+ function relateModels(left, right) {
742
+ const a = modelIdentity(left);
743
+ const b = modelIdentity(right);
744
+ if (a.familyAndVersion !== b.familyAndVersion) {
745
+ return sameFamilyOtherVersion(a, b) ? "similar" : "distinct";
746
+ }
747
+ if (a.variant !== b.variant || a.vendorConflict || b.vendorConflict || a.vendor !== "" && b.vendor !== "" && a.vendor !== b.vendor) {
748
+ return "similar";
749
+ }
750
+ return "same";
751
+ }
752
+ function sameFamilyOtherVersion(a, b) {
753
+ if (a.family !== b.family) {
754
+ return false;
755
+ }
756
+ if (a.vendor !== "" && b.vendor !== "" && a.vendor !== b.vendor) {
757
+ return false;
758
+ }
759
+ return true;
760
+ }
761
+ var NON_IDENTITY_BRACKET_RE, CONTEXT_MARKER_1M, DATE_STAMP_RE, KNOWN_VARIANTS, VENDOR_BY_NAMESPACE, VENDOR_BY_TOKEN;
762
+ var init_identity = __esm({
763
+ "src/models/identity.ts"() {
764
+ "use strict";
765
+ NON_IDENTITY_BRACKET_RE = /\[[^\]]*\]/g;
766
+ CONTEXT_MARKER_1M = "[1m]";
767
+ DATE_STAMP_RE = /-(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])$/;
768
+ KNOWN_VARIANTS = /* @__PURE__ */ new Set(["high", "medium", "low", "thinking", "xhigh", "max", "highspeed", "sol", "terra", "luna", "mini", "flash-lite", "turbo"]);
769
+ VENDOR_BY_NAMESPACE = Object.freeze({
770
+ anthropic: "anthropic",
771
+ google: "google",
772
+ openai: "openai",
773
+ zai: "zai",
774
+ "z-ai": "zai",
775
+ minimax: "minimax",
776
+ qwen: "qwen",
777
+ deepseek: "deepseek",
778
+ moonshot: "moonshot",
779
+ meta: "meta",
780
+ mistral: "mistral"
781
+ });
782
+ VENDOR_BY_TOKEN = Object.freeze({
783
+ claude: "anthropic",
784
+ gemini: "google",
785
+ antigravity: "google",
786
+ gpt: "openai",
787
+ glm: "zai",
788
+ minimax: "minimax",
789
+ qwen: "qwen",
790
+ deepseek: "deepseek",
791
+ kimi: "moonshot",
792
+ llama: "meta",
793
+ mistral: "mistral",
794
+ mixtral: "mistral"
795
+ });
796
+ }
797
+ });
798
+
671
799
  // src/versionDiscovery.ts
672
800
  import os from "node:os";
673
801
  import path2 from "node:path";
@@ -802,13 +930,14 @@ function isTimeZone(name) {
802
930
  return false;
803
931
  }
804
932
  }
805
- var CATEGORY_NAMES, OVERRIDABLE_CATEGORIES, CategoryMapSchema, DURATION_RE, DurationSchema, WhenConditionObjectSchema, WhenSchema, EntryValueSchema, ENTRY_KEY_RE, EntriesSchema, LaunchSchema, CREDENTIAL_TARGETS, PROVIDER_CREDENTIAL_TARGETS, CREDENTIAL_TARGET_VARS, ArgvSchema, CommandSourceOptions, EnvCredentialSourceSchema, FileCredentialSourceSchema, CommandCredentialSourceSchema, OpCredentialSourceSchema, KeychainCredentialSourceSchema, LiteralCredentialSourceSchema, CredentialSourceSchema, RemoteCredentialSourceSchema, CREDENTIAL_CACHE_STORES, CredentialCacheSchema, CredentialSchema, ProviderCredentialSchema, RESERVED_PROVIDER_ENV_KEYS, ProviderEnvSchema, PROVIDER_KINDS, ANTIGRAVITY_MODES, CLAUDE_TIERS, ANTIGRAVITY_EFFORTS, ANTIGRAVITY_DEFAULT_MODE, ANTIGRAVITY_DEFAULT_MODEL, ANTIGRAVITY_DEFAULT_TIER_MODELS, ANTIGRAVITY_DEFAULT_EFFORT, AntigravityModelTargetSchema, AntigravityProviderConfigSchema, CODEX_EFFORTS, CODEX_LOGINS, CODEX_DEFAULT_LOGIN, CODEX_DEFAULT_MODEL, CODEX_DEFAULT_TIER_MODELS, CODEX_DEFAULT_EFFORT, CodexProviderConfigSchema, ProviderRouteSchema, PickerModelSchema, PickerModelsSchema, ProviderCatalogueSchema, MAX_TIMER_DELAY_MS, HttpBaseUrlSchema, HttpProviderSchema, CodexProviderSchema, RouterProviderSchema, AntigravityProviderSchema, ProviderSchema, SELECTION_MODES, VirtualModelSchema, ModelPricesSchema, FamilySettingsSchema, ModelsConfigSchema, ModelsLayerSchema, ConfigProfileSchema, POOL_SELECTOR_PREFIX, POOL_NAME_PATTERN, PoolNameSchema, SELECTOR_RE, IdentitySelectorSchema, PoolMemberSchema, POOL_PREFERENCES, PoolPreferenceSchema, WHOLE_PERCENT_MAX, CompactAtUtilisationSchema, PoolSchema, WEEKDAYS, AnchorSchema, JOB_WINDOWS, JobTriggerSchema, JobTargetSchema, JobSchema, DirectoryRuleSchema, DirectoryRulesSchema, PortableConfigSchema, HEADROOM_MODES, HEADROOM_CCR_MODES, HEADROOM_ROLLOUT_CHANNELS, INTERCEPT_CHANNELS, READ_MATURATION_CHANNELS, HeadroomGlobalConfigObjectSchema, HeadroomGlobalConfigSchema, HEADROOM_DEFAULT_SOURCE, HEADROOM_DEFAULT_IDLE_SHUTDOWN_MINUTES, FrontDoorGlobalConfigSchema, UPDATE_MODES, UpdateGlobalConfigSchema, GlobalConfigSchema, IdentitySchema, CategoryClassificationSchema, CategoryClassificationOverlaySchema, SHIPPED_CATEGORY_DEFAULTS;
933
+ var CATEGORY_NAMES, OVERRIDABLE_CATEGORIES, CategoryMapSchema, DURATION_RE, DurationSchema, WhenConditionObjectSchema, WhenSchema, EntryValueSchema, ENTRY_KEY_RE, EntriesSchema, LaunchSchema, CREDENTIAL_TARGETS, PROVIDER_CREDENTIAL_TARGETS, CREDENTIAL_TARGET_VARS, ArgvSchema, CommandSourceOptions, EnvCredentialSourceSchema, FileCredentialSourceSchema, CommandCredentialSourceSchema, OpCredentialSourceSchema, KeychainCredentialSourceSchema, LiteralCredentialSourceSchema, CredentialSourceSchema, RemoteCredentialSourceSchema, CREDENTIAL_CACHE_STORES, CredentialCacheSchema, CredentialSchema, ProviderCredentialSchema, RESERVED_PROVIDER_ENV_KEYS, TIER_MODEL_ENV_VARIABLES, OTHER_MODEL_ENV_VARIABLES, MODEL_ENV_VARIABLES, ProviderEnvSchema, PROVIDER_KINDS, ANTIGRAVITY_MODES, CLAUDE_TIERS, ANTIGRAVITY_EFFORTS, ANTIGRAVITY_DEFAULT_MODE, ANTIGRAVITY_DEFAULT_MODEL, ANTIGRAVITY_DEFAULT_TIER_MODELS, ANTIGRAVITY_DEFAULT_EFFORT, AntigravityModelTargetSchema, AntigravityProviderConfigSchema, CODEX_EFFORTS, CODEX_LOGINS, CODEX_DEFAULT_LOGIN, CODEX_DEFAULT_MODEL, CODEX_DEFAULT_TIER_MODELS, CODEX_DEFAULT_EFFORT, CodexProviderConfigSchema, ProviderRouteSchema, PickerModelSchema, PickerModelsSchema, ProviderCatalogueSchema, MAX_TIMER_DELAY_MS, HttpBaseUrlSchema, SERVER_TOOLS_MODES, HttpProviderSchema, CodexProviderSchema, RouterProviderSchema, AntigravityProviderSchema, ProviderSchema, SELECTION_MODES, VirtualModelSchema, ModelPricesSchema, FamilySettingsSchema, ModelsConfigSchema, ModelsLayerSchema, ConfigProfileSchema, POOL_SELECTOR_PREFIX, POOL_NAME_PATTERN, PoolNameSchema, SELECTOR_RE, IdentitySelectorSchema, PoolMemberSchema, POOL_PREFERENCES, PoolPreferenceSchema, WHOLE_PERCENT_MAX, CompactAtUtilisationSchema, PoolSchema, WEEKDAYS, AnchorSchema, JOB_WINDOWS, JobTriggerSchema, JobTargetSchema, JobSchema, DirectoryRuleSchema, DirectoryRulesSchema, PortableConfigSchema, HEADROOM_MODES, HEADROOM_CCR_MODES, HEADROOM_ROLLOUT_CHANNELS, INTERCEPT_CHANNELS, READ_MATURATION_CHANNELS, HeadroomGlobalConfigObjectSchema, HeadroomGlobalConfigSchema, HEADROOM_DEFAULT_SOURCE, HEADROOM_DEFAULT_IDLE_SHUTDOWN_MINUTES, FrontDoorGlobalConfigSchema, UPDATE_MODES, UpdateGlobalConfigSchema, GlobalConfigSchema, IdentitySchema, CategoryClassificationSchema, CategoryClassificationOverlaySchema, SHIPPED_CATEGORY_DEFAULTS;
806
934
  var init_schema = __esm({
807
935
  "src/config/schema.ts"() {
808
936
  "use strict";
809
937
  init_proxyBypass();
810
938
  init_names();
811
939
  init_statusline();
940
+ init_identity();
812
941
  init_versionDiscovery();
813
942
  CATEGORY_NAMES = ["secret", "runtime", "history", "knowledge", "settings"];
814
943
  OVERRIDABLE_CATEGORIES = ["runtime", "history", "knowledge", "settings"];
@@ -915,8 +1044,13 @@ var init_schema = __esm({
915
1044
  });
916
1045
  ProviderCredentialSchema = CredentialSchema.extend({ target: z3.enum(PROVIDER_CREDENTIAL_TARGETS).optional() });
917
1046
  RESERVED_PROVIDER_ENV_KEYS = Object.values(CREDENTIAL_TARGET_VARS);
1047
+ TIER_MODEL_ENV_VARIABLES = ["ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"];
1048
+ OTHER_MODEL_ENV_VARIABLES = ["ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL"];
1049
+ MODEL_ENV_VARIABLES = [...OTHER_MODEL_ENV_VARIABLES, ...TIER_MODEL_ENV_VARIABLES];
918
1050
  ProviderEnvSchema = z3.record(z3.string().min(1), z3.string()).refine((env) => !Object.keys(env).some((key) => RESERVED_PROVIDER_ENV_KEYS.includes(key)), {
919
1051
  message: `env may not set ${RESERVED_PROVIDER_ENV_KEYS.join(", ")}: the credential block's target sets one and agent-shim removes the others`
1052
+ }).refine((env) => !MODEL_ENV_VARIABLES.some((key) => env[key] !== void 0 && env[key] !== "" && !namesAModel(env[key])), {
1053
+ message: `env may not set ${MODEL_ENV_VARIABLES.join(", ")} to a context marker or whitespace alone: a model variable names a model, or is empty to leave the tier unset`
920
1054
  });
921
1055
  PROVIDER_KINDS = ["http", "codex", "antigravity", "router"];
922
1056
  ANTIGRAVITY_MODES = ["cloud", "local"];
@@ -1019,6 +1153,7 @@ var init_schema = __esm({
1019
1153
  ctx.addIssue({ code: "custom", message: "a provider's base URL must not name port 0, which nothing listens on: give the port the endpoint serves" });
1020
1154
  }
1021
1155
  });
1156
+ SERVER_TOOLS_MODES = ["forward", "drop"];
1022
1157
  HttpProviderSchema = z3.strictObject({
1023
1158
  $schema: z3.string().optional(),
1024
1159
  kind: z3.literal("http").optional(),
@@ -1033,7 +1168,9 @@ var init_schema = __esm({
1033
1168
  /** The provider's own model catalogue, listed in `/model` when set. */
1034
1169
  catalogue: ProviderCatalogueSchema.optional(),
1035
1170
  /** Per-request routing: when present, each request this provider would serve is matched against the list in order, and the first definite match is sent to that entry's provider instead (itself resolved exactly as a directly dialled request would be). Unmatched requests stay on this provider. */
1036
- routes: z3.array(ProviderRouteSchema).optional()
1171
+ routes: z3.array(ProviderRouteSchema).optional(),
1172
+ /** What happens to tools with no `input_schema` (a `type` and no schema, such as web search) in a request this provider serves. A property of the provider because only its server knows whether it can take them: a backend that implements the Messages API with client tools only (vLLM, SGLang) answers 400 `input_schema: Field required` and fails the whole request, while Anthropic itself and gateways that run them need them forwarded. `forward` (the default) changes nothing for any provider; `drop` removes every tool object with no `input_schema` member before the request is forwarded, which also takes any Anthropic-defined client tool that is given by `type` alone. */
1173
+ serverTools: z3.enum(SERVER_TOOLS_MODES).optional()
1037
1174
  });
1038
1175
  CodexProviderSchema = z3.strictObject({
1039
1176
  $schema: z3.string().optional(),
@@ -1321,7 +1458,7 @@ function parseIgnoringUnrecognisedKeys(schema, raw) {
1321
1458
  return second.success ? { success: true, data: second.data, ignored } : { success: false, issues: second.error.issues };
1322
1459
  }
1323
1460
  function describeIgnoredKeys(filePath, ignored) {
1324
- const places = ignored.map(({ path: path55, keys }) => `${path55.length === 0 ? "" : `${path55.map(String).join(".")}.`}${keys.join(", ")}`);
1461
+ const places = ignored.map(({ path: path56, keys }) => `${path56.length === 0 ? "" : `${path56.map(String).join(".")}.`}${keys.join(", ")}`);
1325
1462
  return `${filePath} has settings this version of agent-shim does not know and ignores: ${places.join("; ")}. A newer release may read them.`;
1326
1463
  }
1327
1464
  function noteIgnoredKeys(filePath, ignored) {
@@ -1343,9 +1480,9 @@ function restoreIgnoredKeys(filePath, value) {
1343
1480
  return value;
1344
1481
  }
1345
1482
  const restored = structuredClone(value);
1346
- for (const { path: path55, values } of ignored) {
1483
+ for (const { path: path56, values } of ignored) {
1347
1484
  let holder = restored;
1348
- for (const step of path55) {
1485
+ for (const step of path56) {
1349
1486
  holder = isRecord(holder) ? holder[step] : void 0;
1350
1487
  }
1351
1488
  if (isRecord(holder)) {
@@ -4316,6 +4453,43 @@ var init_baseUrlDisplay = __esm({
4316
4453
  }
4317
4454
  });
4318
4455
 
4456
+ // src/elapsedWindow.ts
4457
+ function within(sinceMs, nowMs, windowMs) {
4458
+ const age = nowMs - sinceMs;
4459
+ return age >= 0 && age < windowMs;
4460
+ }
4461
+ var init_elapsedWindow = __esm({
4462
+ "src/elapsedWindow.ts"() {
4463
+ "use strict";
4464
+ }
4465
+ });
4466
+
4467
+ // src/frontdoor/loggedText.ts
4468
+ var UNSAFE_CLASS, UNSAFE_IN_A_LINE, UNSAFE_CHARACTERS;
4469
+ var init_loggedText = __esm({
4470
+ "src/frontdoor/loggedText.ts"() {
4471
+ "use strict";
4472
+ UNSAFE_CLASS = "[\\p{Cc}\\p{Zl}\\p{Zp}\\p{Cf}]";
4473
+ UNSAFE_IN_A_LINE = new RegExp(UNSAFE_CLASS, "u");
4474
+ UNSAFE_CHARACTERS = new RegExp(UNSAFE_CLASS, "gu");
4475
+ }
4476
+ });
4477
+
4478
+ // src/canonicalJson.ts
4479
+ function canonicalJson(value) {
4480
+ return JSON.stringify(value, (_key, member) => {
4481
+ if (typeof member !== "object" || member === null || Array.isArray(member)) {
4482
+ return member;
4483
+ }
4484
+ return Object.fromEntries(Object.entries(member).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0));
4485
+ });
4486
+ }
4487
+ var init_canonicalJson = __esm({
4488
+ "src/canonicalJson.ts"() {
4489
+ "use strict";
4490
+ }
4491
+ });
4492
+
4319
4493
  // src/usage/schema.ts
4320
4494
  import { z as z5 } from "zod";
4321
4495
  var USAGE_SCHEMA_VERSION, VersionSchema, InstantSchema, CLIENT_SESSION_ID_PATTERN, TokenCountSchema, TokenUsageSchema, LIMIT_KINDS, LimitClassificationSchema, REQUEST_CLASSES, RequestClassSchema, UsageRecordSchema, QuotaWindowSchema, ExtraUsageSpendSchema, UnifiedRateLimitSchema, RateLimitStateSchema, LimitEventSchema, ProviderQuotaWindowSchema, ProviderAccountSchema, ProviderQuotaSchema, ProviderUsageStateSchema, AccountMetadataSchema, UsageSnapshotSchema;
@@ -5001,6 +5175,7 @@ var init_doorBounds = __esm({
5001
5175
 
5002
5176
  // src/providerCatalogue.ts
5003
5177
  import picomatch4 from "picomatch";
5178
+ import { createHash as createHash3 } from "node:crypto";
5004
5179
  import path11 from "node:path";
5005
5180
  import { z as z7 } from "zod";
5006
5181
  function catalogueCachePath(paths, name, supervisorPid, generation) {
@@ -5008,6 +5183,20 @@ function catalogueCachePath(paths, name, supervisorPid, generation) {
5008
5183
  const directory = supervisorPid === void 0 || generation === void 0 ? paths.catalogueDir : catalogueGenerationDir(paths, supervisorPid, generation);
5009
5184
  return providerFilePath(directory, name);
5010
5185
  }
5186
+ function catalogueSettingsPath(paths, name) {
5187
+ return path11.join(path11.dirname(catalogueCachePath(paths, name)), "settings", `${name}.json`);
5188
+ }
5189
+ function parseCatalogueSettings(text) {
5190
+ if (text === void 0) {
5191
+ return void 0;
5192
+ }
5193
+ try {
5194
+ const parsed = CatalogueDigestSchema.safeParse(JSON.parse(text));
5195
+ return parsed.success ? parsed.data : void 0;
5196
+ } catch {
5197
+ return void 0;
5198
+ }
5199
+ }
5011
5200
  function catalogueGenerationDir(paths, supervisorPid, generation) {
5012
5201
  return path11.join(paths.catalogueDir, "supervisors", String(supervisorPid), z7.uuid().parse(generation));
5013
5202
  }
@@ -5026,18 +5215,27 @@ function parseCatalogueCache(text) {
5026
5215
  }
5027
5216
  }
5028
5217
  function isCatalogueStale(cache, nowMs) {
5029
- return nowMs - cache.fetchedAt >= CATALOGUE_MAX_AGE_MS;
5218
+ return !within(cache.fetchedAt, nowMs, CATALOGUE_MAX_AGE_MS);
5030
5219
  }
5031
5220
  function filterCatalogue(models, catalogue) {
5032
5221
  const included = catalogue.include === void 0 ? void 0 : picomatch4(catalogue.include, { dot: true });
5033
5222
  const excluded = catalogue.exclude === void 0 ? void 0 : picomatch4(catalogue.exclude, { dot: true });
5034
5223
  return models.filter((model) => included?.(model.id) !== false && excluded?.(model.id) !== true);
5035
5224
  }
5036
- var DEFAULT_CANDIDATE_URLS, MS_PER_SECOND4, SECONDS_PER_HOUR, HOURS_PER_DAY2, MS_PER_HOUR, HOURS_BETWEEN_RETRIES, CATALOGUE_MAX_AGE_MS, CATALOGUE_RETRY_MS, CATALOGUE_REQUEST_SECONDS, CATALOGUE_REQUEST_TIMEOUT_MS, CATALOGUE_REFRESH_TIMEOUT_MS, CATALOGUE_WORKER_ALLOWANCE_MS, CATALOGUE_REFRESH_DEADLINE_MS, CatalogueModelSchema, CatalogueCacheSchema;
5225
+ function catalogueSettingsFingerprint(provider) {
5226
+ return createHash3("sha256").update(canonicalJson([provider.baseUrl, provider.catalogue === void 0 ? false : provider.catalogue.url ?? null, provider.credential])).digest("hex");
5227
+ }
5228
+ function catalogueMatchesSettings(recorded, cache, provider) {
5229
+ return recorded?.fetchedAt === cache.fetchedAt && recorded.settings === catalogueSettingsFingerprint(provider);
5230
+ }
5231
+ var DEFAULT_CANDIDATE_URLS, MS_PER_SECOND4, SECONDS_PER_HOUR, HOURS_PER_DAY2, MS_PER_HOUR, HOURS_BETWEEN_RETRIES, CATALOGUE_MAX_AGE_MS, CATALOGUE_RETRY_MS, CATALOGUE_REQUEST_SECONDS, CATALOGUE_REQUEST_TIMEOUT_MS, CATALOGUE_REFRESH_TIMEOUT_MS, CATALOGUE_MAX_MODELS, CATALOGUE_ENTRY_MAX_BYTES, CATALOGUE_BODY_LIMIT_BYTES, CATALOGUE_WORKER_ALLOWANCE_MS, CATALOGUE_REFRESH_DEADLINE_MS, CatalogueModelSchema, CatalogueCacheSchema, CatalogueDigestSchema;
5037
5232
  var init_providerCatalogue = __esm({
5038
5233
  "src/providerCatalogue.ts"() {
5039
5234
  "use strict";
5040
5235
  init_baseUrlDisplay();
5236
+ init_elapsedWindow();
5237
+ init_loggedText();
5238
+ init_canonicalJson();
5041
5239
  init_names();
5042
5240
  init_doorBounds();
5043
5241
  DEFAULT_CANDIDATE_URLS = 2;
@@ -5051,10 +5249,14 @@ var init_providerCatalogue = __esm({
5051
5249
  CATALOGUE_REQUEST_SECONDS = 10;
5052
5250
  CATALOGUE_REQUEST_TIMEOUT_MS = CATALOGUE_REQUEST_SECONDS * MS_PER_SECOND4;
5053
5251
  CATALOGUE_REFRESH_TIMEOUT_MS = DEFAULT_CANDIDATE_URLS * CATALOGUE_REQUEST_TIMEOUT_MS;
5252
+ CATALOGUE_MAX_MODELS = 1e4;
5253
+ CATALOGUE_ENTRY_MAX_BYTES = 1024;
5254
+ CATALOGUE_BODY_LIMIT_BYTES = CATALOGUE_MAX_MODELS * CATALOGUE_ENTRY_MAX_BYTES;
5054
5255
  CATALOGUE_WORKER_ALLOWANCE_MS = DOOR_WORKER_START_ALLOWANCE_MS + BLOCKING_STEP_TIMEOUTS_MS.credentialCommand + BLOCKING_STEP_TIMEOUTS_MS.codexVersion;
5055
5256
  CATALOGUE_REFRESH_DEADLINE_MS = CATALOGUE_REFRESH_TIMEOUT_MS + CATALOGUE_WORKER_ALLOWANCE_MS;
5056
5257
  CatalogueModelSchema = z7.strictObject({ id: z7.string().min(1), name: z7.string().min(1).optional() });
5057
5258
  CatalogueCacheSchema = z7.strictObject({ fetchedAt: z7.number(), url: z7.string().min(1), models: z7.array(CatalogueModelSchema), credentialFingerprint: z7.string().optional(), supervisorPid: z7.number().int().positive().optional() });
5259
+ CatalogueDigestSchema = z7.strictObject({ settings: z7.string().min(1), fetchedAt: z7.number() });
5058
5260
  }
5059
5261
  });
5060
5262
 
@@ -5086,17 +5288,6 @@ var init_catalogueCleanup = __esm({
5086
5288
  // src/frontdoor/state.ts
5087
5289
  import path13 from "node:path";
5088
5290
  import { z as z9 } from "zod";
5089
- function readCatalogueStatus(fs17, paths, pid, generation, name) {
5090
- const file = path13.join(path13.dirname(catalogueCachePath(paths, name, pid, generation)), `${name}.status.json`);
5091
- const raw = fs17.readFileUtf8(file);
5092
- if (raw === void 0) return void 0;
5093
- try {
5094
- const value = z9.strictObject({ status: z9.enum(["running", "ready", "failed"]), fingerprint: z9.string().min(1).optional(), recordedAt: z9.number().optional() }).safeParse(JSON.parse(raw));
5095
- return value.success ? value.data : void 0;
5096
- } catch {
5097
- return void 0;
5098
- }
5099
- }
5100
5291
  function launchKeyOf(launch) {
5101
5292
  return `${String(launch.pid)}-${String(launch.startedAt)}`;
5102
5293
  }
@@ -5107,7 +5298,12 @@ function writeFrontDoorCodexHome(fs17, frontdoorDir, pid, codexHome, generation)
5107
5298
  `);
5108
5299
  }
5109
5300
  function readFrontDoorCodexRecord(fs17, frontdoorDir, pid) {
5110
- const raw = fs17.readFileUtf8(path13.join(frontdoorDir, "codex-homes", `${String(pid)}.json`));
5301
+ let raw;
5302
+ try {
5303
+ raw = fs17.readFileUtf8(path13.join(frontdoorDir, "codex-homes", `${String(pid)}.json`));
5304
+ } catch {
5305
+ return void 0;
5306
+ }
5111
5307
  if (raw === void 0) return void 0;
5112
5308
  try {
5113
5309
  const parsed = z9.strictObject({ codexHome: z9.string().min(1), generation: z9.uuid() }).safeParse(JSON.parse(raw));
@@ -5292,8 +5488,7 @@ var init_state = __esm({
5292
5488
  "use strict";
5293
5489
  init_schema();
5294
5490
  init_baseUrlDial();
5295
- init_providerCatalogue();
5296
- FRONT_DOOR_PROTOCOL = 8;
5491
+ FRONT_DOOR_PROTOCOL = 9;
5297
5492
  FRONT_DOOR_HANDOVER_PROTOCOL = 6;
5298
5493
  FrontDoorSessionSchema = z9.strictObject({ pid: z9.number().int().positive(), startedAt: z9.number(), token: z9.string().min(1), supervisorPid: z9.number().int().positive().optional(), sessionId: z9.string().min(1).optional(), identity: z9.string().min(1).optional(), models: ModelsConfigSchema.optional() });
5299
5494
  MAX_CONTEXT_TEXT_LENGTH = 256;
@@ -5595,8 +5790,8 @@ function parseConnectTarget(authority) {
5595
5790
  function isInterceptedHost(host, interceptHosts) {
5596
5791
  return interceptHosts.includes(host);
5597
5792
  }
5598
- function servedByPipeline(path55) {
5599
- return path55?.startsWith(ROUTED_PATH_PREFIX) === true;
5793
+ function servedByPipeline(path56) {
5794
+ return path56?.startsWith(ROUTED_PATH_PREFIX) === true;
5600
5795
  }
5601
5796
  function forwardableHeaders(headers) {
5602
5797
  const connectionTokens = new Set(
@@ -6049,6 +6244,7 @@ var init_http = __esm({
6049
6244
  methodNotAllowed: 405,
6050
6245
  conflict: 409,
6051
6246
  payloadTooLarge: 413,
6247
+ unsupportedMediaType: 415,
6052
6248
  tooManyRequests: 429,
6053
6249
  /** Not sent to anyone: the client is gone. Recorded for a response abandoned because the client disconnected, following the convention nginx uses for the same case. */
6054
6250
  clientClosedRequest: 499,
@@ -6453,13 +6649,13 @@ var init_rcQuestions = __esm({
6453
6649
  });
6454
6650
 
6455
6651
  // src/frontdoor/rcSessions.ts
6456
- import { createHash as createHash3 } from "node:crypto";
6652
+ import { createHash as createHash4 } from "node:crypto";
6457
6653
  function pathnameOf(url) {
6458
6654
  return new URL(url ?? "/", "http://127.0.0.1").pathname;
6459
6655
  }
6460
6656
  function isRcSessionExchange(url) {
6461
- const path55 = pathnameOf(url);
6462
- return path55 === RC_SESSIONS_PATH_PREFIX || path55.startsWith(`${RC_SESSIONS_PATH_PREFIX}/`);
6657
+ const path56 = pathnameOf(url);
6658
+ return path56 === RC_SESSIONS_PATH_PREFIX || path56.startsWith(`${RC_SESSIONS_PATH_PREFIX}/`);
6463
6659
  }
6464
6660
  function isSuccessful(status) {
6465
6661
  return status >= HTTP_STATUS.ok && status < SUCCESS_STATUS_MAX_EXCLUSIVE;
@@ -6637,7 +6833,7 @@ function rememberBounded(record, key) {
6637
6833
  }
6638
6834
  }
6639
6835
  function droppedKeyOf(requestId) {
6640
- return requestId.length <= RC_REQUEST_ID_MAX_CHARS ? requestId : createHash3("sha256").update(requestId).digest("hex");
6836
+ return requestId.length <= RC_REQUEST_ID_MAX_CHARS ? requestId : createHash4("sha256").update(requestId).digest("hex");
6641
6837
  }
6642
6838
  function createRcSessionTracker(deps) {
6643
6839
  const entries = /* @__PURE__ */ new Map();
@@ -7193,8 +7389,8 @@ function buildRcGetContextUsagePayload(requestId, detail) {
7193
7389
  function isRcReadFileEncoding(value) {
7194
7390
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value);
7195
7391
  }
7196
- function buildRcReadFilePayload(requestId, path55, options) {
7197
- return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path55, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
7392
+ function buildRcReadFilePayload(requestId, path56, options) {
7393
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path56, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
7198
7394
  }
7199
7395
  function buildRcFileSuggestionsPayload(requestId, query) {
7200
7396
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -7328,15 +7524,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
7328
7524
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
7329
7525
  return result.ok ? { ...result, requestId } : result;
7330
7526
  }
7331
- async function readRcSessionFile(deps, sessionId, path55, options) {
7332
- if (path55 === "") {
7527
+ async function readRcSessionFile(deps, sessionId, path56, options) {
7528
+ if (path56 === "") {
7333
7529
  return { ok: false, message: "a read-file write needs a non-empty path: the SDK's own field names the file the worker resolves against the session's cwd, and an empty string names none" };
7334
7530
  }
7335
7531
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
7336
7532
  return { ok: false, message: "a read-file write's max-bytes is a positive whole number of bytes: the SDK's own field caps the read, and a zero or negative cap reads nothing" };
7337
7533
  }
7338
7534
  const requestId = deps.newUuid();
7339
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path55, options), `read ${path55} from session ${sessionId}`);
7535
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path56, options), `read ${path56} from session ${sessionId}`);
7340
7536
  return result.ok ? { ...result, requestId } : result;
7341
7537
  }
7342
7538
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -7714,11 +7910,11 @@ function createRcControlHandler(deps) {
7714
7910
  path: "read-file",
7715
7911
  read: (body) => {
7716
7912
  const session = bodyString(body, "session");
7717
- const path55 = bodyString(body, "path");
7913
+ const path56 = bodyString(body, "path");
7718
7914
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
7719
7915
  const encoding = "encoding" in body && isRcReadFileEncoding(body.encoding) ? body.encoding : void 0;
7720
- const refused2 = session === void 0 || path55 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
7721
- return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path55, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
7916
+ const refused2 = session === void 0 || path56 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
7917
+ return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path56, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
7722
7918
  }
7723
7919
  },
7724
7920
  {
@@ -8041,9 +8237,9 @@ function requestIdOfBody(body) {
8041
8237
  }
8042
8238
  function frontDoorRcControl(transport, token) {
8043
8239
  const headers = { authorization: `Bearer ${token}` };
8044
- const listAnswerOf = async (path55, what) => {
8240
+ const listAnswerOf = async (path56, what) => {
8045
8241
  try {
8046
- return await transport.request({ method: "GET", path: path55, headers });
8242
+ return await transport.request({ method: "GET", path: path56, headers });
8047
8243
  } catch (error) {
8048
8244
  throw new Error(`${what}: could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
8049
8245
  }
@@ -8115,10 +8311,10 @@ function frontDoorRcControl(transport, token) {
8115
8311
  }
8116
8312
  return pending;
8117
8313
  };
8118
- const writeOf = async (path55, body, describeFailure2) => {
8314
+ const writeOf = async (path56, body, describeFailure2) => {
8119
8315
  let answer;
8120
8316
  try {
8121
- answer = await transport.request({ method: "POST", path: path55, headers: { ...headers, "content-type": "application/json" }, body });
8317
+ answer = await transport.request({ method: "POST", path: path56, headers: { ...headers, "content-type": "application/json" }, body });
8122
8318
  } catch (error) {
8123
8319
  return { ok: false, message: `could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}` };
8124
8320
  }
@@ -8149,10 +8345,10 @@ function frontDoorRcControl(transport, token) {
8149
8345
  endSession: async (sessionId, reason) => await writeOf(`${CONTROL_PATH_PREFIX}/end-session`, JSON.stringify({ session: sessionId, ...reason === void 0 ? {} : { reason } }), (status, message) => `ending ${sessionId} failed (HTTP ${String(status)}): ${message}`),
8150
8346
  getUsage: async (sessionId, skipBehaviors) => await writeOf(`${CONTROL_PATH_PREFIX}/get-usage`, JSON.stringify({ session: sessionId, ...skipBehaviors === void 0 ? {} : { skipBehaviors } }), (status, message) => `requesting the usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
8151
8347
  getContextUsage: async (sessionId, detail) => await writeOf(`${CONTROL_PATH_PREFIX}/get-context-usage`, JSON.stringify({ session: sessionId, ...detail === void 0 ? {} : { detail } }), (status, message) => `requesting the context usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
8152
- readFile: async (sessionId, path55, options) => await writeOf(
8348
+ readFile: async (sessionId, path56, options) => await writeOf(
8153
8349
  `${CONTROL_PATH_PREFIX}/read-file`,
8154
- JSON.stringify({ session: sessionId, path: path55, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
8155
- (status, message) => `reading ${path55} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
8350
+ JSON.stringify({ session: sessionId, path: path56, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
8351
+ (status, message) => `reading ${path56} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
8156
8352
  ),
8157
8353
  fileSuggestions: async (sessionId, query) => await writeOf(`${CONTROL_PATH_PREFIX}/file-suggestions`, JSON.stringify({ session: sessionId, query }), (status, message) => `requesting file suggestions from ${sessionId} failed (HTTP ${String(status)}): ${message}`),
8158
8354
  keepAlive: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/keep-alive`, JSON.stringify({ session: sessionId }), (status, message) => `keeping ${sessionId} alive failed (HTTP ${String(status)}): ${message}`),
@@ -8393,12 +8589,12 @@ function tlsFacts(options) {
8393
8589
  }
8394
8590
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
8395
8591
  const agent = new ExemptTlsAgent();
8396
- const post = async (path55, headers, body) => await new Promise((resolve, reject) => {
8592
+ const post = async (path56, headers, body) => await new Promise((resolve, reject) => {
8397
8593
  const options = {
8398
8594
  host: target.host,
8399
8595
  port: target.port,
8400
8596
  method: "POST",
8401
- path: path55,
8597
+ path: path56,
8402
8598
  // The Host header names the host whose API this is, not the address dialled: a redirected test dials a loopback stand-in while still speaking to the API host by name, exactly as the forwarded paths present their SNI.
8403
8599
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
8404
8600
  agent
@@ -8458,12 +8654,12 @@ function lateRcStreamDial(resolve) {
8458
8654
  }
8459
8655
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
8460
8656
  const agent = new ExemptTlsAgent();
8461
- const request4 = async (method, path55, headers, body, signal) => await new Promise((resolve, reject) => {
8657
+ const request4 = async (method, path56, headers, body, signal) => await new Promise((resolve, reject) => {
8462
8658
  const options = {
8463
8659
  host: target.host,
8464
8660
  port: target.port,
8465
8661
  method,
8466
- path: path55,
8662
+ path: path56,
8467
8663
  // The Host header names the host whose API this is, not the address dialled: a redirected test dials a loopback stand-in while still speaking to the API host by name, exactly as the forwarded paths present their SNI.
8468
8664
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
8469
8665
  agent,
@@ -8505,9 +8701,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
8505
8701
  return { status, body: await readAll(response) };
8506
8702
  },
8507
8703
  openStream: async (sessionId, headers, resume, signal) => {
8508
- const path55 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
8704
+ const path56 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
8509
8705
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
8510
- const { status, response } = await request4("GET", path55, streamHeaders, void 0, signal);
8706
+ const { status, response } = await request4("GET", path56, streamHeaders, void 0, signal);
8511
8707
  if (!isSuccessful2(status)) {
8512
8708
  await readAll(response);
8513
8709
  return { status, chunks: NO_CHUNKS };
@@ -8946,7 +9142,7 @@ function loadIdentity(identitiesDir, name, fs17) {
8946
9142
  return id === void 0 ? void 0 : loadConfigFile(path15.join(identitiesDir, id, "identity.json"), IdentitySchema, fs17.readConfigFile);
8947
9143
  }
8948
9144
  var IDENTITY_DECISION_SOURCES, IDENTITY_SOURCE_LABELS, CONFIG_PROFILE_DECISION_SOURCES;
8949
- var init_identity = __esm({
9145
+ var init_identity2 = __esm({
8950
9146
  "src/launcher/identity.ts"() {
8951
9147
  "use strict";
8952
9148
  init_load();
@@ -8995,9 +9191,9 @@ var init_identity = __esm({
8995
9191
 
8996
9192
  // src/statusline/keys.ts
8997
9193
  import { z as z13 } from "zod";
8998
- function valueAt(source, path55) {
9194
+ function valueAt(source, path56) {
8999
9195
  let current = source;
9000
- for (const part of path55) {
9196
+ for (const part of path56) {
9001
9197
  if (!isPlainObject(current)) {
9002
9198
  return void 0;
9003
9199
  }
@@ -9005,14 +9201,14 @@ function valueAt(source, path55) {
9005
9201
  }
9006
9202
  return current;
9007
9203
  }
9008
- function acceptsNull(path55) {
9009
- const layer = path55.reduceRight((inner, part) => ({ [part]: inner }), null);
9204
+ function acceptsNull(path56) {
9205
+ const layer = path56.reduceRight((inner, part) => ({ [part]: inner }), null);
9010
9206
  return StatuslineSchema.safeParse(layer).success;
9011
9207
  }
9012
- function keyOf(path55, declared) {
9208
+ function keyOf(path56, declared) {
9013
9209
  const optional = declared instanceof z13.ZodOptional;
9014
9210
  const leaf = optional ? declared.unwrap() : declared;
9015
- const common = { path: path55.join("."), description: declared.description ?? "", defaultValue: valueAt(STATUSLINE_DEFAULTS, path55), optional, unsettable: acceptsNull(path55) };
9211
+ const common = { path: path56.join("."), description: declared.description ?? "", defaultValue: valueAt(STATUSLINE_DEFAULTS, path56), optional, unsettable: acceptsNull(path56) };
9016
9212
  if (leaf instanceof z13.ZodNumber) {
9017
9213
  return { ...common, kind: "integer", choices: [] };
9018
9214
  }
@@ -9037,7 +9233,7 @@ function keyOf(path55, declared) {
9037
9233
  if (leaf instanceof z13.ZodArray && leaf.element instanceof z13.ZodString) {
9038
9234
  return { ...common, kind: "textList", choices: [] };
9039
9235
  }
9040
- throw new TypeError(`statusline setting ${path55.join(".")} has a kind the key listing does not describe`);
9236
+ throw new TypeError(`statusline setting ${path56.join(".")} has a kind the key listing does not describe`);
9041
9237
  }
9042
9238
  function walk(shape, prefix) {
9043
9239
  return Object.entries(shape).flatMap(([name, schema]) => schema instanceof z13.ZodObject ? walk(schema.shape, [...prefix, name]) : [keyOf([...prefix, name], schema)]);
@@ -9053,15 +9249,15 @@ var init_keys = __esm({
9053
9249
  });
9054
9250
 
9055
9251
  // src/statusline/change.ts
9056
- function keyNamed(path55) {
9057
- const found = statuslineKeys().find((key) => key.path === path55);
9252
+ function keyNamed(path56) {
9253
+ const found = statuslineKeys().find((key) => key.path === path56);
9058
9254
  if (found === void 0) {
9059
- throw new UsageError(`"${path55}" is not a statusline setting; \`agent-shim statusline keys\` lists them.`);
9255
+ throw new UsageError(`"${path56}" is not a statusline setting; \`agent-shim statusline keys\` lists them.`);
9060
9256
  }
9061
9257
  return found;
9062
9258
  }
9063
- function setAt(target, path55, value) {
9064
- const [head, ...rest] = path55;
9259
+ function setAt(target, path56, value) {
9260
+ const [head, ...rest] = path56;
9065
9261
  if (head === void 0) {
9066
9262
  return;
9067
9263
  }
@@ -9074,8 +9270,8 @@ function setAt(target, path55, value) {
9074
9270
  target[head] = next;
9075
9271
  setAt(next, rest, value);
9076
9272
  }
9077
- function removeAt(target, path55) {
9078
- const [head, ...rest] = path55;
9273
+ function removeAt(target, path56) {
9274
+ const [head, ...rest] = path56;
9079
9275
  if (head === void 0) {
9080
9276
  return;
9081
9277
  }
@@ -9093,13 +9289,13 @@ function removeAt(target, path55) {
9093
9289
  }
9094
9290
  function applyStatuslineChange(existing, change) {
9095
9291
  const draft = structuredClone(existing ?? {});
9096
- for (const [path55, value] of Object.entries(change.set ?? {})) {
9097
- keyNamed(path55);
9098
- setAt(draft, path55.split("."), value);
9292
+ for (const [path56, value] of Object.entries(change.set ?? {})) {
9293
+ keyNamed(path56);
9294
+ setAt(draft, path56.split("."), value);
9099
9295
  }
9100
- for (const path55 of change.unset ?? []) {
9101
- keyNamed(path55);
9102
- removeAt(draft, path55.split("."));
9296
+ for (const path56 of change.unset ?? []) {
9297
+ keyNamed(path56);
9298
+ removeAt(draft, path56.split("."));
9103
9299
  }
9104
9300
  const result = StatuslineSchema.safeParse(draft);
9105
9301
  if (!result.success) {
@@ -9335,19 +9531,19 @@ function writePools(paths, pools) {
9335
9531
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
9336
9532
  }
9337
9533
  function poolCycleOf(pools, name) {
9338
- const walk2 = (current, path55) => {
9534
+ const walk2 = (current, path56) => {
9339
9535
  for (const entry of pools[current]?.identities ?? []) {
9340
9536
  const nested = poolNameOf(poolMemberIdentity(entry));
9341
9537
  if (nested === void 0) {
9342
9538
  continue;
9343
9539
  }
9344
9540
  if (nested === name) {
9345
- return [...path55, nested];
9541
+ return [...path56, nested];
9346
9542
  }
9347
- if (path55.includes(nested)) {
9543
+ if (path56.includes(nested)) {
9348
9544
  continue;
9349
9545
  }
9350
- const found = walk2(nested, [...path55, nested]);
9546
+ const found = walk2(nested, [...path56, nested]);
9351
9547
  if (found !== void 0) {
9352
9548
  return found;
9353
9549
  }
@@ -9426,7 +9622,7 @@ var init_poolStore = __esm({
9426
9622
  init_configProfilesStore();
9427
9623
  init_store();
9428
9624
  init_schema();
9429
- init_identity();
9625
+ init_identity2();
9430
9626
  PoolNotFoundError = class extends CliError {
9431
9627
  constructor(poolName) {
9432
9628
  super(`No pool named "${poolName}". Run \`agent-shim pool add ${poolName} --identity <name>...\` first.`);
@@ -9763,13 +9959,13 @@ var init_headers = __esm({
9763
9959
  });
9764
9960
 
9765
9961
  // src/launcher/injected.ts
9766
- import { createHash as createHash4 } from "node:crypto";
9962
+ import { createHash as createHash5 } from "node:crypto";
9767
9963
  import { z as z14 } from "zod";
9768
9964
  function listKey(list) {
9769
9965
  return `${list},appended`;
9770
9966
  }
9771
9967
  function digest2(value) {
9772
- return createHash4("sha256").update(value).digest("hex");
9968
+ return createHash5("sha256").update(value).digest("hex");
9773
9969
  }
9774
9970
  function recordedDigests(env) {
9775
9971
  const raw = env[INJECTED_ENV];
@@ -9927,10 +10123,10 @@ var init_guard = __esm({
9927
10123
  });
9928
10124
 
9929
10125
  // src/usage/signIn.ts
9930
- import { createHash as createHash5 } from "node:crypto";
10126
+ import { createHash as createHash6 } from "node:crypto";
9931
10127
  import path19 from "node:path";
9932
10128
  function claudeCodeKeychainService(configDir) {
9933
- return `${KEYCHAIN_SERVICE_PREFIX}-${createHash5("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
10129
+ return `${KEYCHAIN_SERVICE_PREFIX}-${createHash6("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
9934
10130
  }
9935
10131
  function keychainHasItem(run, configDir) {
9936
10132
  return run.run("security", ["find-generic-password", "-s", claudeCodeKeychainService(configDir)]).status === 0;
@@ -10357,7 +10553,7 @@ var init_supervisorProcesses = __esm({
10357
10553
  });
10358
10554
 
10359
10555
  // src/headroom/state.ts
10360
- import { createHash as createHash6 } from "node:crypto";
10556
+ import { createHash as createHash7 } from "node:crypto";
10361
10557
  import path21 from "node:path";
10362
10558
  import { z as z15 } from "zod";
10363
10559
  function parseJson(raw, schema) {
@@ -10406,7 +10602,7 @@ function migrateHeadroomState(fs17, files, isRunning) {
10406
10602
  fs17.removeRecursive(files.legacyStateFile);
10407
10603
  }
10408
10604
  function hashAllowlist(allowlist) {
10409
- return createHash6("sha256").update(allowlist.join("\n")).digest("hex");
10605
+ return createHash7("sha256").update(allowlist.join("\n")).digest("hex");
10410
10606
  }
10411
10607
  function formatAllowlistFile(allowlist) {
10412
10608
  return allowlist.map((entry) => `${entry}
@@ -10731,7 +10927,7 @@ var init_ensure = __esm({
10731
10927
  });
10732
10928
 
10733
10929
  // src/headroom/settings.ts
10734
- import { createHash as createHash7 } from "node:crypto";
10930
+ import { createHash as createHash8 } from "node:crypto";
10735
10931
  function settingsOf(config) {
10736
10932
  return {
10737
10933
  ...config.mode === void 0 ? {} : { mode: config.mode },
@@ -10756,7 +10952,7 @@ function settingsEnv(settings) {
10756
10952
  return settings.rolloutChannel === void 0 ? {} : { HEADROOM_ROLLOUT_CHANNEL: settings.rolloutChannel };
10757
10953
  }
10758
10954
  function hashSettings(settings) {
10759
- return createHash7("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
10955
+ return createHash8("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
10760
10956
  }
10761
10957
  var init_settings = __esm({
10762
10958
  "src/headroom/settings.ts"() {
@@ -11415,7 +11611,7 @@ var init_logStyle = __esm({
11415
11611
 
11416
11612
  // src/realPorts.ts
11417
11613
  import { execFile, spawn } from "node:child_process";
11418
- import { createHash as createHash8 } from "node:crypto";
11614
+ import { createHash as createHash9 } from "node:crypto";
11419
11615
  import fs6 from "node:fs";
11420
11616
  import os2 from "node:os";
11421
11617
  import path24 from "node:path";
@@ -11852,7 +12048,7 @@ var init_realPorts = __esm({
11852
12048
  },
11853
12049
  hashFile(filePath) {
11854
12050
  try {
11855
- return createHash8("sha256").update(fs6.readFileSync(filePath)).digest("hex");
12051
+ return createHash9("sha256").update(fs6.readFileSync(filePath)).digest("hex");
11856
12052
  } catch (error) {
11857
12053
  if (isEnoent3(error) || isErrorWithCode(error, "EISDIR")) {
11858
12054
  return void 0;
@@ -13104,7 +13300,7 @@ var init_poolPick = __esm({
13104
13300
  "src/usage/poolPick.ts"() {
13105
13301
  "use strict";
13106
13302
  init_cliError();
13107
- init_identity();
13303
+ init_identity2();
13108
13304
  init_schema();
13109
13305
  init_identityAccounts();
13110
13306
  init_account();
@@ -13129,11 +13325,11 @@ var init_poolPick = __esm({
13129
13325
  });
13130
13326
 
13131
13327
  // src/identityRenameJournal.ts
13132
- import { createHash as createHash9 } from "node:crypto";
13328
+ import { createHash as createHash10 } from "node:crypto";
13133
13329
  import path27 from "node:path";
13134
13330
  import { z as z20 } from "zod";
13135
13331
  function renamePairFileName(from, to, suffix) {
13136
- return `${createHash9("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
13332
+ return `${createHash10("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
13137
13333
  }
13138
13334
  function readRenameJournal(fs17, file) {
13139
13335
  const raw = fs17.readFileUtf8(file);
@@ -13811,7 +14007,7 @@ var init_identityStore = __esm({
13811
14007
  init_store();
13812
14008
  init_schema();
13813
14009
  init_cliError();
13814
- init_identity();
14010
+ init_identity2();
13815
14011
  init_poolStore();
13816
14012
  init_read();
13817
14013
  init_credential();
@@ -13885,7 +14081,7 @@ var init_package = __esm({
13885
14081
  "package.json"() {
13886
14082
  package_default = {
13887
14083
  name: "claude-use",
13888
- version: "14.2.4",
14084
+ version: "14.3.0",
13889
14085
  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.",
13890
14086
  license: "MIT",
13891
14087
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -14176,325 +14372,422 @@ var init_claudeShim = __esm({
14176
14372
  }
14177
14373
  });
14178
14374
 
14179
- // src/cli/bool.ts
14180
- function parseBoolWord(input) {
14181
- switch (input) {
14182
- case "true":
14183
- case "1":
14184
- return true;
14185
- case "false":
14186
- case "0":
14187
- return false;
14188
- default:
14189
- return void 0;
14190
- }
14375
+ // src/frontdoor/probe.ts
14376
+ import { Worker } from "node:worker_threads";
14377
+ function probeWorkerSource(body) {
14378
+ return `const { workerData } = require("node:worker_threads");
14379
+ ${STARTED_SIGNAL_SOURCE}
14380
+ ${body}`;
14191
14381
  }
14192
- var init_bool = __esm({
14193
- "src/cli/bool.ts"() {
14194
- "use strict";
14195
- }
14196
- });
14197
-
14198
- // src/cli/envBool.ts
14199
- function parseEnvBool(variable, value) {
14200
- if (value === void 0 || value === "") {
14201
- return void 0;
14202
- }
14203
- const parsed = parseBoolWord(value);
14204
- if (parsed === void 0) {
14205
- throw new InvalidEnvBoolError(variable, value);
14206
- }
14207
- return parsed;
14382
+ function requestCatalogueRefreshSync(port, caPem, token, timeoutMs = PROBE_TIMEOUT_MS, workers = realProbeWorkers) {
14383
+ refuseToBlockInRole("a synchronous catalogue refresh request");
14384
+ return workers.start(CATALOGUE_REQUEST_SOURCE, { port, ca: caPem, token }, timeoutMs).verdict();
14208
14385
  }
14209
- var InvalidEnvBoolError;
14210
- var init_envBool = __esm({
14211
- "src/cli/envBool.ts"() {
14212
- "use strict";
14213
- init_cliError();
14214
- init_bool();
14215
- InvalidEnvBoolError = class extends UsageError {
14216
- constructor(variable, value) {
14217
- super(`${variable} must be one of true, false, 1 or 0, got "${value}".`);
14218
- this.variable = variable;
14219
- this.value = value;
14220
- this.name = "InvalidEnvBoolError";
14221
- }
14222
- variable;
14223
- value;
14224
- };
14225
- }
14226
- });
14227
-
14228
- // src/pathNorm.ts
14229
- import path37 from "node:path";
14230
- function expandTilde(value, home) {
14231
- if (value === "~") {
14232
- return home;
14233
- }
14234
- if (value.startsWith("~/")) {
14235
- return path37.join(home, value.slice(2));
14236
- }
14237
- return value;
14386
+ function probeFrontDoorSync(port, caPem, timeoutMs = PROBE_TIMEOUT_MS, workers = realProbeWorkers) {
14387
+ refuseToBlockInRole("a synchronous probe of the front door");
14388
+ return workers.start(PROBE_SOURCE, { port, ca: caPem }, timeoutMs).verdict();
14238
14389
  }
14239
- function normaliseRulePath(rulePath, home) {
14240
- return path37.resolve(expandTilde(rulePath, home));
14390
+ function probeListenerAcceptSync(port, timeoutMs = PROBE_TIMEOUT_MS, workers = realProbeWorkers) {
14391
+ refuseToBlockInRole("a synchronous probe of a front door listener");
14392
+ return workers.start(ACCEPT_PROBE_SOURCE, { host: "127.0.0.1", port, portStart: DOOR_SOURCE_PORT_START, portEnd: DOOR_SOURCE_PORT_END, platform: process.platform }, timeoutMs).verdict();
14241
14393
  }
14242
- var init_pathNorm = __esm({
14243
- "src/pathNorm.ts"() {
14244
- "use strict";
14394
+ function startAddressProbes(targets, workers = realProbeWorkers, portBase) {
14395
+ refuseToBlockInRole("a synchronous probe of a provider's address");
14396
+ const base = portBase ?? processPortBase();
14397
+ const distinct = /* @__PURE__ */ new Map();
14398
+ for (const target of targets) {
14399
+ distinct.set(targetKey(target), target);
14245
14400
  }
14246
- });
14247
-
14248
- // src/launcher/cascade.ts
14249
- import path38 from "node:path";
14250
- function loadCascadeInput(params) {
14251
- const globalConfig = loadConfigFile(params.paths.globalConfigFile, GlobalConfigSchema, params.read);
14252
- const directoryRules = loadConfigFile(params.paths.directoryRulesFile, DirectoryRulesSchema, params.read);
14253
- const loadProfile = (name) => {
14254
- const filepath = profileFilePath(params.paths.configProfilesDir, name);
14255
- const loaded = loadConfigFile(filepath, ConfigProfileSchema, params.read);
14256
- if (loaded === void 0) {
14257
- return void 0;
14401
+ const unique = Array.from(distinct.values());
14402
+ const stride = Math.max(1, Math.floor(DOOR_SOURCE_PORT_COUNT / unique.length));
14403
+ const verdicts = /* @__PURE__ */ new Map();
14404
+ const running = [];
14405
+ const settleOldest = () => {
14406
+ const oldest = running.shift();
14407
+ if (oldest !== void 0) {
14408
+ verdicts.set(oldest.key, oldest.verdict());
14258
14409
  }
14259
- return { name, profile: loaded.config, entryOrder: loaded.entryOrder, filepath: loaded.filepath };
14260
14410
  };
14261
- const limit = globalConfig?.config.walkUpLimit;
14262
- const dirs = walkDirectoryAncestors(params.cwd, {
14263
- home: params.home,
14264
- ...limit === void 0 ? {} : { limit: expandTilde(limit, params.home) },
14265
- ...params.isReadable === void 0 ? {} : { isReadable: params.isReadable }
14411
+ unique.forEach((target, index) => {
14412
+ if (running.length >= MAX_CONCURRENT_PROBES) {
14413
+ settleOldest();
14414
+ }
14415
+ const portFirst = DOOR_SOURCE_PORT_START + (base + index * stride) % DOOR_SOURCE_PORT_COUNT;
14416
+ try {
14417
+ const started = workers.start(ACCEPT_PROBE_SOURCE, { host: target.host, port: target.port, portStart: DOOR_SOURCE_PORT_START, portEnd: DOOR_SOURCE_PORT_END, portFirst, platform: process.platform }, target.timeoutMs);
14418
+ running.push({ key: targetKey(target), verdict: started.verdict, cancel: started.cancel });
14419
+ } catch (error) {
14420
+ const reason = `${PROBE_WORKER_FAILURE_PREFIX}the worker could not be started: ${error instanceof Error ? error.message : String(error)}`;
14421
+ running.push({ key: targetKey(target), verdict: () => ({ ok: false, reason }), cancel: () => void 0 });
14422
+ }
14266
14423
  });
14267
- const levels = [];
14268
- for (const dir of dirs) {
14269
- const portable = loadConfigFile(path38.join(dir, PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(path38.join(dir, LEGACY_PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read);
14270
- const portableLocal = loadConfigFile(path38.join(dir, PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(path38.join(dir, LEGACY_PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read);
14271
- const rules = (directoryRules?.config.rules ?? []).map((rule, index) => ({ rule, index })).filter(({ rule }) => normaliseRulePath(rule.path, params.home) === dir).map(({ rule, index }) => {
14272
- const entryOrder = directoryRules?.ruleEntryOrders[index];
14273
- return {
14274
- rule,
14275
- ...entryOrder === void 0 ? {} : { entryOrder },
14276
- filepath: params.paths.directoryRulesFile
14277
- };
14278
- });
14279
- if (portable === void 0 && portableLocal === void 0 && rules.length === 0) {
14280
- continue;
14424
+ return {
14425
+ settle: () => {
14426
+ while (running.length > 0) {
14427
+ settleOldest();
14428
+ }
14429
+ return targets.map((target) => {
14430
+ const verdict = verdicts.get(targetKey(target));
14431
+ if (verdict === void 0) {
14432
+ throw new Error("the batch probe settled no verdict for one of its targets");
14433
+ }
14434
+ return verdict;
14435
+ });
14436
+ },
14437
+ cancel: () => {
14438
+ for (const started of running.splice(0)) {
14439
+ started.cancel();
14440
+ }
14281
14441
  }
14282
- levels.push({
14283
- dir,
14284
- ...portable === void 0 ? {} : { portable: { config: portable.config, entryOrder: portable.entryOrder, filepath: portable.filepath } },
14285
- ...rules.length === 0 ? {} : { rules },
14286
- ...portableLocal === void 0 ? {} : { portableLocal: { config: portableLocal.config, entryOrder: portableLocal.entryOrder, filepath: portableLocal.filepath } }
14287
- });
14288
- }
14289
- const input = {
14290
- home: params.home,
14291
- ...globalConfig === void 0 ? {} : { globalConfig: { config: globalConfig.config, entryOrder: globalConfig.entryOrder, filepath: globalConfig.filepath } },
14292
- ...params.baseConfigProfile === void 0 ? {} : { baseConfigProfile: params.baseConfigProfile },
14293
- loadProfile,
14294
- levels,
14295
- ...params.cliOverride === void 0 ? {} : { cliOverride: params.cliOverride }
14296
14442
  };
14297
- return { input, ...globalConfig === void 0 ? {} : { globalConfig: globalConfig.config } };
14298
14443
  }
14299
- function readDirectorySelections(loaded) {
14300
- let identity;
14301
- let configProfile;
14302
- for (const level of loaded.input.levels ?? []) {
14303
- for (const source of [level.portable?.config, ...(level.rules ?? []).map((entry) => entry.rule), level.portableLocal?.config]) {
14304
- if (source === void 0) {
14305
- continue;
14306
- }
14307
- if (source.identity !== void 0) {
14308
- identity = source.identity;
14309
- }
14310
- if (source.configProfile !== void 0) {
14311
- configProfile = source.configProfile;
14444
+ function startProbeWorker(source, data, timeoutMs, spawn3 = spawnRealWorker, startLimitMs = PROBE_WORKER_START_LIMIT_MS, wait = slicedProbeWait) {
14445
+ const startLimit = performance.now() + startLimitMs;
14446
+ const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
14447
+ const header = new Int32Array(shared, 0, HEADER_SLOTS);
14448
+ let worker;
14449
+ try {
14450
+ worker = spawn3(`${WORKER_PRELUDE_SOURCE}
14451
+ new Function("require", ${JSON.stringify(source)})(require);`, {
14452
+ eval: true,
14453
+ workerData: { ...data, timeoutMs, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS, startedSlot: STARTED_SLOT, failurePrefix: PROBE_WORKER_FAILURE_PREFIX, claimSlot: CLAIM_SLOT }
14454
+ });
14455
+ } catch (error) {
14456
+ const reason = `${PROBE_WORKER_FAILURE_PREFIX}the worker could not be started: ${error instanceof Error ? error.message : String(error)}`;
14457
+ return { verdict: () => ({ ok: false, reason }), cancel: () => void 0 };
14458
+ }
14459
+ worker.on("error", (error) => {
14460
+ if (Atomics.compareExchange(header, CLAIM_SLOT, 0, 1) !== 0) {
14461
+ return;
14462
+ }
14463
+ const bytes = Buffer.from(PROBE_WORKER_FAILURE_PREFIX + error.message, "utf8").subarray(0, REASON_BYTES);
14464
+ new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES).set(bytes);
14465
+ Atomics.store(header, 1, bytes.length);
14466
+ Atomics.store(header, 0, VERDICT_FAILED);
14467
+ Atomics.store(header, STARTED_SLOT, 1);
14468
+ });
14469
+ worker.unref();
14470
+ return {
14471
+ verdict: () => {
14472
+ try {
14473
+ wait(header, STARTED_SLOT, WORKER_NOT_STARTED, Math.max(0, startLimit - performance.now()));
14474
+ if (Atomics.load(header, STARTED_SLOT) === WORKER_NOT_STARTED && Atomics.load(header, 0) === VERDICT_PENDING) {
14475
+ return { ok: false, reason: `the probe worker did not start within ${String(startLimitMs)}ms` };
14476
+ }
14477
+ wait(header, 0, VERDICT_PENDING, timeoutMs + PROBE_WAIT_MARGIN_MS);
14478
+ const verdict = Atomics.load(header, 0);
14479
+ if (verdict === VERDICT_PENDING) {
14480
+ return { ok: false, reason: `the probe did not finish within ${String(timeoutMs + PROBE_WAIT_MARGIN_MS)}ms` };
14481
+ }
14482
+ if (verdict === VERDICT_OK) {
14483
+ return { ok: true };
14484
+ }
14485
+ const length = Atomics.load(header, 1);
14486
+ return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
14487
+ } finally {
14488
+ void worker.terminate();
14312
14489
  }
14490
+ },
14491
+ cancel: () => {
14492
+ void worker.terminate();
14313
14493
  }
14314
- }
14315
- return { ...identity === void 0 ? {} : { identity }, ...configProfile === void 0 ? {} : { configProfile } };
14494
+ };
14316
14495
  }
14317
- var PORTABLE_CONFIG_FILENAME, PORTABLE_LOCAL_CONFIG_FILENAME;
14318
- var init_cascade = __esm({
14319
- "src/launcher/cascade.ts"() {
14496
+ var PROBE_TIMEOUT_MS, PROBE_WAIT_MARGIN_MS, REASON_BYTES, HEADER_SLOTS, STARTED_SLOT, CLAIM_SLOT, PROBE_WORKER_START_LIMIT_MS, STARTED_SIGNAL_SOURCE, PROBE_WORKER_FAILURE_PREFIX, INT32_BYTES, VERDICT_PENDING, WORKER_NOT_STARTED, VERDICT_OK, VERDICT_FAILED, WORKER_PRELUDE_SOURCE, PROBE_SOURCE, CATALOGUE_REQUEST_SOURCE, realProbeWorkers, ACCEPT_PROBE_SOURCE, PROBE_PORT_SHARE_DENOMINATOR, MAX_CONCURRENT_PROBES, PORT_BASE_SPREAD, processPortBase, targetKey, PROBE_WAIT_SLICE_MS, slicedProbeWait, spawnRealWorker;
14497
+ var init_probe = __esm({
14498
+ "src/frontdoor/probe.ts"() {
14320
14499
  "use strict";
14321
- init_load();
14322
- init_schema();
14323
- init_pathNorm();
14324
- init_walk();
14325
- init_legacy();
14326
- init_names();
14327
- PORTABLE_CONFIG_FILENAME = ".agent-shim.json";
14328
- PORTABLE_LOCAL_CONFIG_FILENAME = ".agent-shim.local.json";
14500
+ init_processRole();
14501
+ init_connectEffects();
14502
+ init_doorDial();
14503
+ PROBE_TIMEOUT_MS = 2e3;
14504
+ PROBE_WAIT_MARGIN_MS = 1e3;
14505
+ REASON_BYTES = 1024;
14506
+ HEADER_SLOTS = 4;
14507
+ STARTED_SLOT = 2;
14508
+ CLAIM_SLOT = 3;
14509
+ PROBE_WORKER_START_LIMIT_MS = 1e4;
14510
+ STARTED_SIGNAL_SOURCE = "Atomics.store(new Int32Array(workerData.shared, 0, workerData.headerSlots), workerData.startedSlot, 1); Atomics.notify(new Int32Array(workerData.shared, 0, workerData.headerSlots), workerData.startedSlot);";
14511
+ PROBE_WORKER_FAILURE_PREFIX = "the probe worker failed: ";
14512
+ INT32_BYTES = 4;
14513
+ VERDICT_PENDING = 0;
14514
+ WORKER_NOT_STARTED = 0;
14515
+ VERDICT_OK = 1;
14516
+ VERDICT_FAILED = 2;
14517
+ WORKER_PRELUDE_SOURCE = `
14518
+ (() => {
14519
+ const { workerData } = require("node:worker_threads");
14520
+ const header = new Int32Array(workerData.shared, 0, workerData.headerSlots);
14521
+ const reason = new Uint8Array(workerData.shared, workerData.headerSlots * 4);
14522
+ globalThis.finishProbe = (verdict, message) => {
14523
+ try {
14524
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
14525
+ if (Atomics.compareExchange(header, workerData.claimSlot, 0, 1) === 0) {
14526
+ reason.set(bytes);
14527
+ Atomics.store(header, 1, bytes.length);
14528
+ Atomics.store(header, 0, verdict);
14529
+ }
14530
+ } finally {
14531
+ Atomics.notify(header, 0);
14532
+ }
14533
+ };
14534
+ const fail = (error) => {
14535
+ let message;
14536
+ try {
14537
+ message = workerData.failurePrefix + (error instanceof Error ? error.message : String(error));
14538
+ } catch {
14539
+ message = workerData.failurePrefix + "an error that cannot be described";
14540
+ }
14541
+ try {
14542
+ globalThis.finishProbe(workerData.failed, message);
14543
+ } finally {
14544
+ Atomics.store(header, workerData.startedSlot, 1);
14545
+ Atomics.notify(header, workerData.startedSlot);
14546
+ }
14547
+ };
14548
+ process.on("uncaughtException", fail);
14549
+ process.on("unhandledRejection", fail);
14550
+ // A worker that ends itself (process.exit in a probe source or a library it calls) runs this in its own thread before it goes: the waiting thread cannot hear the exit event of a worker, since its event loop is blocked on the verdict, so the worker says so itself. A verdict already published is not replaced (the writer takes the claim once).
14551
+ process.on("exit", (code) => {
14552
+ globalThis.finishProbe(workerData.failed, workerData.failurePrefix + "the worker exited without a verdict (exit code " + String(code) + ")");
14553
+ });
14554
+ })();
14555
+ `;
14556
+ PROBE_SOURCE = probeWorkerSource(`
14557
+ const https = require("node:https");
14558
+ const { port, ca, timeoutMs, ok, failed } = workerData;
14559
+ const finish = finishProbe;
14560
+ const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
14561
+ let body = "";
14562
+ response.setEncoding("utf8");
14563
+ response.on("data", (chunk) => { body += chunk; });
14564
+ response.on("end", () => {
14565
+ if (response.statusCode === 200 && body === "ok") finish(ok, "");
14566
+ else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
14567
+ });
14568
+ response.on("error", (error) => finish(failed, error.message));
14569
+ });
14570
+ // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
14571
+ setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
14572
+ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
14573
+ `);
14574
+ CATALOGUE_REQUEST_SOURCE = probeWorkerSource(`
14575
+ const https = require("node:https");
14576
+ const { port, ca, token, timeoutMs, ok, failed } = workerData;
14577
+ const finish = finishProbe;
14578
+ const request = https.request({ host: "127.0.0.1", port, path: "/__agent-shim/orpc/rest/frontdoor/catalogues/refresh", method: "POST", headers: { authorization: "Bearer " + token }, ca: [ca], agent: false }, (response) => {
14579
+ response.resume();
14580
+ response.on("end", () => response.statusCode === 200 ? finish(ok, "") : finish(failed, "catalogue refresh request returned HTTP " + String(response.statusCode)));
14581
+ response.on("error", (error) => finish(failed, error.message));
14582
+ });
14583
+ setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
14584
+ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
14585
+ request.end();
14586
+ `);
14587
+ realProbeWorkers = { start: (source, data, timeoutMs) => startProbeWorker(source, data, timeoutMs) };
14588
+ ACCEPT_PROBE_SOURCE = probeWorkerSource(`
14589
+ const net = require("node:net");
14590
+ const dns = require("node:dns");
14591
+ const { host, port, portStart, portEnd, portFirst, platform, timeoutMs, ok, failed } = workerData;
14592
+ const finish = finishProbe;
14593
+ const SourcePortRange = ${SourcePortRange.toString()};
14594
+ const createDoorLookup = ${createDoorLookup.toString()};
14595
+ const sourcePortClassifier = ${sourcePortClassifier.toString()};
14596
+ const doorDial = ${doorDial.toString()};
14597
+ const probeAccept = ${probeAccept.toString()};
14598
+ const runAcceptProbe = ${runAcceptProbe.toString()};
14599
+ const startTimer = (callback, ms) => { const timer = setTimeout(callback, ms); return () => { clearTimeout(timer); }; };
14600
+ runAcceptProbe({ net, dns, createDoorLookup, doorDial, probeAccept, SourcePortRange, sourcePortClassifier }, { host, port, portStart, portEnd, portFirst, platform, timeoutMs }, startTimer).then((verdict) => {
14601
+ finish(verdict.ok ? ok : failed, verdict.ok ? "" : verdict.reason);
14602
+ });
14603
+ `);
14604
+ PROBE_PORT_SHARE_DENOMINATOR = 100;
14605
+ MAX_CONCURRENT_PROBES = Math.max(1, Math.floor(DOOR_SOURCE_PORT_COUNT / PROBE_PORT_SHARE_DENOMINATOR));
14606
+ PORT_BASE_SPREAD = 389;
14607
+ processPortBase = () => process.pid * PORT_BASE_SPREAD % DOOR_SOURCE_PORT_COUNT;
14608
+ targetKey = (target) => `${target.host}\0${String(target.port)}\0${String(target.timeoutMs)}`;
14609
+ PROBE_WAIT_SLICE_MS = 1e3;
14610
+ slicedProbeWait = (header, index, value, timeoutMs) => {
14611
+ const end = performance.now() + timeoutMs;
14612
+ for (; ; ) {
14613
+ noteBlockingStep();
14614
+ const left = end - performance.now();
14615
+ if (left <= 0) {
14616
+ return "timed-out";
14617
+ }
14618
+ const answer = Atomics.wait(header, index, value, Math.min(left, PROBE_WAIT_SLICE_MS));
14619
+ if (answer !== "timed-out") {
14620
+ return answer;
14621
+ }
14622
+ }
14623
+ };
14624
+ spawnRealWorker = (source, options) => new Worker(source, options);
14329
14625
  }
14330
14626
  });
14331
14627
 
14332
- // src/providerAliases.ts
14333
- import { z as z30 } from "zod";
14334
- function parseAliases(file, raw) {
14335
- const parsed = ProviderAliasesSchema.safeParse(raw);
14336
- if (!parsed.success) {
14337
- throw new ConfigValidationError(file, parsed.error.issues);
14338
- }
14339
- return parsed.data;
14628
+ // src/providerReachability.ts
14629
+ function providerConnectTimeoutMs(provider) {
14630
+ return provider.connectTimeoutMs ?? DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS;
14340
14631
  }
14341
- function readProviderAliases(paths) {
14342
- return readJson(paths.providerAliasesFile, ProviderAliasesSchema) ?? {};
14632
+ function couldNotConnectMessage(subject, baseUrl, reason) {
14633
+ return `${subject} could not connect to ${displayBaseUrl(baseUrl)}: ${reason.trim() === "" ? "the connection failed with no reason given" : reason}`;
14343
14634
  }
14344
- function loadProviderAliases(file, port) {
14345
- const raw = port.readConfigFile(file);
14346
- return raw === void 0 ? {} : parseAliases(file, raw);
14635
+ function probeProviderReachability(name, provider, probe) {
14636
+ const verdict = probe(provider.baseUrl, providerConnectTimeoutMs(provider));
14637
+ return verdict.ok ? { ok: true } : { ok: false, message: couldNotConnectMessage(`provider ${name}`, provider.baseUrl, verdict.reason) };
14347
14638
  }
14348
- function canonicalProviderName(name, defined, aliases) {
14349
- if (defined(name)) {
14350
- return name;
14639
+ function startProviderReachability(name, provider, start) {
14640
+ if (start === void 0 || !isHttpProvider(provider)) {
14641
+ return void 0;
14351
14642
  }
14352
- return aliases()[name] ?? name;
14643
+ const started = start(provider.baseUrl, providerConnectTimeoutMs(provider));
14644
+ return {
14645
+ cancel: started.cancel,
14646
+ line: () => {
14647
+ const verdict = started.verdict();
14648
+ return verdict.ok ? void 0 : couldNotConnectMessage(`provider ${name}`, provider.baseUrl, verdict.reason);
14649
+ }
14650
+ };
14353
14651
  }
14354
- function aliasFindings(aliases, providerNames) {
14355
- return Object.entries(aliases).map(([alias, target]) => {
14356
- if (!providerNames.has(target)) {
14357
- return { level: "fail", alias, message: `${alias} is recorded as a former name of ${target}, which is not a provider. Run \`agent-shim provider unalias ${alias}\`.` };
14652
+ function probeProviderReachabilities(providers, probe) {
14653
+ const http3 = providers.flatMap((entry) => isHttpProvider(entry.provider) ? [{ name: entry.name, provider: entry.provider }] : []);
14654
+ const verdicts = probe(http3.map((entry) => ({ baseUrl: entry.provider.baseUrl, timeoutMs: providerConnectTimeoutMs(entry.provider) })));
14655
+ const lines = /* @__PURE__ */ new Map();
14656
+ http3.forEach((entry, index) => {
14657
+ const verdict = verdicts[index];
14658
+ if (verdict === void 0) {
14659
+ throw new Error("the batch probe answered fewer verdicts than it was given base URLs");
14358
14660
  }
14359
- if (providerNames.has(alias)) {
14360
- return { level: "warn", alias, message: `${alias} is both a provider and a recorded former name of ${target}; the provider wins. Run \`agent-shim provider unalias ${alias}\`.` };
14661
+ if (!verdict.ok) {
14662
+ lines.set(entry.name, couldNotConnectMessage(`provider ${entry.name}`, entry.provider.baseUrl, verdict.reason));
14361
14663
  }
14362
- return { level: "pass", alias, message: `${alias} is a former name of ${target}, still honoured for sessions launched under it. Run \`agent-shim provider unalias ${alias}\` once none is running.` };
14363
14664
  });
14665
+ return lines;
14364
14666
  }
14365
- var ProviderAliasesSchema;
14366
- var init_providerAliases = __esm({
14367
- "src/providerAliases.ts"() {
14667
+ var TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS, CONNECT_SYN_RETRANSMISSIONS_TOLERATED, DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS, startBaseUrlBatchProbe, realBaseUrlBatchProbe, realStartBaseUrlProbe, realBaseUrlProbe;
14668
+ var init_providerReachability = __esm({
14669
+ "src/providerReachability.ts"() {
14368
14670
  "use strict";
14369
- init_cliError();
14370
- init_load();
14371
- init_store();
14372
- ProviderAliasesSchema = z30.record(z30.string().min(1), z30.string().min(1));
14671
+ init_schema();
14672
+ init_baseUrlDial();
14673
+ init_baseUrlDisplay();
14674
+ init_probe();
14675
+ TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS = 1e3;
14676
+ CONNECT_SYN_RETRANSMISSIONS_TOLERATED = 2;
14677
+ DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS = TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS * (2 ** (CONNECT_SYN_RETRANSMISSIONS_TOLERATED + 1) - 1);
14678
+ startBaseUrlBatchProbe = (targets, workers) => {
14679
+ const started = startAddressProbes(targets.map((target) => ({ ...dialTargetOf(target.baseUrl), timeoutMs: target.timeoutMs })), workers);
14680
+ return { cancel: started.cancel, verdicts: started.settle };
14681
+ };
14682
+ realBaseUrlBatchProbe = (targets, workers) => startBaseUrlBatchProbe(targets, workers).verdicts();
14683
+ realStartBaseUrlProbe = (baseUrl, timeoutMs) => {
14684
+ const started = startBaseUrlBatchProbe([{ baseUrl, timeoutMs }]);
14685
+ return {
14686
+ cancel: started.cancel,
14687
+ verdict: () => {
14688
+ const [verdict] = started.verdicts();
14689
+ if (verdict === void 0) {
14690
+ throw new Error("the batch probe answered no verdict for one base URL");
14691
+ }
14692
+ return verdict;
14693
+ }
14694
+ };
14695
+ };
14696
+ realBaseUrlProbe = (baseUrl, timeoutMs) => realStartBaseUrlProbe(baseUrl, timeoutMs).verdict();
14373
14697
  }
14374
14698
  });
14375
14699
 
14376
- // src/models/identity.ts
14377
- function withoutContextMarker(model) {
14378
- return model.toLowerCase().endsWith(CONTEXT_MARKER_1M) ? model.slice(0, -CONTEXT_MARKER_1M.length) : model;
14379
- }
14380
- function canonicalText(name) {
14381
- return name.trim().toLowerCase().replace(NON_IDENTITY_BRACKET_RE, "").replace(/[\s_]+/g, "-").replace(/([a-z])(\d+(?:\.\d+)+)/g, "$1-$2").replace(/-+/g, "-").replace(/^-|-$/g, "");
14700
+ // src/models/tiers.ts
14701
+ function claudeNameTier(model) {
14702
+ const name = model.toLowerCase().replace(/\[1m\]$/, "");
14703
+ const parts = name.split("-");
14704
+ return parts[0] === "claude" ? CLAUDE_TIERS.find((tier) => parts.includes(tier)) : CLAUDE_TIERS.find((tier) => name === tier);
14382
14705
  }
14383
- function splitVariants(tokens) {
14384
- const variants = [];
14385
- let end = tokens.length;
14386
- for (; ; ) {
14387
- const token = tokens[end - 1];
14388
- if (token === void 0 || !KNOWN_VARIANTS.has(token)) {
14389
- return { familyTokens: tokens.slice(0, end), variants };
14390
- }
14391
- variants.unshift(token);
14392
- end -= 1;
14706
+ var TIER_ENV_VARIABLES;
14707
+ var init_tiers = __esm({
14708
+ "src/models/tiers.ts"() {
14709
+ "use strict";
14710
+ init_schema();
14711
+ TIER_ENV_VARIABLES = Object.freeze({
14712
+ fable: "ANTHROPIC_DEFAULT_FABLE_MODEL",
14713
+ opus: "ANTHROPIC_DEFAULT_OPUS_MODEL",
14714
+ sonnet: "ANTHROPIC_DEFAULT_SONNET_MODEL",
14715
+ haiku: "ANTHROPIC_DEFAULT_HAIKU_MODEL"
14716
+ });
14393
14717
  }
14394
- }
14395
- function versionOf(tokens) {
14396
- for (let index = 0; index < tokens.length; index += 1) {
14397
- const token = tokens[index];
14398
- const next = tokens[index + 1];
14399
- if (token === void 0) {
14400
- return "";
14401
- }
14402
- if (/^\d+$/.test(token) && next !== void 0 && /^\d+$/.test(next)) {
14403
- return `${token}.${next}`;
14404
- }
14405
- const dotted = /^\d+(?:\.\d+)+$/.exec(token);
14406
- if (dotted !== null) {
14407
- return dotted[0];
14408
- }
14718
+ });
14719
+
14720
+ // src/models/reservedModelNames.ts
14721
+ function reservedProviderNameReason(name) {
14722
+ const bare = withoutContextMarker(name);
14723
+ if (bare === AUTO_MODEL) {
14724
+ return `"${AUTO_MODEL}" is the model name that follows the server's live model`;
14409
14725
  }
14410
- return "";
14726
+ if (CLAUDE_CODE_ALIASES.has(bare.toLowerCase())) {
14727
+ return `"${name}" is a model alias Claude Code resolves itself`;
14728
+ }
14729
+ const tier = claudeNameTier(name);
14730
+ return tier === void 0 ? void 0 : `"${name}" is a Claude model name (the ${tier} tier)`;
14411
14731
  }
14412
- function modelIdentity(rawName) {
14413
- const segments = rawName.trim().toLowerCase().split("/");
14414
- const stripped = canonicalText(segments[segments.length - 1] ?? "").split(":")[0] ?? "";
14415
- const withoutDate = stripped.replace(DATE_STAMP_RE, "");
14416
- const tokens = withoutDate.split("-").filter((token) => token !== "");
14417
- const { familyTokens, variants } = splitVariants(tokens);
14418
- const version = versionOf(familyTokens);
14419
- const versionless = familyTokens.filter((token, index) => {
14420
- if (version === "") {
14421
- return true;
14422
- }
14423
- const dotted = /^\d+(?:\.\d+)+$/.test(token);
14424
- const previous = familyTokens[index - 1];
14425
- const next = familyTokens[index + 1];
14426
- const insideVersionRun = dotted || /^\d+$/.test(token) && (previous !== void 0 && /^\d+$/.test(previous) || next !== void 0 && /^\d+$/.test(next));
14427
- return !insideVersionRun;
14428
- });
14429
- const family = versionless.join("-");
14430
- const tokenVendor = familyTokens.find((token) => Object.keys(VENDOR_BY_TOKEN).some((key) => token === key || token.startsWith(key)));
14431
- const namespace = segments.length >= 2 ? (segments[0] ?? "").split(":").pop() ?? "" : "";
14432
- const namespaceVendor = VENDOR_BY_NAMESPACE[namespace] ?? "";
14433
- const tokenVendorName = tokenVendor === void 0 ? "" : VENDOR_BY_TOKEN[Object.keys(VENDOR_BY_TOKEN).find((key) => tokenVendor === key || tokenVendor.startsWith(key)) ?? ""] ?? "";
14434
- return {
14435
- vendor: tokenVendorName === "" ? namespaceVendor : tokenVendorName,
14436
- vendorConflict: tokenVendorName !== "" && namespaceVendor !== "" && tokenVendorName !== namespaceVendor,
14437
- family,
14438
- version,
14439
- variant: variants.join("-"),
14440
- familyAndVersion: version === "" ? family : `${family}-${version.replace(/\./g, "-")}`
14441
- };
14732
+ function requireUnreservedProviderName(name) {
14733
+ const reason = reservedProviderNameReason(name);
14734
+ if (reason !== void 0) {
14735
+ throw new InvalidProviderNameError(name, `must not be a bare model name, because ${reason}`);
14736
+ }
14442
14737
  }
14443
- function relateModels(left, right) {
14444
- const a = modelIdentity(left);
14445
- const b = modelIdentity(right);
14446
- if (a.familyAndVersion !== b.familyAndVersion) {
14447
- return sameFamilyOtherVersion(a, b) ? "similar" : "distinct";
14738
+ var AUTO_MODEL, CLAUDE_CODE_ALIASES;
14739
+ var init_reservedModelNames = __esm({
14740
+ "src/models/reservedModelNames.ts"() {
14741
+ "use strict";
14742
+ init_names();
14743
+ init_identity();
14744
+ init_tiers();
14745
+ AUTO_MODEL = "auto";
14746
+ CLAUDE_CODE_ALIASES = /* @__PURE__ */ new Set(["default", "best", "opusplan"]);
14448
14747
  }
14449
- if (a.variant !== b.variant || a.vendorConflict || b.vendorConflict || a.vendor !== "" && b.vendor !== "" && a.vendor !== b.vendor) {
14450
- return "similar";
14748
+ });
14749
+
14750
+ // src/providerAliases.ts
14751
+ import { z as z30 } from "zod";
14752
+ function parseAliases(file, raw) {
14753
+ const parsed = ProviderAliasesSchema.safeParse(raw);
14754
+ if (!parsed.success) {
14755
+ throw new ConfigValidationError(file, parsed.error.issues);
14451
14756
  }
14452
- return "same";
14757
+ return parsed.data;
14453
14758
  }
14454
- function sameFamilyOtherVersion(a, b) {
14455
- if (a.family !== b.family) {
14456
- return false;
14457
- }
14458
- if (a.vendor !== "" && b.vendor !== "" && a.vendor !== b.vendor) {
14459
- return false;
14759
+ function readProviderAliases(paths) {
14760
+ return readJson(paths.providerAliasesFile, ProviderAliasesSchema) ?? {};
14761
+ }
14762
+ function loadProviderAliases(file, port) {
14763
+ const raw = port.readConfigFile(file);
14764
+ return raw === void 0 ? {} : parseAliases(file, raw);
14765
+ }
14766
+ function canonicalProviderName(name, defined, aliases) {
14767
+ if (defined(name)) {
14768
+ return name;
14460
14769
  }
14461
- return true;
14770
+ return aliases()[name] ?? name;
14462
14771
  }
14463
- var NON_IDENTITY_BRACKET_RE, CONTEXT_MARKER_1M, DATE_STAMP_RE, KNOWN_VARIANTS, VENDOR_BY_NAMESPACE, VENDOR_BY_TOKEN;
14464
- var init_identity2 = __esm({
14465
- "src/models/identity.ts"() {
14772
+ function aliasFindings(aliases, providerNames) {
14773
+ return Object.entries(aliases).map(([alias, target]) => {
14774
+ if (!providerNames.has(target)) {
14775
+ return { level: "fail", alias, message: `${alias} is recorded as a former name of ${target}, which is not a provider. Run \`agent-shim provider unalias ${alias}\`.` };
14776
+ }
14777
+ if (providerNames.has(alias)) {
14778
+ return { level: "warn", alias, message: `${alias} is both a provider and a recorded former name of ${target}; the provider wins. Run \`agent-shim provider unalias ${alias}\`.` };
14779
+ }
14780
+ return { level: "pass", alias, message: `${alias} is a former name of ${target}, still honoured for sessions launched under it. Run \`agent-shim provider unalias ${alias}\` once none is running.` };
14781
+ });
14782
+ }
14783
+ var ProviderAliasesSchema;
14784
+ var init_providerAliases = __esm({
14785
+ "src/providerAliases.ts"() {
14466
14786
  "use strict";
14467
- NON_IDENTITY_BRACKET_RE = /\[[^\]]*\]/g;
14468
- CONTEXT_MARKER_1M = "[1m]";
14469
- DATE_STAMP_RE = /-(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])$/;
14470
- KNOWN_VARIANTS = /* @__PURE__ */ new Set(["high", "medium", "low", "thinking", "xhigh", "max", "highspeed", "sol", "terra", "luna", "mini", "flash-lite", "turbo"]);
14471
- VENDOR_BY_NAMESPACE = Object.freeze({
14472
- anthropic: "anthropic",
14473
- google: "google",
14474
- openai: "openai",
14475
- zai: "zai",
14476
- "z-ai": "zai",
14477
- minimax: "minimax",
14478
- qwen: "qwen",
14479
- deepseek: "deepseek",
14480
- moonshot: "moonshot",
14481
- meta: "meta",
14482
- mistral: "mistral"
14483
- });
14484
- VENDOR_BY_TOKEN = Object.freeze({
14485
- claude: "anthropic",
14486
- gemini: "google",
14487
- antigravity: "google",
14488
- gpt: "openai",
14489
- glm: "zai",
14490
- minimax: "minimax",
14491
- qwen: "qwen",
14492
- deepseek: "deepseek",
14493
- kimi: "moonshot",
14494
- llama: "meta",
14495
- mistral: "mistral",
14496
- mixtral: "mistral"
14497
- });
14787
+ init_cliError();
14788
+ init_load();
14789
+ init_store();
14790
+ ProviderAliasesSchema = z30.record(z30.string().min(1), z30.string().min(1));
14498
14791
  }
14499
14792
  });
14500
14793
 
@@ -14574,7 +14867,7 @@ var FAMILY_PREFIX, VARIANT_SEPARATOR;
14574
14867
  var init_families = __esm({
14575
14868
  "src/models/families.ts"() {
14576
14869
  "use strict";
14577
- init_identity2();
14870
+ init_identity();
14578
14871
  FAMILY_PREFIX = "family:";
14579
14872
  VARIANT_SEPARATOR = "+";
14580
14873
  }
@@ -14714,6 +15007,7 @@ function addProvider(paths, name, input) {
14714
15007
  throw new ProviderAlreadyExistsError(name);
14715
15008
  }
14716
15009
  requireNewProviderName(name);
15010
+ requireUnreservedProviderName(name);
14717
15011
  const kind = input.kind ?? "http";
14718
15012
  if (kind === "codex" && input.baseUrl !== void 0) {
14719
15013
  throw new ProviderKindMismatchError("A codex provider has no base URL: the launcher points its sessions at the front-door daemon. Drop --base-url.");
@@ -14736,6 +15030,9 @@ function addProvider(paths, name, input) {
14736
15030
  if (kind !== "http" && input.connectTimeoutMs !== void 0) {
14737
15031
  throw new ProviderKindMismatchError("A connect timeout applies only to an http provider, the one kind that dials a base URL.");
14738
15032
  }
15033
+ if (kind !== "http" && input.serverTools !== void 0) {
15034
+ throw new ProviderKindMismatchError("The server-tools setting applies only to an http provider.");
15035
+ }
14739
15036
  if (kind !== "codex" && !isEmptyCodexConfig(input.codex)) {
14740
15037
  throw new ProviderKindMismatchError("Codex settings apply only to a codex provider (--kind codex).");
14741
15038
  }
@@ -14749,7 +15046,7 @@ function addProvider(paths, name, input) {
14749
15046
  ...input.pickerModels === void 0 || input.pickerModels.length === 0 ? {} : { pickerModels: input.pickerModels }
14750
15047
  };
14751
15048
  const parsed = ProviderSchema.safeParse(
14752
- kind === "router" ? { kind, displayName: input.displayName } : kind === "codex" ? { kind, ...shared, ...isEmptyCodexConfig(input.codex) ? {} : { codex: input.codex } } : kind === "antigravity" ? { kind, ...shared, ...isEmptyAntigravityConfig(input.antigravity) ? {} : { antigravity: input.antigravity } } : { ...shared, baseUrl: input.baseUrl, ...input.connectTimeoutMs === void 0 ? {} : { connectTimeoutMs: input.connectTimeoutMs }, ...input.catalogue === void 0 ? {} : { catalogue: input.catalogue } }
15049
+ kind === "router" ? { kind, displayName: input.displayName } : kind === "codex" ? { kind, ...shared, ...isEmptyCodexConfig(input.codex) ? {} : { codex: input.codex } } : kind === "antigravity" ? { kind, ...shared, ...isEmptyAntigravityConfig(input.antigravity) ? {} : { antigravity: input.antigravity } } : { ...shared, baseUrl: input.baseUrl, ...input.connectTimeoutMs === void 0 ? {} : { connectTimeoutMs: input.connectTimeoutMs }, ...input.catalogue === void 0 ? {} : { catalogue: input.catalogue }, ...input.serverTools === void 0 ? {} : { serverTools: input.serverTools } }
14753
15050
  );
14754
15051
  if (!parsed.success) {
14755
15052
  throw new ConfigValidationError(providerJsonPath(paths, name), parsed.error.issues);
@@ -14787,6 +15084,9 @@ function updateProvider(paths, name, input) {
14787
15084
  if ((isCodexProvider(existing) || isAntigravityProvider(existing)) && input.catalogue !== void 0 && input.catalogue !== false) {
14788
15085
  throw new ProviderKindMismatchError(`Provider "${name}" is not an http provider; a model catalogue applies only to an http provider.`);
14789
15086
  }
15087
+ if ((isCodexProvider(existing) || isAntigravityProvider(existing) || router) && input.serverTools !== void 0) {
15088
+ throw new ProviderKindMismatchError(`Provider "${name}" is not an http provider; the server-tools setting applies only to an http provider.`);
15089
+ }
14790
15090
  if (!isCodexProvider(existing) && !isEmptyCodexConfig(input.codex)) {
14791
15091
  throw new ProviderKindMismatchError(`Provider "${name}" is not a codex provider; codex settings apply only to a codex provider.`);
14792
15092
  }
@@ -14825,7 +15125,7 @@ function updateProvider(paths, name, input) {
14825
15125
  } else {
14826
15126
  const catalogue = input.catalogue === void 0 ? existing.catalogue : input.catalogue === false ? void 0 : input.catalogue;
14827
15127
  const connectTimeoutMs = input.connectTimeoutMs === void 0 ? existing.connectTimeoutMs : input.connectTimeoutMs === false ? void 0 : input.connectTimeoutMs;
14828
- candidate = { ...existing, ...shared, catalogue, connectTimeoutMs, ...input.baseUrl === void 0 ? {} : { baseUrl: input.baseUrl } };
15128
+ candidate = { ...existing, ...shared, catalogue, connectTimeoutMs, ...input.serverTools === void 0 ? {} : { serverTools: input.serverTools }, ...input.baseUrl === void 0 ? {} : { baseUrl: input.baseUrl } };
14829
15129
  }
14830
15130
  const parsed = ProviderSchema.safeParse(candidate);
14831
15131
  if (!parsed.success) {
@@ -14967,6 +15267,7 @@ var init_providersStore = __esm({
14967
15267
  init_walk();
14968
15268
  init_families();
14969
15269
  init_names();
15270
+ init_reservedModelNames();
14970
15271
  ProviderNotFoundError = class extends CliError {
14971
15272
  constructor(name) {
14972
15273
  super(`No provider named "${name}". Run \`agent-shim provider add ${name}\` first.`);
@@ -15008,512 +15309,475 @@ var init_providersStore = __esm({
15008
15309
  }
15009
15310
  });
15010
15311
 
15011
- // src/launcher/memberProvider.ts
15012
- function unreadableFileReason(error) {
15013
- if (error instanceof ConfigValidationError) {
15014
- return `${error.filepath} is invalid`;
15015
- }
15016
- if (error instanceof ConfigFileNotJsonError) {
15017
- return error.message.replace(/\.$/, "");
15018
- }
15019
- if (error instanceof LegacyProviderFileError) {
15020
- return `${error.filePath} uses ${error.conversion.fields.join(", ")}, which a credential block replaced`;
15021
- }
15022
- return void 0;
15023
- }
15024
- function memberProviderResolver(params) {
15025
- if (params.cliProvider === false) {
15026
- return () => void 0;
15312
+ // src/cli/bool.ts
15313
+ function parseBoolWord(input) {
15314
+ switch (input) {
15315
+ case "true":
15316
+ case "1":
15317
+ return true;
15318
+ case "false":
15319
+ case "0":
15320
+ return false;
15321
+ default:
15322
+ return void 0;
15027
15323
  }
15028
- const cliProvider = params.cliProvider;
15029
- const identities = identityReader(params.paths.identitiesDir, params.fs);
15030
- const cascades = /* @__PURE__ */ new Map();
15031
- const cascadeOver = (baseConfigProfile) => {
15032
- const cached = cascades.get(baseConfigProfile);
15033
- if (cached !== void 0) {
15034
- return cached;
15035
- }
15036
- const loaded = params.loadCascade(baseConfigProfile);
15037
- cascades.set(baseConfigProfile, loaded);
15038
- return loaded;
15039
- };
15040
- return (name) => {
15041
- let declared;
15042
- try {
15043
- declared = identities.load(name);
15044
- } catch (error) {
15045
- if (!(error instanceof ConfigValidationError)) {
15046
- throw error;
15047
- }
15048
- }
15049
- const profile = decideConfigProfile({
15050
- env: params.env,
15051
- ...params.cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile: params.cliFlagConfigProfile },
15052
- ...params.directoryRuleConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: params.directoryRuleConfigProfile },
15053
- ...declared?.defaultConfigProfile === void 0 ? {} : { identityDefaultConfigProfile: declared.defaultConfigProfile },
15054
- ...params.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: params.globalDefaultConfigProfile }
15055
- });
15056
- const flagged = cliProvider !== void 0 && cliProvider !== "" ? cliProvider : void 0;
15057
- let named = flagged ?? declared?.provider;
15058
- try {
15059
- const cascade = cascadeOver(profile.name);
15060
- named = flagged ?? cascadeProviderName(cascade, declared?.provider);
15061
- return selectedProviderName({
15062
- paths: params.paths,
15063
- port: params.fs,
15064
- ...cliProvider === void 0 ? {} : { cliProvider },
15065
- cascade,
15066
- ...declared?.provider === void 0 ? {} : { identityProvider: declared.provider }
15067
- });
15068
- } catch (error) {
15069
- const reason = unreadableFileReason(error);
15070
- if (reason === void 0) {
15071
- throw error;
15072
- }
15073
- return { ...named === void 0 ? {} : { named }, reason };
15074
- }
15075
- };
15076
15324
  }
15077
- var init_memberProvider = __esm({
15078
- "src/launcher/memberProvider.ts"() {
15325
+ var init_bool = __esm({
15326
+ "src/cli/bool.ts"() {
15079
15327
  "use strict";
15080
- init_load();
15081
- init_providersStore();
15082
- init_identity();
15083
15328
  }
15084
15329
  });
15085
15330
 
15086
- // src/paths.ts
15087
- import fs12 from "node:fs";
15088
- import os6 from "node:os";
15089
- import path39 from "node:path";
15090
- function resolveAgentShimHome(env = process.env, home = os6.homedir(), isDirectory = isExistingDirectory) {
15091
- const fromEnv = env.AGENT_SHIM_HOME;
15092
- if (fromEnv !== void 0 && fromEnv !== "") {
15093
- return fromEnv;
15331
+ // src/cli/envBool.ts
15332
+ function parseEnvBool(variable, value) {
15333
+ if (value === void 0 || value === "") {
15334
+ return void 0;
15094
15335
  }
15095
- const current = path39.join(home, HOME_DIRNAME);
15096
- const legacy = path39.join(home, LEGACY_HOME_DIRNAME);
15097
- return !isDirectory(current) && isDirectory(legacy) ? legacy : current;
15098
- }
15099
- function isExistingDirectory(candidate) {
15100
- return fs12.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() ?? false;
15101
- }
15102
- function resolveClaudeHome() {
15103
- const fromEnv = process.env.AGENT_SHIM_CLAUDE_HOME;
15104
- if (fromEnv !== void 0 && fromEnv !== "") {
15105
- return fromEnv;
15336
+ const parsed = parseBoolWord(value);
15337
+ if (parsed === void 0) {
15338
+ throw new InvalidEnvBoolError(variable, value);
15106
15339
  }
15107
- return path39.join(os6.homedir(), ".claude");
15108
- }
15109
- function buildLayoutPaths(root) {
15110
- return {
15111
- root,
15112
- identitiesDir: path39.join(root, "identities"),
15113
- configProfilesDir: path39.join(root, "config-profiles"),
15114
- providersDir: path39.join(root, "providers"),
15115
- providerAliasesFile: path39.join(root, "provider-aliases.json"),
15116
- directoryRulesFile: path39.join(root, "directory-rules.json"),
15117
- activeIdentityFile: path39.join(root, "active-identity"),
15118
- globalConfigFile: path39.join(root, "config.json"),
15119
- categoriesLocalFile: path39.join(root, "categories.local.json"),
15120
- claudeShimFile: path39.join(root, "claude-shim.json"),
15121
- headroomDir: path39.join(root, "headroom"),
15122
- headroomStateFile: path39.join(root, "headroom", "state.json"),
15123
- headroomRoutingFile: path39.join(root, "headroom", "routing.json"),
15124
- headroomLegacyStateFile: path39.join(root, "headroom", "state.v2.json"),
15125
- headroomAllowlistFile: path39.join(root, "headroom", "run", "allowlist.txt"),
15126
- headroomSocketDir: path39.join(root, "headroom", "run"),
15127
- headroomLockFile: path39.join(root, "headroom", "start.lock"),
15128
- headroomSessionsDir: path39.join(root, "headroom", "sessions"),
15129
- logsDir: path39.join(root, "logs"),
15130
- headroomLogPath: path39.join(root, "logs", "headroom.log"),
15131
- frontdoorDir: path39.join(root, "frontdoor"),
15132
- frontdoorCaDir: path39.join(root, "frontdoor", "ca"),
15133
- frontdoorCaCertFile: path39.join(root, "frontdoor", "ca", "ca.pem"),
15134
- frontdoorCaKeyFile: path39.join(root, "frontdoor", "ca", "ca.key"),
15135
- frontdoorCaBundlesDir: path39.join(root, "frontdoor", "ca", "bundles"),
15136
- chatgptSignInFile: path39.join(root, "codex", "chatgpt-sign-in.json"),
15137
- frontdoorStateFile: path39.join(root, "frontdoor", "state.json"),
15138
- frontdoorLockFile: path39.join(root, "frontdoor", "start.lock"),
15139
- frontdoorControlTokenFile: path39.join(root, "frontdoor", "control-token"),
15140
- frontdoorSessionsDir: path39.join(root, "frontdoor", "sessions"),
15141
- frontdoorDirectRecordsDir: path39.join(root, "frontdoor", "direct"),
15142
- frontdoorDrainingDir: path39.join(root, "frontdoor", "draining"),
15143
- frontdoorRcCredentialsDir: path39.join(root, "frontdoor", "rc-credentials"),
15144
- frontdoorLogPath: path39.join(root, "logs", "frontdoor.log"),
15145
- usageDir: path39.join(root, "usage"),
15146
- usageLogDir: path39.join(root, "usage", "log"),
15147
- usageSnapshotsDir: path39.join(root, "usage", "snapshots"),
15148
- statuslineDir: path39.join(root, "statusline"),
15149
- catalogueDir: path39.join(root, "catalogues"),
15150
- usagePicksFile: path39.join(root, "usage", "picks.json"),
15151
- usageAnchorsFile: path39.join(root, "usage", "anchors.json"),
15152
- usageJobsFile: path39.join(root, "usage", "jobs.json"),
15153
- jobLogsDir: path39.join(root, "logs", "jobs"),
15154
- identityRenamesDir: path39.join(root, "identity-renames"),
15155
- identityNameRenamesDir: path39.join(root, "identity-name-renames"),
15156
- launchesDir: path39.join(root, "launches"),
15157
- superviseDir: path39.join(root, "supervise"),
15158
- modelMovesDir: path39.join(root, "model-moves"),
15159
- mcpPermissionsFile: path39.join(root, "mcp", "permissions.json")
15160
- };
15161
- }
15162
- function resolveLayoutPaths() {
15163
- return buildLayoutPaths(resolveAgentShimHome());
15340
+ return parsed;
15164
15341
  }
15165
- var init_paths = __esm({
15166
- "src/paths.ts"() {
15342
+ var InvalidEnvBoolError;
15343
+ var init_envBool = __esm({
15344
+ "src/cli/envBool.ts"() {
15167
15345
  "use strict";
15168
- init_legacy();
15346
+ init_cliError();
15347
+ init_bool();
15348
+ InvalidEnvBoolError = class extends UsageError {
15349
+ constructor(variable, value) {
15350
+ super(`${variable} must be one of true, false, 1 or 0, got "${value}".`);
15351
+ this.variable = variable;
15352
+ this.value = value;
15353
+ this.name = "InvalidEnvBoolError";
15354
+ }
15355
+ variable;
15356
+ value;
15357
+ };
15169
15358
  }
15170
15359
  });
15171
15360
 
15172
- // src/frontdoor/probe.ts
15173
- import { Worker } from "node:worker_threads";
15174
- function probeWorkerSource(body) {
15175
- return `const { workerData } = require("node:worker_threads");
15176
- ${STARTED_SIGNAL_SOURCE}
15177
- ${body}`;
15178
- }
15179
- function requestCatalogueRefreshSync(port, caPem, token, timeoutMs = PROBE_TIMEOUT_MS, workers = realProbeWorkers) {
15180
- refuseToBlockInRole("a synchronous catalogue refresh request");
15181
- return workers.start(CATALOGUE_REQUEST_SOURCE, { port, ca: caPem, token }, timeoutMs).verdict();
15182
- }
15183
- function probeFrontDoorSync(port, caPem, timeoutMs = PROBE_TIMEOUT_MS, workers = realProbeWorkers) {
15184
- refuseToBlockInRole("a synchronous probe of the front door");
15185
- return workers.start(PROBE_SOURCE, { port, ca: caPem }, timeoutMs).verdict();
15361
+ // src/pathNorm.ts
15362
+ import path37 from "node:path";
15363
+ function expandTilde(value, home) {
15364
+ if (value === "~") {
15365
+ return home;
15366
+ }
15367
+ if (value.startsWith("~/")) {
15368
+ return path37.join(home, value.slice(2));
15369
+ }
15370
+ return value;
15186
15371
  }
15187
- function probeListenerAcceptSync(port, timeoutMs = PROBE_TIMEOUT_MS, workers = realProbeWorkers) {
15188
- refuseToBlockInRole("a synchronous probe of a front door listener");
15189
- return workers.start(ACCEPT_PROBE_SOURCE, { host: "127.0.0.1", port, portStart: DOOR_SOURCE_PORT_START, portEnd: DOOR_SOURCE_PORT_END, platform: process.platform }, timeoutMs).verdict();
15372
+ function normaliseRulePath(rulePath, home) {
15373
+ return path37.resolve(expandTilde(rulePath, home));
15190
15374
  }
15191
- function startAddressProbes(targets, workers = realProbeWorkers, portBase) {
15192
- refuseToBlockInRole("a synchronous probe of a provider's address");
15193
- const base = portBase ?? processPortBase();
15194
- const distinct = /* @__PURE__ */ new Map();
15195
- for (const target of targets) {
15196
- distinct.set(targetKey(target), target);
15375
+ var init_pathNorm = __esm({
15376
+ "src/pathNorm.ts"() {
15377
+ "use strict";
15197
15378
  }
15198
- const unique = Array.from(distinct.values());
15199
- const stride = Math.max(1, Math.floor(DOOR_SOURCE_PORT_COUNT / unique.length));
15200
- const verdicts = /* @__PURE__ */ new Map();
15201
- const running = [];
15202
- const settleOldest = () => {
15203
- const oldest = running.shift();
15204
- if (oldest !== void 0) {
15205
- verdicts.set(oldest.key, oldest.verdict());
15379
+ });
15380
+
15381
+ // src/launcher/cascade.ts
15382
+ import path38 from "node:path";
15383
+ function loadCascadeInput(params) {
15384
+ const globalConfig = loadConfigFile(params.paths.globalConfigFile, GlobalConfigSchema, params.read);
15385
+ const directoryRules = loadConfigFile(params.paths.directoryRulesFile, DirectoryRulesSchema, params.read);
15386
+ const loadProfile = (name) => {
15387
+ const filepath = profileFilePath(params.paths.configProfilesDir, name);
15388
+ const loaded = loadConfigFile(filepath, ConfigProfileSchema, params.read);
15389
+ if (loaded === void 0) {
15390
+ return void 0;
15206
15391
  }
15392
+ return { name, profile: loaded.config, entryOrder: loaded.entryOrder, filepath: loaded.filepath };
15207
15393
  };
15208
- unique.forEach((target, index) => {
15209
- if (running.length >= MAX_CONCURRENT_PROBES) {
15210
- settleOldest();
15211
- }
15212
- const portFirst = DOOR_SOURCE_PORT_START + (base + index * stride) % DOOR_SOURCE_PORT_COUNT;
15213
- try {
15214
- const started = workers.start(ACCEPT_PROBE_SOURCE, { host: target.host, port: target.port, portStart: DOOR_SOURCE_PORT_START, portEnd: DOOR_SOURCE_PORT_END, portFirst, platform: process.platform }, target.timeoutMs);
15215
- running.push({ key: targetKey(target), verdict: started.verdict, cancel: started.cancel });
15216
- } catch (error) {
15217
- const reason = `${PROBE_WORKER_FAILURE_PREFIX}the worker could not be started: ${error instanceof Error ? error.message : String(error)}`;
15218
- running.push({ key: targetKey(target), verdict: () => ({ ok: false, reason }), cancel: () => void 0 });
15219
- }
15394
+ const limit = globalConfig?.config.walkUpLimit;
15395
+ const dirs = walkDirectoryAncestors(params.cwd, {
15396
+ home: params.home,
15397
+ ...limit === void 0 ? {} : { limit: expandTilde(limit, params.home) },
15398
+ ...params.isReadable === void 0 ? {} : { isReadable: params.isReadable }
15220
15399
  });
15221
- return {
15222
- settle: () => {
15223
- while (running.length > 0) {
15224
- settleOldest();
15225
- }
15226
- return targets.map((target) => {
15227
- const verdict = verdicts.get(targetKey(target));
15228
- if (verdict === void 0) {
15229
- throw new Error("the batch probe settled no verdict for one of its targets");
15230
- }
15231
- return verdict;
15232
- });
15233
- },
15234
- cancel: () => {
15235
- for (const started of running.splice(0)) {
15236
- started.cancel();
15237
- }
15400
+ const levels = [];
15401
+ for (const dir of dirs) {
15402
+ const portable = loadConfigFile(path38.join(dir, PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(path38.join(dir, LEGACY_PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read);
15403
+ const portableLocal = loadConfigFile(path38.join(dir, PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(path38.join(dir, LEGACY_PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read);
15404
+ const rules = (directoryRules?.config.rules ?? []).map((rule, index) => ({ rule, index })).filter(({ rule }) => normaliseRulePath(rule.path, params.home) === dir).map(({ rule, index }) => {
15405
+ const entryOrder = directoryRules?.ruleEntryOrders[index];
15406
+ return {
15407
+ rule,
15408
+ ...entryOrder === void 0 ? {} : { entryOrder },
15409
+ filepath: params.paths.directoryRulesFile
15410
+ };
15411
+ });
15412
+ if (portable === void 0 && portableLocal === void 0 && rules.length === 0) {
15413
+ continue;
15238
15414
  }
15239
- };
15240
- }
15241
- function startProbeWorker(source, data, timeoutMs, spawn3 = spawnRealWorker, startLimitMs = PROBE_WORKER_START_LIMIT_MS, wait = slicedProbeWait) {
15242
- const startLimit = performance.now() + startLimitMs;
15243
- const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
15244
- const header = new Int32Array(shared, 0, HEADER_SLOTS);
15245
- let worker;
15246
- try {
15247
- worker = spawn3(`${WORKER_PRELUDE_SOURCE}
15248
- new Function("require", ${JSON.stringify(source)})(require);`, {
15249
- eval: true,
15250
- workerData: { ...data, timeoutMs, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS, startedSlot: STARTED_SLOT, failurePrefix: PROBE_WORKER_FAILURE_PREFIX, claimSlot: CLAIM_SLOT }
15415
+ levels.push({
15416
+ dir,
15417
+ ...portable === void 0 ? {} : { portable: { config: portable.config, entryOrder: portable.entryOrder, filepath: portable.filepath } },
15418
+ ...rules.length === 0 ? {} : { rules },
15419
+ ...portableLocal === void 0 ? {} : { portableLocal: { config: portableLocal.config, entryOrder: portableLocal.entryOrder, filepath: portableLocal.filepath } }
15251
15420
  });
15252
- } catch (error) {
15253
- const reason = `${PROBE_WORKER_FAILURE_PREFIX}the worker could not be started: ${error instanceof Error ? error.message : String(error)}`;
15254
- return { verdict: () => ({ ok: false, reason }), cancel: () => void 0 };
15255
15421
  }
15256
- worker.on("error", (error) => {
15257
- if (Atomics.compareExchange(header, CLAIM_SLOT, 0, 1) !== 0) {
15258
- return;
15259
- }
15260
- const bytes = Buffer.from(PROBE_WORKER_FAILURE_PREFIX + error.message, "utf8").subarray(0, REASON_BYTES);
15261
- new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES).set(bytes);
15262
- Atomics.store(header, 1, bytes.length);
15263
- Atomics.store(header, 0, VERDICT_FAILED);
15264
- Atomics.store(header, STARTED_SLOT, 1);
15265
- });
15266
- worker.unref();
15267
- return {
15268
- verdict: () => {
15269
- try {
15270
- wait(header, STARTED_SLOT, WORKER_NOT_STARTED, Math.max(0, startLimit - performance.now()));
15271
- if (Atomics.load(header, STARTED_SLOT) === WORKER_NOT_STARTED && Atomics.load(header, 0) === VERDICT_PENDING) {
15272
- return { ok: false, reason: `the probe worker did not start within ${String(startLimitMs)}ms` };
15273
- }
15274
- wait(header, 0, VERDICT_PENDING, timeoutMs + PROBE_WAIT_MARGIN_MS);
15275
- const verdict = Atomics.load(header, 0);
15276
- if (verdict === VERDICT_PENDING) {
15277
- return { ok: false, reason: `the probe did not finish within ${String(timeoutMs + PROBE_WAIT_MARGIN_MS)}ms` };
15278
- }
15279
- if (verdict === VERDICT_OK) {
15280
- return { ok: true };
15281
- }
15282
- const length = Atomics.load(header, 1);
15283
- return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
15284
- } finally {
15285
- void worker.terminate();
15422
+ const input = {
15423
+ home: params.home,
15424
+ ...globalConfig === void 0 ? {} : { globalConfig: { config: globalConfig.config, entryOrder: globalConfig.entryOrder, filepath: globalConfig.filepath } },
15425
+ ...params.baseConfigProfile === void 0 ? {} : { baseConfigProfile: params.baseConfigProfile },
15426
+ loadProfile,
15427
+ levels,
15428
+ ...params.cliOverride === void 0 ? {} : { cliOverride: params.cliOverride }
15429
+ };
15430
+ return { input, ...globalConfig === void 0 ? {} : { globalConfig: globalConfig.config } };
15431
+ }
15432
+ function readDirectorySelections(loaded) {
15433
+ let identity;
15434
+ let configProfile;
15435
+ for (const level of loaded.input.levels ?? []) {
15436
+ for (const source of [level.portable?.config, ...(level.rules ?? []).map((entry) => entry.rule), level.portableLocal?.config]) {
15437
+ if (source === void 0) {
15438
+ continue;
15439
+ }
15440
+ if (source.identity !== void 0) {
15441
+ identity = source.identity;
15442
+ }
15443
+ if (source.configProfile !== void 0) {
15444
+ configProfile = source.configProfile;
15286
15445
  }
15287
- },
15288
- cancel: () => {
15289
- void worker.terminate();
15290
15446
  }
15291
- };
15447
+ }
15448
+ return { ...identity === void 0 ? {} : { identity }, ...configProfile === void 0 ? {} : { configProfile } };
15292
15449
  }
15293
- var PROBE_TIMEOUT_MS, PROBE_WAIT_MARGIN_MS, REASON_BYTES, HEADER_SLOTS, STARTED_SLOT, CLAIM_SLOT, PROBE_WORKER_START_LIMIT_MS, STARTED_SIGNAL_SOURCE, PROBE_WORKER_FAILURE_PREFIX, INT32_BYTES, VERDICT_PENDING, WORKER_NOT_STARTED, VERDICT_OK, VERDICT_FAILED, WORKER_PRELUDE_SOURCE, PROBE_SOURCE, CATALOGUE_REQUEST_SOURCE, realProbeWorkers, ACCEPT_PROBE_SOURCE, PROBE_PORT_SHARE_DENOMINATOR, MAX_CONCURRENT_PROBES, PORT_BASE_SPREAD, processPortBase, targetKey, PROBE_WAIT_SLICE_MS, slicedProbeWait, spawnRealWorker;
15294
- var init_probe = __esm({
15295
- "src/frontdoor/probe.ts"() {
15450
+ var PORTABLE_CONFIG_FILENAME, PORTABLE_LOCAL_CONFIG_FILENAME;
15451
+ var init_cascade = __esm({
15452
+ "src/launcher/cascade.ts"() {
15296
15453
  "use strict";
15297
- init_processRole();
15298
- init_connectEffects();
15299
- init_doorDial();
15300
- PROBE_TIMEOUT_MS = 2e3;
15301
- PROBE_WAIT_MARGIN_MS = 1e3;
15302
- REASON_BYTES = 1024;
15303
- HEADER_SLOTS = 4;
15304
- STARTED_SLOT = 2;
15305
- CLAIM_SLOT = 3;
15306
- PROBE_WORKER_START_LIMIT_MS = 1e4;
15307
- STARTED_SIGNAL_SOURCE = "Atomics.store(new Int32Array(workerData.shared, 0, workerData.headerSlots), workerData.startedSlot, 1); Atomics.notify(new Int32Array(workerData.shared, 0, workerData.headerSlots), workerData.startedSlot);";
15308
- PROBE_WORKER_FAILURE_PREFIX = "the probe worker failed: ";
15309
- INT32_BYTES = 4;
15310
- VERDICT_PENDING = 0;
15311
- WORKER_NOT_STARTED = 0;
15312
- VERDICT_OK = 1;
15313
- VERDICT_FAILED = 2;
15314
- WORKER_PRELUDE_SOURCE = `
15315
- (() => {
15316
- const { workerData } = require("node:worker_threads");
15317
- const header = new Int32Array(workerData.shared, 0, workerData.headerSlots);
15318
- const reason = new Uint8Array(workerData.shared, workerData.headerSlots * 4);
15319
- globalThis.finishProbe = (verdict, message) => {
15320
- try {
15321
- const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
15322
- if (Atomics.compareExchange(header, workerData.claimSlot, 0, 1) === 0) {
15323
- reason.set(bytes);
15324
- Atomics.store(header, 1, bytes.length);
15325
- Atomics.store(header, 0, verdict);
15326
- }
15327
- } finally {
15328
- Atomics.notify(header, 0);
15454
+ init_load();
15455
+ init_schema();
15456
+ init_pathNorm();
15457
+ init_walk();
15458
+ init_legacy();
15459
+ init_names();
15460
+ PORTABLE_CONFIG_FILENAME = ".agent-shim.json";
15461
+ PORTABLE_LOCAL_CONFIG_FILENAME = ".agent-shim.local.json";
15462
+ }
15463
+ });
15464
+
15465
+ // src/launcher/memberProvider.ts
15466
+ function unreadableFileReason(error) {
15467
+ if (error instanceof ConfigValidationError) {
15468
+ return `${error.filepath} is invalid`;
15469
+ }
15470
+ if (error instanceof ConfigFileNotJsonError) {
15471
+ return error.message.replace(/\.$/, "");
15472
+ }
15473
+ if (error instanceof LegacyProviderFileError) {
15474
+ return `${error.filePath} uses ${error.conversion.fields.join(", ")}, which a credential block replaced`;
15475
+ }
15476
+ return void 0;
15477
+ }
15478
+ function memberProviderResolver(params) {
15479
+ if (params.cliProvider === false) {
15480
+ return () => void 0;
15481
+ }
15482
+ const cliProvider = params.cliProvider;
15483
+ const identities = identityReader(params.paths.identitiesDir, params.fs);
15484
+ const cascades = /* @__PURE__ */ new Map();
15485
+ const cascadeOver = (baseConfigProfile) => {
15486
+ const cached = cascades.get(baseConfigProfile);
15487
+ if (cached !== void 0) {
15488
+ return cached;
15329
15489
  }
15490
+ const loaded = params.loadCascade(baseConfigProfile);
15491
+ cascades.set(baseConfigProfile, loaded);
15492
+ return loaded;
15330
15493
  };
15331
- const fail = (error) => {
15332
- let message;
15494
+ return (name) => {
15495
+ let declared;
15333
15496
  try {
15334
- message = workerData.failurePrefix + (error instanceof Error ? error.message : String(error));
15335
- } catch {
15336
- message = workerData.failurePrefix + "an error that cannot be described";
15497
+ declared = identities.load(name);
15498
+ } catch (error) {
15499
+ if (!(error instanceof ConfigValidationError)) {
15500
+ throw error;
15501
+ }
15337
15502
  }
15503
+ const profile = decideConfigProfile({
15504
+ env: params.env,
15505
+ ...params.cliFlagConfigProfile === void 0 ? {} : { cliFlagConfigProfile: params.cliFlagConfigProfile },
15506
+ ...params.directoryRuleConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: params.directoryRuleConfigProfile },
15507
+ ...declared?.defaultConfigProfile === void 0 ? {} : { identityDefaultConfigProfile: declared.defaultConfigProfile },
15508
+ ...params.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: params.globalDefaultConfigProfile }
15509
+ });
15510
+ const flagged = cliProvider !== void 0 && cliProvider !== "" ? cliProvider : void 0;
15511
+ let named = flagged ?? declared?.provider;
15338
15512
  try {
15339
- globalThis.finishProbe(workerData.failed, message);
15340
- } finally {
15341
- Atomics.store(header, workerData.startedSlot, 1);
15342
- Atomics.notify(header, workerData.startedSlot);
15513
+ const cascade = cascadeOver(profile.name);
15514
+ named = flagged ?? cascadeProviderName(cascade, declared?.provider);
15515
+ return selectedProviderName({
15516
+ paths: params.paths,
15517
+ port: params.fs,
15518
+ ...cliProvider === void 0 ? {} : { cliProvider },
15519
+ cascade,
15520
+ ...declared?.provider === void 0 ? {} : { identityProvider: declared.provider }
15521
+ });
15522
+ } catch (error) {
15523
+ const reason = unreadableFileReason(error);
15524
+ if (reason === void 0) {
15525
+ throw error;
15526
+ }
15527
+ return { ...named === void 0 ? {} : { named }, reason };
15343
15528
  }
15344
15529
  };
15345
- process.on("uncaughtException", fail);
15346
- process.on("unhandledRejection", fail);
15347
- // A worker that ends itself (process.exit in a probe source or a library it calls) runs this in its own thread before it goes: the waiting thread cannot hear the exit event of a worker, since its event loop is blocked on the verdict, so the worker says so itself. A verdict already published is not replaced (the writer takes the claim once).
15348
- process.on("exit", (code) => {
15349
- globalThis.finishProbe(workerData.failed, workerData.failurePrefix + "the worker exited without a verdict (exit code " + String(code) + ")");
15350
- });
15351
- })();
15352
- `;
15353
- PROBE_SOURCE = probeWorkerSource(`
15354
- const https = require("node:https");
15355
- const { port, ca, timeoutMs, ok, failed } = workerData;
15356
- const finish = finishProbe;
15357
- const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
15358
- let body = "";
15359
- response.setEncoding("utf8");
15360
- response.on("data", (chunk) => { body += chunk; });
15361
- response.on("end", () => {
15362
- if (response.statusCode === 200 && body === "ok") finish(ok, "");
15363
- else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
15364
- });
15365
- response.on("error", (error) => finish(failed, error.message));
15366
- });
15367
- // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
15368
- setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
15369
- request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
15370
- `);
15371
- CATALOGUE_REQUEST_SOURCE = probeWorkerSource(`
15372
- const https = require("node:https");
15373
- const { port, ca, token, timeoutMs, ok, failed } = workerData;
15374
- const finish = finishProbe;
15375
- const request = https.request({ host: "127.0.0.1", port, path: "/__agent-shim/orpc/rest/frontdoor/catalogues/refresh", method: "POST", headers: { authorization: "Bearer " + token }, ca: [ca], agent: false }, (response) => {
15376
- response.resume();
15377
- response.on("end", () => response.statusCode === 200 ? finish(ok, "") : finish(failed, "catalogue refresh request returned HTTP " + String(response.statusCode)));
15378
- response.on("error", (error) => finish(failed, error.message));
15530
+ }
15531
+ var init_memberProvider = __esm({
15532
+ "src/launcher/memberProvider.ts"() {
15533
+ "use strict";
15534
+ init_load();
15535
+ init_providersStore();
15536
+ init_identity2();
15537
+ }
15379
15538
  });
15380
- setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
15381
- request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
15382
- request.end();
15383
- `);
15384
- realProbeWorkers = { start: (source, data, timeoutMs) => startProbeWorker(source, data, timeoutMs) };
15385
- ACCEPT_PROBE_SOURCE = probeWorkerSource(`
15386
- const net = require("node:net");
15387
- const dns = require("node:dns");
15388
- const { host, port, portStart, portEnd, portFirst, platform, timeoutMs, ok, failed } = workerData;
15389
- const finish = finishProbe;
15390
- const SourcePortRange = ${SourcePortRange.toString()};
15391
- const createDoorLookup = ${createDoorLookup.toString()};
15392
- const sourcePortClassifier = ${sourcePortClassifier.toString()};
15393
- const doorDial = ${doorDial.toString()};
15394
- const probeAccept = ${probeAccept.toString()};
15395
- const runAcceptProbe = ${runAcceptProbe.toString()};
15396
- const startTimer = (callback, ms) => { const timer = setTimeout(callback, ms); return () => { clearTimeout(timer); }; };
15397
- runAcceptProbe({ net, dns, createDoorLookup, doorDial, probeAccept, SourcePortRange, sourcePortClassifier }, { host, port, portStart, portEnd, portFirst, platform, timeoutMs }, startTimer).then((verdict) => {
15398
- finish(verdict.ok ? ok : failed, verdict.ok ? "" : verdict.reason);
15539
+
15540
+ // src/paths.ts
15541
+ import fs12 from "node:fs";
15542
+ import os6 from "node:os";
15543
+ import path39 from "node:path";
15544
+ function resolveAgentShimHome(env = process.env, home = os6.homedir(), isDirectory = isExistingDirectory) {
15545
+ const fromEnv = env.AGENT_SHIM_HOME;
15546
+ if (fromEnv !== void 0 && fromEnv !== "") {
15547
+ return fromEnv;
15548
+ }
15549
+ const current = path39.join(home, HOME_DIRNAME);
15550
+ const legacy = path39.join(home, LEGACY_HOME_DIRNAME);
15551
+ return !isDirectory(current) && isDirectory(legacy) ? legacy : current;
15552
+ }
15553
+ function isExistingDirectory(candidate) {
15554
+ return fs12.statSync(candidate, { throwIfNoEntry: false })?.isDirectory() ?? false;
15555
+ }
15556
+ function resolveClaudeHome() {
15557
+ const fromEnv = process.env.AGENT_SHIM_CLAUDE_HOME;
15558
+ if (fromEnv !== void 0 && fromEnv !== "") {
15559
+ return fromEnv;
15560
+ }
15561
+ return path39.join(os6.homedir(), ".claude");
15562
+ }
15563
+ function buildLayoutPaths(root) {
15564
+ return {
15565
+ root,
15566
+ identitiesDir: path39.join(root, "identities"),
15567
+ configProfilesDir: path39.join(root, "config-profiles"),
15568
+ providersDir: path39.join(root, "providers"),
15569
+ providerAliasesFile: path39.join(root, "provider-aliases.json"),
15570
+ directoryRulesFile: path39.join(root, "directory-rules.json"),
15571
+ activeIdentityFile: path39.join(root, "active-identity"),
15572
+ globalConfigFile: path39.join(root, "config.json"),
15573
+ categoriesLocalFile: path39.join(root, "categories.local.json"),
15574
+ claudeShimFile: path39.join(root, "claude-shim.json"),
15575
+ headroomDir: path39.join(root, "headroom"),
15576
+ headroomStateFile: path39.join(root, "headroom", "state.json"),
15577
+ headroomRoutingFile: path39.join(root, "headroom", "routing.json"),
15578
+ headroomLegacyStateFile: path39.join(root, "headroom", "state.v2.json"),
15579
+ headroomAllowlistFile: path39.join(root, "headroom", "run", "allowlist.txt"),
15580
+ headroomSocketDir: path39.join(root, "headroom", "run"),
15581
+ headroomLockFile: path39.join(root, "headroom", "start.lock"),
15582
+ headroomSessionsDir: path39.join(root, "headroom", "sessions"),
15583
+ logsDir: path39.join(root, "logs"),
15584
+ headroomLogPath: path39.join(root, "logs", "headroom.log"),
15585
+ frontdoorDir: path39.join(root, "frontdoor"),
15586
+ frontdoorCaDir: path39.join(root, "frontdoor", "ca"),
15587
+ frontdoorCaCertFile: path39.join(root, "frontdoor", "ca", "ca.pem"),
15588
+ frontdoorCaKeyFile: path39.join(root, "frontdoor", "ca", "ca.key"),
15589
+ frontdoorCaBundlesDir: path39.join(root, "frontdoor", "ca", "bundles"),
15590
+ chatgptSignInFile: path39.join(root, "codex", "chatgpt-sign-in.json"),
15591
+ frontdoorStateFile: path39.join(root, "frontdoor", "state.json"),
15592
+ frontdoorLockFile: path39.join(root, "frontdoor", "start.lock"),
15593
+ frontdoorControlTokenFile: path39.join(root, "frontdoor", "control-token"),
15594
+ frontdoorSessionsDir: path39.join(root, "frontdoor", "sessions"),
15595
+ frontdoorDirectRecordsDir: path39.join(root, "frontdoor", "direct"),
15596
+ frontdoorDrainingDir: path39.join(root, "frontdoor", "draining"),
15597
+ frontdoorRcCredentialsDir: path39.join(root, "frontdoor", "rc-credentials"),
15598
+ frontdoorLogPath: path39.join(root, "logs", "frontdoor.log"),
15599
+ usageDir: path39.join(root, "usage"),
15600
+ usageLogDir: path39.join(root, "usage", "log"),
15601
+ usageSnapshotsDir: path39.join(root, "usage", "snapshots"),
15602
+ statuslineDir: path39.join(root, "statusline"),
15603
+ catalogueDir: path39.join(root, "catalogues"),
15604
+ usagePicksFile: path39.join(root, "usage", "picks.json"),
15605
+ usageAnchorsFile: path39.join(root, "usage", "anchors.json"),
15606
+ usageJobsFile: path39.join(root, "usage", "jobs.json"),
15607
+ jobLogsDir: path39.join(root, "logs", "jobs"),
15608
+ identityRenamesDir: path39.join(root, "identity-renames"),
15609
+ identityNameRenamesDir: path39.join(root, "identity-name-renames"),
15610
+ launchesDir: path39.join(root, "launches"),
15611
+ superviseDir: path39.join(root, "supervise"),
15612
+ modelMovesDir: path39.join(root, "model-moves"),
15613
+ mcpPermissionsFile: path39.join(root, "mcp", "permissions.json")
15614
+ };
15615
+ }
15616
+ function resolveLayoutPaths() {
15617
+ return buildLayoutPaths(resolveAgentShimHome());
15618
+ }
15619
+ var init_paths = __esm({
15620
+ "src/paths.ts"() {
15621
+ "use strict";
15622
+ init_legacy();
15623
+ }
15399
15624
  });
15400
- `);
15401
- PROBE_PORT_SHARE_DENOMINATOR = 100;
15402
- MAX_CONCURRENT_PROBES = Math.max(1, Math.floor(DOOR_SOURCE_PORT_COUNT / PROBE_PORT_SHARE_DENOMINATOR));
15403
- PORT_BASE_SPREAD = 389;
15404
- processPortBase = () => process.pid * PORT_BASE_SPREAD % DOOR_SOURCE_PORT_COUNT;
15405
- targetKey = (target) => `${target.host}\0${String(target.port)}\0${String(target.timeoutMs)}`;
15406
- PROBE_WAIT_SLICE_MS = 1e3;
15407
- slicedProbeWait = (header, index, value, timeoutMs) => {
15408
- const end = performance.now() + timeoutMs;
15409
- for (; ; ) {
15410
- noteBlockingStep();
15411
- const left = end - performance.now();
15412
- if (left <= 0) {
15413
- return "timed-out";
15625
+
15626
+ // src/storedCatalogue.ts
15627
+ import path41 from "node:path";
15628
+ function catalogueReadFault(error) {
15629
+ if (error instanceof UnreadableCatalogueError) {
15630
+ return error.fault;
15631
+ }
15632
+ const code = error instanceof Error && "code" in error ? error.code : void 0;
15633
+ return typeof code === "string" && /^[A-Z0-9_]{1,32}$/u.test(code) ? code : error instanceof Error ? error.name : "an error";
15634
+ }
15635
+ function catalogueStatusFile(paths, owner, name) {
15636
+ return path41.join(path41.dirname(catalogueCachePath(paths, name, owner.pid, owner.generation)), `${name}.status.json`);
15637
+ }
15638
+ function catalogueFailureFile(paths, owner, name) {
15639
+ return path41.join(path41.dirname(catalogueCachePath(paths, name, owner.pid, owner.generation)), "failures", `${name}.json`);
15640
+ }
15641
+ var UnreadableCatalogueError, skipUnreadableCatalogue, TolerantReader, StoredCatalogue;
15642
+ var init_storedCatalogue = __esm({
15643
+ "src/storedCatalogue.ts"() {
15644
+ "use strict";
15645
+ init_providerCatalogue();
15646
+ UnreadableCatalogueError = class extends Error {
15647
+ fault;
15648
+ constructor(fault) {
15649
+ super(`stored catalogue cannot be read (${fault})`);
15650
+ this.name = "UnreadableCatalogueError";
15651
+ this.fault = fault;
15652
+ }
15653
+ };
15654
+ skipUnreadableCatalogue = () => void 0;
15655
+ TolerantReader = class {
15656
+ #read;
15657
+ #onUnreadable;
15658
+ constructor(read, onUnreadable) {
15659
+ this.#read = read;
15660
+ this.#onUnreadable = onUnreadable;
15661
+ }
15662
+ /** The text of `file`, `undefined` when it is absent or unreadable (`onUnreadable` returned). */
15663
+ read(file) {
15664
+ try {
15665
+ return this.#read(file);
15666
+ } catch (error) {
15667
+ this.#onUnreadable(catalogueReadFault(error));
15668
+ return void 0;
15414
15669
  }
15415
- const answer = Atomics.wait(header, index, value, Math.min(left, PROBE_WAIT_SLICE_MS));
15416
- if (answer !== "timed-out") {
15417
- return answer;
15670
+ }
15671
+ /** `take()`, `undefined` when it throws: for a stat of a stored file, which fails the way a read does. The fault is reported as a read's is. */
15672
+ attempt(take) {
15673
+ try {
15674
+ return take();
15675
+ } catch (error) {
15676
+ this.#onUnreadable(catalogueReadFault(error));
15677
+ return void 0;
15418
15678
  }
15419
15679
  }
15420
15680
  };
15421
- spawnRealWorker = (source, options) => new Worker(source, options);
15681
+ StoredCatalogue = class {
15682
+ #paths;
15683
+ #reader;
15684
+ constructor(paths, reader) {
15685
+ this.#paths = paths;
15686
+ this.#reader = reader;
15687
+ }
15688
+ /** The catalogue file of `name`: a Codex provider's is in the directory of the supervisor generation that fetched it (`owner`), an `http` provider's is shared. */
15689
+ cacheText(name, owner) {
15690
+ return this.#reader.read(catalogueCachePath(this.#paths, name, owner?.pid, owner?.generation));
15691
+ }
15692
+ /** The file holding the digest of the settings an `http` provider's catalogue was fetched under. */
15693
+ digestText(name) {
15694
+ return this.#reader.read(catalogueSettingsPath(this.#paths, name));
15695
+ }
15696
+ /** The non-secret binding between a Codex catalogue and the login that fetched it. */
15697
+ bindingText(name, owner) {
15698
+ return this.#reader.read(catalogueBindingPath(this.#paths, name, owner?.pid, owner?.generation));
15699
+ }
15700
+ /** The refresh status the supervisor generation `owner` recorded for `name`. */
15701
+ statusText(owner, name) {
15702
+ return this.#reader.read(catalogueStatusFile(this.#paths, owner, name));
15703
+ }
15704
+ /** The record of why `name`'s last refresh failed in the supervisor generation `owner`. */
15705
+ failureText(owner, name) {
15706
+ return this.#reader.read(catalogueFailureFile(this.#paths, owner, name));
15707
+ }
15708
+ /** What identifies the stored files of an `http` provider's catalogue (the catalogue and its digest) as they are now, or `undefined` when either cannot be named (it cannot be statted, or `revisionOf` knows no revision of it): the key a parse of them is kept under. */
15709
+ revision(name, revisionOf) {
15710
+ const cacheRevision = this.#reader.attempt(() => revisionOf(catalogueCachePath(this.#paths, name)));
15711
+ const digestRevision = this.#reader.attempt(() => revisionOf(catalogueSettingsPath(this.#paths, name)));
15712
+ return cacheRevision === void 0 || digestRevision === void 0 ? void 0 : `${cacheRevision}\0${digestRevision}`;
15713
+ }
15714
+ };
15422
15715
  }
15423
15716
  });
15424
15717
 
15425
- // src/providerReachability.ts
15426
- function providerConnectTimeoutMs(provider) {
15427
- return provider.connectTimeoutMs ?? DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS;
15428
- }
15429
- function couldNotConnectMessage(subject, baseUrl, reason) {
15430
- return `${subject} could not connect to ${displayBaseUrl(baseUrl)}: ${reason.trim() === "" ? "the connection failed with no reason given" : reason}`;
15431
- }
15432
- function probeProviderReachability(name, provider, probe) {
15433
- const verdict = probe(provider.baseUrl, providerConnectTimeoutMs(provider));
15434
- return verdict.ok ? { ok: true } : { ok: false, message: couldNotConnectMessage(`provider ${name}`, provider.baseUrl, verdict.reason) };
15718
+ // src/tolerantReaders.ts
15719
+ function skippingReader(fs17) {
15720
+ return new TolerantReader((file) => fs17.readFileUtf8(file), skipUnreadableCatalogue);
15435
15721
  }
15436
- function startProviderReachability(name, provider, start) {
15437
- if (start === void 0 || !isHttpProvider(provider)) {
15722
+ var init_tolerantReaders = __esm({
15723
+ "src/tolerantReaders.ts"() {
15724
+ "use strict";
15725
+ init_storedCatalogue();
15726
+ }
15727
+ });
15728
+
15729
+ // src/frontdoor/catalogueState.ts
15730
+ import { z as z32 } from "zod";
15731
+ function readCatalogueFailure(fs17, paths, pid, generation, name) {
15732
+ const raw = new StoredCatalogue(paths, skippingReader(fs17)).failureText({ pid, generation }, name);
15733
+ if (raw === void 0) return void 0;
15734
+ try {
15735
+ const value = z32.strictObject({ reason: z32.string().max(CATALOGUE_FAILURE_REASON_MAX_CHARS), redirected: z32.literal(true).optional(), settings: z32.string().optional() }).safeParse(JSON.parse(raw));
15736
+ return value.success ? { reason: value.data.reason, redirected: value.data.redirected === true, settings: value.data.settings } : void 0;
15737
+ } catch {
15438
15738
  return void 0;
15439
15739
  }
15440
- const started = start(provider.baseUrl, providerConnectTimeoutMs(provider));
15441
- return {
15442
- cancel: started.cancel,
15443
- line: () => {
15444
- const verdict = started.verdict();
15445
- return verdict.ok ? void 0 : couldNotConnectMessage(`provider ${name}`, provider.baseUrl, verdict.reason);
15446
- }
15447
- };
15448
15740
  }
15449
- function probeProviderReachabilities(providers, probe) {
15450
- const http3 = providers.flatMap((entry) => isHttpProvider(entry.provider) ? [{ name: entry.name, provider: entry.provider }] : []);
15451
- const verdicts = probe(http3.map((entry) => ({ baseUrl: entry.provider.baseUrl, timeoutMs: providerConnectTimeoutMs(entry.provider) })));
15452
- const lines = /* @__PURE__ */ new Map();
15453
- http3.forEach((entry, index) => {
15454
- const verdict = verdicts[index];
15455
- if (verdict === void 0) {
15456
- throw new Error("the batch probe answered fewer verdicts than it was given base URLs");
15457
- }
15458
- if (!verdict.ok) {
15459
- lines.set(entry.name, couldNotConnectMessage(`provider ${entry.name}`, entry.provider.baseUrl, verdict.reason));
15460
- }
15461
- });
15462
- return lines;
15741
+ function readCatalogueStatus(fs17, paths, pid, generation, name) {
15742
+ const raw = new StoredCatalogue(paths, skippingReader(fs17)).statusText({ pid, generation }, name);
15743
+ if (raw === void 0) return void 0;
15744
+ try {
15745
+ const value = z32.strictObject({ status: z32.enum(["running", "ready", "failed"]), fingerprint: z32.string().min(1).optional(), recordedAt: z32.number().optional() }).safeParse(JSON.parse(raw));
15746
+ return value.success ? value.data : void 0;
15747
+ } catch {
15748
+ return void 0;
15749
+ }
15463
15750
  }
15464
- var TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS, CONNECT_SYN_RETRANSMISSIONS_TOLERATED, DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS, startBaseUrlBatchProbe, realBaseUrlBatchProbe, realStartBaseUrlProbe, realBaseUrlProbe;
15465
- var init_providerReachability = __esm({
15466
- "src/providerReachability.ts"() {
15751
+ var CATALOGUE_FAILURE_REASON_MAX_CHARS;
15752
+ var init_catalogueState = __esm({
15753
+ "src/frontdoor/catalogueState.ts"() {
15467
15754
  "use strict";
15468
- init_schema();
15469
- init_baseUrlDial();
15470
- init_baseUrlDisplay();
15471
- init_probe();
15472
- TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS = 1e3;
15473
- CONNECT_SYN_RETRANSMISSIONS_TOLERATED = 2;
15474
- DEFAULT_PROVIDER_CONNECT_TIMEOUT_MS = TCP_INITIAL_RETRANSMISSION_TIMEOUT_MS * (2 ** (CONNECT_SYN_RETRANSMISSIONS_TOLERATED + 1) - 1);
15475
- startBaseUrlBatchProbe = (targets, workers) => {
15476
- const started = startAddressProbes(targets.map((target) => ({ ...dialTargetOf(target.baseUrl), timeoutMs: target.timeoutMs })), workers);
15477
- return { cancel: started.cancel, verdicts: started.settle };
15478
- };
15479
- realBaseUrlBatchProbe = (targets, workers) => startBaseUrlBatchProbe(targets, workers).verdicts();
15480
- realStartBaseUrlProbe = (baseUrl, timeoutMs) => {
15481
- const started = startBaseUrlBatchProbe([{ baseUrl, timeoutMs }]);
15482
- return {
15483
- cancel: started.cancel,
15484
- verdict: () => {
15485
- const [verdict] = started.verdicts();
15486
- if (verdict === void 0) {
15487
- throw new Error("the batch probe answered no verdict for one base URL");
15488
- }
15489
- return verdict;
15490
- }
15491
- };
15492
- };
15493
- realBaseUrlProbe = (baseUrl, timeoutMs) => realStartBaseUrlProbe(baseUrl, timeoutMs).verdict();
15755
+ init_storedCatalogue();
15756
+ init_tolerantReaders();
15757
+ CATALOGUE_FAILURE_REASON_MAX_CHARS = 600;
15494
15758
  }
15495
15759
  });
15496
15760
 
15497
15761
  // src/codex/auth.ts
15498
- import { z as z32 } from "zod";
15762
+ import { z as z33 } from "zod";
15499
15763
  var AuthFileSchema, TokenGrantSchema, CodexAuthError;
15500
15764
  var init_auth = __esm({
15501
15765
  "src/codex/auth.ts"() {
15502
15766
  "use strict";
15503
- AuthFileSchema = z32.looseObject({
15504
- tokens: z32.looseObject({
15505
- access_token: z32.string().optional(),
15506
- refresh_token: z32.string().optional(),
15507
- id_token: z32.string().optional(),
15508
- account_id: z32.string().optional()
15767
+ AuthFileSchema = z33.looseObject({
15768
+ tokens: z33.looseObject({
15769
+ access_token: z33.string().optional(),
15770
+ refresh_token: z33.string().optional(),
15771
+ id_token: z33.string().optional(),
15772
+ account_id: z33.string().optional()
15509
15773
  }).nullish(),
15510
- last_refresh: z32.string().optional()
15774
+ last_refresh: z33.string().optional()
15511
15775
  });
15512
- TokenGrantSchema = z32.looseObject({
15513
- access_token: z32.string().min(1).optional(),
15514
- refresh_token: z32.string().min(1).optional(),
15515
- id_token: z32.string().min(1).optional(),
15516
- account_id: z32.string().min(1).optional()
15776
+ TokenGrantSchema = z33.looseObject({
15777
+ access_token: z33.string().min(1).optional(),
15778
+ refresh_token: z33.string().min(1).optional(),
15779
+ id_token: z33.string().min(1).optional(),
15780
+ account_id: z33.string().min(1).optional()
15517
15781
  });
15518
15782
  CodexAuthError = class extends Error {
15519
15783
  constructor(message) {
@@ -15525,7 +15789,7 @@ var init_auth = __esm({
15525
15789
  });
15526
15790
 
15527
15791
  // src/codex/siwc.ts
15528
- import { z as z33 } from "zod";
15792
+ import { z as z34 } from "zod";
15529
15793
  var SIWC_RESOURCE, SIWC_RESPONSES_URL, SIWC_PLAN_SCOPE, TokenResponseSchema, JwtHeaderSchema, IdTokenClaimsSchema, JwksSchema;
15530
15794
  var init_siwc = __esm({
15531
15795
  "src/codex/siwc.ts"() {
@@ -15533,28 +15797,28 @@ var init_siwc = __esm({
15533
15797
  SIWC_RESOURCE = "https://api.openai.com/v1";
15534
15798
  SIWC_RESPONSES_URL = `${SIWC_RESOURCE}/responses`;
15535
15799
  SIWC_PLAN_SCOPE = "chatgpt.tokens.use.direct";
15536
- TokenResponseSchema = z33.looseObject({
15537
- access_token: z33.string().min(1),
15538
- refresh_token: z33.string().min(1).optional(),
15539
- id_token: z33.string().min(1).optional(),
15540
- expires_in: z33.number().positive(),
15541
- scope: z33.string().optional()
15800
+ TokenResponseSchema = z34.looseObject({
15801
+ access_token: z34.string().min(1),
15802
+ refresh_token: z34.string().min(1).optional(),
15803
+ id_token: z34.string().min(1).optional(),
15804
+ expires_in: z34.number().positive(),
15805
+ scope: z34.string().optional()
15542
15806
  });
15543
- JwtHeaderSchema = z33.looseObject({ alg: z33.string(), kid: z33.string().optional() });
15544
- IdTokenClaimsSchema = z33.looseObject({
15545
- iss: z33.string(),
15546
- sub: z33.string().min(1),
15547
- aud: z33.union([z33.string(), z33.array(z33.string())]),
15548
- exp: z33.number(),
15549
- nonce: z33.string().optional(),
15550
- email: z33.string().optional()
15807
+ JwtHeaderSchema = z34.looseObject({ alg: z34.string(), kid: z34.string().optional() });
15808
+ IdTokenClaimsSchema = z34.looseObject({
15809
+ iss: z34.string(),
15810
+ sub: z34.string().min(1),
15811
+ aud: z34.union([z34.string(), z34.array(z34.string())]),
15812
+ exp: z34.number(),
15813
+ nonce: z34.string().optional(),
15814
+ email: z34.string().optional()
15551
15815
  });
15552
- JwksSchema = z33.object({ keys: z33.array(z33.looseObject({ kid: z33.string().optional(), kty: z33.string() })) });
15816
+ JwksSchema = z34.object({ keys: z34.array(z34.looseObject({ kid: z34.string().optional(), kty: z34.string() })) });
15553
15817
  }
15554
15818
  });
15555
15819
 
15556
15820
  // src/codex/siwcStore.ts
15557
- import { z as z34 } from "zod";
15821
+ import { z as z35 } from "zod";
15558
15822
  function parseSiwcFile(raw, filePath) {
15559
15823
  let json;
15560
15824
  try {
@@ -15574,18 +15838,18 @@ var init_siwcStore = __esm({
15574
15838
  "use strict";
15575
15839
  init_auth();
15576
15840
  init_siwc();
15577
- SiwcGrantSchema = z34.strictObject({
15578
- clientId: z34.string().min(1),
15579
- sub: z34.string().min(1),
15580
- email: z34.string().optional(),
15581
- idToken: z34.string().min(1),
15582
- accessToken: z34.string().min(1),
15583
- refreshToken: z34.string().min(1),
15584
- scopes: z34.array(z34.string()).readonly(),
15841
+ SiwcGrantSchema = z35.strictObject({
15842
+ clientId: z35.string().min(1),
15843
+ sub: z35.string().min(1),
15844
+ email: z35.string().optional(),
15845
+ idToken: z35.string().min(1),
15846
+ accessToken: z35.string().min(1),
15847
+ refreshToken: z35.string().min(1),
15848
+ scopes: z35.array(z35.string()).readonly(),
15585
15849
  /** When the access token stops working, in milliseconds since the epoch. */
15586
- expiresAt: z34.number()
15850
+ expiresAt: z35.number()
15587
15851
  });
15588
- SiwcFileSchema = z34.strictObject({ registeredClientId: z34.string().min(1).optional(), grant: SiwcGrantSchema.optional() });
15852
+ SiwcFileSchema = z35.strictObject({ registeredClientId: z35.string().min(1).optional(), grant: SiwcGrantSchema.optional() });
15589
15853
  }
15590
15854
  });
15591
15855
 
@@ -15643,9 +15907,9 @@ var init_modelsStore = __esm({
15643
15907
  });
15644
15908
 
15645
15909
  // src/codex/catalogueCredential.ts
15646
- import { createHash as createHash10 } from "node:crypto";
15647
- import path41 from "node:path";
15648
- import { z as z35 } from "zod";
15910
+ import { createHash as createHash11 } from "node:crypto";
15911
+ import path42 from "node:path";
15912
+ import { z as z36 } from "zod";
15649
15913
  function parseCatalogueBinding(raw) {
15650
15914
  if (raw === void 0) return void 0;
15651
15915
  try {
@@ -15656,7 +15920,7 @@ function parseCatalogueBinding(raw) {
15656
15920
  }
15657
15921
  }
15658
15922
  function catalogueCredentialFingerprint(cli, token, accountId) {
15659
- return createHash10("sha256").update(JSON.stringify([cli, token, accountId])).digest("hex");
15923
+ return createHash11("sha256").update(JSON.stringify([cli, token, accountId])).digest("hex");
15660
15924
  }
15661
15925
  function cliCatalogueFingerprint(raw) {
15662
15926
  if (raw === void 0) return void 0;
@@ -15675,33 +15939,18 @@ function signInCatalogueFingerprint(raw, filePath) {
15675
15939
  const grant = parseSiwcFile(raw, filePath).grant;
15676
15940
  return grant === void 0 ? void 0 : catalogueCredentialFingerprint(false, grant.accessToken, void 0);
15677
15941
  }
15678
- function savedCatalogueFingerprint(provider, paths, env, home, read) {
15679
- if (provider.codex?.login === "chatgpt-sign-in") return signInCatalogueFingerprint(read(paths.chatgptSignInFile), paths.chatgptSignInFile);
15942
+ function savedCatalogueFingerprint(provider, paths, env, home, reader) {
15943
+ if (provider.codex?.login === "chatgpt-sign-in") return signInCatalogueFingerprint(reader.read(paths.chatgptSignInFile), paths.chatgptSignInFile);
15680
15944
  const configuredHome = env.CODEX_HOME;
15681
- const codexHome = configuredHome === void 0 || configuredHome === "" ? path41.join(home, ".codex") : configuredHome;
15682
- return cliCatalogueFingerprint(read(path41.join(codexHome, "auth.json")));
15945
+ const codexHome = configuredHome === void 0 || configuredHome === "" ? path42.join(home, ".codex") : configuredHome;
15946
+ return cliCatalogueFingerprint(reader.read(path42.join(codexHome, "auth.json")));
15683
15947
  }
15684
15948
  var CatalogueBindingSchema;
15685
15949
  var init_catalogueCredential = __esm({
15686
15950
  "src/codex/catalogueCredential.ts"() {
15687
15951
  "use strict";
15688
15952
  init_siwcStore();
15689
- CatalogueBindingSchema = z35.strictObject({ fingerprint: z35.string().min(1), source: z35.string().min(1), revision: z35.string().min(1) });
15690
- }
15691
- });
15692
-
15693
- // src/models/tiers.ts
15694
- var TIER_ENV_VARIABLES;
15695
- var init_tiers = __esm({
15696
- "src/models/tiers.ts"() {
15697
- "use strict";
15698
- init_schema();
15699
- TIER_ENV_VARIABLES = Object.freeze({
15700
- fable: "ANTHROPIC_DEFAULT_FABLE_MODEL",
15701
- opus: "ANTHROPIC_DEFAULT_OPUS_MODEL",
15702
- sonnet: "ANTHROPIC_DEFAULT_SONNET_MODEL",
15703
- haiku: "ANTHROPIC_DEFAULT_HAIKU_MODEL"
15704
- });
15953
+ CatalogueBindingSchema = z36.strictObject({ fingerprint: z36.string().min(1), source: z36.string().min(1), revision: z36.string().min(1) });
15705
15954
  }
15706
15955
  });
15707
15956
 
@@ -15752,64 +16001,64 @@ var init_signatures = __esm({
15752
16001
  });
15753
16002
 
15754
16003
  // src/codex/anthropic.ts
15755
- import { z as z36 } from "zod";
16004
+ import { z as z37 } from "zod";
15756
16005
  var TextBlockSchema, Base64ImageSourceSchema, UrlImageSourceSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultContentBlockSchema, ToolResultBlockSchema, OtherBlockSchema, ContentBlockSchema, MessageSchema, ToolSchema, ToolChoiceSchema, SystemSchema, MessagesRequestSchema, CountTokensRequestSchema;
15757
16006
  var init_anthropic = __esm({
15758
16007
  "src/codex/anthropic.ts"() {
15759
16008
  "use strict";
15760
- TextBlockSchema = z36.looseObject({ type: z36.literal("text"), text: z36.string() });
15761
- Base64ImageSourceSchema = z36.looseObject({ type: z36.literal("base64"), media_type: z36.string().min(1), data: z36.string() });
15762
- UrlImageSourceSchema = z36.looseObject({ type: z36.literal("url"), url: z36.string().min(1) });
15763
- ImageBlockSchema = z36.looseObject({
15764
- type: z36.literal("image"),
15765
- source: z36.union([Base64ImageSourceSchema, UrlImageSourceSchema])
16009
+ TextBlockSchema = z37.looseObject({ type: z37.literal("text"), text: z37.string() });
16010
+ Base64ImageSourceSchema = z37.looseObject({ type: z37.literal("base64"), media_type: z37.string().min(1), data: z37.string() });
16011
+ UrlImageSourceSchema = z37.looseObject({ type: z37.literal("url"), url: z37.string().min(1) });
16012
+ ImageBlockSchema = z37.looseObject({
16013
+ type: z37.literal("image"),
16014
+ source: z37.union([Base64ImageSourceSchema, UrlImageSourceSchema])
15766
16015
  });
15767
- ToolUseBlockSchema = z36.looseObject({
15768
- type: z36.literal("tool_use"),
15769
- id: z36.string().min(1),
15770
- name: z36.string().min(1),
15771
- input: z36.unknown()
16016
+ ToolUseBlockSchema = z37.looseObject({
16017
+ type: z37.literal("tool_use"),
16018
+ id: z37.string().min(1),
16019
+ name: z37.string().min(1),
16020
+ input: z37.unknown()
15772
16021
  });
15773
- ToolResultContentBlockSchema = z36.union([TextBlockSchema, z36.looseObject({ type: z36.string() })]);
15774
- ToolResultBlockSchema = z36.looseObject({
15775
- type: z36.literal("tool_result"),
15776
- tool_use_id: z36.string().min(1),
15777
- content: z36.union([z36.string(), z36.array(ToolResultContentBlockSchema)]).optional()
16022
+ ToolResultContentBlockSchema = z37.union([TextBlockSchema, z37.looseObject({ type: z37.string() })]);
16023
+ ToolResultBlockSchema = z37.looseObject({
16024
+ type: z37.literal("tool_result"),
16025
+ tool_use_id: z37.string().min(1),
16026
+ content: z37.union([z37.string(), z37.array(ToolResultContentBlockSchema)]).optional()
15778
16027
  });
15779
- OtherBlockSchema = z36.looseObject({ type: z36.string() });
15780
- ContentBlockSchema = z36.union([TextBlockSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultBlockSchema, OtherBlockSchema]);
15781
- MessageSchema = z36.looseObject({
15782
- role: z36.enum(["user", "assistant", "system"]),
15783
- content: z36.union([z36.string(), z36.array(ContentBlockSchema)])
16028
+ OtherBlockSchema = z37.looseObject({ type: z37.string() });
16029
+ ContentBlockSchema = z37.union([TextBlockSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultBlockSchema, OtherBlockSchema]);
16030
+ MessageSchema = z37.looseObject({
16031
+ role: z37.enum(["user", "assistant", "system"]),
16032
+ content: z37.union([z37.string(), z37.array(ContentBlockSchema)])
15784
16033
  });
15785
- ToolSchema = z36.looseObject({
15786
- name: z36.string().min(1),
15787
- description: z36.string().optional(),
15788
- input_schema: z36.record(z36.string(), z36.unknown()).optional(),
15789
- allowed_domains: z36.array(z36.string()).optional(),
15790
- blocked_domains: z36.array(z36.string()).optional()
16034
+ ToolSchema = z37.looseObject({
16035
+ name: z37.string().min(1),
16036
+ description: z37.string().optional(),
16037
+ input_schema: z37.record(z37.string(), z37.unknown()).optional(),
16038
+ allowed_domains: z37.array(z37.string()).optional(),
16039
+ blocked_domains: z37.array(z37.string()).optional()
15791
16040
  });
15792
- ToolChoiceSchema = z36.union([
15793
- z36.looseObject({ type: z36.enum(["auto", "none", "any"]) }),
15794
- z36.looseObject({ type: z36.literal("tool"), name: z36.string().min(1) })
16041
+ ToolChoiceSchema = z37.union([
16042
+ z37.looseObject({ type: z37.enum(["auto", "none", "any"]) }),
16043
+ z37.looseObject({ type: z37.literal("tool"), name: z37.string().min(1) })
15795
16044
  ]);
15796
- SystemSchema = z36.union([z36.string(), z36.array(z36.union([TextBlockSchema, OtherBlockSchema]))]);
15797
- MessagesRequestSchema = z36.looseObject({
15798
- model: z36.string().optional(),
16045
+ SystemSchema = z37.union([z37.string(), z37.array(z37.union([TextBlockSchema, OtherBlockSchema]))]);
16046
+ MessagesRequestSchema = z37.looseObject({
16047
+ model: z37.string().optional(),
15799
16048
  system: SystemSchema.optional(),
15800
- messages: z36.array(MessageSchema),
15801
- tools: z36.array(ToolSchema).optional(),
16049
+ messages: z37.array(MessageSchema),
16050
+ tools: z37.array(ToolSchema).optional(),
15802
16051
  tool_choice: ToolChoiceSchema.optional(),
15803
- stream: z36.boolean().optional(),
16052
+ stream: z37.boolean().optional(),
15804
16053
  /** `user_id` is stable for one Claude Code session and differs between sessions, which is what makes it the right key for both the backend's prompt cache and its session header. */
15805
- metadata: z36.looseObject({ user_id: z36.string().optional() }).optional(),
16054
+ metadata: z37.looseObject({ user_id: z37.string().optional() }).optional(),
15806
16055
  /** Claude Code's effort setting. Any string is accepted; the translator honours only the levels the backend understands. */
15807
- output_config: z36.looseObject({ effort: z36.string().optional(), format: z36.object({ type: z36.literal("json_schema"), schema: z36.record(z36.string(), z36.unknown()) }).optional() }).optional()
16056
+ output_config: z37.looseObject({ effort: z37.string().optional(), format: z37.object({ type: z37.literal("json_schema"), schema: z37.record(z37.string(), z37.unknown()) }).optional() }).optional()
15808
16057
  });
15809
- CountTokensRequestSchema = z36.looseObject({
15810
- system: z36.unknown().optional(),
15811
- messages: z36.unknown().optional(),
15812
- tools: z36.unknown().optional()
16058
+ CountTokensRequestSchema = z37.looseObject({
16059
+ system: z37.unknown().optional(),
16060
+ messages: z37.unknown().optional(),
16061
+ tools: z37.unknown().optional()
15813
16062
  });
15814
16063
  }
15815
16064
  });
@@ -15858,7 +16107,7 @@ var AUTO_ALIAS;
15858
16107
  var init_translate = __esm({
15859
16108
  "src/antigravity/translate.ts"() {
15860
16109
  "use strict";
15861
- init_identity2();
16110
+ init_identity();
15862
16111
  init_tiers();
15863
16112
  init_engine();
15864
16113
  init_quota();
@@ -16019,7 +16268,7 @@ var init_modelPicker = __esm({
16019
16268
  init_translate2();
16020
16269
  init_providerCatalogue();
16021
16270
  init_schema();
16022
- init_identity2();
16271
+ init_identity();
16023
16272
  init_families();
16024
16273
  init_modelsStore();
16025
16274
  init_tiers();
@@ -16040,13 +16289,17 @@ function providerModels(paths) {
16040
16289
  const supervisorPid = recordedPid !== void 0 && realIsProcessAlive(recordedPid) ? recordedPid : void 0;
16041
16290
  const doorRecord = supervisorPid === void 0 ? void 0 : readFrontDoorCodexRecord(realFarmFs, paths.frontdoorDir, supervisorPid);
16042
16291
  const doorHome = doorRecord?.codexHome;
16292
+ const reader = new TolerantReader((file) => realFsPort.readFileUtf8(file), skipUnreadableCatalogue);
16293
+ const files = new StoredCatalogue(paths, reader);
16043
16294
  return listProviders(paths).flatMap((entry) => {
16044
16295
  if (entry.provider.kind === "codex" && supervisorPid !== void 0 && doorRecord === void 0) return [];
16045
- const catalogue = parseCatalogueCache(realFsPort.readFileUtf8(entry.provider.kind === "codex" ? catalogueCachePath(paths, entry.name, supervisorPid, doorRecord?.generation) : catalogueCachePath(paths, entry.name)));
16296
+ const owner = supervisorPid === void 0 || doorRecord === void 0 ? void 0 : { pid: supervisorPid, generation: doorRecord.generation };
16297
+ const stored = parseCatalogueCache(files.cacheText(entry.name, entry.provider.kind === "codex" ? owner : void 0));
16298
+ const catalogue = stored !== void 0 && isHttpProvider(entry.provider) && !catalogueMatchesSettings(parseCatalogueSettings(files.digestText(entry.name)), stored, entry.provider) ? void 0 : stored;
16046
16299
  if (entry.provider.kind === "codex") {
16047
16300
  if (catalogue !== void 0 && catalogue.supervisorPid !== supervisorPid) return [];
16048
16301
  const env = doorHome === void 0 ? process.env : { ...process.env, CODEX_HOME: doorHome };
16049
- const fingerprint = savedCatalogueFingerprint(entry.provider, paths, env, os8.homedir(), realFsPort.readFileUtf8);
16302
+ const fingerprint = savedCatalogueFingerprint(entry.provider, paths, env, os8.homedir(), reader);
16050
16303
  if (fingerprint === void 0 || catalogue?.credentialFingerprint !== fingerprint) return [];
16051
16304
  }
16052
16305
  return providerModelRows(entry.provider, catalogue?.models).map((row) => ({ provider: entry.name, model: row.model }));
@@ -16061,7 +16314,9 @@ var init_targets = __esm({
16061
16314
  init_catalogueCredential();
16062
16315
  init_state();
16063
16316
  init_modelPicker();
16317
+ init_schema();
16064
16318
  init_providerCatalogue();
16319
+ init_storedCatalogue();
16065
16320
  init_providersStore();
16066
16321
  init_realPorts();
16067
16322
  }
@@ -16704,7 +16959,7 @@ var init_settings2 = __esm({
16704
16959
  });
16705
16960
 
16706
16961
  // src/launcher/flags.ts
16707
- import path49 from "node:path";
16962
+ import path50 from "node:path";
16708
16963
  function resolveLaunchFlags(params) {
16709
16964
  const statusline = resolveStatuslineSettings(params);
16710
16965
  return {
@@ -16763,7 +17018,7 @@ function buildEnv(params) {
16763
17018
  const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
16764
17019
  let providerCustomHeaders;
16765
17020
  if (!params.configDirEscapeHatch && params.identityId !== void 0) {
16766
- env.CLAUDE_CONFIG_DIR = path49.join(params.identitiesDir, params.identityId);
17021
+ env.CLAUDE_CONFIG_DIR = path50.join(params.identitiesDir, params.identityId);
16767
17022
  }
16768
17023
  if (params.provider !== void 0) {
16769
17024
  const providerEnv = params.provider.definition.kind !== void 0 && params.provider.definition.kind !== "http" ? {} : params.provider.definition.env ?? {};
@@ -16879,7 +17134,7 @@ var init_extraFlags = __esm({
16879
17134
  });
16880
17135
 
16881
17136
  // src/usage/resumeContext.ts
16882
- import path50 from "node:path";
17137
+ import path51 from "node:path";
16883
17138
  function projectDirNameOf(cwd) {
16884
17139
  return cwd.replace(/[^A-Za-z0-9]/g, "-");
16885
17140
  }
@@ -16937,7 +17192,7 @@ function newestTranscript(fs17, projectDir) {
16937
17192
  if (!name.endsWith(".jsonl")) {
16938
17193
  continue;
16939
17194
  }
16940
- const candidate = path50.join(projectDir, name);
17195
+ const candidate = path51.join(projectDir, name);
16941
17196
  const stat = fs17.lstat(candidate);
16942
17197
  if (stat?.kind === "file" && stat.mtimeMs > newestMs) {
16943
17198
  newestMs = stat.mtimeMs;
@@ -16951,8 +17206,8 @@ function resumedContextTokens(fs17, params) {
16951
17206
  if (target === void 0) {
16952
17207
  return void 0;
16953
17208
  }
16954
- const projectDir = path50.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
16955
- const file = target.kind === "id" ? path50.join(projectDir, `${target.id}.jsonl`) : newestTranscript(fs17, projectDir);
17209
+ const projectDir = path51.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
17210
+ const file = target.kind === "id" ? path51.join(projectDir, `${target.id}.jsonl`) : newestTranscript(fs17, projectDir);
16956
17211
  const text = file === void 0 ? void 0 : fs17.readFileUtf8(file);
16957
17212
  return text === void 0 ? void 0 : contextTokensOfTranscript(text);
16958
17213
  }
@@ -17455,7 +17710,7 @@ var RESUME_FLAGS, TERMINATOR3, REASONS_LOGGED;
17455
17710
  var init_pool = __esm({
17456
17711
  "src/launcher/pool.ts"() {
17457
17712
  "use strict";
17458
- init_identity();
17713
+ init_identity2();
17459
17714
  init_preflight();
17460
17715
  init_poolPick();
17461
17716
  RESUME_FLAGS = /* @__PURE__ */ new Set(["--continue", "-c", "--resume", "-r"]);
@@ -17566,7 +17821,7 @@ var init_launchHook = __esm({
17566
17821
  import { randomUUID as randomUUID6 } from "node:crypto";
17567
17822
  import os10 from "node:os";
17568
17823
  import { isDeepStrictEqual } from "node:util";
17569
- import path51 from "node:path";
17824
+ import path52 from "node:path";
17570
17825
  function resolveIdentityCredential(identity, credential, env, port) {
17571
17826
  if (port === void 0) {
17572
17827
  return { ok: false, status: 1, message: `agent-shim: identity ${identity.name} needs its credential resolved, but this launcher has no credential port wired` };
@@ -17668,7 +17923,7 @@ function decideLaunch(params, readOnly, onRecorded) {
17668
17923
  const farmIdentity = configDirEscapeHatchApplies || identityDecision.name === void 0 ? void 0 : resolveIdentityId(paths.identitiesDir, identityDecision.name, fs17);
17669
17924
  const farm = farmIdentity === void 0 ? void 0 : params.farm;
17670
17925
  if (!readOnly && params.supervised?.member === void 0 && farmIdentity !== void 0 && identityDecision.name !== void 0) {
17671
- warnOfSupersededConfigDir(log.warn, fs17, identityDecision.supersededConfigDir, identityDecision.name, path51.join(paths.identitiesDir, farmIdentity));
17926
+ warnOfSupersededConfigDir(log.warn, fs17, identityDecision.supersededConfigDir, identityDecision.name, path52.join(paths.identitiesDir, farmIdentity));
17672
17927
  }
17673
17928
  if (!readOnly && farm !== void 0 && farmIdentity !== void 0) {
17674
17929
  try {
@@ -17849,25 +18104,27 @@ function decideLaunch(params, readOnly, onRecorded) {
17849
18104
  const doorRecord = doorPid === void 0 ? void 0 : readFrontDoorCodexRecord(params.fs, paths.frontdoorDir, doorPid);
17850
18105
  const doorHome = doorRecord?.codexHome;
17851
18106
  const catalogueEnv = doorHome === void 0 ? env : { ...env, CODEX_HOME: doorHome };
18107
+ const reader = new TolerantReader((file) => params.fs.readFileUtf8(file), skipUnreadableCatalogue);
18108
+ const stored = new StoredCatalogue(paths, reader);
17852
18109
  const listedProviders = listProviderNames(fs17.readdir, paths.providersDir).flatMap((name) => {
17853
18110
  try {
17854
18111
  const definition = loadProvider(paths.providersDir, name, fs17);
17855
18112
  if (definition === void 0) return [];
17856
- const catalogueOwner = definition.kind === "codex" ? doorPid : void 0;
17857
- const generation = definition.kind === "codex" ? doorRecord?.generation : void 0;
17858
- const cache = parseCatalogueCache(params.fs.readFileUtf8(catalogueCachePath(paths, name, catalogueOwner, generation)));
18113
+ const owner = definition.kind === "codex" && doorPid !== void 0 && doorRecord !== void 0 ? { pid: doorPid, generation: doorRecord.generation } : void 0;
18114
+ const cache = parseCatalogueCache(stored.cacheText(name, owner));
17859
18115
  if (definition.kind === "codex" && cache !== void 0 && cache.supervisorPid !== doorPid) return [];
17860
18116
  if (definition.kind === "codex" && doorPid !== void 0 && doorRecord === void 0) return [];
17861
18117
  if (definition.kind === "codex" && readOnly && cache !== void 0) {
17862
- const binding = parseCatalogueBinding(params.fs.readFileUtf8(catalogueBindingPath(paths, name, catalogueOwner, generation)));
18118
+ const binding = parseCatalogueBinding(stored.bindingText(name, owner));
17863
18119
  const configuredHome = catalogueEnv.CODEX_HOME;
17864
- const home = configuredHome === void 0 || configuredHome === "" ? path51.join(os10.homedir(), ".codex") : configuredHome;
17865
- const source = definition.codex?.login === "chatgpt-sign-in" ? paths.chatgptSignInFile : path51.resolve(home, "auth.json");
18120
+ const home = configuredHome === void 0 || configuredHome === "" ? path52.join(os10.homedir(), ".codex") : configuredHome;
18121
+ const source = definition.codex?.login === "chatgpt-sign-in" ? paths.chatgptSignInFile : path52.resolve(home, "auth.json");
17866
18122
  const revision = params.fs.fileRevision?.(source);
17867
18123
  if (binding === void 0 || binding.fingerprint !== cache.credentialFingerprint || binding.source !== source || revision === void 0 || revision !== binding.revision) return [];
17868
18124
  }
17869
- const fingerprint = definition.kind === "codex" && !readOnly ? savedCatalogueFingerprint(definition, paths, catalogueEnv, os10.homedir(), params.fs.readFileUtf8) : void 0;
18125
+ const fingerprint = definition.kind === "codex" && !readOnly ? savedCatalogueFingerprint(definition, paths, catalogueEnv, os10.homedir(), reader) : void 0;
17870
18126
  if (definition.kind === "codex" && !readOnly && cache !== void 0 && (fingerprint === void 0 || cache.credentialFingerprint !== fingerprint)) return [];
18127
+ if (isHttpProvider(definition) && cache !== void 0 && !catalogueMatchesSettings(parseCatalogueSettings(stored.digestText(name)), cache, definition)) return [[name, definition, []]];
17871
18128
  return [[name, definition, cache?.models ?? []]];
17872
18129
  } catch {
17873
18130
  return [];
@@ -17883,7 +18140,7 @@ function decideLaunch(params, readOnly, onRecorded) {
17883
18140
  return { args: args2, pickerSuppressed: startsSession && pickerSettings !== void 0 && callerSettings };
17884
18141
  };
17885
18142
  const args = argsForSupervisor().args;
17886
- const configDir = configDirEscapeHatchApplies || farmIdentity === void 0 ? env.CLAUDE_CONFIG_DIR : path51.join(paths.identitiesDir, farmIdentity);
18143
+ const configDir = configDirEscapeHatchApplies || farmIdentity === void 0 ? env.CLAUDE_CONFIG_DIR : path52.join(paths.identitiesDir, farmIdentity);
17887
18144
  const decision = {
17888
18145
  identitySource: identityDecision.source,
17889
18146
  configDirEscapeHatch: identityDecision.configDirEscapeHatch,
@@ -17979,7 +18236,7 @@ function prepareRegisteredLaunch(params, onRecorded) {
17979
18236
  let warnings = [];
17980
18237
  const updateCheck = runLaunchUpdateCheck({
17981
18238
  mode: params.updateMode ?? "off",
17982
- checkPath: path51.join(paths.root, "update.check"),
18239
+ checkPath: path52.join(paths.root, "update.check"),
17983
18240
  currentVersion: package_default.version,
17984
18241
  port: params.update
17985
18242
  });
@@ -18002,7 +18259,7 @@ function prepareRegisteredLaunch(params, onRecorded) {
18002
18259
  classification: resyncFarmRuntime.classification,
18003
18260
  now: resyncFarmRuntime.now,
18004
18261
  uniqueSuffix: resyncFarmRuntime.uniqueSuffix,
18005
- identityExists: () => params.fs.readConfigFile(path51.join(paths.identitiesDir, resyncIdentity, IDENTITY_FILE)) !== void 0,
18262
+ identityExists: () => params.fs.readConfigFile(path52.join(paths.identitiesDir, resyncIdentity, IDENTITY_FILE)) !== void 0,
18006
18263
  lock: resyncFarmRuntime.lock
18007
18264
  });
18008
18265
  } catch (error) {
@@ -18164,7 +18421,7 @@ var init_launcher = __esm({
18164
18421
  init_guard();
18165
18422
  init_identityRecords();
18166
18423
  init_identityNameRenameRecord();
18167
- init_identity();
18424
+ init_identity2();
18168
18425
  init_flags();
18169
18426
  init_extraFlags();
18170
18427
  init_claudeSession();
@@ -18175,6 +18432,7 @@ var init_launcher = __esm({
18175
18432
  init_modelPicker();
18176
18433
  init_state();
18177
18434
  init_providerCatalogue();
18435
+ init_storedCatalogue();
18178
18436
  init_providersStore();
18179
18437
  init_memberProvider();
18180
18438
  init_pool();
@@ -18202,12 +18460,12 @@ var init_launcher = __esm({
18202
18460
  });
18203
18461
 
18204
18462
  // src/ownCli.ts
18205
- import path52 from "node:path";
18463
+ import path53 from "node:path";
18206
18464
  function agentShimCliPath(distDir = typeof __AGENT_SHIM_DIST_DIR__ === "string" ? __AGENT_SHIM_DIST_DIR__ : void 0) {
18207
18465
  if (distDir === void 0) {
18208
18466
  throw new OwnCliPathUnknownError();
18209
18467
  }
18210
- return path52.join(distDir, OWN_CLI_FILE_NAME);
18468
+ return path53.join(distDir, OWN_CLI_FILE_NAME);
18211
18469
  }
18212
18470
  var OWN_CLI_FILE_NAME, OwnCliPathUnknownError;
18213
18471
  var init_ownCli = __esm({
@@ -18252,11 +18510,11 @@ var init_selfIdentity = __esm({
18252
18510
  });
18253
18511
 
18254
18512
  // src/frontdoor/trust.ts
18255
- import { createHash as createHash11 } from "node:crypto";
18256
- import path53 from "node:path";
18513
+ import { createHash as createHash12 } from "node:crypto";
18514
+ import path54 from "node:path";
18257
18515
  function resolveTrustBundle(params) {
18258
18516
  const { caCertFile, bundlesDir, variable, inherited, fs: fs17 } = params;
18259
- if (inherited === void 0 || inherited === "" || path53.resolve(inherited) === path53.resolve(caCertFile)) {
18517
+ if (inherited === void 0 || inherited === "" || path54.resolve(inherited) === path54.resolve(caCertFile)) {
18260
18518
  return { path: caCertFile };
18261
18519
  }
18262
18520
  const caPem = fs17.readFileUtf8(caCertFile);
@@ -18274,7 +18532,7 @@ function resolveTrustBundle(params) {
18274
18532
  }
18275
18533
  const combined = `${inheritedPem.trimEnd()}
18276
18534
  ${caPem}`;
18277
- const bundle = path53.join(bundlesDir, `${createHash11("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
18535
+ const bundle = path54.join(bundlesDir, `${createHash12("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
18278
18536
  if (!fs17.exists(bundle)) {
18279
18537
  fs17.mkdirp(bundlesDir);
18280
18538
  fs17.writeFileAtomic(bundle, combined);
@@ -18335,35 +18593,49 @@ function realFrontDoorPort(paths, spawnDaemon) {
18335
18593
  return {
18336
18594
  waitForCatalogues: (supervisorPid) => {
18337
18595
  const timedOut = deadlineAfter(CATALOGUE_REFRESH_DEADLINE_MS);
18596
+ const stored = new StoredCatalogue(paths, new TolerantReader((file) => realFarmFs.readFileUtf8(file), skipUnreadableCatalogue));
18338
18597
  let requested = false;
18339
18598
  const warnings = /* @__PURE__ */ new Set();
18340
18599
  while (!isDeclaredFrontDoor(supervisorPid) && listProviders(paths).map(({ name, provider }) => {
18341
18600
  const owner = readFrontDoorCodexRecord(realFarmFs, paths.frontdoorDir, supervisorPid);
18342
18601
  const published = owner === void 0 ? void 0 : readCatalogueStatus(realFarmFs, paths, supervisorPid, owner.generation, name);
18343
- if (provider.kind !== "codex" && published?.status === "failed" && published.recordedAt !== void 0 && published.recordedAt <= Date.now() && Date.now() - published.recordedAt < CATALOGUE_RETRY_MS) {
18602
+ const failedUnderCurrentSettings = () => {
18603
+ if (!isHttpProvider(provider) || owner === void 0) return true;
18604
+ if (provider.catalogue === void 0) return false;
18605
+ const recorded = readCatalogueFailure(realFarmFs, paths, supervisorPid, owner.generation, name)?.settings;
18606
+ return recorded === void 0 || recorded === catalogueSettingsFingerprint(provider);
18607
+ };
18608
+ if (provider.kind !== "codex" && published?.status === "failed" && published.recordedAt !== void 0 && within(published.recordedAt, Date.now(), CATALOGUE_RETRY_MS) && failedUnderCurrentSettings()) {
18344
18609
  warnings.add(`Catalogue refresh failed for ${name}`);
18345
18610
  return false;
18346
18611
  }
18347
18612
  if (provider.kind === "codex") {
18348
18613
  if (owner === void 0) return true;
18349
- const cache2 = parseCatalogueCache(realFarmFs.readFileUtf8(catalogueCachePath(paths, name, supervisorPid, owner.generation)));
18614
+ const cache2 = parseCatalogueCache(stored.cacheText(name, { pid: supervisorPid, generation: owner.generation }));
18350
18615
  let fingerprint;
18616
+ let loginFault;
18351
18617
  try {
18352
- fingerprint = savedCatalogueFingerprint(provider, paths, { ...process.env, CODEX_HOME: owner.codexHome }, os11.homedir(), realFarmFs.readFileUtf8);
18618
+ fingerprint = savedCatalogueFingerprint(provider, paths, { ...process.env, CODEX_HOME: owner.codexHome }, os11.homedir(), new TolerantReader((file) => realFarmFs.readFileUtf8(file), (fault) => {
18619
+ loginFault = fault;
18620
+ }));
18353
18621
  } catch (error) {
18354
18622
  warnings.add(`Cannot read catalogue credentials for ${name}: ${error instanceof Error ? error.message : String(error)}`);
18355
18623
  return false;
18356
18624
  }
18625
+ if (loginFault !== void 0) {
18626
+ warnings.add(`Cannot read the catalogue credentials for ${name} (${loginFault})`);
18627
+ return false;
18628
+ }
18357
18629
  const outcome = readCatalogueStatus(realFarmFs, paths, supervisorPid, owner.generation, name);
18358
- if (outcome?.status === "failed" && outcome.fingerprint === fingerprint && outcome.recordedAt !== void 0 && outcome.recordedAt <= Date.now() && Date.now() - outcome.recordedAt < CATALOGUE_RETRY_MS) {
18630
+ if (outcome?.status === "failed" && outcome.fingerprint === fingerprint && outcome.recordedAt !== void 0 && within(outcome.recordedAt, Date.now(), CATALOGUE_RETRY_MS)) {
18359
18631
  warnings.add(`Catalogue refresh failed for ${name}`);
18360
18632
  return false;
18361
18633
  }
18362
18634
  return cache2 === void 0 || isCatalogueStale(cache2, Date.now()) || cache2.supervisorPid !== supervisorPid || fingerprint === void 0 || cache2.credentialFingerprint !== fingerprint;
18363
18635
  }
18364
18636
  if (provider.kind !== void 0 && provider.kind !== "http" || provider.catalogue === void 0) return false;
18365
- const cache = parseCatalogueCache(realFarmFs.readFileUtf8(catalogueCachePath(paths, name)));
18366
- return cache === void 0 || isCatalogueStale(cache, Date.now());
18637
+ const cache = parseCatalogueCache(stored.cacheText(name));
18638
+ return cache === void 0 || isCatalogueStale(cache, Date.now()) || !catalogueMatchesSettings(parseCatalogueSettings(stored.digestText(name)), cache, provider);
18367
18639
  }).some(Boolean)) {
18368
18640
  if (timedOut()) return [...warnings, "Timed out waiting for provider catalogues"].join("; ");
18369
18641
  if (!requested) {
@@ -18404,12 +18676,16 @@ var init_realFrontDoorPort = __esm({
18404
18676
  "src/frontdoor/realFrontDoorPort.ts"() {
18405
18677
  "use strict";
18406
18678
  init_providersStore();
18679
+ init_schema();
18407
18680
  init_providerCatalogue();
18681
+ init_storedCatalogue();
18682
+ init_elapsedWindow();
18408
18683
  init_catalogueCredential();
18409
18684
  init_realPorts();
18410
18685
  init_doorLog();
18411
18686
  init_ensure2();
18412
18687
  init_state();
18688
+ init_catalogueState();
18413
18689
  init_probe();
18414
18690
  init_selfIdentity();
18415
18691
  init_trust();
@@ -18429,7 +18705,7 @@ var init_realFrontDoorPort = __esm({
18429
18705
 
18430
18706
  // src/launchWiring.ts
18431
18707
  import os12 from "node:os";
18432
- import path54 from "node:path";
18708
+ import path55 from "node:path";
18433
18709
  import { randomUUID as randomUUID7 } from "node:crypto";
18434
18710
  function buildFarmRuntime(paths, cwd, run = realRunPort) {
18435
18711
  const home = os12.homedir();
@@ -18485,8 +18761,8 @@ function realPrepareLaunchParams(paths, options) {
18485
18761
  credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
18486
18762
  startBaseUrlProbe: realStartBaseUrlProbe,
18487
18763
  hold: realHoldPort,
18488
- 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",
18489
- hasUsableLogin: (identity, claudeBin) => storedLoginUsable(options.run ?? realRunPort, claudeBin, path54.join(paths.identitiesDir, identity), options.proc.env),
18764
+ hasStoredLogin: (identity) => identitySignIn(realFarmFs, { platform: process.platform, run: options.run ?? realRunPort }, { farmRoot: path55.join(paths.identitiesDir, identity), hasCredentialBlock: false, provider: void 0 }).state !== "signed-out",
18765
+ hasUsableLogin: (identity, claudeBin) => storedLoginUsable(options.run ?? realRunPort, claudeBin, path55.join(paths.identitiesDir, identity), options.proc.env),
18490
18766
  ...farm.directoryIdentity === void 0 ? {} : { directoryPinnedIdentity: farm.directoryIdentity },
18491
18767
  ...farm.directoryConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: farm.directoryConfigProfile },
18492
18768
  ...farm.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: farm.globalDefaultConfigProfile },
@@ -18708,7 +18984,7 @@ var init_anthropicUsageRefresh = __esm({
18708
18984
  "src/usage/anthropicUsageRefresh.ts"() {
18709
18985
  "use strict";
18710
18986
  init_schema();
18711
- init_identity();
18987
+ init_identity2();
18712
18988
  init_middleware();
18713
18989
  init_windowLengths();
18714
18990
  init_plan2();
@@ -18779,7 +19055,7 @@ var init_identityClaude = __esm({
18779
19055
  });
18780
19056
 
18781
19057
  // src/usage/providerQuota.ts
18782
- import { z as z47 } from "zod";
19058
+ import { z as z48 } from "zod";
18783
19059
  var MS_PER_SECOND9, SECONDS_PER_HOUR3, HOURS_PER_DAY6, DAYS_PER_MONTH, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZaiLimitSchema, ZaiResponseSchema, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, ANTIGRAVITY_HOST, ANTIGRAVITY_QUOTA_URL, ANTIGRAVITY_USER_URL, FIVE_HOURS2, DAYS_PER_WEEK2, FIVE_HOURS_MS, WEEK_MS, AntigravityBucketSchema, AntigravitySummarySchema, GoogleTokenInfoSchema, AntigravityUserSchema;
18784
19060
  var init_providerQuota = __esm({
18785
19061
  "src/usage/providerQuota.ts"() {
@@ -18798,35 +19074,35 @@ var init_providerQuota = __esm({
18798
19074
  [ZAI_UNIT_HOURS, SECONDS_PER_HOUR3 * MS_PER_SECOND9],
18799
19075
  [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9]
18800
19076
  ]);
18801
- ZaiLimitSchema = z47.object({
18802
- type: z47.string(),
18803
- unit: z47.number().int(),
18804
- number: z47.number().int().positive(),
18805
- percentage: z47.number().nonnegative(),
18806
- nextResetTime: z47.number().positive().optional(),
18807
- usage: z47.number().nonnegative().optional(),
18808
- currentValue: z47.number().nonnegative().optional(),
18809
- remaining: z47.number().nonnegative().optional()
19077
+ ZaiLimitSchema = z48.object({
19078
+ type: z48.string(),
19079
+ unit: z48.number().int(),
19080
+ number: z48.number().int().positive(),
19081
+ percentage: z48.number().nonnegative(),
19082
+ nextResetTime: z48.number().positive().optional(),
19083
+ usage: z48.number().nonnegative().optional(),
19084
+ currentValue: z48.number().nonnegative().optional(),
19085
+ remaining: z48.number().nonnegative().optional()
18810
19086
  });
18811
- ZaiResponseSchema = z47.object({
18812
- success: z47.boolean(),
18813
- msg: z47.string().optional(),
18814
- data: z47.object({ level: z47.string().optional(), limits: z47.array(ZaiLimitSchema) })
19087
+ ZaiResponseSchema = z48.object({
19088
+ success: z48.boolean(),
19089
+ msg: z48.string().optional(),
19090
+ data: z48.object({ level: z48.string().optional(), limits: z48.array(ZaiLimitSchema) })
18815
19091
  });
18816
19092
  OPENROUTER_HOST = "openrouter.ai";
18817
19093
  OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
18818
19094
  OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
18819
19095
  MS_PER_DAY2 = HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
18820
- OpenRouterKeySchema = z47.object({
18821
- data: z47.object({
18822
- limit: z47.number().nonnegative().nullable(),
18823
- limit_remaining: z47.number().nullable(),
18824
- limit_reset: z47.string().nullable(),
18825
- is_free_tier: z47.boolean().optional(),
18826
- free_model_daily_requests: z47.object({ used: z47.number().nonnegative(), limit: z47.number().nonnegative(), remaining: z47.number() }).optional()
19096
+ OpenRouterKeySchema = z48.object({
19097
+ data: z48.object({
19098
+ limit: z48.number().nonnegative().nullable(),
19099
+ limit_remaining: z48.number().nullable(),
19100
+ limit_reset: z48.string().nullable(),
19101
+ is_free_tier: z48.boolean().optional(),
19102
+ free_model_daily_requests: z48.object({ used: z48.number().nonnegative(), limit: z48.number().nonnegative(), remaining: z48.number() }).optional()
18827
19103
  })
18828
19104
  });
18829
- OpenRouterCreditsSchema = z47.object({ data: z47.object({ total_credits: z47.number().nonnegative(), total_usage: z47.number().nonnegative() }) });
19105
+ OpenRouterCreditsSchema = z48.object({ data: z48.object({ total_credits: z48.number().nonnegative(), total_usage: z48.number().nonnegative() }) });
18830
19106
  ANTIGRAVITY_HOST = "daily-cloudcode-pa.googleapis.com";
18831
19107
  ANTIGRAVITY_QUOTA_URL = `https://${ANTIGRAVITY_HOST}/v1internal:retrieveUserQuotaSummary`;
18832
19108
  ANTIGRAVITY_USER_URL = `https://${ANTIGRAVITY_HOST}/v1internal:loadCodeAssist`;
@@ -18834,21 +19110,21 @@ var init_providerQuota = __esm({
18834
19110
  DAYS_PER_WEEK2 = 7;
18835
19111
  FIVE_HOURS_MS = FIVE_HOURS2 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
18836
19112
  WEEK_MS = DAYS_PER_WEEK2 * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
18837
- AntigravityBucketSchema = z47.object({
18838
- bucketId: z47.string(),
18839
- remainingFraction: z47.number().optional(),
18840
- resetTime: z47.string().optional()
19113
+ AntigravityBucketSchema = z48.object({
19114
+ bucketId: z48.string(),
19115
+ remainingFraction: z48.number().optional(),
19116
+ resetTime: z48.string().optional()
18841
19117
  });
18842
- AntigravitySummarySchema = z47.object({ groups: z47.array(z47.object({ buckets: z47.array(AntigravityBucketSchema) })) });
18843
- GoogleTokenInfoSchema = z47.object({
18844
- email: z47.string().optional(),
18845
- sub: z47.string().optional()
19118
+ AntigravitySummarySchema = z48.object({ groups: z48.array(z48.object({ buckets: z48.array(AntigravityBucketSchema) })) });
19119
+ GoogleTokenInfoSchema = z48.object({
19120
+ email: z48.string().optional(),
19121
+ sub: z48.string().optional()
18846
19122
  });
18847
- AntigravityUserSchema = z47.object({
19123
+ AntigravityUserSchema = z48.object({
18848
19124
  /** The code-assist tier context, which defaults to the free tier for every account. */
18849
- currentTier: z47.object({ name: z47.string().optional(), id: z47.string().optional() }).optional(),
19125
+ currentTier: z48.object({ name: z48.string().optional(), id: z48.string().optional() }).optional(),
18850
19126
  /** The account's paid subscription; absent when the account has none. */
18851
- paidTier: z47.object({ name: z47.string().optional(), id: z47.string().optional() }).optional()
19127
+ paidTier: z48.object({ name: z48.string().optional(), id: z48.string().optional() }).optional()
18852
19128
  });
18853
19129
  }
18854
19130
  });
@@ -20067,7 +20343,7 @@ import { openapi as openapi9 } from "@orpc/openapi";
20067
20343
  // src/checkReportSchema.ts
20068
20344
  init_schema();
20069
20345
  init_claudeVersion();
20070
- init_identity();
20346
+ init_identity2();
20071
20347
  init_projects();
20072
20348
  import { z as z27 } from "zod";
20073
20349
 
@@ -20284,8 +20560,8 @@ var ResetRowSchema = z28.strictObject({
20284
20560
  var ResetScheduleSchema = z28.strictObject({ resets: z28.readonly(z28.array(ResetRowSchema)) });
20285
20561
 
20286
20562
  // src/frontdoor/controlSchemas.ts
20287
- import path43 from "node:path";
20288
- import { z as z37 } from "zod";
20563
+ import path44 from "node:path";
20564
+ import { z as z38 } from "zod";
20289
20565
 
20290
20566
  // src/codex/doctor.ts
20291
20567
  function codexIdentityFindings(entry, identity) {
@@ -20370,7 +20646,56 @@ function resolveMiseDispatcher(target, pathDirs, env, trustedExecutable) {
20370
20646
  }
20371
20647
 
20372
20648
  // src/doctorReport.ts
20373
- import path42 from "node:path";
20649
+ init_signIn();
20650
+ init_identityAccounts();
20651
+ init_read();
20652
+ init_providerReachability();
20653
+ import path43 from "node:path";
20654
+
20655
+ // src/doctorNameFinding.ts
20656
+ init_names();
20657
+ init_reservedModelNames();
20658
+ function pushNameFinding(push, section, kind, entry) {
20659
+ if (section === "provider") {
20660
+ pushReservedProviderNameFinding(push, entry);
20661
+ }
20662
+ if (isFileName(entry.name)) {
20663
+ return true;
20664
+ }
20665
+ if (!isStoredName(entry.name)) {
20666
+ push(section, "fail", `${entry.path} cannot be used as a ${kind}: its name is ${JSON.stringify(entry.name)}, and a name ${FILE_NAME_RULE}. Rename or remove the file.`, entry.name);
20667
+ return false;
20668
+ }
20669
+ push(
20670
+ section,
20671
+ "warn",
20672
+ `The ${kind} ${JSON.stringify(entry.name)} is stored under a name that does not fit the shape names are given now (a name ${FILE_NAME_RULE}). It still works from your own configuration, but a project file cannot name it. Rename ${entry.path} to a name that fits, and change what names it.`,
20673
+ entry.name
20674
+ );
20675
+ return true;
20676
+ }
20677
+ function pushReservedProviderNameFinding(push, entry) {
20678
+ const reason = reservedProviderNameReason(entry.name);
20679
+ if (reason !== void 0) {
20680
+ push("provider", "warn", `The provider ${JSON.stringify(entry.name)} is called a bare model name: ${reason}, so a session's bare ${JSON.stringify(entry.name)} follows its route and never selects this provider. Rename it, or select it with ${JSON.stringify(`${entry.name}/<model>`)}.`, entry.name);
20681
+ }
20682
+ }
20683
+
20684
+ // src/doctorCatalogueRedirect.ts
20685
+ init_schema();
20686
+ init_providerCatalogue();
20687
+ init_providersStore();
20688
+ function pushCatalogueRedirectFinding(push, providerName, reason) {
20689
+ push("provider", "warn", `The catalogue refresh of provider ${JSON.stringify(providerName)} reached a redirect, which a catalogue read never follows (its request carries the provider's credential, and a redirect target is another origin), so its catalogue is not being kept current. Set the provider's base URL (or its catalogue.url) to the address it redirects to, which running agent-shim provider models <name> --refresh from a shell prints. The refresh recorded: ${JSON.stringify(reason)}.`, providerName);
20690
+ }
20691
+ function currentCatalogueSettings(paths, name) {
20692
+ try {
20693
+ const provider = readProvider(paths, name);
20694
+ return provider === void 0 || !isHttpProvider(provider) || provider.catalogue === void 0 ? void 0 : catalogueSettingsFingerprint(provider);
20695
+ } catch {
20696
+ return void 0;
20697
+ }
20698
+ }
20374
20699
 
20375
20700
  // src/checkReport.ts
20376
20701
  init_cliError();
@@ -20405,11 +20730,11 @@ init_load();
20405
20730
  // src/launchSelection.ts
20406
20731
  init_load();
20407
20732
  init_cascade();
20408
- init_identity();
20733
+ init_identity2();
20409
20734
  import os5 from "node:os";
20410
20735
 
20411
20736
  // src/poolPickReport.ts
20412
- init_identity();
20737
+ init_identity2();
20413
20738
  init_poolPick();
20414
20739
  function candidateView(candidate) {
20415
20740
  return {
@@ -20930,29 +21255,39 @@ function collectCheckReport(params) {
20930
21255
  return report;
20931
21256
  }
20932
21257
 
20933
- // src/doctorReport.ts
20934
- init_signIn();
20935
- init_identityAccounts();
20936
- init_read();
20937
- init_providerReachability();
20938
-
20939
- // src/doctorNameFinding.ts
20940
- init_names();
20941
- function pushNameFinding(push, section, kind, entry) {
20942
- if (isFileName(entry.name)) {
20943
- return true;
21258
+ // src/doctorKeychain.ts
21259
+ function pushKeychainFindings(push, platform, run, identities, agentOf) {
21260
+ if (platform !== "darwin" || run === void 0) {
21261
+ push("keychain", "pass", "Skipped (not macOS).");
21262
+ return;
20944
21263
  }
20945
- if (!isStoredName(entry.name)) {
20946
- push(section, "fail", `${entry.path} cannot be used as a ${kind}: its name is ${JSON.stringify(entry.name)}, and a name ${FILE_NAME_RULE}. Rename or remove the file.`, entry.name);
20947
- return false;
21264
+ for (const entry of identities) {
21265
+ if (agentOf.get(entry.name) === "codex") continue;
21266
+ const result = lookupKeychainService(run, entry.farmRoot);
21267
+ push("keychain", "pass", result.found ? result.note : `${result.note} The sign-in section reports whether a login is stored elsewhere.`, entry.name);
20948
21268
  }
20949
- push(
20950
- section,
20951
- "warn",
20952
- `The ${kind} ${JSON.stringify(entry.name)} is stored under a name that does not fit the shape names are given now (a name ${FILE_NAME_RULE}). It still works from your own configuration, but a project file cannot name it. Rename ${entry.path} to a name that fits, and change what names it.`,
20953
- entry.name
20954
- );
20955
- return true;
21269
+ }
21270
+
21271
+ // src/frontdoor/catalogueFailures.ts
21272
+ init_state();
21273
+ init_catalogueState();
21274
+ function providersWithRedirectedCatalogue(fs17, paths, settingsOf2) {
21275
+ const supervisorPid = readFrontDoorState(fs17, paths.frontdoorStateFile)?.supervisorPid;
21276
+ const generation = supervisorPid === void 0 ? void 0 : readFrontDoorCodexRecord(fs17, paths.frontdoorDir, supervisorPid)?.generation;
21277
+ if (supervisorPid === void 0 || generation === void 0) {
21278
+ return /* @__PURE__ */ new Map();
21279
+ }
21280
+ const found = /* @__PURE__ */ new Map();
21281
+ for (const [name, settings] of settingsOf2) {
21282
+ if (readCatalogueStatus(fs17, paths, supervisorPid, generation, name)?.status !== "failed") {
21283
+ continue;
21284
+ }
21285
+ const failure = readCatalogueFailure(fs17, paths, supervisorPid, generation, name);
21286
+ if (settings !== void 0 && failure?.redirected === true && failure.settings === settings) {
21287
+ found.set(name, failure.reason);
21288
+ }
21289
+ }
21290
+ return found;
20956
21291
  }
20957
21292
 
20958
21293
  // src/doctorReport.ts
@@ -20969,7 +21304,7 @@ init_source();
20969
21304
  // src/models/doctor.ts
20970
21305
  init_modelsStore();
20971
21306
  init_families();
20972
- init_identity2();
21307
+ init_identity();
20973
21308
  function modelsFindings(input) {
20974
21309
  const findings = [];
20975
21310
  const { models } = input;
@@ -21232,12 +21567,12 @@ init_identityRenameJournal();
21232
21567
  init_providerAliases();
21233
21568
  init_providersStore();
21234
21569
  init_guard();
21235
- init_identity();
21570
+ init_identity2();
21236
21571
  init_poolStore();
21237
21572
 
21238
21573
  // src/poolSharedLogins.ts
21239
21574
  init_identityAccounts();
21240
- init_identity();
21575
+ init_identity2();
21241
21576
  function sharedLoginMembers(members, accountOf) {
21242
21577
  const known = members.flatMap((identity) => {
21243
21578
  const account = poolNameOf(identity) === void 0 ? accountOf(identity) : void 0;
@@ -21256,7 +21591,7 @@ function describeSharedLoginMembers(poolName, shared) {
21256
21591
 
21257
21592
  // src/poolWindowReads.ts
21258
21593
  init_schema();
21259
- init_identity();
21594
+ init_identity2();
21260
21595
  init_conditions();
21261
21596
  init_middleware();
21262
21597
  init_rateLimit();
@@ -21387,7 +21722,7 @@ function tcpPortEraRecord(raw) {
21387
21722
  return (has("port") || has("lastPort")) && !has("socketPath");
21388
21723
  }
21389
21724
  function pushPathResolution(push, resolution) {
21390
- const ownDir = path42.dirname(resolution.ownExecutablePath);
21725
+ const ownDir = path43.dirname(resolution.ownExecutablePath);
21391
21726
  switch (resolution.agentShim.status) {
21392
21727
  case "ok":
21393
21728
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -21507,14 +21842,14 @@ function pushProvider(push, entry, cacheEnv, signIn, unreachable) {
21507
21842
  }
21508
21843
  function pushLegacyName(push, params) {
21509
21844
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
21510
- if (legacyVariables.length === 0 && path42.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
21845
+ if (legacyVariables.length === 0 && path43.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
21511
21846
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
21512
21847
  return;
21513
21848
  }
21514
21849
  for (const name of legacyVariables) {
21515
21850
  push("legacy-name", "warn", `${name} is the former name of ${name.replace(LEGACY_ENV_PREFIX, ENV_PREFIX)}. Rename it; the old name still works but is only a fallback.`, name);
21516
21851
  }
21517
- if (path42.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
21852
+ if (path43.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
21518
21853
  push(
21519
21854
  "legacy-name",
21520
21855
  "warn",
@@ -21604,7 +21939,7 @@ function runDoctor(params) {
21604
21939
  push("identity", "warn", `identities/${name} cannot be reached (${code}), so it is not counted as an identity. Repair the permissions of the directory or of what a symlink points through, or remove the entry.`, name);
21605
21940
  }
21606
21941
  for (const { file, detail } of params.renameJournals?.unreadable ?? []) {
21607
- push("identity", "fail", `${file} is not a rename journal this agent-shim can read (${detail}), so no identity can be renamed until it is fixed or removed, and it may be the trace of a rename that was left unfinished.`, path42.basename(file));
21942
+ push("identity", "fail", `${file} is not a rename journal this agent-shim can read (${detail}), so no identity can be renamed until it is fixed or removed, and it may be the trace of a rename that was left unfinished.`, path43.basename(file));
21608
21943
  }
21609
21944
  const validIdentityAgents = /* @__PURE__ */ new Map();
21610
21945
  const signedInAccounts = [];
@@ -21730,20 +22065,16 @@ function runDoctor(params) {
21730
22065
  continue;
21731
22066
  }
21732
22067
  pushProvider(push, entry, params.credentialCache, params.chatgptSignIn, unreachableLines.get(entry.name));
22068
+ const redirectReason = params.catalogueRedirects?.get(entry.name);
22069
+ if (redirectReason !== void 0) {
22070
+ pushCatalogueRedirectFinding(push, entry.name, redirectReason);
22071
+ }
21733
22072
  }
21734
22073
  const providerNames = new Set(params.providers.map((entry) => entry.name));
21735
22074
  for (const finding of aliasFindings(params.providerAliases ?? {}, providerNames)) {
21736
22075
  push("provider", finding.level, finding.message, finding.alias);
21737
22076
  }
21738
- if (params.platform !== "darwin" || params.run === void 0) {
21739
- push("keychain", "pass", "Skipped (not macOS).");
21740
- } else {
21741
- for (const entry of params.identities) {
21742
- if (validIdentityAgents.get(entry.name) === "codex") continue;
21743
- const result = lookupKeychainService(params.run, entry.farmRoot);
21744
- push("keychain", "pass", result.found ? result.note : `${result.note} The sign-in section reports whether a login is stored elsewhere.`, entry.name);
21745
- }
21746
- }
22077
+ pushKeychainFindings(push, params.platform, params.run, params.identities, validIdentityAgents);
21747
22078
  if (params.directoryRules.raw === void 0) {
21748
22079
  push("directory-rules", "pass", "No directory-rules.json configured.");
21749
22080
  } else {
@@ -21970,9 +22301,9 @@ function collectDoctorReport(params) {
21970
22301
  const { names: identityNames, unreachable: unreachableIdentities } = listIdentityDirectories(paths);
21971
22302
  const records = identityRecords(paths);
21972
22303
  const displacedIdentities = records.filter((record) => !identityIdExists(paths, record.id) && !unreachableIdentities.some((entry) => entry.name === record.id));
21973
- const identities = identityNames.filter((id) => (records.some((record) => record.id === id) || !fs14.existsSync(path42.join(paths.identitiesDir, id, "identity.json"))) && !displacedIdentities.some((record) => record.id === id)).map((id) => {
21974
- const farmRoot = path42.join(paths.identitiesDir, id);
21975
- const identityPath = path42.join(farmRoot, "identity.json");
22304
+ const identities = identityNames.filter((id) => (records.some((record) => record.id === id) || !fs14.existsSync(path43.join(paths.identitiesDir, id, "identity.json"))) && !displacedIdentities.some((record) => record.id === id)).map((id) => {
22305
+ const farmRoot = path43.join(paths.identitiesDir, id);
22306
+ const identityPath = path43.join(farmRoot, "identity.json");
21976
22307
  return { name: identityNameIn(records, id) ?? id, id, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot, credentialsFilePresent: fs14.existsSync(credentialsFilePath(farmRoot)), account: readIdentityAccount(realFsPort, paths.identitiesDir, id)?.account };
21977
22308
  });
21978
22309
  const usageSnapshots = {};
@@ -21990,12 +22321,12 @@ function collectDoctorReport(params) {
21990
22321
  }
21991
22322
  const profileNames = fs14.existsSync(paths.configProfilesDir) ? fs14.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
21992
22323
  const configProfiles = profileNames.map((name) => {
21993
- const profilePath = path42.join(paths.configProfilesDir, `${name}.json`);
22324
+ const profilePath = path43.join(paths.configProfilesDir, `${name}.json`);
21994
22325
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
21995
22326
  });
21996
22327
  const providerNames = fs14.existsSync(paths.providersDir) ? fs14.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
21997
22328
  const providers = providerNames.map((name) => {
21998
- const providerPath = path42.join(paths.providersDir, `${name}.json`);
22329
+ const providerPath = path43.join(paths.providersDir, `${name}.json`);
21999
22330
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
22000
22331
  });
22001
22332
  const ownExecutablePath = realOwnExecutablePath();
@@ -22007,12 +22338,12 @@ function collectDoctorReport(params) {
22007
22338
  binaryDiscovery = { ok: false, message: error instanceof Error ? error.message : String(error) };
22008
22339
  }
22009
22340
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
22010
- const pathDirs = (params.env.PATH ?? "").split(path42.delimiter).filter((dir) => dir !== "");
22341
+ const pathDirs = (params.env.PATH ?? "").split(path43.delimiter).filter((dir) => dir !== "");
22011
22342
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
22012
22343
  findPathShadow({
22013
22344
  pathDirs,
22014
- targetDir: path42.dirname(shimState.targetPath),
22015
- targetFilename: path42.basename(shimState.targetPath),
22345
+ targetDir: path43.dirname(shimState.targetPath),
22346
+ targetFilename: path43.basename(shimState.targetPath),
22016
22347
  findExecutableInDir
22017
22348
  }),
22018
22349
  shimState.targetPath,
@@ -22037,9 +22368,10 @@ function collectDoctorReport(params) {
22037
22368
  providers,
22038
22369
  providerAliases: readProviderAliases(paths),
22039
22370
  probeBaseUrls: realBaseUrlBatchProbe,
22371
+ catalogueRedirects: providersWithRedirectedCatalogue(realFarmFs, paths, new Map(providers.map((entry) => [entry.name, currentCatalogueSettings(paths, entry.name)]))),
22040
22372
  renameJournals: listRenameJournals(realFarmFs, paths.identityRenamesDir),
22041
22373
  unreachableIdentities,
22042
- identityRecords: { all: records, displaced: displacedIdentities.map((record) => ({ ...record, directoryPresent: fs14.existsSync(path42.join(paths.identitiesDir, record.id)) })), nameRenames: unfinishedNameRenames(paths).map((record) => ({ from: record.from, description: describeInterruptedNameRename(paths, record) })), strayNameRenameFiles: strayNameRenameRecordFiles(paths) },
22374
+ identityRecords: { all: records, displaced: displacedIdentities.map((record) => ({ ...record, directoryPresent: fs14.existsSync(path43.join(paths.identitiesDir, record.id)) })), nameRenames: unfinishedNameRenames(paths).map((record) => ({ from: record.from, description: describeInterruptedNameRename(paths, record) })), strayNameRenameFiles: strayNameRenameRecordFiles(paths) },
22043
22375
  directoryRules: { path: paths.directoryRulesFile, raw: realFsPort.readFileUtf8(paths.directoryRulesFile) },
22044
22376
  globalConfig: { path: paths.globalConfigFile, raw: realFsPort.readFileUtf8(paths.globalConfigFile) },
22045
22377
  models: readableOr(() => readGlobalConfig(paths)?.models, void 0),
@@ -22054,7 +22386,7 @@ function collectDoctorReport(params) {
22054
22386
  agentShim: refinePathShadow(
22055
22387
  findPathShadow({
22056
22388
  pathDirs,
22057
- targetDir: path42.dirname(ownExecutablePath),
22389
+ targetDir: path43.dirname(ownExecutablePath),
22058
22390
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
22059
22391
  findExecutableInDir
22060
22392
  }),
@@ -22097,93 +22429,93 @@ function collectDoctorReport(params) {
22097
22429
  init_schema2();
22098
22430
  init_rcSchemas();
22099
22431
  init_state();
22100
- var UsageListOutputSchema = z37.strictObject({ snapshots: z37.readonly(z37.array(UsageSnapshotSchema)) });
22101
- var UsageWindowsInputSchema = z37.strictObject({
22102
- identity: z37.string().min(1),
22103
- provider: z37.string().min(1).optional()
22432
+ var UsageListOutputSchema = z38.strictObject({ snapshots: z38.readonly(z38.array(UsageSnapshotSchema)) });
22433
+ var UsageWindowsInputSchema = z38.strictObject({
22434
+ identity: z38.string().min(1),
22435
+ provider: z38.string().min(1).optional()
22104
22436
  });
22105
- var EffectiveWindowSchema = z37.strictObject({
22437
+ var EffectiveWindowSchema = z38.strictObject({
22106
22438
  /** True when the window's reset time has passed, so the recorded observation describes a window that no longer exists. */
22107
- reset: z37.boolean(),
22439
+ reset: z38.boolean(),
22108
22440
  /** The fraction used: 0 for a reset window, otherwise what was last observed, absent when none was reported. */
22109
- utilization: z37.number().optional(),
22441
+ utilization: z38.number().optional(),
22110
22442
  /** The reset instant, for a window that has not reset yet and reported one. */
22111
- resetsAtMs: z37.number().optional(),
22443
+ resetsAtMs: z38.number().optional(),
22112
22444
  /** The window's own status, for a window that has not reset yet. */
22113
- status: z37.string().optional()
22445
+ status: z38.string().optional()
22114
22446
  });
22115
- var UsageWindowsOutputSchema = z37.strictObject({
22116
- identity: z37.string(),
22117
- provider: z37.string(),
22447
+ var UsageWindowsOutputSchema = z38.strictObject({
22448
+ identity: z38.string(),
22449
+ provider: z38.string(),
22118
22450
  /** When the rate-limit state the windows come from was observed. */
22119
- observedAt: z37.iso.datetime().optional(),
22451
+ observedAt: z38.iso.datetime().optional(),
22120
22452
  fiveHour: EffectiveWindowSchema.optional(),
22121
22453
  sevenDay: EffectiveWindowSchema.optional()
22122
22454
  });
22123
- var UsageLiveOutputSchema = z37.strictObject({
22455
+ var UsageLiveOutputSchema = z38.strictObject({
22124
22456
  /** The freshest observation the door holds, never narrowed by the read's session filter because it is the door's single latest statement of the account's quota; absent while no rate_limit_event has been filed at all. */
22125
22457
  latest: RcLiveRateLimitSchema.optional(),
22126
22458
  /** One observation per session whose stream has filed a rate_limit_event this door generation. */
22127
- sessions: z37.readonly(z37.array(RcLiveRateLimitSchema))
22459
+ sessions: z38.readonly(z38.array(RcLiveRateLimitSchema))
22128
22460
  });
22129
- var FrontDoorSessionStatusSchema = z37.strictObject({
22130
- pid: z37.int().positive(),
22131
- startedAt: z37.number(),
22132
- alive: z37.boolean()
22461
+ var FrontDoorSessionStatusSchema = z38.strictObject({
22462
+ pid: z38.int().positive(),
22463
+ startedAt: z38.number(),
22464
+ alive: z38.boolean()
22133
22465
  });
22134
- var HeadroomSocketTargetSchema = z37.union([z37.strictObject({ socketPath: z37.string() }), z37.strictObject({ refused: z37.string() })]);
22135
- var FrontDoorStatusOutputSchema = z37.strictObject({
22466
+ var HeadroomSocketTargetSchema = z38.union([z38.strictObject({ socketPath: z38.string() }), z38.strictObject({ refused: z38.string() })]);
22467
+ var FrontDoorStatusOutputSchema = z38.strictObject({
22136
22468
  state: FrontDoorStateSchema,
22137
- supervisorAlive: z37.boolean(),
22469
+ supervisorAlive: z38.boolean(),
22138
22470
  /** The pids of earlier doors that released their addresses and are finishing the connections they carried: running, but not serving anything new. */
22139
- draining: z37.readonly(z37.array(z37.number().int().positive())),
22140
- sessions: z37.readonly(z37.array(FrontDoorSessionStatusSchema)),
22471
+ draining: z38.readonly(z38.array(z38.number().int().positive())),
22472
+ sessions: z38.readonly(z38.array(FrontDoorSessionStatusSchema)),
22141
22473
  headroomSocket: HeadroomSocketTargetSchema.optional(),
22142
- logPath: z37.string(),
22143
- logExists: z37.boolean()
22474
+ logPath: z38.string(),
22475
+ logExists: z38.boolean()
22144
22476
  });
22145
- var FrontDoorSessionsOutputSchema = z37.strictObject({ sessions: z37.readonly(z37.array(FrontDoorSessionStatusSchema)) });
22477
+ var FrontDoorSessionsOutputSchema = z38.strictObject({ sessions: z38.readonly(z38.array(FrontDoorSessionStatusSchema)) });
22146
22478
  var DOOR_REPORT_ENVIRONMENT_NOTE = "The report is collected in a worker thread of the door under the door's own environment and PATH, as a launch the door plans for itself would inherit them, not under the caller's shell: the identity is the caller's to name, the cascade is read from files at the path, and the environment-driven findings (AGENT_SHIM_IDENTITY, AGENT_SHIM_CONFIG_PROFILE, the Claude Code version pin, the ambient-credential check, and for doctor the PATH and shim findings) describe the door's launch. Run agent-shim check or agent-shim doctor from a shell for the caller's own reading.";
22147
- var CheckRunInputSchema = z37.strictObject({
22148
- path: z37.string().min(1),
22149
- identity: z37.string().min(1).optional()
22150
- }).refine((input) => path43.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
22151
- var PoolPickInputSchema = z37.strictObject({
22152
- pool: z37.string().min(1),
22153
- path: z37.string().min(1)
22154
- }).refine((input) => path43.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
22155
- var DoctorFindingSchema = z37.strictObject({
22156
- section: z37.enum(DOCTOR_SECTIONS),
22157
- subject: z37.string().optional(),
22158
- severity: z37.enum(DOCTOR_SEVERITIES),
22159
- message: z37.string()
22479
+ var CheckRunInputSchema = z38.strictObject({
22480
+ path: z38.string().min(1),
22481
+ identity: z38.string().min(1).optional()
22482
+ }).refine((input) => path44.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
22483
+ var PoolPickInputSchema = z38.strictObject({
22484
+ pool: z38.string().min(1),
22485
+ path: z38.string().min(1)
22486
+ }).refine((input) => path44.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
22487
+ var DoctorFindingSchema = z38.strictObject({
22488
+ section: z38.enum(DOCTOR_SECTIONS),
22489
+ subject: z38.string().optional(),
22490
+ severity: z38.enum(DOCTOR_SEVERITIES),
22491
+ message: z38.string()
22160
22492
  });
22161
- var DoctorRunOutputSchema = z37.strictObject({
22493
+ var DoctorRunOutputSchema = z38.strictObject({
22162
22494
  /** False exactly when any finding is a `fail`; a `warn` never fails the report on its own. */
22163
- ok: z37.boolean(),
22164
- findings: z37.readonly(z37.array(DoctorFindingSchema))
22495
+ ok: z38.boolean(),
22496
+ findings: z38.readonly(z38.array(DoctorFindingSchema))
22165
22497
  });
22166
- var FrontDoorRestartOutputSchema = z37.strictObject({
22167
- action: z37.literal("restarting"),
22168
- previousPid: z37.int().positive()
22498
+ var FrontDoorRestartOutputSchema = z38.strictObject({
22499
+ action: z38.literal("restarting"),
22500
+ previousPid: z38.int().positive()
22169
22501
  });
22170
- var UpdateCheckOutputSchema = z37.strictObject({
22171
- current: z37.string(),
22172
- latest: z37.string(),
22173
- action: z37.enum(["current", "available", "updated"])
22502
+ var UpdateCheckOutputSchema = z38.strictObject({
22503
+ current: z38.string(),
22504
+ latest: z38.string(),
22505
+ action: z38.enum(["current", "available", "updated"])
22174
22506
  });
22175
- var CodexSignInSchema = z37.discriminatedUnion("state", [
22176
- z37.strictObject({ state: z37.literal("none") }),
22177
- z37.strictObject({ state: z37.literal("signed-in"), email: z37.string().optional(), planScope: z37.boolean(), accessTokenExpiresAt: z37.number() }),
22178
- z37.strictObject({ state: z37.literal("unreadable"), message: z37.string() })
22507
+ var CodexSignInSchema = z38.discriminatedUnion("state", [
22508
+ z38.strictObject({ state: z38.literal("none") }),
22509
+ z38.strictObject({ state: z38.literal("signed-in"), email: z38.string().optional(), planScope: z38.boolean(), accessTokenExpiresAt: z38.number() }),
22510
+ z38.strictObject({ state: z38.literal("unreadable"), message: z38.string() })
22179
22511
  ]);
22180
- var CodexStatusOutputSchema = z37.strictObject({
22512
+ var CodexStatusOutputSchema = z38.strictObject({
22181
22513
  signIn: CodexSignInSchema,
22182
- codexProviders: z37.readonly(z37.array(z37.string()))
22514
+ codexProviders: z38.readonly(z38.array(z38.string()))
22183
22515
  });
22184
- var CodexLogoutOutputSchema = z37.strictObject({
22185
- hadGrant: z37.boolean(),
22186
- revoked: z37.boolean()
22516
+ var CodexLogoutOutputSchema = z38.strictObject({
22517
+ hadGrant: z38.boolean(),
22518
+ revoked: z38.boolean()
22187
22519
  });
22188
22520
 
22189
22521
  // src/frontdoor/codexApi.ts
@@ -22204,20 +22536,21 @@ function createCodexApiRouter(deps) {
22204
22536
 
22205
22537
  // src/frontdoor/doorWorker.ts
22206
22538
  import { getAsset, isSea as isSea2 } from "node:sea";
22207
- import { z as z39 } from "zod";
22539
+ import { z as z40 } from "zod";
22208
22540
  init_cliError();
22209
22541
  init_doorBounds();
22210
22542
  init_providerCatalogue();
22211
22543
 
22212
22544
  // src/frontdoor/doorWorkerProtocol.ts
22213
- import { z as z38 } from "zod";
22545
+ init_providerCatalogue();
22546
+ import { z as z39 } from "zod";
22214
22547
  var doorWorkerInputSchemas = {
22215
22548
  /** `agent-shim check` for `path` as `identity` (the identity a launch there would resolve when absent). */
22216
- check: z38.strictObject({ root: z38.string().min(1), path: z38.string().min(1), identity: z38.string().min(1).optional() }),
22549
+ check: z39.strictObject({ root: z39.string().min(1), path: z39.string().min(1), identity: z39.string().min(1).optional() }),
22217
22550
  /** `agent-shim doctor`. */
22218
- doctor: z38.strictObject({ root: z38.string().min(1) }),
22551
+ doctor: z39.strictObject({ root: z39.string().min(1) }),
22219
22552
  /** Fetch and store one provider's model catalogue for the door generation that asked. */
22220
- "refresh-catalogue": z38.strictObject({ root: z38.string().min(1), name: z38.string().min(1), supervisorPid: z38.int().positive(), generation: z38.uuid() })
22553
+ "refresh-catalogue": z39.strictObject({ root: z39.string().min(1), name: z39.string().min(1), supervisorPid: z39.int().positive(), generation: z39.uuid() })
22221
22554
  };
22222
22555
 
22223
22556
  // src/frontdoor/doorWorker.ts
@@ -22232,15 +22565,18 @@ var DoorWorkerBusyError = class extends CliError {
22232
22565
  var NEXT_STEP = {
22233
22566
  check: "run `agent-shim check` from a shell for the detail",
22234
22567
  doctor: "run `agent-shim doctor` from a shell for the detail",
22235
- "refresh-catalogue": "run `agent-shim provider models --refresh <name>` from a shell for the detail"
22568
+ "refresh-catalogue": "run `agent-shim provider models <name> --refresh` from a shell for the detail"
22236
22569
  };
22237
22570
  var DoorWorkerFailedError = class extends CliError {
22238
- constructor(task, reason, kind) {
22571
+ constructor(task, reason, kind, redirected = false) {
22239
22572
  super(`${task} failed in its worker: ${reason}${task === "an unknown task" ? "" : `; ${NEXT_STEP[task]}`}`);
22240
22573
  this.kind = kind;
22241
22574
  this.name = "DoorWorkerFailedError";
22575
+ this.redirected = redirected;
22242
22576
  }
22243
22577
  kind;
22578
+ /** Whether the worker's error said a catalogue read met a redirect: the one fact of a worker's error that crosses the thread besides its class name and code. */
22579
+ redirected;
22244
22580
  };
22245
22581
 
22246
22582
  // src/frontdoor/configApi.ts
@@ -22297,7 +22633,7 @@ init_identityStore();
22297
22633
  init_keychainLogin();
22298
22634
  init_identityNamesLock();
22299
22635
  init_lock();
22300
- init_identity();
22636
+ init_identity2();
22301
22637
  init_replayRun();
22302
22638
  init_poolStore();
22303
22639
  init_baseUrlDisplay();
@@ -22308,68 +22644,68 @@ init_schema();
22308
22644
  init_names();
22309
22645
  init_keychainLogin();
22310
22646
  init_statusline();
22311
- import { z as z40 } from "zod";
22312
- var RemovalConfirmationSchema = z40.boolean();
22313
- var CredentialWriteSchema = (targets) => z40.strictObject({
22314
- sources: z40.array(RemoteCredentialSourceSchema).min(1).optional(),
22315
- target: z40.enum(targets).optional(),
22316
- cache: z40.union([z40.literal(false), CredentialCacheSchema]).optional()
22647
+ import { z as z41 } from "zod";
22648
+ var RemovalConfirmationSchema = z41.boolean();
22649
+ var CredentialWriteSchema = (targets) => z41.strictObject({
22650
+ sources: z41.array(RemoteCredentialSourceSchema).min(1).optional(),
22651
+ target: z41.enum(targets).optional(),
22652
+ cache: z41.union([z41.literal(false), CredentialCacheSchema]).optional()
22317
22653
  });
22318
- var CredentialSummarySchema2 = z40.strictObject({
22319
- target: z40.enum(CREDENTIAL_TARGETS),
22320
- sources: z40.readonly(z40.array(
22321
- z40.discriminatedUnion("kind", [
22322
- z40.strictObject({ kind: z40.literal("env"), variable: z40.string() }),
22323
- z40.strictObject({ kind: z40.literal("file"), path: z40.string() }),
22324
- z40.strictObject({ kind: z40.literal("command"), program: z40.string() }),
22325
- z40.strictObject({ kind: z40.literal("op"), reference: z40.string() }),
22326
- z40.strictObject({ kind: z40.literal("keychain"), service: z40.string(), account: z40.string().optional() }),
22327
- z40.strictObject({ kind: z40.literal("literal") })
22654
+ var CredentialSummarySchema2 = z41.strictObject({
22655
+ target: z41.enum(CREDENTIAL_TARGETS),
22656
+ sources: z41.readonly(z41.array(
22657
+ z41.discriminatedUnion("kind", [
22658
+ z41.strictObject({ kind: z41.literal("env"), variable: z41.string() }),
22659
+ z41.strictObject({ kind: z41.literal("file"), path: z41.string() }),
22660
+ z41.strictObject({ kind: z41.literal("command"), program: z41.string() }),
22661
+ z41.strictObject({ kind: z41.literal("op"), reference: z41.string() }),
22662
+ z41.strictObject({ kind: z41.literal("keychain"), service: z41.string(), account: z41.string().optional() }),
22663
+ z41.strictObject({ kind: z41.literal("literal") })
22328
22664
  ])
22329
22665
  )),
22330
22666
  cache: CredentialCacheSchema.optional()
22331
22667
  });
22332
- var mutationOutput = (kind, action) => z40.strictObject({ action: z40.literal(action), kind: z40.literal(kind), name: z40.string() });
22333
- var storedMutationOutput = (kind, action, value) => z40.strictObject({ action: z40.literal(action), kind: z40.literal(kind), name: z40.string(), value });
22334
- var IdentityValueSchema = z40.strictObject({
22335
- agent: z40.enum(["claude", "codex"]).optional(),
22336
- name: z40.string(),
22337
- label: z40.string().optional(),
22338
- defaultConfigProfile: z40.string().optional(),
22339
- provider: z40.string().optional(),
22340
- allowAmbientCredential: z40.boolean(),
22668
+ var mutationOutput = (kind, action) => z41.strictObject({ action: z41.literal(action), kind: z41.literal(kind), name: z41.string() });
22669
+ var storedMutationOutput = (kind, action, value) => z41.strictObject({ action: z41.literal(action), kind: z41.literal(kind), name: z41.string(), value });
22670
+ var IdentityValueSchema = z41.strictObject({
22671
+ agent: z41.enum(["claude", "codex"]).optional(),
22672
+ name: z41.string(),
22673
+ label: z41.string().optional(),
22674
+ defaultConfigProfile: z41.string().optional(),
22675
+ provider: z41.string().optional(),
22676
+ allowAmbientCredential: z41.boolean(),
22341
22677
  credential: CredentialSummarySchema2.optional(),
22342
- anchors: z40.array(AnchorSchema).optional()
22678
+ anchors: z41.array(AnchorSchema).optional()
22343
22679
  });
22344
22680
  var ProfileValueSchema = ConfigProfileSchema.omit({ $schema: true });
22345
- var ProviderValueSchema = z40.strictObject({
22346
- name: z40.string(),
22347
- kind: z40.enum(PROVIDER_KINDS),
22348
- displayName: z40.string(),
22349
- baseUrl: z40.string().optional(),
22681
+ var ProviderValueSchema = z41.strictObject({
22682
+ name: z41.string(),
22683
+ kind: z41.enum(PROVIDER_KINDS),
22684
+ displayName: z41.string(),
22685
+ baseUrl: z41.string().optional(),
22350
22686
  codex: CodexProviderConfigSchema.optional(),
22351
22687
  credential: CredentialSummarySchema2.optional(),
22352
- env: z40.record(z40.string(), z40.string()).optional()
22688
+ env: z41.record(z41.string(), z41.string()).optional()
22353
22689
  });
22354
- var ConfigNameInputSchema = z40.strictObject({ name: z40.string().min(1) });
22355
- var ConfigIdentityAddInputSchema = z40.strictObject({ name: z40.string().min(1), keepKeychainLogin: z40.boolean().optional().describe(KEEP_KEYCHAIN_LOGIN_DESCRIPTION) });
22690
+ var ConfigNameInputSchema = z41.strictObject({ name: z41.string().min(1) });
22691
+ var ConfigIdentityAddInputSchema = z41.strictObject({ name: z41.string().min(1), keepKeychainLogin: z41.boolean().optional().describe(KEEP_KEYCHAIN_LOGIN_DESCRIPTION) });
22356
22692
  var ConfigIdentityAddOutputSchema = storedMutationOutput("identity", "created", IdentityValueSchema);
22357
- var ConfigIdentitySetInputSchema = z40.strictObject({
22358
- name: z40.string().min(1),
22693
+ var ConfigIdentitySetInputSchema = z41.strictObject({
22694
+ name: z41.string().min(1),
22359
22695
  /** The identity's display label; `false` clears it. */
22360
- label: z40.union([IdentityLabelSchema, z40.literal(false)]).optional(),
22361
- defaultConfigProfile: z40.union([z40.string().min(1), z40.literal(false)]).optional(),
22696
+ label: z41.union([IdentityLabelSchema, z41.literal(false)]).optional(),
22697
+ defaultConfigProfile: z41.union([z41.string().min(1), z41.literal(false)]).optional(),
22362
22698
  /** The provider the identity exists for; `false` clears it. */
22363
- provider: z40.union([z40.string().min(1), z40.literal(false)]).optional(),
22364
- allowAmbientCredential: z40.boolean().optional(),
22365
- credential: z40.union([z40.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
22699
+ provider: z41.union([z41.string().min(1), z41.literal(false)]).optional(),
22700
+ allowAmbientCredential: z41.boolean().optional(),
22701
+ credential: z41.union([z41.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
22366
22702
  /** `false` removes the anchors; a list replaces them. */
22367
- anchors: z40.union([z40.literal(false), z40.array(AnchorSchema).min(1)]).optional()
22703
+ anchors: z41.union([z41.literal(false), z41.array(AnchorSchema).min(1)]).optional()
22368
22704
  });
22369
22705
  var ConfigIdentitySetOutputSchema = storedMutationOutput("identity", "updated", IdentityValueSchema);
22370
- var ConfigIdentityRemoveInputSchema = z40.strictObject({ name: z40.string().min(1), confirm: RemovalConfirmationSchema });
22706
+ var ConfigIdentityRemoveInputSchema = z41.strictObject({ name: z41.string().min(1), confirm: RemovalConfirmationSchema });
22371
22707
  var ConfigIdentityRemoveOutputSchema = mutationOutput("identity", "removed");
22372
- var ConfigStatuslineSetSchema = z40.record(z40.string(), z40.unknown()).superRefine((settings, context) => {
22708
+ var ConfigStatuslineSetSchema = z41.record(z41.string(), z41.unknown()).superRefine((settings, context) => {
22373
22709
  for (const key of Object.keys(settings)) {
22374
22710
  if (key === STATUSLINE_EXTRA_GROUP || key.startsWith(`${STATUSLINE_EXTRA_GROUP}.`)) {
22375
22711
  context.addIssue({ code: "custom", path: [key], message: `a config write through the API cannot set "${key}": the extra segment's command runs a program, so only your own configuration (the global config, a profile you edit yourself, a directory rule or a command-line assignment) may set it` });
@@ -22377,93 +22713,93 @@ var ConfigStatuslineSetSchema = z40.record(z40.string(), z40.unknown()).superRef
22377
22713
  }
22378
22714
  });
22379
22715
  var ConfigIdentityUseOutputSchema = mutationOutput("identity", "selected");
22380
- var ConfigProfileAddInputSchema = z40.strictObject({
22381
- name: z40.string().min(1),
22382
- extends: z40.array(z40.string().min(1)).optional(),
22383
- description: z40.string().optional()
22716
+ var ConfigProfileAddInputSchema = z41.strictObject({
22717
+ name: z41.string().min(1),
22718
+ extends: z41.array(z41.string().min(1)).optional(),
22719
+ description: z41.string().optional()
22384
22720
  });
22385
22721
  var ConfigProfileAddOutputSchema = storedMutationOutput("profile", "created", ProfileValueSchema);
22386
- var ConfigProfileSetInputSchema = z40.strictObject({
22387
- name: z40.string().min(1),
22388
- category: z40.record(z40.string(), z40.boolean()).optional(),
22389
- entry: z40.record(z40.string(), z40.boolean()).optional(),
22390
- extends: z40.union([z40.array(z40.string().min(1)), z40.literal(false)]).optional(),
22391
- description: z40.union([z40.string(), z40.literal(false)]).optional(),
22392
- launch: z40.strictObject({
22393
- skipPermissions: z40.boolean().optional(),
22394
- remoteControl: z40.boolean().optional(),
22395
- headroom: z40.boolean().optional(),
22396
- trackUsage: z40.boolean().optional(),
22397
- provider: z40.union([z40.string().min(1), z40.literal(false)]).optional(),
22398
- claudeVersion: z40.union([z40.string().min(1), z40.literal(false)]).optional(),
22399
- delay: z40.union([z40.string().regex(DURATION_RE), z40.literal(false)]).optional(),
22400
- pause: z40.boolean().optional(),
22401
- explain: z40.boolean().optional(),
22402
- proxyBypass: z40.union([z40.array(z40.string().min(1)), z40.literal(false)]).optional(),
22403
- statusline: z40.strictObject({
22722
+ var ConfigProfileSetInputSchema = z41.strictObject({
22723
+ name: z41.string().min(1),
22724
+ category: z41.record(z41.string(), z41.boolean()).optional(),
22725
+ entry: z41.record(z41.string(), z41.boolean()).optional(),
22726
+ extends: z41.union([z41.array(z41.string().min(1)), z41.literal(false)]).optional(),
22727
+ description: z41.union([z41.string(), z41.literal(false)]).optional(),
22728
+ launch: z41.strictObject({
22729
+ skipPermissions: z41.boolean().optional(),
22730
+ remoteControl: z41.boolean().optional(),
22731
+ headroom: z41.boolean().optional(),
22732
+ trackUsage: z41.boolean().optional(),
22733
+ provider: z41.union([z41.string().min(1), z41.literal(false)]).optional(),
22734
+ claudeVersion: z41.union([z41.string().min(1), z41.literal(false)]).optional(),
22735
+ delay: z41.union([z41.string().regex(DURATION_RE), z41.literal(false)]).optional(),
22736
+ pause: z41.boolean().optional(),
22737
+ explain: z41.boolean().optional(),
22738
+ proxyBypass: z41.union([z41.array(z41.string().min(1)), z41.literal(false)]).optional(),
22739
+ statusline: z41.strictObject({
22404
22740
  set: ConfigStatuslineSetSchema.optional(),
22405
- unset: z40.array(z40.string()).optional()
22741
+ unset: z41.array(z41.string()).optional()
22406
22742
  }).optional()
22407
22743
  }).optional()
22408
22744
  });
22409
22745
  var ConfigProfileSetOutputSchema = storedMutationOutput("profile", "updated", ProfileValueSchema);
22410
- var ConfigProfileRemoveInputSchema = z40.strictObject({ name: z40.string().min(1), confirm: RemovalConfirmationSchema });
22746
+ var ConfigProfileRemoveInputSchema = z41.strictObject({ name: z41.string().min(1), confirm: RemovalConfirmationSchema });
22411
22747
  var ConfigProfileRemoveOutputSchema = mutationOutput("profile", "removed");
22412
22748
  var ConfigProfileUseOutputSchema = mutationOutput("profile", "selected");
22413
- var PoolMembersInputSchema = z40.array(z40.string().min(1)).min(1);
22414
- var ConfigPoolAddInputSchema = z40.strictObject({
22415
- name: z40.string().min(1),
22749
+ var PoolMembersInputSchema = z41.array(z41.string().min(1)).min(1);
22750
+ var ConfigPoolAddInputSchema = z41.strictObject({
22751
+ name: z41.string().min(1),
22416
22752
  identities: PoolMembersInputSchema,
22417
- preference: z40.enum(POOL_PREFERENCES).optional(),
22418
- resumeOnLimit: z40.boolean().optional(),
22419
- compactBeforeLimit: z40.boolean().optional(),
22753
+ preference: z41.enum(POOL_PREFERENCES).optional(),
22754
+ resumeOnLimit: z41.boolean().optional(),
22755
+ compactBeforeLimit: z41.boolean().optional(),
22420
22756
  compactAtUtilisation: CompactAtUtilisationSchema.optional()
22421
22757
  });
22422
22758
  var ConfigPoolAddOutputSchema = storedMutationOutput("pool", "created", PoolSchema);
22423
- var ConfigPoolSetInputSchema = z40.strictObject({
22424
- name: z40.string().min(1),
22759
+ var ConfigPoolSetInputSchema = z41.strictObject({
22760
+ name: z41.string().min(1),
22425
22761
  identities: PoolMembersInputSchema.optional(),
22426
- preference: z40.union([z40.enum(POOL_PREFERENCES), z40.literal(false)]).optional(),
22427
- resumeOnLimit: z40.boolean().optional(),
22428
- compactBeforeLimit: z40.boolean().optional(),
22429
- compactAtUtilisation: z40.union([CompactAtUtilisationSchema, z40.literal(false)]).optional()
22762
+ preference: z41.union([z41.enum(POOL_PREFERENCES), z41.literal(false)]).optional(),
22763
+ resumeOnLimit: z41.boolean().optional(),
22764
+ compactBeforeLimit: z41.boolean().optional(),
22765
+ compactAtUtilisation: z41.union([CompactAtUtilisationSchema, z41.literal(false)]).optional()
22430
22766
  });
22431
22767
  var ConfigPoolSetOutputSchema = storedMutationOutput("pool", "updated", PoolSchema);
22432
- var ConfigPoolRemoveInputSchema = z40.strictObject({ name: z40.string().min(1), confirm: RemovalConfirmationSchema });
22768
+ var ConfigPoolRemoveInputSchema = z41.strictObject({ name: z41.string().min(1), confirm: RemovalConfirmationSchema });
22433
22769
  var ConfigPoolRemoveOutputSchema = mutationOutput("pool", "removed");
22434
22770
  var ConfigPoolUseOutputSchema = mutationOutput("pool", "selected");
22435
- var ConfigProviderAddInputSchema = z40.strictObject({
22436
- name: z40.string().min(1),
22437
- kind: z40.enum(PROVIDER_KINDS).optional(),
22438
- displayName: z40.string().min(1),
22439
- baseUrl: z40.string().min(1).optional(),
22771
+ var ConfigProviderAddInputSchema = z41.strictObject({
22772
+ name: z41.string().min(1),
22773
+ kind: z41.enum(PROVIDER_KINDS).optional(),
22774
+ displayName: z41.string().min(1),
22775
+ baseUrl: z41.string().min(1).optional(),
22440
22776
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).required({ sources: true }),
22441
22777
  codex: CodexProviderConfigSchema.optional()
22442
22778
  });
22443
22779
  var ConfigProviderAddOutputSchema = storedMutationOutput("provider", "created", ProviderValueSchema);
22444
- var ConfigProviderSetInputSchema = z40.strictObject({
22445
- name: z40.string().min(1),
22446
- displayName: z40.string().min(1).optional(),
22447
- baseUrl: z40.string().min(1).optional(),
22780
+ var ConfigProviderSetInputSchema = z41.strictObject({
22781
+ name: z41.string().min(1),
22782
+ displayName: z41.string().min(1).optional(),
22783
+ baseUrl: z41.string().min(1).optional(),
22448
22784
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).optional(),
22449
22785
  codex: CodexProviderConfigSchema.optional()
22450
22786
  });
22451
22787
  var ConfigProviderSetOutputSchema = storedMutationOutput("provider", "updated", ProviderValueSchema);
22452
- var ConfigProviderRemoveInputSchema = z40.strictObject({ name: z40.string().min(1), confirm: RemovalConfirmationSchema });
22788
+ var ConfigProviderRemoveInputSchema = z41.strictObject({ name: z41.string().min(1), confirm: RemovalConfirmationSchema });
22453
22789
  var ConfigProviderRemoveOutputSchema = mutationOutput("provider", "removed");
22454
- var ConfigRuleAddInputSchema = z40.strictObject({
22455
- path: z40.string().min(1),
22456
- configProfile: z40.string().min(1).optional(),
22457
- identity: z40.string().min(1).optional()
22790
+ var ConfigRuleAddInputSchema = z41.strictObject({
22791
+ path: z41.string().min(1),
22792
+ configProfile: z41.string().min(1).optional(),
22793
+ identity: z41.string().min(1).optional()
22458
22794
  });
22459
22795
  var ConfigRuleAddOutputSchema = storedMutationOutput("rule", "created", DirectoryRuleSchema);
22460
- var ConfigRuleSetInputSchema = z40.strictObject({
22461
- path: z40.string().min(1),
22462
- configProfile: z40.union([z40.string().min(1), z40.literal(false)]).optional(),
22463
- identity: z40.union([z40.string().min(1), z40.literal(false)]).optional()
22796
+ var ConfigRuleSetInputSchema = z41.strictObject({
22797
+ path: z41.string().min(1),
22798
+ configProfile: z41.union([z41.string().min(1), z41.literal(false)]).optional(),
22799
+ identity: z41.union([z41.string().min(1), z41.literal(false)]).optional()
22464
22800
  });
22465
22801
  var ConfigRuleSetOutputSchema = storedMutationOutput("rule", "updated", DirectoryRuleSchema);
22466
- var ConfigRuleRemoveInputSchema = z40.strictObject({ path: z40.string().min(1), confirm: RemovalConfirmationSchema });
22802
+ var ConfigRuleRemoveInputSchema = z41.strictObject({ path: z41.string().min(1), confirm: RemovalConfirmationSchema });
22467
22803
  var ConfigRuleRemoveOutputSchema = mutationOutput("rule", "removed");
22468
22804
 
22469
22805
  // src/frontdoor/configApi.ts
@@ -22537,7 +22873,7 @@ function profileValue(name, paths) {
22537
22873
  function createConfigApiRouter(deps) {
22538
22874
  const authed = doorApiAuth(deps.expectedToken);
22539
22875
  const { paths } = deps;
22540
- const route = (path55, summary) => authed.meta(openapi3({ method: "POST", path: path55, summary, tags: [CONFIG_API_TAG] }));
22876
+ const route = (path56, summary) => authed.meta(openapi3({ method: "POST", path: path56, summary, tags: [CONFIG_API_TAG] }));
22541
22877
  return {
22542
22878
  config: {
22543
22879
  identity: {
@@ -22808,50 +23144,50 @@ import { eventIterator as eventIterator2, withEventMeta as withEventMeta2 } from
22808
23144
 
22809
23145
  // src/frontdoor/eventSchemas.ts
22810
23146
  init_schema2();
22811
- import { z as z41 } from "zod";
23147
+ import { z as z42 } from "zod";
22812
23148
  var DOOR_EVENT_SOURCE_RC = "rc";
22813
23149
  var LAUNCH_EVENT_SOURCE = "launch";
22814
23150
  var USAGE_EVENT_SOURCE = "usage";
22815
23151
  var DOOR_HEALTH_EVENT_SOURCE = "door";
22816
23152
  var QUOTA_EXPIRING_EVENT_SOURCE = "quota-expiring";
22817
- var DoorEventSchema = z41.strictObject({
22818
- source: z41.string().min(1),
23153
+ var DoorEventSchema = z42.strictObject({
23154
+ source: z42.string().min(1),
22819
23155
  /** A positive integer because the backbone's counters start at one and only ever increase. */
22820
- sequence: z41.number().int().positive(),
22821
- payload: z41.unknown()
23156
+ sequence: z42.number().int().positive(),
23157
+ payload: z42.unknown()
22822
23158
  });
22823
- var DoorEventSourceQuerySchema = z41.strictObject({
22824
- sources: z41.array(z41.string().min(1)).min(1).optional()
23159
+ var DoorEventSourceQuerySchema = z42.strictObject({
23160
+ sources: z42.array(z42.string().min(1)).min(1).optional()
22825
23161
  });
22826
- var LaunchLifecycleEventSchema = z41.strictObject({
22827
- kind: z41.enum(["registered", "pruned", "ended"]),
22828
- pid: z41.number().int().positive(),
22829
- startedAt: z41.number(),
22830
- observedAt: z41.number()
23162
+ var LaunchLifecycleEventSchema = z42.strictObject({
23163
+ kind: z42.enum(["registered", "pruned", "ended"]),
23164
+ pid: z42.number().int().positive(),
23165
+ startedAt: z42.number(),
23166
+ observedAt: z42.number()
22831
23167
  });
22832
- var DoorHealthEventSchema = z41.discriminatedUnion("kind", [
22833
- z41.strictObject({ kind: z41.literal("generation"), pid: z41.number().int().positive(), providerPort: z41.number().int().positive(), connectPort: z41.number().int().positive(), directPort: z41.number().int().positive(), observedAt: z41.number() }),
22834
- z41.strictObject({ kind: z41.literal("listenerFailed"), pid: z41.number().int().positive(), listener: z41.enum(["provider", "connect", "direct"]), message: z41.string(), observedAt: z41.number() }),
22835
- z41.strictObject({ kind: z41.literal("binaryTurnover"), pid: z41.number().int().positive(), observedAt: z41.number() }),
22836
- z41.strictObject({ kind: z41.literal("idleShutdown"), pid: z41.number().int().positive(), observedAt: z41.number() }),
22837
- z41.strictObject({ kind: z41.literal("superseded"), pid: z41.number().int().positive(), ownerPid: z41.number().int().positive(), observedAt: z41.number() }),
22838
- z41.strictObject({ kind: z41.literal("drained"), pid: z41.number().int().positive(), observedAt: z41.number() })
23168
+ var DoorHealthEventSchema = z42.discriminatedUnion("kind", [
23169
+ z42.strictObject({ kind: z42.literal("generation"), pid: z42.number().int().positive(), providerPort: z42.number().int().positive(), connectPort: z42.number().int().positive(), directPort: z42.number().int().positive(), observedAt: z42.number() }),
23170
+ z42.strictObject({ kind: z42.literal("listenerFailed"), pid: z42.number().int().positive(), listener: z42.enum(["provider", "connect", "direct"]), message: z42.string(), observedAt: z42.number() }),
23171
+ z42.strictObject({ kind: z42.literal("binaryTurnover"), pid: z42.number().int().positive(), observedAt: z42.number() }),
23172
+ z42.strictObject({ kind: z42.literal("idleShutdown"), pid: z42.number().int().positive(), observedAt: z42.number() }),
23173
+ z42.strictObject({ kind: z42.literal("superseded"), pid: z42.number().int().positive(), ownerPid: z42.number().int().positive(), observedAt: z42.number() }),
23174
+ z42.strictObject({ kind: z42.literal("drained"), pid: z42.number().int().positive(), observedAt: z42.number() })
22839
23175
  ]);
22840
- var QuotaExpiringEventSchema = z41.strictObject({
23176
+ var QuotaExpiringEventSchema = z42.strictObject({
22841
23177
  /** The id of the identity whose window it is: what its usage is filed under, which a rename keeps. */
22842
- id: z41.string().min(1),
23178
+ id: z42.string().min(1),
22843
23179
  /** The identity's name when the event was published, absent for an identity no longer stored under the id. */
22844
- name: z41.string().min(1).optional(),
22845
- provider: z41.string().min(1),
22846
- window: z41.enum(["fiveHour", "sevenDay"]),
23180
+ name: z42.string().min(1).optional(),
23181
+ provider: z42.string().min(1),
23182
+ window: z42.enum(["fiveHour", "sevenDay"]),
22847
23183
  /** The fraction of the window already used when it was seen expiring, always below one because a fully used window has nothing left to spend. */
22848
- utilization: z41.number().min(0).max(1),
22849
- resetsAt: z41.iso.datetime(),
22850
- observedAt: z41.number()
23184
+ utilization: z42.number().min(0).max(1),
23185
+ resetsAt: z42.iso.datetime(),
23186
+ observedAt: z42.number()
22851
23187
  });
22852
23188
  var UsageChangeEventSchema = UsageSnapshotSchema.extend({
22853
- id: z41.string().min(1),
22854
- name: z41.string().min(1).optional()
23189
+ id: z42.string().min(1),
23190
+ name: z42.string().min(1).optional()
22855
23191
  });
22856
23192
 
22857
23193
  // src/frontdoor/eventsApi.ts
@@ -22896,14 +23232,14 @@ function createEventsApiRouter(deps) {
22896
23232
  init_update();
22897
23233
  import { ORPCError as ORPCError4 } from "@orpc/client";
22898
23234
  import { openapi as openapi5 } from "@orpc/openapi";
22899
- import { z as z42 } from "zod";
23235
+ import { z as z43 } from "zod";
22900
23236
  var FRONTDOOR_API_TAG = "frontdoor";
22901
23237
  var UPDATE_API_TAG = "update";
22902
23238
  function createLifecycleApiRouter(deps) {
22903
23239
  const authed = doorApiAuth(deps.expectedToken);
22904
23240
  return {
22905
23241
  frontdoor: {
22906
- refreshCatalogues: authed.meta(openapi5({ method: "POST", path: "/rest/frontdoor/catalogues/refresh", summary: "Request a catalogue refresh tick", tags: [FRONTDOOR_API_TAG] })).output(z42.strictObject({ requested: z42.literal(true) })).handler(() => {
23242
+ refreshCatalogues: authed.meta(openapi5({ method: "POST", path: "/rest/frontdoor/catalogues/refresh", summary: "Request a catalogue refresh tick", tags: [FRONTDOOR_API_TAG] })).output(z43.strictObject({ requested: z43.literal(true) })).handler(() => {
22907
23243
  deps.refreshCatalogues();
22908
23244
  return { requested: true };
22909
23245
  }),
@@ -22939,65 +23275,65 @@ import { ORPCError as ORPCError5 } from "@orpc/client";
22939
23275
  import { openapi as openapi6 } from "@orpc/openapi";
22940
23276
 
22941
23277
  // src/frontdoor/launchSchemas.ts
22942
- import path44 from "node:path";
22943
- import { z as z43 } from "zod";
23278
+ import path45 from "node:path";
23279
+ import { z as z44 } from "zod";
22944
23280
  init_statusline();
22945
23281
  init_claudeVersion();
22946
- init_identity();
22947
- var LaunchResolveInputSchema = z43.strictObject({
22948
- path: z43.string().min(1),
23282
+ init_identity2();
23283
+ var LaunchResolveInputSchema = z44.strictObject({
23284
+ path: z44.string().min(1),
22949
23285
  /** `@name`, launch flags, then the arguments for `claude`; empty for a bare launch. */
22950
- argv: z43.readonly(z43.array(z43.string())).optional(),
23286
+ argv: z44.readonly(z44.array(z44.string())).optional(),
22951
23287
  /** The launch's inherited environment. Absent means an empty one: the door's own environment is never a substitute for the caller's, so a caller that wants `AGENT_SHIM_*` switches or a `CLAUDE_CONFIG_DIR` considered names them here. Values are read, never reported. */
22952
- env: z43.record(z43.string(), z43.string()).optional()
22953
- }).refine((input) => path44.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
22954
- var LaunchPoolDecisionSchema = z43.strictObject({
22955
- name: z43.string(),
22956
- reasons: z43.readonly(z43.array(z43.string())),
23288
+ env: z44.record(z44.string(), z44.string()).optional()
23289
+ }).refine((input) => path45.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
23290
+ var LaunchPoolDecisionSchema = z44.strictObject({
23291
+ name: z44.string(),
23292
+ reasons: z44.readonly(z44.array(z44.string())),
22957
23293
  /** The provider the ranking read for the chosen member, when the launch spends one in place of the member's Claude account. */
22958
- provider: z43.string().optional(),
22959
- movedOff: z43.strictObject({ identity: z43.string(), reason: z43.string() }).optional()
23294
+ provider: z44.string().optional(),
23295
+ movedOff: z44.strictObject({ identity: z44.string(), reason: z44.string() }).optional()
22960
23296
  });
22961
- var LaunchDecisionSchema = z43.strictObject({
22962
- identity: z43.string().optional(),
22963
- identityId: z43.string().optional(),
22964
- identitySource: z43.enum(IDENTITY_DECISION_SOURCES),
23297
+ var LaunchDecisionSchema = z44.strictObject({
23298
+ identity: z44.string().optional(),
23299
+ identityId: z44.string().optional(),
23300
+ identitySource: z44.enum(IDENTITY_DECISION_SOURCES),
22965
23301
  pool: LaunchPoolDecisionSchema.optional(),
22966
23302
  /** True when `CLAUDE_CONFIG_DIR` was already set and nothing on the command line named an identity; an identity named there outranks the variable and leaves it false. */
22967
- configDirEscapeHatch: z43.boolean(),
22968
- configDir: z43.string().optional(),
22969
- configProfile: z43.string().optional(),
22970
- configProfileSource: z43.enum(CONFIG_PROFILE_DECISION_SOURCES),
22971
- provider: z43.string().optional()
23303
+ configDirEscapeHatch: z44.boolean(),
23304
+ configDir: z44.string().optional(),
23305
+ configProfile: z44.string().optional(),
23306
+ configProfileSource: z44.enum(CONFIG_PROFILE_DECISION_SOURCES),
23307
+ provider: z44.string().optional()
22972
23308
  });
22973
- var LaunchFlagsSchema = z43.strictObject({
22974
- skipPermissions: z43.boolean(),
22975
- remoteControl: z43.boolean(),
22976
- headroom: z43.boolean(),
22977
- trackUsage: z43.boolean(),
22978
- pause: z43.boolean(),
22979
- explain: z43.boolean(),
23309
+ var LaunchFlagsSchema = z44.strictObject({
23310
+ skipPermissions: z44.boolean(),
23311
+ remoteControl: z44.boolean(),
23312
+ headroom: z44.boolean(),
23313
+ trackUsage: z44.boolean(),
23314
+ pause: z44.boolean(),
23315
+ explain: z44.boolean(),
22980
23316
  /** How long the launch waits after its own output before it starts claude, in milliseconds. */
22981
- delayMs: z43.number(),
23317
+ delayMs: z44.number(),
22982
23318
  /** The hosts the launch keeps off the front door by adding them to the child's `NO_PROXY`. */
22983
- proxyBypass: z43.array(z43.string()).readonly(),
23319
+ proxyBypass: z44.array(z44.string()).readonly(),
22984
23320
  /** How the session's built-in statusline looks, when the launch configures any of it. */
22985
23321
  statusline: StatuslineSchema.optional()
22986
23322
  });
22987
- var LaunchResolveOutputSchema = z43.strictObject({
23323
+ var LaunchResolveOutputSchema = z44.strictObject({
22988
23324
  decision: LaunchDecisionSchema,
22989
23325
  flags: LaunchFlagsSchema,
22990
- claudeVersion: z43.strictObject({ version: z43.string(), source: z43.enum(CLAUDE_VERSION_SOURCES) }).optional(),
23326
+ claudeVersion: z44.strictObject({ version: z44.string(), source: z44.enum(CLAUDE_VERSION_SOURCES) }).optional(),
22991
23327
  /** The real `claude` binary the launch would spawn, on the door's host. */
22992
- bin: z43.string(),
23328
+ bin: z44.string(),
22993
23329
  /** The arguments the launch would pass it: the tool's own flags, then `CLAUDE_EXTRA_FLAGS`, then the caller's own. */
22994
- args: z43.readonly(z43.array(z43.string())),
23330
+ args: z44.readonly(z44.array(z44.string())),
22995
23331
  /** The credential the launch would authenticate with, by target and source kinds. Absent when none applies. */
22996
- credential: z43.strictObject({ subject: z43.enum(["provider", "identity"]), name: z43.string(), summary: CredentialSummarySchema }).optional(),
22997
- routing: z43.strictObject({ frontDoor: z43.boolean(), headroom: z43.boolean() }),
23332
+ credential: z44.strictObject({ subject: z44.enum(["provider", "identity"]), name: z44.string(), summary: CredentialSummarySchema }).optional(),
23333
+ routing: z44.strictObject({ frontDoor: z44.boolean(), headroom: z44.boolean() }),
22998
23334
  /** The names of the environment variables the launch would set or unset, sorted. Values are not reported. */
22999
- environment: z43.readonly(z43.array(z43.string())),
23000
- warnings: z43.readonly(z43.array(z43.string()))
23335
+ environment: z44.readonly(z44.array(z44.string())),
23336
+ warnings: z44.readonly(z44.array(z44.string()))
23001
23337
  });
23002
23338
 
23003
23339
  // src/frontdoor/launchApi.ts
@@ -23036,21 +23372,21 @@ init_schema3();
23036
23372
  init_cliError();
23037
23373
  import { ORPCError as ORPCError6 } from "@orpc/client";
23038
23374
  import { openapi as openapi7 } from "@orpc/openapi";
23039
- import { z as z44 } from "zod";
23040
- var AgentTreesListInputSchema = z44.strictObject({
23375
+ import { z as z45 } from "zod";
23376
+ var AgentTreesListInputSchema = z45.strictObject({
23041
23377
  /** Only this identity's sessions. */
23042
- identity: z44.string().optional(),
23378
+ identity: z45.string().optional(),
23043
23379
  /** Include sessions that spawned no agent and ran no workflow. */
23044
- all: z44.boolean().optional()
23380
+ all: z45.boolean().optional()
23045
23381
  });
23046
- var AgentTreesListOutputSchema = z44.array(SessionSummarySchema);
23047
- var AgentTreesShowInputSchema = z44.strictObject({
23382
+ var AgentTreesListOutputSchema = z45.array(SessionSummarySchema);
23383
+ var AgentTreesShowInputSchema = z45.strictObject({
23048
23384
  /** A session id, or an unambiguous prefix of one. */
23049
- session: z44.string().min(1),
23385
+ session: z45.string().min(1),
23050
23386
  /** Look only in this identity. */
23051
- identity: z44.string().optional()
23387
+ identity: z45.string().optional()
23052
23388
  });
23053
- var AgentTreesShowOutputSchema = z44.strictObject({ identities: z44.array(z44.string()), ...MergedAgentTreeSchema.shape });
23389
+ var AgentTreesShowOutputSchema = z45.strictObject({ identities: z45.array(z45.string()), ...MergedAgentTreeSchema.shape });
23054
23390
  function asBadRequest(error) {
23055
23391
  if (error instanceof CliError) {
23056
23392
  throw new ORPCError6("BAD_REQUEST", { message: error.message });
@@ -23103,7 +23439,7 @@ import { openapi as openapi8 } from "@orpc/openapi";
23103
23439
  import { eventIterator as eventIterator3, withEventMeta as withEventMeta3 } from "@orpc/server";
23104
23440
 
23105
23441
  // src/frontdoor/rcEventLog.ts
23106
- import { z as z45 } from "zod";
23442
+ import { z as z46 } from "zod";
23107
23443
 
23108
23444
  // src/frontdoor/eventHub.ts
23109
23445
  var DOOR_EVENT_BUFFER_EVENTS = 100;
@@ -23228,46 +23564,46 @@ var NUMBER_FIELDS = ["at", "sequence"].length;
23228
23564
  var BYTES_PER_CODE_UNIT = Uint16Array.BYTES_PER_ELEMENT;
23229
23565
  var RC_SESSION_END_REASONS = ["expired", "archived", "conflict"];
23230
23566
  var RC_PENDING_RETIRE_REASONS = ["answered", "withdrawn", "worker-stopped", "session-ended"];
23231
- var transitionBase = { session: z45.string(), at: z45.number() };
23232
- var cursorFields = { cursor: z45.string(), sequence: z45.int().positive() };
23233
- var sessionAppearedShape = { kind: z45.literal("session-appeared"), ...transitionBase };
23234
- var sessionEndedShape = { kind: z45.literal("session-ended"), reason: z45.enum(RC_SESSION_END_REASONS), ...transitionBase };
23235
- var workerStateShape = { kind: z45.literal("worker-state"), state: z45.string(), previous: z45.string().optional(), ...transitionBase };
23236
- var pendingBornShape = { kind: z45.literal("pending-born"), requestId: z45.string(), type: z45.string(), summary: z45.string(), ...transitionBase };
23237
- var pendingRetiredShape = { kind: z45.literal("pending-retired"), requestId: z45.string(), reason: z45.enum(RC_PENDING_RETIRE_REASONS), ...transitionBase };
23238
- var RcSessionTransitionSchema = z45.discriminatedUnion("kind", [
23239
- z45.strictObject(sessionAppearedShape),
23240
- z45.strictObject(sessionEndedShape),
23241
- z45.strictObject(workerStateShape),
23242
- z45.strictObject(pendingBornShape),
23243
- z45.strictObject(pendingRetiredShape)
23567
+ var transitionBase = { session: z46.string(), at: z46.number() };
23568
+ var cursorFields = { cursor: z46.string(), sequence: z46.int().positive() };
23569
+ var sessionAppearedShape = { kind: z46.literal("session-appeared"), ...transitionBase };
23570
+ var sessionEndedShape = { kind: z46.literal("session-ended"), reason: z46.enum(RC_SESSION_END_REASONS), ...transitionBase };
23571
+ var workerStateShape = { kind: z46.literal("worker-state"), state: z46.string(), previous: z46.string().optional(), ...transitionBase };
23572
+ var pendingBornShape = { kind: z46.literal("pending-born"), requestId: z46.string(), type: z46.string(), summary: z46.string(), ...transitionBase };
23573
+ var pendingRetiredShape = { kind: z46.literal("pending-retired"), requestId: z46.string(), reason: z46.enum(RC_PENDING_RETIRE_REASONS), ...transitionBase };
23574
+ var RcSessionTransitionSchema = z46.discriminatedUnion("kind", [
23575
+ z46.strictObject(sessionAppearedShape),
23576
+ z46.strictObject(sessionEndedShape),
23577
+ z46.strictObject(workerStateShape),
23578
+ z46.strictObject(pendingBornShape),
23579
+ z46.strictObject(pendingRetiredShape)
23244
23580
  ]);
23245
23581
  var KIND_MAX_CHARS = Math.max(...RcSessionTransitionSchema.options.map((option) => option.shape.kind.value.length));
23246
23582
  var RC_SESSION_EVENT_MAX_BYTES = (RC_SESSION_EVENT_GENERATION_MAX_CHARS + ".".length + SEQUENCE_MAX_DIGITS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + KIND_MAX_CHARS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + RC_SESSION_EVENT_SUMMARY_MAX_CHARS) * BYTES_PER_CODE_UNIT + NUMBER_FIELDS * NUMBER_BYTES;
23247
23583
  var RC_SESSION_EVENT_LOG_CAPACITY = Math.floor(CONTROL_BODY_CAP_BYTES / RC_SESSION_EVENT_MAX_BYTES);
23248
- var RcSessionEventSchema = z45.discriminatedUnion("kind", [
23249
- z45.strictObject({ ...cursorFields, ...sessionAppearedShape }),
23250
- z45.strictObject({ ...cursorFields, ...sessionEndedShape }),
23251
- z45.strictObject({ ...cursorFields, ...workerStateShape }),
23252
- z45.strictObject({ ...cursorFields, ...pendingBornShape }),
23253
- z45.strictObject({ ...cursorFields, ...pendingRetiredShape })
23584
+ var RcSessionEventSchema = z46.discriminatedUnion("kind", [
23585
+ z46.strictObject({ ...cursorFields, ...sessionAppearedShape }),
23586
+ z46.strictObject({ ...cursorFields, ...sessionEndedShape }),
23587
+ z46.strictObject({ ...cursorFields, ...workerStateShape }),
23588
+ z46.strictObject({ ...cursorFields, ...pendingBornShape }),
23589
+ z46.strictObject({ ...cursorFields, ...pendingRetiredShape })
23254
23590
  ]);
23255
- var RcSessionEventsReadInputSchema = z45.strictObject({
23591
+ var RcSessionEventsReadInputSchema = z46.strictObject({
23256
23592
  /** The cursor of the last event the caller saw; every retained event when omitted. */
23257
- since: z45.string().min(1).optional(),
23593
+ since: z46.string().min(1).optional(),
23258
23594
  /** One `cse_` session id; every session when omitted. */
23259
- session: z45.string().min(1).optional(),
23595
+ session: z46.string().min(1).optional(),
23260
23596
  /** The most events one answer carries; every event after `since` when omitted. */
23261
- limit: z45.int().positive().optional()
23597
+ limit: z46.int().positive().optional()
23262
23598
  });
23263
23599
  var RcSessionEventsPageInputSchema = RcSessionEventsReadInputSchema.extend({
23264
23600
  /** The most events this page carries: by default and at most, the bound the door's event backbone already holds per slow consumer (`DOOR_EVENT_BUFFER_EVENTS`, oRPC's own documented default for that case). A page lands whole in its reader, so a reader receives at most one consumer buffer's worth at a time (at worst `DOOR_EVENT_BUFFER_EVENTS` times `RC_SESSION_EVENT_MAX_BYTES`) and pages on with the cursor for more; a maximum of the whole window would let one page carry the log's entire memory budget into an agent's context. */
23265
- limit: z45.int().positive().max(DOOR_EVENT_BUFFER_EVENTS).default(DOOR_EVENT_BUFFER_EVENTS)
23601
+ limit: z46.int().positive().max(DOOR_EVENT_BUFFER_EVENTS).default(DOOR_EVENT_BUFFER_EVENTS)
23266
23602
  });
23267
23603
  var RcSessionEventsStreamInputSchema = RcSessionEventsReadInputSchema.omit({ limit: true });
23268
- var RcSessionEventsReadOutputSchema = z45.discriminatedUnion("status", [
23269
- z45.strictObject({ status: z45.literal("ok"), events: z45.readonly(z45.array(RcSessionEventSchema)), cursor: z45.string(), more: z45.boolean(), head: z45.string() }),
23270
- z45.strictObject({ status: z45.literal("expired"), message: z45.string(), head: z45.string() })
23604
+ var RcSessionEventsReadOutputSchema = z46.discriminatedUnion("status", [
23605
+ z46.strictObject({ status: z46.literal("ok"), events: z46.readonly(z46.array(RcSessionEventSchema)), cursor: z46.string(), more: z46.boolean(), head: z46.string() }),
23606
+ z46.strictObject({ status: z46.literal("expired"), message: z46.string(), head: z46.string() })
23271
23607
  ]);
23272
23608
  var CURSOR_SEPARATOR = ".";
23273
23609
  var RESYNC_ADVICE = "cursor expired, resync from status: read `rc status` for every session's present state, then resume after the head this answer names";
@@ -25456,7 +25792,7 @@ data: ${JSON.stringify(envelope)}
25456
25792
  // src/frontdoor/rcSelfHostMint.ts
25457
25793
  init_identityRecords();
25458
25794
  init_account();
25459
- import path45 from "node:path";
25795
+ import path46 from "node:path";
25460
25796
  var CREDENTIALS_FILE2 = ".credentials.json";
25461
25797
  var CLAUDE_JSON2 = ".claude.json";
25462
25798
  var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
@@ -25480,7 +25816,7 @@ function readJsonObject(fs17, file) {
25480
25816
  return isRecord16(parsed) ? parsed : void 0;
25481
25817
  }
25482
25818
  function readRcSelfHostRecord(fs17, frontdoorDir) {
25483
- const parsed = readJsonObject(fs17, path45.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
25819
+ const parsed = readJsonObject(fs17, path46.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
25484
25820
  if (parsed === void 0) {
25485
25821
  return void 0;
25486
25822
  }
@@ -25498,11 +25834,11 @@ function mintRcSelfHostCredential(deps) {
25498
25834
  if (id === void 0) {
25499
25835
  throw new Error(`No identity named "${deps.identity}".`);
25500
25836
  }
25501
- const identityDir = path45.join(deps.identitiesDir, id);
25502
- const credentialsFile = path45.join(identityDir, CREDENTIALS_FILE2);
25503
- const claudeJsonFile = path45.join(identityDir, CLAUDE_JSON2);
25504
- const recordDir = path45.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
25505
- const recordFile2 = path45.join(recordDir, RC_SELF_HOST_RECORD_FILE);
25837
+ const identityDir = path46.join(deps.identitiesDir, id);
25838
+ const credentialsFile = path46.join(identityDir, CREDENTIALS_FILE2);
25839
+ const claudeJsonFile = path46.join(identityDir, CLAUDE_JSON2);
25840
+ const recordDir = path46.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
25841
+ const recordFile2 = path46.join(recordDir, RC_SELF_HOST_RECORD_FILE);
25506
25842
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
25507
25843
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
25508
25844
  const existingOauth = isRecord16(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
@@ -25518,7 +25854,7 @@ function mintRcSelfHostCredential(deps) {
25518
25854
  const organizationUuid = deps.newUuid();
25519
25855
  const accountUuid = deps.newUuid();
25520
25856
  const mintedAt = new Date(deps.now()).toISOString();
25521
- deps.fs.mkdirPrivate(path45.dirname(credentialsFile));
25857
+ deps.fs.mkdirPrivate(path46.dirname(credentialsFile));
25522
25858
  deps.fs.writeFilePrivate(credentialsFile, `${JSON.stringify({ ...existingCredentials, claudeAiOauth: { accessToken, refreshToken, expiresAt: null, scopes: [...RC_SELF_HOST_SCOPE_LIST], subscriptionType: SELF_HOST_SUBSCRIPTION_TYPE, rateLimitTier: null } }, null, 2)}
25523
25859
  `);
25524
25860
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
@@ -25556,7 +25892,7 @@ init_ensure2();
25556
25892
  // src/frontdoor/liveSessionRegistry.ts
25557
25893
  init_capability();
25558
25894
  init_state();
25559
- import path46 from "node:path";
25895
+ import path47 from "node:path";
25560
25896
  function sameStat(recorded, current) {
25561
25897
  return recorded?.mtimeMs === current.mtimeMs && recorded.sizeBytes === current.sizeBytes;
25562
25898
  }
@@ -25578,7 +25914,7 @@ function createLiveSessionRegistry(ports) {
25578
25914
  const load = (name, stat) => {
25579
25915
  known.set(name, { stat: { mtimeMs: stat.mtimeMs, sizeBytes: stat.sizeBytes }, record: readFrontDoorSessionRecord(fs17, sessionsDir, name) });
25580
25916
  };
25581
- const statOf = (name) => fs17.lstat(path46.join(sessionsDir, name));
25917
+ const statOf = (name) => fs17.lstat(path47.join(sessionsDir, name));
25582
25918
  const reconcile = () => {
25583
25919
  const names = new Set(recordNames());
25584
25920
  let changed = false;
@@ -25653,8 +25989,8 @@ init_liveTasks();
25653
25989
 
25654
25990
  // src/agents/read.ts
25655
25991
  init_schema3();
25656
- import path47 from "node:path";
25657
- import { z as z46 } from "zod";
25992
+ import path48 from "node:path";
25993
+ import { z as z47 } from "zod";
25658
25994
  var PROJECTS_DIR = "projects";
25659
25995
  var TASKS_DIR = "tasks";
25660
25996
  var SUBAGENTS_DIR = "subagents";
@@ -25679,15 +26015,15 @@ function parseEntry2(project, entry) {
25679
26015
  }
25680
26016
  function listSessions2(fs17, configDir) {
25681
26017
  const found = [];
25682
- for (const project of fs17.readdir(path47.join(configDir, PROJECTS_DIR))) {
25683
- const projectDir = path47.join(configDir, PROJECTS_DIR, project);
26018
+ for (const project of fs17.readdir(path48.join(configDir, PROJECTS_DIR))) {
26019
+ const projectDir = path48.join(configDir, PROJECTS_DIR, project);
25684
26020
  const entries = /* @__PURE__ */ new Set();
25685
26021
  for (const name of fs17.readdir(projectDir)) {
25686
26022
  if (name.endsWith(TRANSCRIPT_SUFFIX)) {
25687
26023
  entries.add(name.slice(0, -TRANSCRIPT_SUFFIX.length));
25688
26024
  continue;
25689
26025
  }
25690
- const children = fs17.readdir(path47.join(projectDir, name));
26026
+ const children = fs17.readdir(path48.join(projectDir, name));
25691
26027
  if (children.includes(SUBAGENTS_DIR) || children.includes(WORKFLOWS_DIR)) {
25692
26028
  entries.add(name);
25693
26029
  }
@@ -25707,8 +26043,8 @@ function locateAgents(fs17, configDir, relativeDir, workflowRunId, report) {
25707
26043
  const id = name.slice(AGENT_FILE_PREFIX.length, -META_SUFFIX.length);
25708
26044
  located.push({
25709
26045
  id,
25710
- metaPath: path47.join(relativeDir, name),
25711
- transcriptPath: path47.join(relativeDir, `${AGENT_FILE_PREFIX}${id}${TRANSCRIPT_SUFFIX}`),
26046
+ metaPath: path48.join(relativeDir, name),
26047
+ transcriptPath: path48.join(relativeDir, `${AGENT_FILE_PREFIX}${id}${TRANSCRIPT_SUFFIX}`),
25712
26048
  workflowRunId
25713
26049
  });
25714
26050
  }
@@ -25751,7 +26087,7 @@ function describeFailure(error) {
25751
26087
  }
25752
26088
  function readFileOrReport(fs17, configDir, relative, report) {
25753
26089
  try {
25754
- return fs17.readFileUtf8(path47.join(configDir, relative));
26090
+ return fs17.readFileUtf8(path48.join(configDir, relative));
25755
26091
  } catch (error) {
25756
26092
  report({ path: relative, reason: `could not be read: ${describeFailure(error)}` });
25757
26093
  return void 0;
@@ -25759,7 +26095,7 @@ function readFileOrReport(fs17, configDir, relative, report) {
25759
26095
  }
25760
26096
  function listDirOrReport(fs17, configDir, relative, report) {
25761
26097
  try {
25762
- return fs17.readdir(path47.join(configDir, relative));
26098
+ return fs17.readdir(path48.join(configDir, relative));
25763
26099
  } catch (error) {
25764
26100
  report({ path: relative, reason: `could not be listed: ${describeFailure(error)}` });
25765
26101
  return [];
@@ -25773,28 +26109,28 @@ function parseJson2(text) {
25773
26109
  return void 0;
25774
26110
  }
25775
26111
  }
25776
- var TaskFileSchema = z46.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z46.array(z46.string()).default([]), blockedBy: z46.array(z46.string()).default([]) });
25777
- var WorkflowRunFileSchema = z46.object({
25778
- runId: z46.string(),
25779
- workflowName: z46.string().optional(),
25780
- status: z46.string().optional(),
25781
- startTime: z46.number().optional(),
25782
- phases: z46.array(z46.object({ title: z46.string() })).default([]),
25783
- summary: z46.string().optional()
26112
+ var TaskFileSchema = z47.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z47.array(z47.string()).default([]), blockedBy: z47.array(z47.string()).default([]) });
26113
+ var WorkflowRunFileSchema = z47.object({
26114
+ runId: z47.string(),
26115
+ workflowName: z47.string().optional(),
26116
+ status: z47.string().optional(),
26117
+ startTime: z47.number().optional(),
26118
+ phases: z47.array(z47.object({ title: z47.string() })).default([]),
26119
+ summary: z47.string().optional()
25784
26120
  });
25785
26121
  function summariseSession(fs17, configDir, ref) {
25786
- const sessionRelative = path47.join(PROJECTS_DIR, ref.project, ref.entry);
25787
- const subagentsRelative = path47.join(sessionRelative, SUBAGENTS_DIR);
25788
- const workflowsUnderSubagents = path47.join(subagentsRelative, WORKFLOWS_DIR);
26122
+ const sessionRelative = path48.join(PROJECTS_DIR, ref.project, ref.entry);
26123
+ const subagentsRelative = path48.join(sessionRelative, SUBAGENTS_DIR);
26124
+ const workflowsUnderSubagents = path48.join(subagentsRelative, WORKFLOWS_DIR);
25789
26125
  const isMeta = (name) => name.startsWith(AGENT_FILE_PREFIX) && name.endsWith(META_SUFFIX);
25790
- let agentCount = fs17.readdir(path47.join(configDir, subagentsRelative)).filter(isMeta).length;
25791
- for (const runDir of fs17.readdir(path47.join(configDir, workflowsUnderSubagents))) {
26126
+ let agentCount = fs17.readdir(path48.join(configDir, subagentsRelative)).filter(isMeta).length;
26127
+ for (const runDir of fs17.readdir(path48.join(configDir, workflowsUnderSubagents))) {
25792
26128
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
25793
- agentCount += fs17.readdir(path47.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
26129
+ agentCount += fs17.readdir(path48.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
25794
26130
  }
25795
26131
  }
25796
- const workflowRunCount = fs17.readdir(path47.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
25797
- const transcript = fs17.lstat(path47.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
26132
+ const workflowRunCount = fs17.readdir(path48.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
26133
+ const transcript = fs17.lstat(path48.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
25798
26134
  return { ...ref, agentCount, workflowRunCount, ...transcript === void 0 ? {} : { updatedAt: new Date(transcript.mtimeMs).toISOString() } };
25799
26135
  }
25800
26136
  function readSessionAgentTree(fs17, configDir, ref, options = {}) {
@@ -25802,13 +26138,13 @@ function readSessionAgentTree(fs17, configDir, ref, options = {}) {
25802
26138
  const report = (problem) => {
25803
26139
  problems.push(problem);
25804
26140
  };
25805
- const sessionRelative = path47.join(PROJECTS_DIR, ref.project, ref.entry);
25806
- const subagentsRelative = path47.join(sessionRelative, SUBAGENTS_DIR);
25807
- const workflowsUnderSubagents = path47.join(subagentsRelative, WORKFLOWS_DIR);
26141
+ const sessionRelative = path48.join(PROJECTS_DIR, ref.project, ref.entry);
26142
+ const subagentsRelative = path48.join(sessionRelative, SUBAGENTS_DIR);
26143
+ const workflowsUnderSubagents = path48.join(subagentsRelative, WORKFLOWS_DIR);
25808
26144
  const located = locateAgents(fs17, configDir, subagentsRelative, void 0, report);
25809
26145
  for (const runDir of listDirOrReport(fs17, configDir, workflowsUnderSubagents, report)) {
25810
26146
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
25811
- located.push(...locateAgents(fs17, configDir, path47.join(workflowsUnderSubagents, runDir), runDir, report));
26147
+ located.push(...locateAgents(fs17, configDir, path48.join(workflowsUnderSubagents, runDir), runDir, report));
25812
26148
  }
25813
26149
  }
25814
26150
  const agents = /* @__PURE__ */ new Map();
@@ -25849,7 +26185,7 @@ function readSessionAgentTree(fs17, configDir, ref, options = {}) {
25849
26185
  superseded: ref.superseded,
25850
26186
  agents: roots.sort().map(build),
25851
26187
  tasks: readTasks(fs17, configDir, ownTaskLists(ref.sessionId), [.../* @__PURE__ */ new Set([...teamNames, ...options.taskListIds ?? []])].filter((id) => !ownTaskLists(ref.sessionId).includes(id)), report),
25852
- workflowRuns: readWorkflowRuns(fs17, configDir, path47.join(sessionRelative, WORKFLOWS_DIR), report),
26188
+ workflowRuns: readWorkflowRuns(fs17, configDir, path48.join(sessionRelative, WORKFLOWS_DIR), report),
25853
26189
  problems
25854
26190
  };
25855
26191
  }
@@ -25914,12 +26250,12 @@ function ownTaskLists(sessionId) {
25914
26250
  function readTasks(fs17, configDir, ownLists, sharedLists, report) {
25915
26251
  const tasks = [];
25916
26252
  [...ownLists, ...sharedLists].forEach((scope, index) => {
25917
- const relativeDir = path47.join(TASKS_DIR, scope);
26253
+ const relativeDir = path48.join(TASKS_DIR, scope);
25918
26254
  for (const name of [...listDirOrReport(fs17, configDir, relativeDir, report)].sort()) {
25919
26255
  if (name.startsWith(".") || !name.endsWith(JSON_SUFFIX)) {
25920
26256
  continue;
25921
26257
  }
25922
- const relative = path47.join(relativeDir, name);
26258
+ const relative = path48.join(relativeDir, name);
25923
26259
  const text = readFileOrReport(fs17, configDir, relative, report);
25924
26260
  const parsed = TaskFileSchema.safeParse(text === void 0 ? void 0 : parseJson2(text));
25925
26261
  if (parsed.success) {
@@ -25937,7 +26273,7 @@ function readWorkflowRuns(fs17, configDir, relativeDir, report) {
25937
26273
  if (!name.startsWith(WORKFLOW_RUN_PREFIX) || !name.endsWith(JSON_SUFFIX)) {
25938
26274
  continue;
25939
26275
  }
25940
- const relative = path47.join(relativeDir, name);
26276
+ const relative = path48.join(relativeDir, name);
25941
26277
  const text = readFileOrReport(fs17, configDir, relative, report);
25942
26278
  const parsed = WorkflowRunFileSchema.safeParse(text === void 0 ? void 0 : parseJson2(text));
25943
26279
  if (!parsed.success) {
@@ -25954,7 +26290,7 @@ function readWorkflowRuns(fs17, configDir, relativeDir, report) {
25954
26290
 
25955
26291
  // src/agents/sessions.ts
25956
26292
  init_cliError();
25957
- import path48 from "node:path";
26293
+ import path49 from "node:path";
25958
26294
  var SessionLookupError = class extends CliError {
25959
26295
  constructor(message) {
25960
26296
  super(message);
@@ -25965,7 +26301,7 @@ function historyStores(fs17, configDirOf, identities) {
25965
26301
  const byRealPath = /* @__PURE__ */ new Map();
25966
26302
  for (const identity of identities) {
25967
26303
  const configDir = configDirOf(identity);
25968
- const real = fs17.realpath(path48.join(configDir, "projects"));
26304
+ const real = fs17.realpath(path49.join(configDir, "projects"));
25969
26305
  if (real === void 0) {
25970
26306
  continue;
25971
26307
  }
@@ -26066,7 +26402,7 @@ init_load();
26066
26402
  init_launchWiring();
26067
26403
  init_argv();
26068
26404
  init_cascade();
26069
- init_identity();
26405
+ init_identity2();
26070
26406
  import os13 from "node:os";
26071
26407
 
26072
26408
  // src/launcher/poolRefresh.ts