agent-shim 11.40.5 → 11.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -248,7 +248,7 @@ function isTimeZone(name) {
248
248
  return false;
249
249
  }
250
250
  }
251
- var import_node_path2, import_zod, import_trilean, 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, HttpProviderSchema, CodexProviderSchema, RouterProviderSchema, AntigravityProviderSchema, ProviderSchema, SELECTION_MODES, VirtualModelSchema, ModelPricesSchema, ModelsConfigSchema, ModelsLayerSchema, ConfigProfileSchema, POOL_SELECTOR_PREFIX, POOL_NAME_PATTERN, IDENTITY_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;
251
+ var import_node_path2, import_zod, import_trilean, 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, HttpProviderSchema, CodexProviderSchema, RouterProviderSchema, AntigravityProviderSchema, ProviderSchema, SELECTION_MODES, VirtualModelSchema, ModelPricesSchema, FamilySettingsSchema, ModelsConfigSchema, ModelsLayerSchema, ConfigProfileSchema, POOL_SELECTOR_PREFIX, POOL_NAME_PATTERN, IDENTITY_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;
252
252
  var init_schema = __esm({
253
253
  "src/config/schema.ts"() {
254
254
  "use strict";
@@ -495,6 +495,14 @@ var init_schema = __esm({
495
495
  input: import_zod.z.number().positive(),
496
496
  output: import_zod.z.number().positive()
497
497
  });
498
+ FamilySettingsSchema = import_zod.z.strictObject({
499
+ names: import_zod.z.array(import_zod.z.string().min(1)).optional(),
500
+ mode: import_zod.z.enum(SELECTION_MODES).optional(),
501
+ context: import_zod.z.number().int().positive().optional(),
502
+ vision: import_zod.z.boolean().optional(),
503
+ tools: import_zod.z.boolean().optional(),
504
+ thinking: import_zod.z.boolean().optional()
505
+ });
498
506
  ModelsConfigSchema = import_zod.z.strictObject({
499
507
  /** Virtual models, by name. */
500
508
  virtual: import_zod.z.record(import_zod.z.string().min(1), VirtualModelSchema).optional(),
@@ -510,7 +518,13 @@ var init_schema = __esm({
510
518
  /** Model refs hidden from the picker and from routing, whatever else names them. */
511
519
  hide: import_zod.z.array(import_zod.z.string().min(1)).optional(),
512
520
  /** When set, the only model refs visible; everything else is hidden. */
513
- show: import_zod.z.array(import_zod.z.string().min(1)).optional()
521
+ show: import_zod.z.array(import_zod.z.string().min(1)).optional(),
522
+ /** Assertions that each group of refs is one model under several names, overriding what the names alone say. */
523
+ same: import_zod.z.array(import_zod.z.array(import_zod.z.string().min(1)).min(2)).optional(),
524
+ /** Assertions that each pair of refs is two models however alike their names look. */
525
+ distinct: import_zod.z.array(import_zod.z.tuple([import_zod.z.string().min(1), import_zod.z.string().min(1)])).optional(),
526
+ /** Per-family settings and the names the normaliser cannot know, by family key. */
527
+ families: import_zod.z.record(import_zod.z.string().min(1), FamilySettingsSchema).optional()
514
528
  });
515
529
  ModelsLayerSchema = import_zod.z.strictObject({
516
530
  virtual: import_zod.z.record(import_zod.z.string().min(1), import_zod.z.union([VirtualModelSchema, import_zod.z.null()])).optional(),
@@ -522,7 +536,10 @@ var init_schema = __esm({
522
536
  }).optional(),
523
537
  prices: import_zod.z.record(import_zod.z.string().min(1), import_zod.z.union([ModelPricesSchema, import_zod.z.null()])).optional(),
524
538
  hide: import_zod.z.array(import_zod.z.string().min(1)).optional(),
525
- show: import_zod.z.array(import_zod.z.string().min(1)).optional()
539
+ show: import_zod.z.array(import_zod.z.string().min(1)).optional(),
540
+ same: import_zod.z.array(import_zod.z.array(import_zod.z.string().min(1)).min(2)).optional(),
541
+ distinct: import_zod.z.array(import_zod.z.tuple([import_zod.z.string().min(1), import_zod.z.string().min(1)])).optional(),
542
+ families: import_zod.z.record(import_zod.z.string().min(1), import_zod.z.union([FamilySettingsSchema, import_zod.z.null()])).optional()
526
543
  });
527
544
  ConfigProfileSchema = import_zod.z.strictObject({
528
545
  $schema: import_zod.z.string().optional(),
@@ -1599,6 +1616,26 @@ function mergeModels(current, layer) {
1599
1616
  if (layer.show !== void 0) {
1600
1617
  pieces.show = layer.show;
1601
1618
  }
1619
+ if (layer.same !== void 0) {
1620
+ pieces.same = [...current?.same ?? [], ...layer.same.filter((group) => !(current?.same ?? []).some((known) => known.length === group.length && known.every((ref, index) => ref === group[index])))];
1621
+ }
1622
+ if (layer.distinct !== void 0) {
1623
+ pieces.distinct = [...current?.distinct ?? [], ...layer.distinct.filter(([left, right]) => !(current?.distinct ?? []).some(([a, b]) => a === left && b === right))];
1624
+ }
1625
+ if (layer.families !== void 0) {
1626
+ const families = {};
1627
+ for (const [key, settings] of Object.entries(current?.families ?? {})) {
1628
+ if (layer.families[key] === void 0) {
1629
+ families[key] = settings;
1630
+ }
1631
+ }
1632
+ for (const [key, settings] of Object.entries(layer.families)) {
1633
+ if (settings !== null) {
1634
+ families[key] = settings;
1635
+ }
1636
+ }
1637
+ pieces.families = families;
1638
+ }
1602
1639
  const merged = modelsOf(pieces);
1603
1640
  return Object.keys(merged).length === 0 ? void 0 : merged;
1604
1641
  }
@@ -1608,7 +1645,10 @@ function modelsOf(pieces) {
1608
1645
  ...pieces.tiers === void 0 || Object.keys(pieces.tiers).length === 0 ? {} : { tiers: pieces.tiers },
1609
1646
  ...pieces.prices === void 0 || Object.keys(pieces.prices).length === 0 ? {} : { prices: pieces.prices },
1610
1647
  ...pieces.hide === void 0 || pieces.hide.length === 0 ? {} : { hide: [...pieces.hide] },
1611
- ...pieces.show === void 0 || pieces.show.length === 0 ? {} : { show: [...pieces.show] }
1648
+ ...pieces.show === void 0 || pieces.show.length === 0 ? {} : { show: [...pieces.show] },
1649
+ ...pieces.same === void 0 || pieces.same.length === 0 ? {} : { same: pieces.same.map((group) => [...group]) },
1650
+ ...pieces.distinct === void 0 || pieces.distinct.length === 0 ? {} : { distinct: pieces.distinct.map(([left, right]) => [left, right]) },
1651
+ ...pieces.families === void 0 || Object.keys(pieces.families).length === 0 ? {} : { families: pieces.families }
1612
1652
  };
1613
1653
  }
1614
1654
  var init_flatten = __esm({
@@ -2036,7 +2076,8 @@ function assembleCascade(input) {
2036
2076
  ...config.categories === void 0 ? {} : { categories: config.categories },
2037
2077
  ...config.entries === void 0 ? {} : { entries: config.entries },
2038
2078
  ...entryOrder === void 0 ? {} : { entryOrder },
2039
- ...config.launch === void 0 ? {} : { launch: config.launch }
2079
+ ...config.launch === void 0 ? {} : { launch: config.launch },
2080
+ ...config.models === void 0 ? {} : { models: config.models }
2040
2081
  });
2041
2082
  nextId += 1;
2042
2083
  }
@@ -2992,6 +3033,9 @@ function pruneDeadFrontDoorDirectRecords(fs13, recordsDir, records, liveness) {
2992
3033
  }
2993
3034
  }
2994
3035
  }
3036
+ function recordOf(details) {
3037
+ return details === void 0 ? {} : { sessionId: details.sessionId, ...details.models === void 0 ? {} : { models: details.models } };
3038
+ }
2995
3039
  function writeFrontDoorSession(fs13, sessionsDir, session) {
2996
3040
  fs13.mkdirPrivate(sessionsDir);
2997
3041
  fs13.writeFilePrivate(import_node_path8.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
@@ -3033,8 +3077,9 @@ var init_state = __esm({
3033
3077
  "use strict";
3034
3078
  import_node_path8 = __toESM(require("node:path"), 1);
3035
3079
  import_zod3 = require("zod");
3080
+ init_schema();
3036
3081
  FRONT_DOOR_PROTOCOL = 4;
3037
- FrontDoorSessionSchema = import_zod3.z.strictObject({ pid: import_zod3.z.number().int().positive(), startedAt: import_zod3.z.number(), token: import_zod3.z.string().min(1), supervisorPid: import_zod3.z.number().int().positive().optional() });
3082
+ FrontDoorSessionSchema = import_zod3.z.strictObject({ pid: import_zod3.z.number().int().positive(), startedAt: import_zod3.z.number(), token: import_zod3.z.string().min(1), supervisorPid: import_zod3.z.number().int().positive().optional(), sessionId: import_zod3.z.string().min(1).optional(), models: ModelsConfigSchema.optional() });
3038
3083
  FrontDoorStateSchema = import_zod3.z.strictObject({
3039
3084
  /**
3040
3085
  * The launcher-to-door wire protocol this supervisor speaks, written once it is serving; absent in state written by a release that predates the field, which `ensureFrontDoor` reads as protocol 0. A launcher replaces a door whose protocol is lower than its own (see `FRONT_DOOR_PROTOCOL`).
@@ -3106,7 +3151,7 @@ var init_package = __esm({
3106
3151
  "package.json"() {
3107
3152
  package_default = {
3108
3153
  name: "agent-shim",
3109
- version: "11.40.5",
3154
+ version: "11.42.0",
3110
3155
  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.",
3111
3156
  license: "MIT",
3112
3157
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -6890,6 +6935,213 @@ var init_credential = __esm({
6890
6935
  }
6891
6936
  });
6892
6937
 
6938
+ // src/models/identity.ts
6939
+ function withoutContextMarker(model) {
6940
+ return model.toLowerCase().endsWith(CONTEXT_MARKER_1M) ? model.slice(0, -CONTEXT_MARKER_1M.length) : model;
6941
+ }
6942
+ function canonicalText(name) {
6943
+ return name.trim().toLowerCase().replace(NON_IDENTITY_BRACKET_RE, "").replace(/[\s_]+/g, "-").replace(/([a-z])(\d+(?:\.\d+)+)/g, "$1-$2").replace(/-+/g, "-").replace(/^-|-$/g, "");
6944
+ }
6945
+ function splitVariants(tokens) {
6946
+ const variants = [];
6947
+ let end = tokens.length;
6948
+ for (; ; ) {
6949
+ const token = tokens[end - 1];
6950
+ if (token === void 0 || !KNOWN_VARIANTS.has(token)) {
6951
+ return { familyTokens: tokens.slice(0, end), variants };
6952
+ }
6953
+ variants.unshift(token);
6954
+ end -= 1;
6955
+ }
6956
+ }
6957
+ function versionOf(tokens) {
6958
+ for (let index = 0; index < tokens.length; index += 1) {
6959
+ const token = tokens[index];
6960
+ const next = tokens[index + 1];
6961
+ if (token === void 0) {
6962
+ return "";
6963
+ }
6964
+ if (/^\d+$/.test(token) && next !== void 0 && /^\d+$/.test(next)) {
6965
+ return `${token}.${next}`;
6966
+ }
6967
+ const dotted = /^\d+(?:\.\d+)+$/.exec(token);
6968
+ if (dotted !== null) {
6969
+ return dotted[0];
6970
+ }
6971
+ }
6972
+ return "";
6973
+ }
6974
+ function modelIdentity(rawName) {
6975
+ const segments = rawName.trim().toLowerCase().split("/");
6976
+ const stripped = canonicalText(segments[segments.length - 1] ?? "").split(":")[0] ?? "";
6977
+ const withoutDate = stripped.replace(DATE_STAMP_RE, "");
6978
+ const tokens = withoutDate.split("-").filter((token) => token !== "");
6979
+ const { familyTokens, variants } = splitVariants(tokens);
6980
+ const version = versionOf(familyTokens);
6981
+ const versionless = familyTokens.filter((token, index) => {
6982
+ if (version === "") {
6983
+ return true;
6984
+ }
6985
+ const dotted = /^\d+(?:\.\d+)+$/.test(token);
6986
+ const previous = familyTokens[index - 1];
6987
+ const next = familyTokens[index + 1];
6988
+ const insideVersionRun = dotted || /^\d+$/.test(token) && (previous !== void 0 && /^\d+$/.test(previous) || next !== void 0 && /^\d+$/.test(next));
6989
+ return !insideVersionRun;
6990
+ });
6991
+ const family = versionless.join("-");
6992
+ const tokenVendor = familyTokens.find((token) => Object.keys(VENDOR_BY_TOKEN).some((key) => token === key || token.startsWith(key)));
6993
+ const namespace = segments.length >= 2 ? (segments[0] ?? "").split(":").pop() ?? "" : "";
6994
+ const namespaceVendor = VENDOR_BY_NAMESPACE[namespace] ?? "";
6995
+ const tokenVendorName = tokenVendor === void 0 ? "" : VENDOR_BY_TOKEN[Object.keys(VENDOR_BY_TOKEN).find((key) => tokenVendor === key || tokenVendor.startsWith(key)) ?? ""] ?? "";
6996
+ return {
6997
+ vendor: tokenVendorName === "" ? namespaceVendor : tokenVendorName,
6998
+ vendorConflict: tokenVendorName !== "" && namespaceVendor !== "" && tokenVendorName !== namespaceVendor,
6999
+ family,
7000
+ version,
7001
+ variant: variants.join("-"),
7002
+ familyAndVersion: version === "" ? family : `${family}-${version.replace(/\./g, "-")}`
7003
+ };
7004
+ }
7005
+ function relateModels(left, right) {
7006
+ const a = modelIdentity(left);
7007
+ const b = modelIdentity(right);
7008
+ if (a.familyAndVersion !== b.familyAndVersion) {
7009
+ return sameFamilyOtherVersion(a, b) ? "similar" : "distinct";
7010
+ }
7011
+ if (a.variant !== b.variant || a.vendorConflict || b.vendorConflict || a.vendor !== "" && b.vendor !== "" && a.vendor !== b.vendor) {
7012
+ return "similar";
7013
+ }
7014
+ return "same";
7015
+ }
7016
+ function sameFamilyOtherVersion(a, b) {
7017
+ if (a.family !== b.family) {
7018
+ return false;
7019
+ }
7020
+ if (a.vendor !== "" && b.vendor !== "" && a.vendor !== b.vendor) {
7021
+ return false;
7022
+ }
7023
+ return true;
7024
+ }
7025
+ var NON_IDENTITY_BRACKET_RE, CONTEXT_MARKER_1M, DATE_STAMP_RE, KNOWN_VARIANTS, VENDOR_BY_NAMESPACE, VENDOR_BY_TOKEN;
7026
+ var init_identity2 = __esm({
7027
+ "src/models/identity.ts"() {
7028
+ "use strict";
7029
+ NON_IDENTITY_BRACKET_RE = /\[[^\]]*\]/g;
7030
+ CONTEXT_MARKER_1M = "[1m]";
7031
+ DATE_STAMP_RE = /-(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])$/;
7032
+ KNOWN_VARIANTS = /* @__PURE__ */ new Set(["high", "medium", "low", "thinking", "xhigh", "max", "highspeed", "sol", "terra", "luna", "mini", "flash-lite", "turbo"]);
7033
+ VENDOR_BY_NAMESPACE = Object.freeze({
7034
+ anthropic: "anthropic",
7035
+ google: "google",
7036
+ openai: "openai",
7037
+ zai: "zai",
7038
+ "z-ai": "zai",
7039
+ minimax: "minimax",
7040
+ qwen: "qwen",
7041
+ deepseek: "deepseek",
7042
+ moonshot: "moonshot",
7043
+ meta: "meta",
7044
+ mistral: "mistral"
7045
+ });
7046
+ VENDOR_BY_TOKEN = Object.freeze({
7047
+ claude: "anthropic",
7048
+ gemini: "google",
7049
+ antigravity: "google",
7050
+ gpt: "openai",
7051
+ glm: "zai",
7052
+ minimax: "minimax",
7053
+ qwen: "qwen",
7054
+ deepseek: "deepseek",
7055
+ kimi: "moonshot",
7056
+ llama: "meta",
7057
+ mistral: "mistral",
7058
+ mixtral: "mistral"
7059
+ });
7060
+ }
7061
+ });
7062
+
7063
+ // src/models/families.ts
7064
+ function modelOf(ref) {
7065
+ const slash = ref.indexOf("/");
7066
+ return slash === -1 ? ref : ref.slice(slash + 1);
7067
+ }
7068
+ function familyKeyOf(rawModel) {
7069
+ const identity = modelIdentity(rawModel);
7070
+ return identity.variant === "" ? identity.familyAndVersion : `${identity.familyAndVersion}${VARIANT_SEPARATOR}${identity.variant}`;
7071
+ }
7072
+ function assertionsOf(models) {
7073
+ return { same: models?.same ?? [], distinct: models?.distinct ?? [] };
7074
+ }
7075
+ function sameModel(left, right, assertions) {
7076
+ if (assertions.distinct.some(([a, b]) => a === left && b === right || a === right && b === left)) {
7077
+ return false;
7078
+ }
7079
+ const leftGroup = assertions.same.find((group) => group.includes(left));
7080
+ const rightGroup = assertions.same.find((group) => group.includes(right));
7081
+ if (leftGroup !== void 0 && leftGroup === rightGroup) {
7082
+ return true;
7083
+ }
7084
+ if (leftGroup !== void 0 && !leftGroup.includes(right) || rightGroup !== void 0 && !rightGroup.includes(left)) {
7085
+ return false;
7086
+ }
7087
+ return relateModels(modelOf(left), modelOf(right)) === "same";
7088
+ }
7089
+ function pinnedTo(settings, ref) {
7090
+ return settings?.names?.some((name) => name === ref || name === modelOf(ref)) === true;
7091
+ }
7092
+ function buildFamilies(refs, models) {
7093
+ const assertions = assertionsOf(models);
7094
+ const settingsByKey = models?.families ?? {};
7095
+ const groups = [];
7096
+ for (const ref of refs) {
7097
+ const pinnedKey = Object.entries(settingsByKey).find(([, settings]) => pinnedTo(settings, ref))?.[0];
7098
+ const joined2 = groups.find((group) => pinnedKey === void 0 ? group.refs.some((first) => sameModel(first, ref, assertions)) : group.key === pinnedKey);
7099
+ if (joined2 !== void 0) {
7100
+ joined2.refs.push(ref);
7101
+ } else {
7102
+ groups.push({ key: pinnedKey ?? familyKeyOf(modelOf(ref)), refs: [ref] });
7103
+ }
7104
+ }
7105
+ return groups.map((group) => ({ key: group.key, refs: group.refs, settings: settingsByKey[group.key] ?? {} }));
7106
+ }
7107
+ function familyNamed(families, member) {
7108
+ if (!member.startsWith(FAMILY_PREFIX)) {
7109
+ return void 0;
7110
+ }
7111
+ const key = member.slice(FAMILY_PREFIX.length);
7112
+ return families.find((family) => family.key === key);
7113
+ }
7114
+ function familyMode(settings) {
7115
+ return settings.mode ?? "ordered";
7116
+ }
7117
+ function sharedFamilies(families) {
7118
+ return families.filter((family) => family.refs.length > 1);
7119
+ }
7120
+ function expandFamilyMembers(members, families) {
7121
+ const expanded = [];
7122
+ for (const member of members) {
7123
+ for (const ref of member.startsWith(FAMILY_PREFIX) ? familyNamed(families, member)?.refs ?? [] : [member]) {
7124
+ if (!expanded.includes(ref)) {
7125
+ expanded.push(ref);
7126
+ }
7127
+ }
7128
+ }
7129
+ return expanded;
7130
+ }
7131
+ function accountRefsOf(models) {
7132
+ const named = [...(models?.same ?? []).flat(), ...Object.values(models?.families ?? {}).flatMap((settings) => settings.names ?? [])];
7133
+ return [...new Set(named.filter((ref) => ref.startsWith("acct:")))];
7134
+ }
7135
+ var FAMILY_PREFIX, VARIANT_SEPARATOR;
7136
+ var init_families = __esm({
7137
+ "src/models/families.ts"() {
7138
+ "use strict";
7139
+ init_identity2();
7140
+ FAMILY_PREFIX = "family:";
7141
+ VARIANT_SEPARATOR = "+";
7142
+ }
7143
+ });
7144
+
6893
7145
  // src/providersStore.ts
6894
7146
  function providerJsonPath(paths, name) {
6895
7147
  return import_node_path25.default.join(paths.providersDir, `${name}.json`);
@@ -7184,8 +7436,15 @@ function resolveRoutedProviderCredentials(params) {
7184
7436
  }
7185
7437
  const virtualNames = new Set(Object.keys(models.virtual ?? {}));
7186
7438
  const providerNames = /* @__PURE__ */ new Set();
7439
+ const families = () => buildFamilies(params.targets?.() ?? [], models);
7187
7440
  const collect = (ref) => {
7188
- if (ref.startsWith("acct:") || ref.startsWith("family:") || virtualNames.has(ref)) {
7441
+ if (ref.startsWith(FAMILY_PREFIX)) {
7442
+ for (const target of expandFamilyMembers([ref], families())) {
7443
+ collect(target);
7444
+ }
7445
+ return;
7446
+ }
7447
+ if (ref.startsWith("acct:") || virtualNames.has(ref)) {
7189
7448
  return;
7190
7449
  }
7191
7450
  const [provider] = ref.split("/", 1);
@@ -7242,6 +7501,7 @@ var init_providersStore = __esm({
7242
7501
  init_cliError();
7243
7502
  init_credential();
7244
7503
  init_walk();
7504
+ init_families();
7245
7505
  ProviderNotFoundError = class extends CliError {
7246
7506
  constructor(name) {
7247
7507
  super(`No provider named "${name}". Run \`agent-shim provider add ${name}\` first.`);
@@ -7547,9 +7807,6 @@ var init_claudeShim = __esm({
7547
7807
  });
7548
7808
 
7549
7809
  // src/modelsStore.ts
7550
- function readModels(paths) {
7551
- return readGlobalConfig(paths)?.models;
7552
- }
7553
7810
  function memberKindOf(ref, models) {
7554
7811
  if (ref.startsWith("acct:")) {
7555
7812
  return "account";
@@ -7602,1447 +7859,1438 @@ var init_modelsStore = __esm({
7602
7859
  }
7603
7860
  });
7604
7861
 
7605
- // src/frontdoor/probe.ts
7606
- function probeFrontDoorSync(port, caPem) {
7607
- refuseToBlockInRole("a synchronous probe of the front door");
7608
- return runProbeWorker(PROBE_SOURCE, { port, ca: caPem });
7609
- }
7610
- function probeListenerAcceptSync(port) {
7611
- refuseToBlockInRole("a synchronous probe of a front door listener");
7612
- return runProbeWorker(ACCEPT_PROBE_SOURCE, { port });
7613
- }
7614
- function runProbeWorker(source, data) {
7615
- const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
7616
- const header = new Int32Array(shared, 0, HEADER_SLOTS);
7617
- const worker = new import_node_worker_threads.Worker(source, {
7618
- eval: true,
7619
- workerData: { ...data, timeoutMs: PROBE_TIMEOUT_MS, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS }
7620
- });
7621
- worker.unref();
7622
- try {
7623
- const waited = Atomics.wait(header, 0, VERDICT_PENDING, PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS);
7624
- const verdict = Atomics.load(header, 0);
7625
- if (waited === "timed-out" || verdict === VERDICT_PENDING) {
7626
- return { ok: false, reason: `the probe did not finish within ${String(PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS)}ms` };
7627
- }
7628
- if (verdict === VERDICT_OK) {
7629
- return { ok: true };
7630
- }
7631
- const length = Atomics.load(header, 1);
7632
- return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
7633
- } finally {
7634
- void worker.terminate();
7635
- }
7636
- }
7637
- var import_node_worker_threads, PROBE_TIMEOUT_MS, PROBE_WAIT_MARGIN_MS, REASON_BYTES, HEADER_SLOTS, INT32_BYTES, VERDICT_PENDING, VERDICT_OK, VERDICT_FAILED, PROBE_SOURCE, ACCEPT_PROBE_SOURCE;
7638
- var init_probe = __esm({
7639
- "src/frontdoor/probe.ts"() {
7862
+ // src/selection/engine.ts
7863
+ var init_engine = __esm({
7864
+ "src/selection/engine.ts"() {
7640
7865
  "use strict";
7641
- init_processRole();
7642
- import_node_worker_threads = require("node:worker_threads");
7643
- PROBE_TIMEOUT_MS = 2e3;
7644
- PROBE_WAIT_MARGIN_MS = 1e3;
7645
- REASON_BYTES = 1024;
7646
- HEADER_SLOTS = 2;
7647
- INT32_BYTES = 4;
7648
- VERDICT_PENDING = 0;
7649
- VERDICT_OK = 1;
7650
- VERDICT_FAILED = 2;
7651
- PROBE_SOURCE = `
7652
- const { workerData } = require("node:worker_threads");
7653
- const https = require("node:https");
7654
- const { port, ca, timeoutMs, shared, ok, failed, headerSlots } = workerData;
7655
- const header = new Int32Array(shared, 0, headerSlots);
7656
- const reason = new Uint8Array(shared, headerSlots * 4);
7657
- let done = false;
7658
- const finish = (verdict, message) => {
7659
- if (done) return;
7660
- done = true;
7661
- const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
7662
- reason.set(bytes);
7663
- Atomics.store(header, 1, bytes.length);
7664
- Atomics.store(header, 0, verdict);
7665
- Atomics.notify(header, 0);
7666
- };
7667
- const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
7668
- let body = "";
7669
- response.setEncoding("utf8");
7670
- response.on("data", (chunk) => { body += chunk; });
7671
- response.on("end", () => {
7672
- if (response.statusCode === 200 && body === "ok") finish(ok, "");
7673
- else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
7674
- });
7675
- response.on("error", (error) => finish(failed, error.message));
7676
- });
7677
- // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
7678
- setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
7679
- request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
7680
- `;
7681
- ACCEPT_PROBE_SOURCE = `
7682
- const { workerData } = require("node:worker_threads");
7683
- const net = require("node:net");
7684
- const { port, timeoutMs, shared, ok, failed, headerSlots } = workerData;
7685
- const header = new Int32Array(shared, 0, headerSlots);
7686
- const reason = new Uint8Array(shared, headerSlots * 4);
7687
- let done = false;
7688
- const finish = (verdict, message) => {
7689
- if (done) return;
7690
- done = true;
7691
- const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
7692
- reason.set(bytes);
7693
- Atomics.store(header, 1, bytes.length);
7694
- Atomics.store(header, 0, verdict);
7695
- Atomics.notify(header, 0);
7696
- };
7697
- const socket = net.connect({ host: "127.0.0.1", port });
7698
- socket.once("connect", () => { socket.destroy(); finish(ok, ""); });
7699
- socket.once("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
7700
- setTimeout(() => { socket.destroy(); finish(failed, "no connection accepted within " + String(timeoutMs) + "ms"); }, timeoutMs);
7701
- `;
7702
7866
  }
7703
7867
  });
7704
7868
 
7705
- // src/update/update.ts
7706
- function compareVersions3(left, right) {
7707
- const parse = (version) => {
7708
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
7709
- if (match === null) {
7710
- throw new Error(`not a plain release version: ${version}`);
7711
- }
7712
- return [Number(match[1]), Number(match[2]), Number(match[3])];
7713
- };
7714
- const leftParts = parse(left);
7715
- const rightParts = parse(right);
7716
- return leftParts.map((part, index) => part - (rightParts[index] ?? 0)).find((difference) => difference !== 0) ?? 0;
7717
- }
7718
- function releaseTagFromUrl(url) {
7719
- const segment = url.split("?")[0]?.split("/").at(-1);
7720
- const candidate = segment?.startsWith("v") === true ? segment.slice(1) : void 0;
7721
- return candidate !== void 0 && /^\d+\.\d+\.\d+$/.test(candidate) ? candidate : void 0;
7722
- }
7723
- var LATEST_RELEASE_URL, UpdateChannelError, UpdateConflictError, UpdateDownloadError;
7724
- var init_update = __esm({
7725
- "src/update/update.ts"() {
7869
+ // src/antigravity/cloudUpstream.ts
7870
+ var init_cloudUpstream = __esm({
7871
+ "src/antigravity/cloudUpstream.ts"() {
7726
7872
  "use strict";
7727
- init_cliError();
7728
- LATEST_RELEASE_URL = "https://github.com/ExaDev/agent-shim/releases/latest";
7729
- UpdateChannelError = class extends CliError {
7730
- constructor(message) {
7731
- super(message);
7732
- this.name = "UpdateChannelError";
7733
- }
7734
- };
7735
- UpdateConflictError = class extends CliError {
7736
- constructor(message) {
7737
- super(message);
7738
- this.name = "UpdateConflictError";
7739
- }
7740
- };
7741
- UpdateDownloadError = class extends CliError {
7742
- constructor(message) {
7743
- super(message);
7744
- this.name = "UpdateDownloadError";
7745
- }
7746
- };
7747
7873
  }
7748
7874
  });
7749
7875
 
7750
- // src/frontdoor/ensure.ts
7751
- function ensureFrontDoor(params) {
7752
- const { paths, ports } = params;
7753
- const deadline = ports.now() + FRONTDOOR_START_TIMEOUT_MS;
7754
- let spawned = false;
7755
- let replaced = false;
7756
- const distrusted = /* @__PURE__ */ new Set();
7757
- let lastRejection;
7758
- let busyDoor;
7759
- const liveSessionsOn = (doorPid) => listFrontDoorSessions(ports.fs, paths.frontdoorSessionsDir).filter(
7760
- (session) => session.pid !== params.launcherPid && ports.isRunning(session.pid) && (session.supervisorPid === void 0 || session.supervisorPid === doorPid)
7761
- ).length;
7762
- const verifyWithRetry = (port) => {
7763
- let verdict = ports.verifyListener(port);
7764
- for (let attempt = 1; !verdict.ok && attempt < FRONTDOOR_PROBE_ATTEMPTS; attempt += 1) {
7765
- ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
7766
- verdict = ports.verifyListener(port);
7876
+ // src/antigravity/quota.ts
7877
+ var SECONDS_PER_HOUR, HOURS_PER_FIVE_HOUR_WINDOW, DAYS_PER_WEEK, HOURS_PER_DAY4, FIVE_HOUR_PERIOD_SECONDS, WEEK_PERIOD_SECONDS;
7878
+ var init_quota = __esm({
7879
+ "src/antigravity/quota.ts"() {
7880
+ "use strict";
7881
+ init_cloudUpstream();
7882
+ SECONDS_PER_HOUR = 3600;
7883
+ HOURS_PER_FIVE_HOUR_WINDOW = 5;
7884
+ DAYS_PER_WEEK = 7;
7885
+ HOURS_PER_DAY4 = 24;
7886
+ FIVE_HOUR_PERIOD_SECONDS = HOURS_PER_FIVE_HOUR_WINDOW * SECONDS_PER_HOUR;
7887
+ WEEK_PERIOD_SECONDS = DAYS_PER_WEEK * HOURS_PER_DAY4 * SECONDS_PER_HOUR;
7888
+ }
7889
+ });
7890
+
7891
+ // src/antigravity/signatures.ts
7892
+ var init_signatures = __esm({
7893
+ "src/antigravity/signatures.ts"() {
7894
+ "use strict";
7895
+ }
7896
+ });
7897
+
7898
+ // src/codex/anthropic.ts
7899
+ var import_zod23, TextBlockSchema, Base64ImageSourceSchema, UrlImageSourceSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultContentBlockSchema, ToolResultBlockSchema, OtherBlockSchema, ContentBlockSchema, MessageSchema, ToolSchema, ToolChoiceSchema, SystemSchema, MessagesRequestSchema, CountTokensRequestSchema;
7900
+ var init_anthropic = __esm({
7901
+ "src/codex/anthropic.ts"() {
7902
+ "use strict";
7903
+ import_zod23 = require("zod");
7904
+ TextBlockSchema = import_zod23.z.looseObject({ type: import_zod23.z.literal("text"), text: import_zod23.z.string() });
7905
+ Base64ImageSourceSchema = import_zod23.z.looseObject({ type: import_zod23.z.literal("base64"), media_type: import_zod23.z.string().min(1), data: import_zod23.z.string() });
7906
+ UrlImageSourceSchema = import_zod23.z.looseObject({ type: import_zod23.z.literal("url"), url: import_zod23.z.string().min(1) });
7907
+ ImageBlockSchema = import_zod23.z.looseObject({
7908
+ type: import_zod23.z.literal("image"),
7909
+ source: import_zod23.z.union([Base64ImageSourceSchema, UrlImageSourceSchema])
7910
+ });
7911
+ ToolUseBlockSchema = import_zod23.z.looseObject({
7912
+ type: import_zod23.z.literal("tool_use"),
7913
+ id: import_zod23.z.string().min(1),
7914
+ name: import_zod23.z.string().min(1),
7915
+ input: import_zod23.z.unknown()
7916
+ });
7917
+ ToolResultContentBlockSchema = import_zod23.z.union([TextBlockSchema, import_zod23.z.looseObject({ type: import_zod23.z.string() })]);
7918
+ ToolResultBlockSchema = import_zod23.z.looseObject({
7919
+ type: import_zod23.z.literal("tool_result"),
7920
+ tool_use_id: import_zod23.z.string().min(1),
7921
+ content: import_zod23.z.union([import_zod23.z.string(), import_zod23.z.array(ToolResultContentBlockSchema)]).optional()
7922
+ });
7923
+ OtherBlockSchema = import_zod23.z.looseObject({ type: import_zod23.z.string() });
7924
+ ContentBlockSchema = import_zod23.z.union([TextBlockSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultBlockSchema, OtherBlockSchema]);
7925
+ MessageSchema = import_zod23.z.looseObject({
7926
+ role: import_zod23.z.enum(["user", "assistant", "system"]),
7927
+ content: import_zod23.z.union([import_zod23.z.string(), import_zod23.z.array(ContentBlockSchema)])
7928
+ });
7929
+ ToolSchema = import_zod23.z.looseObject({
7930
+ name: import_zod23.z.string().min(1),
7931
+ description: import_zod23.z.string().optional(),
7932
+ input_schema: import_zod23.z.record(import_zod23.z.string(), import_zod23.z.unknown()).optional()
7933
+ });
7934
+ ToolChoiceSchema = import_zod23.z.union([
7935
+ import_zod23.z.looseObject({ type: import_zod23.z.enum(["auto", "none", "any"]) }),
7936
+ import_zod23.z.looseObject({ type: import_zod23.z.literal("tool"), name: import_zod23.z.string().min(1) })
7937
+ ]);
7938
+ SystemSchema = import_zod23.z.union([import_zod23.z.string(), import_zod23.z.array(import_zod23.z.union([TextBlockSchema, OtherBlockSchema]))]);
7939
+ MessagesRequestSchema = import_zod23.z.looseObject({
7940
+ model: import_zod23.z.string().optional(),
7941
+ system: SystemSchema.optional(),
7942
+ messages: import_zod23.z.array(MessageSchema),
7943
+ tools: import_zod23.z.array(ToolSchema).optional(),
7944
+ tool_choice: ToolChoiceSchema.optional(),
7945
+ stream: import_zod23.z.boolean().optional(),
7946
+ /** `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. */
7947
+ metadata: import_zod23.z.looseObject({ user_id: import_zod23.z.string().optional() }).optional(),
7948
+ /** Claude Code's effort setting. Any string is accepted; the translator honours only the levels the backend understands. */
7949
+ output_config: import_zod23.z.looseObject({ effort: import_zod23.z.string().optional() }).optional()
7950
+ });
7951
+ CountTokensRequestSchema = import_zod23.z.looseObject({
7952
+ system: import_zod23.z.unknown().optional(),
7953
+ messages: import_zod23.z.unknown().optional(),
7954
+ tools: import_zod23.z.unknown().optional()
7955
+ });
7956
+ }
7957
+ });
7958
+
7959
+ // src/antigravity/translate.ts
7960
+ function candidatesOf(target) {
7961
+ return typeof target === "string" ? [target] : target;
7962
+ }
7963
+ function isAntigravityTier(key) {
7964
+ return CLAUDE_TIERS.some((tier) => tier === key);
7965
+ }
7966
+ function resolveAntigravityConfig(config) {
7967
+ const overrides = config?.models ?? {};
7968
+ const aliases = /* @__PURE__ */ new Map();
7969
+ for (const [key, target] of Object.entries(overrides)) {
7970
+ if (!isAntigravityTier(key)) {
7971
+ aliases.set(key.toLowerCase(), candidatesOf(target));
7767
7972
  }
7768
- return verdict;
7973
+ }
7974
+ const tierModel = (tier) => {
7975
+ const target = overrides[tier];
7976
+ return target === void 0 ? ANTIGRAVITY_DEFAULT_TIER_MODELS[tier] : candidatesOf(target);
7769
7977
  };
7770
- const stopAndAwaitExit = (supervisorPid, failure) => {
7771
- ports.stopSupervisor(supervisorPid);
7772
- const graceEnds = ports.now() + FRONTDOOR_EXIT_GRACE_MS;
7773
- let killed = false;
7774
- while (ports.isRunning(supervisorPid)) {
7775
- if (!killed && ports.now() >= graceEnds) {
7776
- ports.killSupervisor(supervisorPid);
7777
- killed = true;
7778
- }
7779
- if (ports.now() >= deadline) {
7780
- throw new FrontDoorStartError(`${failure}. Daemon log: ${paths.frontdoorLogPath}`);
7781
- }
7782
- ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
7978
+ if (!aliases.has(AUTO_ALIAS)) {
7979
+ aliases.set(AUTO_ALIAS, [...new Set(CLAUDE_TIERS.flatMap(tierModel))]);
7980
+ }
7981
+ return {
7982
+ mode: config?.mode ?? ANTIGRAVITY_DEFAULT_MODE,
7983
+ defaultModel: config?.defaultModel ?? ANTIGRAVITY_DEFAULT_MODEL,
7984
+ models: { fable: tierModel("fable"), opus: tierModel("opus"), sonnet: tierModel("sonnet"), haiku: tierModel("haiku") },
7985
+ aliases,
7986
+ degradeDownTiers: config?.degradeDownTiers ?? false,
7987
+ effort: config?.effort ?? ANTIGRAVITY_DEFAULT_EFFORT,
7988
+ cloud: {
7989
+ endpoint: config?.cloud?.endpoint,
7990
+ projectId: config?.cloud?.projectId,
7991
+ location: config?.cloud?.location
7992
+ },
7993
+ local: {
7994
+ command: config?.local?.command,
7995
+ socketPath: config?.local?.socketPath
7783
7996
  }
7784
7997
  };
7785
- for (; ; ) {
7786
- const state = readFrontDoorState(ports.fs, paths.frontdoorStateFile);
7787
- const supervisorPid = state?.supervisorPid;
7788
- if (supervisorPid !== void 0 && !distrusted.has(supervisorPid) && ports.isRunning(supervisorPid)) {
7789
- if (state?.port !== void 0 && state.connectPort !== void 0) {
7790
- if (supervisorPid === params.launcherPid && params.replace !== true && ports.isFrontDoorSupervisor(supervisorPid)) {
7791
- const token = (0, import_node_crypto10.randomUUID)();
7792
- writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token, supervisorPid });
7793
- return { port: state.port, connectPort: state.connectPort, token };
7794
- }
7795
- const verdict = verifyWithRetry(state.port);
7796
- if (verdict.ok && !replaced && !spawned && (params.replace === true || (state.protocol ?? 0) < FRONT_DOOR_PROTOCOL)) {
7797
- stopAndAwaitExit(
7798
- supervisorPid,
7799
- `the front door (pid ${String(supervisorPid)}, protocol ${String(state.protocol ?? 0)}; this launcher speaks protocol ${String(FRONT_DOOR_PROTOCOL)}) was asked to be replaced and did not exit`
7800
- );
7801
- replaced = true;
7802
- continue;
7803
- }
7804
- if (verdict.ok) {
7805
- const token = (0, import_node_crypto10.randomUUID)();
7806
- writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token, supervisorPid });
7807
- return { port: state.port, connectPort: state.connectPort, token };
7808
- }
7809
- lastRejection = `the listener on 127.0.0.1:${String(state.port)} (recorded for pid ${String(supervisorPid)}) failed authentication: ${verdict.reason}`;
7810
- if (spawned) {
7811
- throw new FrontDoorStartError(`${lastRejection}; refusing to send this session's credentials to it. Daemon log: ${paths.frontdoorLogPath}`);
7812
- }
7813
- if (ports.isFrontDoorSupervisor(supervisorPid)) {
7814
- const stranded = liveSessionsOn(supervisorPid);
7815
- if (params.replace === true && !replaced) {
7816
- stopAndAwaitExit(supervisorPid, `the front door (pid ${String(supervisorPid)}) stopped answering and did not exit when asked to`);
7817
- replaced = true;
7818
- continue;
7819
- }
7820
- if (stranded > 0) {
7821
- busyDoor = { pid: supervisorPid, sessions: stranded };
7822
- } else {
7823
- stopAndAwaitExit(supervisorPid, `the front door (pid ${String(supervisorPid)}) stopped answering and did not exit when asked to`);
7824
- continue;
7825
- }
7826
- } else {
7827
- distrusted.add(supervisorPid);
7828
- continue;
7829
- }
7830
- }
7831
- if (state?.lastError !== void 0) {
7832
- throw new FrontDoorStartError(`the front door reported a fatal error and is not serving: ${state.lastError} (daemon log: ${paths.frontdoorLogPath})`);
7833
- }
7834
- } else if (!spawned) {
7835
- ports.fs.mkdirp(paths.frontdoorDir);
7836
- const created = ports.fs.writeFileExclusive(paths.frontdoorLockFile, `${JSON.stringify({ pid: params.launcherPid, at: ports.now() })}
7837
- `);
7838
- if (created) {
7839
- ports.spawnSupervisor(paths);
7840
- spawned = true;
7841
- } else {
7842
- const lock = readStartLock(ports.fs, paths.frontdoorLockFile);
7843
- if (lock === void 0 || !ports.isRunning(lock.pid)) {
7844
- ports.fs.removeRecursive(paths.frontdoorLockFile);
7845
- continue;
7846
- }
7847
- }
7848
- }
7849
- if (ports.now() >= deadline) {
7850
- const lastError = state?.lastError;
7851
- throw new FrontDoorStartError(
7852
- `the front door did not become ready within ${String(FRONTDOOR_START_TIMEOUT_MS)}ms` + (lastError === void 0 ? "" : ` (last error: ${lastError})`) + (lastRejection === void 0 ? "" : ` (${lastRejection})`) + (busyDoor === void 0 ? "" : `. It was not replaced because ${String(busyDoor.sessions)} live session(s) are using it and would lose their connections; run \`agent-shim frontdoor restart\` to replace it deliberately`) + `. Daemon log: ${paths.frontdoorLogPath}`
7853
- );
7854
- }
7855
- ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
7856
- }
7857
7998
  }
7858
- var import_node_crypto10, FRONTDOOR_START_TIMEOUT_MS, FRONTDOOR_LAUNCHER_POLL_MS, FRONTDOOR_PROBE_ATTEMPTS, FRONTDOOR_EXIT_GRACE_MS, FrontDoorStartError;
7859
- var init_ensure2 = __esm({
7860
- "src/frontdoor/ensure.ts"() {
7999
+ var AUTO_ALIAS;
8000
+ var init_translate = __esm({
8001
+ "src/antigravity/translate.ts"() {
7861
8002
  "use strict";
7862
- import_node_crypto10 = require("node:crypto");
7863
- init_cliError();
7864
- init_state2();
7865
- init_state();
7866
- FRONTDOOR_START_TIMEOUT_MS = 3e4;
7867
- FRONTDOOR_LAUNCHER_POLL_MS = 100;
7868
- FRONTDOOR_PROBE_ATTEMPTS = 3;
7869
- FRONTDOOR_EXIT_GRACE_MS = 5e3;
7870
- FrontDoorStartError = class extends CliError {
7871
- constructor(message) {
7872
- super(message);
7873
- this.name = "FrontDoorStartError";
7874
- }
7875
- };
8003
+ init_identity2();
8004
+ init_engine();
8005
+ init_quota();
8006
+ init_signatures();
8007
+ init_schema();
8008
+ init_anthropic();
8009
+ AUTO_ALIAS = "auto";
7876
8010
  }
7877
8011
  });
7878
8012
 
7879
- // src/launcher/argv.ts
7880
- function matchValuedFlag(token) {
7881
- for (const flag of VALUED_FLAGS) {
7882
- if (token === flag) {
7883
- return { flag };
7884
- }
7885
- if (token.startsWith(`${flag}=`)) {
7886
- return { flag, inlineValue: token.slice(flag.length + 1) };
7887
- }
7888
- }
7889
- return void 0;
8013
+ // src/codex/translate.ts
8014
+ function resolveCodexConfig(config) {
8015
+ const overrides = config?.models;
8016
+ return {
8017
+ defaultModel: config?.defaultModel ?? CODEX_DEFAULT_MODEL,
8018
+ models: {
8019
+ fable: overrides?.fable ?? CODEX_DEFAULT_TIER_MODELS.fable,
8020
+ opus: overrides?.opus ?? CODEX_DEFAULT_TIER_MODELS.opus,
8021
+ sonnet: overrides?.sonnet ?? CODEX_DEFAULT_TIER_MODELS.sonnet,
8022
+ haiku: overrides?.haiku ?? CODEX_DEFAULT_TIER_MODELS.haiku
8023
+ },
8024
+ effort: config?.effort ?? CODEX_DEFAULT_EFFORT,
8025
+ login: config?.login ?? CODEX_DEFAULT_LOGIN
8026
+ };
7890
8027
  }
7891
- function matchBooleanFlag(token) {
7892
- for (const { flag, key } of BOOLEAN_FLAGS) {
7893
- if (token === flag) {
7894
- return { key, value: true };
7895
- }
7896
- if (token === `--no-${flag.slice(2)}`) {
7897
- return { key, value: false };
7898
- }
8028
+ var init_translate2 = __esm({
8029
+ "src/codex/translate.ts"() {
8030
+ "use strict";
8031
+ init_schema();
8032
+ init_anthropic();
7899
8033
  }
7900
- return void 0;
8034
+ });
8035
+
8036
+ // src/providerCatalogue.ts
8037
+ function catalogueCachePath(paths, name) {
8038
+ return import_node_path30.default.join(paths.catalogueDir, `${name}.json`);
7901
8039
  }
7902
- function parseLauncherArgv(argv) {
7903
- const first = argv[0];
7904
- const positionalIdentity = first !== void 0 && first.startsWith("@") && first.length > 1 ? first.slice(1) : void 0;
7905
- const remaining = positionalIdentity === void 0 ? argv : argv.slice(1);
7906
- let native = false;
7907
- let flagIdentity;
7908
- let configProfile;
7909
- let provider;
7910
- let claudeVersion;
7911
- let delay;
7912
- const booleans = {};
7913
- const categoryFlags = [];
7914
- const shareFlags = [];
7915
- const hideFlags = [];
7916
- const rest = [];
7917
- for (let index = 0; index < remaining.length; index += 1) {
7918
- const token = remaining[index];
7919
- if (token === void 0) {
7920
- continue;
7921
- }
7922
- if (token === TERMINATOR) {
7923
- rest.push(...remaining.slice(index));
7924
- break;
7925
- }
7926
- if (token === "--no-provider") {
7927
- provider = false;
7928
- continue;
7929
- }
7930
- if (token === NATIVE_FLAG) {
7931
- native = true;
7932
- continue;
7933
- }
7934
- const booleanFlag = matchBooleanFlag(token);
7935
- if (booleanFlag !== void 0) {
7936
- booleans[booleanFlag.key] = booleanFlag.value;
7937
- continue;
7938
- }
7939
- const matched = matchValuedFlag(token);
7940
- if (matched === void 0) {
7941
- rest.push(token);
7942
- continue;
7943
- }
7944
- let value;
7945
- if (matched.inlineValue !== void 0) {
7946
- value = matched.inlineValue;
7947
- } else {
7948
- const next = remaining[index + 1];
7949
- if (next === void 0 || next === TERMINATOR) {
7950
- rest.push(token);
7951
- continue;
7952
- }
7953
- value = next;
7954
- index += 1;
7955
- }
7956
- switch (matched.flag) {
7957
- case "--identity":
7958
- flagIdentity = value;
7959
- break;
7960
- case "--config-profile":
7961
- configProfile = value;
7962
- break;
7963
- case "--provider":
7964
- provider = value;
7965
- break;
7966
- case "--claude-version":
7967
- claudeVersion = value;
7968
- break;
7969
- case "--delay":
7970
- delay = value;
7971
- break;
7972
- case "--category":
7973
- categoryFlags.push(value);
7974
- break;
7975
- case "--share":
7976
- shareFlags.push(value);
7977
- break;
7978
- case "--hide":
7979
- hideFlags.push(value);
7980
- break;
7981
- default:
7982
- matched.flag;
7983
- }
8040
+ function parseCatalogueCache(text) {
8041
+ if (text === void 0) {
8042
+ return void 0;
7984
8043
  }
7985
- if (positionalIdentity !== void 0 && flagIdentity !== void 0 && positionalIdentity !== flagIdentity) {
7986
- throw new ConflictingIdentityError(positionalIdentity, flagIdentity);
8044
+ try {
8045
+ const parsed = CatalogueCacheSchema.safeParse(JSON.parse(text));
8046
+ return parsed.success ? parsed.data : void 0;
8047
+ } catch {
8048
+ return void 0;
7987
8049
  }
7988
- const identity = flagIdentity ?? positionalIdentity;
7989
- return {
7990
- ...identity === void 0 ? {} : { identity },
7991
- ...configProfile === void 0 ? {} : { configProfile },
7992
- ...provider === void 0 ? {} : { provider },
7993
- ...claudeVersion === void 0 ? {} : { claudeVersion },
7994
- ...delay === void 0 ? {} : { delay },
7995
- ...native ? { native: true } : {},
7996
- ...booleans,
7997
- categoryFlags,
7998
- shareFlags,
7999
- hideFlags,
8000
- rest
8001
- };
8002
8050
  }
8003
- var ConflictingIdentityError, VALUED_FLAGS, BOOLEAN_FLAGS, LAUNCHER_FLAG_NAMES, NATIVE_FLAG, TERMINATOR;
8004
- var init_argv = __esm({
8005
- "src/launcher/argv.ts"() {
8051
+ function filterCatalogue(models, catalogue) {
8052
+ const included = catalogue.include === void 0 ? void 0 : (0, import_picomatch4.default)(catalogue.include, { dot: true });
8053
+ const excluded = catalogue.exclude === void 0 ? void 0 : (0, import_picomatch4.default)(catalogue.exclude, { dot: true });
8054
+ return models.filter((model) => included?.(model.id) !== false && excluded?.(model.id) !== true);
8055
+ }
8056
+ var import_node_path30, import_picomatch4, import_zod24, DEFAULT_CANDIDATE_URLS, MS_PER_SECOND5, SECONDS_PER_HOUR2, HOURS_PER_DAY5, MS_PER_HOUR4, HOURS_BETWEEN_RETRIES, CATALOGUE_MAX_AGE_MS, CATALOGUE_RETRY_MS, CATALOGUE_REQUEST_SECONDS, CATALOGUE_REQUEST_TIMEOUT_MS, CATALOGUE_REFRESH_TIMEOUT_MS, CatalogueModelSchema, CatalogueCacheSchema;
8057
+ var init_providerCatalogue = __esm({
8058
+ "src/providerCatalogue.ts"() {
8006
8059
  "use strict";
8007
- init_cliError();
8008
- ConflictingIdentityError = class extends UsageError {
8009
- constructor(positional, flag) {
8010
- super(`The launch names two identities: "@${positional}" and "--identity ${flag}". Pass only one.`);
8011
- this.positional = positional;
8012
- this.flag = flag;
8013
- this.name = "ConflictingIdentityError";
8014
- }
8015
- positional;
8016
- flag;
8017
- };
8018
- VALUED_FLAGS = ["--identity", "--config-profile", "--provider", "--claude-version", "--delay", "--category", "--share", "--hide"];
8019
- BOOLEAN_FLAGS = [
8020
- { flag: "--headroom", key: "headroom" },
8021
- { flag: "--track-usage", key: "trackUsage" },
8022
- { flag: "--skip-permissions", key: "skipPermissions" },
8023
- { flag: "--remote-control", key: "remoteControl" },
8024
- { flag: "--wait", key: "wait" },
8025
- { flag: "--pause", key: "pause" },
8026
- { flag: "--explain", key: "explain" },
8027
- { flag: "--route-by-name", key: "routeByName" }
8028
- ];
8029
- LAUNCHER_FLAG_NAMES = [
8030
- ...VALUED_FLAGS,
8031
- "--native",
8032
- "--no-provider",
8033
- ...BOOLEAN_FLAGS.flatMap(({ flag }) => [flag, `--no-${flag.slice(2)}`])
8034
- ];
8035
- NATIVE_FLAG = "--native";
8036
- TERMINATOR = "--";
8060
+ import_node_path30 = __toESM(require("node:path"), 1);
8061
+ import_picomatch4 = __toESM(require("picomatch"), 1);
8062
+ import_zod24 = require("zod");
8063
+ DEFAULT_CANDIDATE_URLS = 2;
8064
+ MS_PER_SECOND5 = 1e3;
8065
+ SECONDS_PER_HOUR2 = 3600;
8066
+ HOURS_PER_DAY5 = 24;
8067
+ MS_PER_HOUR4 = SECONDS_PER_HOUR2 * MS_PER_SECOND5;
8068
+ HOURS_BETWEEN_RETRIES = 1;
8069
+ CATALOGUE_MAX_AGE_MS = HOURS_PER_DAY5 * MS_PER_HOUR4;
8070
+ CATALOGUE_RETRY_MS = HOURS_BETWEEN_RETRIES * MS_PER_HOUR4;
8071
+ CATALOGUE_REQUEST_SECONDS = 10;
8072
+ CATALOGUE_REQUEST_TIMEOUT_MS = CATALOGUE_REQUEST_SECONDS * MS_PER_SECOND5;
8073
+ CATALOGUE_REFRESH_TIMEOUT_MS = DEFAULT_CANDIDATE_URLS * CATALOGUE_REQUEST_TIMEOUT_MS;
8074
+ CatalogueModelSchema = import_zod24.z.strictObject({ id: import_zod24.z.string().min(1), name: import_zod24.z.string().min(1).optional() });
8075
+ CatalogueCacheSchema = import_zod24.z.strictObject({ fetchedAt: import_zod24.z.number(), url: import_zod24.z.string().min(1), models: import_zod24.z.array(CatalogueModelSchema) });
8037
8076
  }
8038
8077
  });
8039
8078
 
8040
- // src/cli/pairs.ts
8041
- function splitCommas(input) {
8042
- if (input === "") {
8079
+ // src/launcher/modelPicker.ts
8080
+ function labelOf(model) {
8081
+ return withoutContextMarker(model);
8082
+ }
8083
+ function describedAs(model, description) {
8084
+ return model.toLowerCase().endsWith(CONTEXT_MARKER_1M) ? `${description}; 1M context` : description;
8085
+ }
8086
+ function joined(parts) {
8087
+ const last = parts[parts.length - 1];
8088
+ return last === void 0 || parts.length === 1 ? last ?? "" : `${parts.slice(0, -1).join(", ")} and ${last}`;
8089
+ }
8090
+ function rowOf2(model, reaches) {
8091
+ const lead = reaches.find((reach) => reach.standing === "first") ?? reaches[0];
8092
+ if (lead === void 0) {
8093
+ throw new Error(`model ${model} is reached by no tier`);
8094
+ }
8095
+ const firsts = reaches.filter((reach) => reach.standing === "first").map((reach) => reach.tier);
8096
+ const fallbacks = reaches.filter((reach) => reach.standing === "fallback").map((reach) => reach.tier);
8097
+ const serves = firsts.length === 0 ? [] : [`Serves the ${joined(firsts)} tier${firsts.length === 1 ? "" : "s"}`];
8098
+ const falls = fallbacks.length === 0 ? [] : [`${serves.length === 0 ? "Fallback" : "fallback"} for ${joined(fallbacks)}`];
8099
+ return { model, label: labelOf(model), description: describedAs(model, [...serves, ...falls].join("; ")), behavesAs: TIER_BEHAVES_AS[lead.tier] };
8100
+ }
8101
+ function rowsOfTable(table) {
8102
+ const reachesByModel = /* @__PURE__ */ new Map();
8103
+ for (const [tier, candidates] of table) {
8104
+ candidates.forEach((model, index) => {
8105
+ const reaches = reachesByModel.get(model) ?? [];
8106
+ if (!reaches.some((reach) => reach.tier === tier)) {
8107
+ reaches.push({ tier, standing: index === 0 ? "first" : "fallback" });
8108
+ }
8109
+ reachesByModel.set(model, reaches);
8110
+ });
8111
+ }
8112
+ return [...reachesByModel].map(([model, reaches]) => rowOf2(model, reaches));
8113
+ }
8114
+ function antigravityRows(provider) {
8115
+ const config = resolveAntigravityConfig(provider.antigravity);
8116
+ const tiers = rowsOfTable(CLAUDE_TIERS.map((tier) => [tier, config.models[tier]]));
8117
+ const behavesAsOf = new Map(tiers.map((row) => [row.model, row.behavesAs]));
8118
+ const aliases = [...config.aliases].flatMap(([alias, candidates]) => {
8119
+ const [first] = candidates;
8120
+ const behavesAs = first === void 0 ? void 0 : behavesAsOf.get(first);
8121
+ const description = alias === AUTO_ALIAS ? `Routes each request to a backend model with quota left, best first (${String(candidates.length)} models)` : `Alias for ${candidates.join(", then ")}`;
8122
+ return behavesAs === void 0 ? [] : [{ model: alias, label: labelOf(alias), description, behavesAs }];
8123
+ });
8124
+ return [...aliases.filter((row) => row.model === AUTO_ALIAS), ...tiers, ...aliases.filter((row) => row.model !== AUTO_ALIAS)];
8125
+ }
8126
+ function codexRows(provider) {
8127
+ const config = resolveCodexConfig(provider.codex);
8128
+ return rowsOfTable(CLAUDE_TIERS.map((tier) => [tier, [config.models[tier]]]));
8129
+ }
8130
+ function httpRows(provider) {
8131
+ const env = provider.env ?? {};
8132
+ const table = CLAUDE_TIERS.flatMap((tier) => {
8133
+ const model = env[TIER_ENV_VARIABLES[tier]];
8134
+ return model === void 0 || model === "" ? [] : [[tier, [model]]];
8135
+ });
8136
+ return rowsOfTable(table);
8137
+ }
8138
+ function declaredRow(entry) {
8139
+ return {
8140
+ model: entry.model,
8141
+ label: entry.label ?? labelOf(entry.model),
8142
+ description: entry.description ?? describedAs(entry.model, `Declared by the provider for the ${entry.tier} tier`),
8143
+ behavesAs: TIER_BEHAVES_AS[entry.tier]
8144
+ };
8145
+ }
8146
+ function catalogueRows(provider, models) {
8147
+ if (provider.kind !== void 0 && provider.kind !== "http" || provider.catalogue === void 0) {
8043
8148
  return [];
8044
8149
  }
8045
- return input.split(",");
8150
+ const { tier } = provider.catalogue;
8151
+ return filterCatalogue(models, provider.catalogue).map((model) => ({ model: model.id, label: labelOf(model.id), description: describedAs(model.id, model.name === void 0 ? "Listed by the provider" : `Listed by the provider as ${model.name}`), behavesAs: TIER_BEHAVES_AS[tier] })).sort((left, right) => left.model.localeCompare(right.model));
8046
8152
  }
8047
- function parsePair(input) {
8048
- const eqIndex = input.indexOf("=");
8049
- if (eqIndex === -1) {
8050
- throw new Error(`Expected "<key>=<value>", got "${input}" (no "=" found)`);
8051
- }
8052
- const key = input.slice(0, eqIndex);
8053
- const value = input.slice(eqIndex + 1);
8054
- if (key === "") {
8055
- throw new Error(`Expected a non-empty key before "=" in "${input}"`);
8056
- }
8057
- return { key, value };
8153
+ function providerModelRows(provider, catalogue = []) {
8154
+ const derived = provider.kind === "codex" ? codexRows(provider) : provider.kind === "antigravity" ? antigravityRows(provider) : provider.kind === "router" ? [] : httpRows(provider);
8155
+ const declared = provider.kind === "router" ? [] : (provider.pickerModels ?? []).map(declaredRow);
8156
+ const declaredModels = new Set(declared.map((row) => row.model));
8157
+ const named = [...derived.filter((row) => !declaredModels.has(row.model)), ...declared];
8158
+ const taken = new Set(named.map((row) => labelOf(row.model)));
8159
+ return [...named, ...catalogueRows(provider, catalogue).filter((row) => !taken.has(labelOf(row.model)))];
8058
8160
  }
8059
- function parseBool(input) {
8060
- const parsed = parseBoolWord(input);
8061
- if (parsed === void 0) {
8062
- throw new Error(`Expected "true", "false", "1" or "0", got "${input}"`);
8063
- }
8064
- return parsed;
8161
+ function routedModelRows(models, providers) {
8162
+ const hidden = new Set(models.hide ?? []);
8163
+ const shown = models.show === void 0 ? void 0 : new Set(models.show);
8164
+ const visible = (model) => shown === void 0 ? !hidden.has(model) : shown.has(model);
8165
+ const concrete = providers.flatMap(([name, provider]) => providerModelRows(provider).map((row) => ({ ...row, model: `${name}/${row.model}`, label: `${name} / ${row.label}`, description: `${name}: ${row.description}` })));
8166
+ const concreteByRef = new Map(concrete.map((row) => [row.model, row]));
8167
+ const families = buildFamilies([...concrete.map((row) => row.model), ...accountRefsOf(models)], models);
8168
+ const handlingOf = (refs) => refs.map((ref) => concreteByRef.get(ref)?.behavesAs).find((behavesAs) => behavesAs !== void 0) ?? TIER_BEHAVES_AS.sonnet;
8169
+ const virtual = Object.entries(models.virtual ?? {}).flatMap(([name, definition]) => {
8170
+ if (!visible(name)) {
8171
+ return [];
8172
+ }
8173
+ const targets = expandFamilyMembers(safeExpand(name, models), families);
8174
+ return [{ model: name, label: name, description: `Virtual (${definition.mode})`, behavesAs: handlingOf(targets) }];
8175
+ });
8176
+ const familyRows = sharedFamilies(families).flatMap((family) => {
8177
+ const member = `${FAMILY_PREFIX}${family.key}`;
8178
+ return visible(member) ? [{ model: member, label: family.key, description: `Family (${familyMode(family.settings)}): ${family.refs.join(", ")}`, behavesAs: handlingOf(family.refs) }] : [];
8179
+ });
8180
+ return [...virtual, ...familyRows, ...concrete.filter((row) => visible(row.model))];
8065
8181
  }
8066
- function parseBoolPairList(input) {
8067
- const result = {};
8068
- for (const piece of splitCommas(input)) {
8069
- const { key, value } = parsePair(piece);
8070
- result[key] = parseBool(value);
8182
+ function safeExpand(name, models) {
8183
+ try {
8184
+ return expandMembers(name, models);
8185
+ } catch {
8186
+ return models.virtual?.[name]?.members ?? [];
8071
8187
  }
8072
- return result;
8073
8188
  }
8074
- var init_pairs = __esm({
8075
- "src/cli/pairs.ts"() {
8189
+ function modelPickerSettings(provider, catalogue = []) {
8190
+ return modelPickerSettingsFromRows(providerModelRows(provider, catalogue), true);
8191
+ }
8192
+ function modelPickerSettingsFromRows(options, replaceBuiltInOptions) {
8193
+ return options.length === 0 ? void 0 : JSON.stringify({ modelPicker: { options, replaceBuiltInOptions } });
8194
+ }
8195
+ var TIER_BEHAVES_AS, TIER_ENV_VARIABLES;
8196
+ var init_modelPicker = __esm({
8197
+ "src/launcher/modelPicker.ts"() {
8076
8198
  "use strict";
8077
- init_bool();
8199
+ init_translate();
8200
+ init_translate2();
8201
+ init_providerCatalogue();
8202
+ init_schema();
8203
+ init_identity2();
8204
+ init_families();
8205
+ init_modelsStore();
8206
+ TIER_BEHAVES_AS = Object.freeze({
8207
+ fable: "claude-fable-5-1",
8208
+ opus: "claude-opus-5-5",
8209
+ sonnet: "claude-sonnet-5-5",
8210
+ haiku: "claude-haiku-5-5"
8211
+ });
8212
+ TIER_ENV_VARIABLES = Object.freeze({
8213
+ fable: "ANTHROPIC_DEFAULT_FABLE_MODEL",
8214
+ opus: "ANTHROPIC_DEFAULT_OPUS_MODEL",
8215
+ sonnet: "ANTHROPIC_DEFAULT_SONNET_MODEL",
8216
+ haiku: "ANTHROPIC_DEFAULT_HAIKU_MODEL"
8217
+ });
8078
8218
  }
8079
8219
  });
8080
8220
 
8081
- // src/launcher/cliOverride.ts
8082
- function toCategoryMap(pairs) {
8083
- const expanded = expandAllCategoryKey(pairs);
8084
- const result = {};
8085
- for (const [key, value] of Object.entries(expanded)) {
8086
- if (!isOverridableCategory(key)) {
8087
- throw new InvalidCliCategoryError(key);
8088
- }
8089
- result[key] = value;
8090
- }
8091
- return result;
8221
+ // src/models/targets.ts
8222
+ function providerModels(paths) {
8223
+ return listProviders(paths).flatMap((entry) => {
8224
+ const catalogue = parseCatalogueCache(realFsPort.readFileUtf8(catalogueCachePath(paths, entry.name)));
8225
+ return providerModelRows(entry.provider, catalogue?.models).map((row) => ({ provider: entry.name, model: row.model }));
8226
+ });
8092
8227
  }
8093
- function toEntries(pairs) {
8094
- for (const key of Object.keys(pairs)) {
8095
- if (!ENTRY_KEY_RE.test(key)) {
8096
- throw new InvalidCliEntryKeyError(key);
8097
- }
8228
+ function targetRefs(paths) {
8229
+ return providerModels(paths).map((entry) => `${entry.provider}/${entry.model}`);
8230
+ }
8231
+ var init_targets = __esm({
8232
+ "src/models/targets.ts"() {
8233
+ "use strict";
8234
+ init_modelPicker();
8235
+ init_providerCatalogue();
8236
+ init_providersStore();
8237
+ init_realPorts();
8098
8238
  }
8099
- return pairs;
8239
+ });
8240
+
8241
+ // src/frontdoor/probe.ts
8242
+ function probeFrontDoorSync(port, caPem) {
8243
+ refuseToBlockInRole("a synchronous probe of the front door");
8244
+ return runProbeWorker(PROBE_SOURCE, { port, ca: caPem });
8100
8245
  }
8101
- function parseOverride(source, raw, parse) {
8246
+ function probeListenerAcceptSync(port) {
8247
+ refuseToBlockInRole("a synchronous probe of a front door listener");
8248
+ return runProbeWorker(ACCEPT_PROBE_SOURCE, { port });
8249
+ }
8250
+ function runProbeWorker(source, data) {
8251
+ const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
8252
+ const header = new Int32Array(shared, 0, HEADER_SLOTS);
8253
+ const worker = new import_node_worker_threads.Worker(source, {
8254
+ eval: true,
8255
+ workerData: { ...data, timeoutMs: PROBE_TIMEOUT_MS, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS }
8256
+ });
8257
+ worker.unref();
8102
8258
  try {
8103
- return parse(raw);
8104
- } catch (error) {
8105
- if (error instanceof Error && !(error instanceof CliError)) {
8106
- throw new UsageError(`Invalid ${source} value "${raw}": ${error.message}.`);
8259
+ const waited = Atomics.wait(header, 0, VERDICT_PENDING, PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS);
8260
+ const verdict = Atomics.load(header, 0);
8261
+ if (waited === "timed-out" || verdict === VERDICT_PENDING) {
8262
+ return { ok: false, reason: `the probe did not finish within ${String(PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS)}ms` };
8107
8263
  }
8108
- throw error;
8264
+ if (verdict === VERDICT_OK) {
8265
+ return { ok: true };
8266
+ }
8267
+ const length = Atomics.load(header, 1);
8268
+ return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
8269
+ } finally {
8270
+ void worker.terminate();
8109
8271
  }
8110
8272
  }
8111
- function buildCliOverride(params) {
8112
- let categoryPairs = {};
8113
- if (params.env.AGENT_SHIM_CATEGORY_OVERRIDE !== void 0 && params.env.AGENT_SHIM_CATEGORY_OVERRIDE !== "") {
8114
- categoryPairs = parseOverride("AGENT_SHIM_CATEGORY_OVERRIDE", params.env.AGENT_SHIM_CATEGORY_OVERRIDE, parseBoolPairList);
8115
- }
8116
- for (const flagValue of params.categoryFlags) {
8117
- const pair = parseOverride("--category", flagValue, (raw) => {
8118
- const { key, value } = parsePair(raw);
8119
- return { key, value: parseBool(value) };
8120
- });
8121
- categoryPairs[pair.key] = pair.value;
8122
- }
8123
- let entryPairs = {};
8124
- if (params.env.AGENT_SHIM_ENTRY_OVERRIDE !== void 0 && params.env.AGENT_SHIM_ENTRY_OVERRIDE !== "") {
8125
- entryPairs = parseOverride("AGENT_SHIM_ENTRY_OVERRIDE", params.env.AGENT_SHIM_ENTRY_OVERRIDE, parseBoolPairList);
8126
- }
8127
- for (const entryPath of params.shareFlags) {
8128
- entryPairs[entryPath] = true;
8129
- }
8130
- for (const entryPath of params.hideFlags) {
8131
- entryPairs[entryPath] = false;
8132
- }
8133
- const hasCategories = Object.keys(categoryPairs).length > 0;
8134
- const hasEntries = Object.keys(entryPairs).length > 0;
8135
- const hasProvider = params.providerFlag !== void 0 && params.providerFlag !== "";
8136
- if (!hasCategories && !hasEntries && !hasProvider) {
8137
- return void 0;
8273
+ var import_node_worker_threads, PROBE_TIMEOUT_MS, PROBE_WAIT_MARGIN_MS, REASON_BYTES, HEADER_SLOTS, INT32_BYTES, VERDICT_PENDING, VERDICT_OK, VERDICT_FAILED, PROBE_SOURCE, ACCEPT_PROBE_SOURCE;
8274
+ var init_probe = __esm({
8275
+ "src/frontdoor/probe.ts"() {
8276
+ "use strict";
8277
+ init_processRole();
8278
+ import_node_worker_threads = require("node:worker_threads");
8279
+ PROBE_TIMEOUT_MS = 2e3;
8280
+ PROBE_WAIT_MARGIN_MS = 1e3;
8281
+ REASON_BYTES = 1024;
8282
+ HEADER_SLOTS = 2;
8283
+ INT32_BYTES = 4;
8284
+ VERDICT_PENDING = 0;
8285
+ VERDICT_OK = 1;
8286
+ VERDICT_FAILED = 2;
8287
+ PROBE_SOURCE = `
8288
+ const { workerData } = require("node:worker_threads");
8289
+ const https = require("node:https");
8290
+ const { port, ca, timeoutMs, shared, ok, failed, headerSlots } = workerData;
8291
+ const header = new Int32Array(shared, 0, headerSlots);
8292
+ const reason = new Uint8Array(shared, headerSlots * 4);
8293
+ let done = false;
8294
+ const finish = (verdict, message) => {
8295
+ if (done) return;
8296
+ done = true;
8297
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
8298
+ reason.set(bytes);
8299
+ Atomics.store(header, 1, bytes.length);
8300
+ Atomics.store(header, 0, verdict);
8301
+ Atomics.notify(header, 0);
8302
+ };
8303
+ const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
8304
+ let body = "";
8305
+ response.setEncoding("utf8");
8306
+ response.on("data", (chunk) => { body += chunk; });
8307
+ response.on("end", () => {
8308
+ if (response.statusCode === 200 && body === "ok") finish(ok, "");
8309
+ else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
8310
+ });
8311
+ response.on("error", (error) => finish(failed, error.message));
8312
+ });
8313
+ // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
8314
+ setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
8315
+ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
8316
+ `;
8317
+ ACCEPT_PROBE_SOURCE = `
8318
+ const { workerData } = require("node:worker_threads");
8319
+ const net = require("node:net");
8320
+ const { port, timeoutMs, shared, ok, failed, headerSlots } = workerData;
8321
+ const header = new Int32Array(shared, 0, headerSlots);
8322
+ const reason = new Uint8Array(shared, headerSlots * 4);
8323
+ let done = false;
8324
+ const finish = (verdict, message) => {
8325
+ if (done) return;
8326
+ done = true;
8327
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
8328
+ reason.set(bytes);
8329
+ Atomics.store(header, 1, bytes.length);
8330
+ Atomics.store(header, 0, verdict);
8331
+ Atomics.notify(header, 0);
8332
+ };
8333
+ const socket = net.connect({ host: "127.0.0.1", port });
8334
+ socket.once("connect", () => { socket.destroy(); finish(ok, ""); });
8335
+ socket.once("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
8336
+ setTimeout(() => { socket.destroy(); finish(failed, "no connection accepted within " + String(timeoutMs) + "ms"); }, timeoutMs);
8337
+ `;
8138
8338
  }
8139
- return {
8140
- ...hasCategories ? { categories: toCategoryMap(categoryPairs) } : {},
8141
- ...hasEntries ? { entries: toEntries(entryPairs) } : {},
8142
- ...hasProvider ? { launch: { provider: params.providerFlag } } : {}
8339
+ });
8340
+
8341
+ // src/update/update.ts
8342
+ function compareVersions3(left, right) {
8343
+ const parse = (version) => {
8344
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
8345
+ if (match === null) {
8346
+ throw new Error(`not a plain release version: ${version}`);
8347
+ }
8348
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
8143
8349
  };
8350
+ const leftParts = parse(left);
8351
+ const rightParts = parse(right);
8352
+ return leftParts.map((part, index) => part - (rightParts[index] ?? 0)).find((difference) => difference !== 0) ?? 0;
8144
8353
  }
8145
- var InvalidCliCategoryError, InvalidCliEntryKeyError;
8146
- var init_cliOverride = __esm({
8147
- "src/launcher/cliOverride.ts"() {
8354
+ function releaseTagFromUrl(url) {
8355
+ const segment = url.split("?")[0]?.split("/").at(-1);
8356
+ const candidate = segment?.startsWith("v") === true ? segment.slice(1) : void 0;
8357
+ return candidate !== void 0 && /^\d+\.\d+\.\d+$/.test(candidate) ? candidate : void 0;
8358
+ }
8359
+ var LATEST_RELEASE_URL, UpdateChannelError, UpdateConflictError, UpdateDownloadError;
8360
+ var init_update = __esm({
8361
+ "src/update/update.ts"() {
8148
8362
  "use strict";
8149
- init_pairs();
8150
- init_schema();
8151
8363
  init_cliError();
8152
- InvalidCliCategoryError = class extends CliError {
8153
- constructor(categoryName) {
8154
- super(`"${categoryName}" is not a category this launch may toggle (runtime, history, knowledge, settings).`);
8155
- this.categoryName = categoryName;
8156
- this.name = "InvalidCliCategoryError";
8364
+ LATEST_RELEASE_URL = "https://github.com/ExaDev/agent-shim/releases/latest";
8365
+ UpdateChannelError = class extends CliError {
8366
+ constructor(message) {
8367
+ super(message);
8368
+ this.name = "UpdateChannelError";
8157
8369
  }
8158
- categoryName;
8159
8370
  };
8160
- InvalidCliEntryKeyError = class extends CliError {
8161
- constructor(key) {
8162
- super(`"${key}" is not a valid entries key \u2014 it must start with "<category>/", e.g. "knowledge/skills/commit".`);
8163
- this.key = key;
8164
- this.name = "InvalidCliEntryKeyError";
8371
+ UpdateConflictError = class extends CliError {
8372
+ constructor(message) {
8373
+ super(message);
8374
+ this.name = "UpdateConflictError";
8375
+ }
8376
+ };
8377
+ UpdateDownloadError = class extends CliError {
8378
+ constructor(message) {
8379
+ super(message);
8380
+ this.name = "UpdateDownloadError";
8165
8381
  }
8166
- key;
8167
8382
  };
8168
8383
  }
8169
8384
  });
8170
8385
 
8171
- // src/headroom/headers.ts
8172
- function mergeAnthropicCustomHeaders(existing, additions) {
8173
- const merged = /* @__PURE__ */ new Map();
8174
- for (const block of existing) {
8175
- if (block === void 0) {
8176
- continue;
8386
+ // src/frontdoor/ensure.ts
8387
+ function ensureFrontDoor(params) {
8388
+ const { paths, ports } = params;
8389
+ const deadline = ports.now() + FRONTDOOR_START_TIMEOUT_MS;
8390
+ let spawned = false;
8391
+ let replaced = false;
8392
+ const distrusted = /* @__PURE__ */ new Set();
8393
+ let lastRejection;
8394
+ let busyDoor;
8395
+ const liveSessionsOn = (doorPid) => listFrontDoorSessions(ports.fs, paths.frontdoorSessionsDir).filter(
8396
+ (session) => session.pid !== params.launcherPid && ports.isRunning(session.pid) && (session.supervisorPid === void 0 || session.supervisorPid === doorPid)
8397
+ ).length;
8398
+ const verifyWithRetry = (port) => {
8399
+ let verdict = ports.verifyListener(port);
8400
+ for (let attempt = 1; !verdict.ok && attempt < FRONTDOOR_PROBE_ATTEMPTS; attempt += 1) {
8401
+ ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
8402
+ verdict = ports.verifyListener(port);
8177
8403
  }
8178
- for (const line of block.split("\n")) {
8179
- const entry = parseCustomHeaderLine(line);
8180
- if (entry === void 0) {
8181
- continue;
8404
+ return verdict;
8405
+ };
8406
+ const stopAndAwaitExit = (supervisorPid, failure) => {
8407
+ ports.stopSupervisor(supervisorPid);
8408
+ const graceEnds = ports.now() + FRONTDOOR_EXIT_GRACE_MS;
8409
+ let killed = false;
8410
+ while (ports.isRunning(supervisorPid)) {
8411
+ if (!killed && ports.now() >= graceEnds) {
8412
+ ports.killSupervisor(supervisorPid);
8413
+ killed = true;
8182
8414
  }
8183
- merged.set(entry.name, entry.value);
8415
+ if (ports.now() >= deadline) {
8416
+ throw new FrontDoorStartError(`${failure}. Daemon log: ${paths.frontdoorLogPath}`);
8417
+ }
8418
+ ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
8184
8419
  }
8185
- }
8186
- for (const entry of additions) {
8187
- merged.set(entry.name, entry.value);
8188
- }
8189
- return [...merged].map(([name, value]) => `${name}: ${value}`).join("\n");
8190
- }
8191
- function parseCustomHeaderLine(line) {
8192
- const trimmed = line.trim();
8193
- if (trimmed === "") {
8194
- return void 0;
8195
- }
8196
- const colon = trimmed.indexOf(":");
8197
- if (colon <= 0) {
8198
- return void 0;
8199
- }
8200
- return { name: trimmed.slice(0, colon).trim(), value: trimmed.slice(colon + 1).trim() };
8201
- }
8202
- var init_headers = __esm({
8203
- "src/headroom/headers.ts"() {
8204
- "use strict";
8205
- }
8206
- });
8207
-
8208
- // src/launcher/flags.ts
8209
- function resolveLaunchFlags(params) {
8210
- return {
8211
- skipPermissions: params.flags?.skipPermissions ?? parseEnvBool("AGENT_SHIM_SKIP_PERMISSIONS", params.env.AGENT_SHIM_SKIP_PERMISSIONS) ?? params.cascade?.skipPermissions ?? false,
8212
- remoteControl: params.flags?.remoteControl ?? parseEnvBool("AGENT_SHIM_REMOTE_CONTROL", params.env.AGENT_SHIM_REMOTE_CONTROL) ?? params.cascade?.remoteControl ?? false,
8213
- headroom: params.flags?.headroom ?? parseEnvBool("AGENT_SHIM_HEADROOM", params.env.AGENT_SHIM_HEADROOM) ?? params.cascade?.headroom ?? false,
8214
- trackUsage: params.flags?.trackUsage ?? parseEnvBool("AGENT_SHIM_TRACK_USAGE", params.env.AGENT_SHIM_TRACK_USAGE) ?? params.cascade?.trackUsage ?? true,
8215
- pause: params.flags?.pause ?? parseEnvBool("AGENT_SHIM_PAUSE", params.env.AGENT_SHIM_PAUSE) ?? params.cascade?.pause ?? false,
8216
- explain: params.flags?.explain ?? parseEnvBool("AGENT_SHIM_EXPLAIN", params.env.AGENT_SHIM_EXPLAIN) ?? params.cascade?.explain ?? false,
8217
- routeByName: params.flags?.routeByName ?? parseEnvBool("AGENT_SHIM_ROUTE_BY_NAME", params.env.AGENT_SHIM_ROUTE_BY_NAME) ?? params.cascade?.routeByName ?? false,
8218
- delayMs: resolveDelayMs(params)
8219
8420
  };
8220
- }
8221
- function resolveDelayMs(params) {
8222
- const fromEnv = params.env.AGENT_SHIM_DELAY === "" ? void 0 : params.env.AGENT_SHIM_DELAY;
8223
- const [literal, source] = params.flags?.delay !== void 0 ? [params.flags.delay, "--delay"] : fromEnv !== void 0 ? [fromEnv, "AGENT_SHIM_DELAY"] : [params.cascade?.delay, "launch.delay"];
8224
- if (literal === void 0) {
8225
- return 0;
8226
- }
8227
- try {
8228
- return parseDuration(literal);
8229
- } catch (error) {
8230
- throw new UsageError(`${source}: ${error instanceof Error ? error.message : String(error)}`);
8231
- }
8232
- }
8233
- function buildFlagArgs(flags) {
8234
- const args = [];
8235
- if (flags.skipPermissions) {
8236
- args.push("--dangerously-skip-permissions");
8237
- }
8238
- if (flags.remoteControl) {
8239
- args.push("--remote-control=");
8240
- }
8241
- return args;
8242
- }
8243
- function buildArgv(params) {
8244
- return [...params.toolFlags, ...params.extraFlags, ...params.passthrough];
8245
- }
8246
- function withLoopbackHosts(existing) {
8247
- const listed = (existing ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
8248
- return [...listed, ...LOOPBACK_HOSTS.filter((host) => !listed.includes(host))].join(",");
8249
- }
8250
- function buildEnv(params) {
8251
- const env = { ...params.baseEnv };
8252
- const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
8253
- let providerCustomHeaders;
8254
- if (!params.configDirEscapeHatch && params.resolvedIdentityName !== void 0) {
8255
- env.CLAUDE_CONFIG_DIR = import_node_path36.default.join(params.identitiesDir, params.resolvedIdentityName);
8256
- }
8257
- if (params.provider !== void 0) {
8258
- const providerEnv = params.provider.definition.kind !== void 0 && params.provider.definition.kind !== "http" ? {} : params.provider.definition.env ?? {};
8259
- providerCustomHeaders = providerEnv.ANTHROPIC_CUSTOM_HEADERS;
8260
- env.ANTHROPIC_BASE_URL = void 0;
8261
- env.AGENT_SHIM_PROVIDER = params.provider.definition.displayName;
8262
- for (const [key, value] of Object.entries(providerEnv)) {
8263
- env[key] = value;
8264
- }
8265
- }
8266
- if (params.provider !== void 0) {
8267
- env.ANTHROPIC_AUTH_TOKEN = params.remoteControl ? void 0 : PROVIDER_SESSION_PLACEHOLDER;
8268
- env.ANTHROPIC_API_KEY = void 0;
8269
- env.CLAUDE_CODE_OAUTH_TOKEN = void 0;
8270
- } else if (params.identityCredential !== void 0) {
8271
- for (const [variable, value] of Object.entries(credentialVariables(params.identityCredential.target, params.identityCredential.token))) {
8272
- env[variable] = value;
8273
- }
8274
- }
8275
- if (params.frontdoor !== void 0) {
8276
- env.ANTHROPIC_CUSTOM_HEADERS = mergeAnthropicCustomHeaders(
8277
- [
8278
- ...parentCustomHeaders === void 0 ? [] : [parentCustomHeaders],
8279
- ...providerCustomHeaders === void 0 ? [] : [providerCustomHeaders]
8280
- ],
8281
- [
8282
- ...params.resolvedIdentityName === void 0 ? [] : [{ name: IDENTITY_HEADER, value: params.resolvedIdentityName }],
8283
- { name: SESSION_HEADER, value: params.sessionId },
8284
- { name: AUTH_HEADER, value: params.frontdoor.sessionToken },
8285
- ...params.provider === void 0 ? [] : [{ name: PROVIDER_HEADER, value: params.provider.name }],
8286
- ...params.routeByName ? [{ name: ROUTE_BY_NAME_HEADER, value: "1" }] : [],
8287
- ...params.headroom === void 0 ? [] : [
8288
- { name: HEADROOM_FLAG_HEADER, value: "1" },
8289
- { name: PROJECT_ID_HEADER, value: params.headroom.projectId }
8290
- ]
8291
- ]
8292
- );
8293
- env.NODE_EXTRA_CA_CERTS = params.frontdoor.trustBundlePath;
8294
- env.HTTPS_PROXY = connectProxyUrl(params.frontdoor.connectPort, params.frontdoor.sessionToken);
8295
- env.NO_PROXY = withLoopbackHosts(env.NO_PROXY);
8296
- env.no_proxy = withLoopbackHosts(env.no_proxy);
8421
+ for (; ; ) {
8422
+ const state = readFrontDoorState(ports.fs, paths.frontdoorStateFile);
8423
+ const supervisorPid = state?.supervisorPid;
8424
+ if (supervisorPid !== void 0 && !distrusted.has(supervisorPid) && ports.isRunning(supervisorPid)) {
8425
+ if (state?.port !== void 0 && state.connectPort !== void 0) {
8426
+ if (supervisorPid === params.launcherPid && params.replace !== true && ports.isFrontDoorSupervisor(supervisorPid)) {
8427
+ const token = (0, import_node_crypto10.randomUUID)();
8428
+ writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token, supervisorPid, ...recordOf(params.session) });
8429
+ return { port: state.port, connectPort: state.connectPort, token };
8430
+ }
8431
+ const verdict = verifyWithRetry(state.port);
8432
+ if (verdict.ok && !replaced && !spawned && (params.replace === true || (state.protocol ?? 0) < FRONT_DOOR_PROTOCOL)) {
8433
+ stopAndAwaitExit(
8434
+ supervisorPid,
8435
+ `the front door (pid ${String(supervisorPid)}, protocol ${String(state.protocol ?? 0)}; this launcher speaks protocol ${String(FRONT_DOOR_PROTOCOL)}) was asked to be replaced and did not exit`
8436
+ );
8437
+ replaced = true;
8438
+ continue;
8439
+ }
8440
+ if (verdict.ok) {
8441
+ const token = (0, import_node_crypto10.randomUUID)();
8442
+ writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token, supervisorPid, ...recordOf(params.session) });
8443
+ return { port: state.port, connectPort: state.connectPort, token };
8444
+ }
8445
+ lastRejection = `the listener on 127.0.0.1:${String(state.port)} (recorded for pid ${String(supervisorPid)}) failed authentication: ${verdict.reason}`;
8446
+ if (spawned) {
8447
+ throw new FrontDoorStartError(`${lastRejection}; refusing to send this session's credentials to it. Daemon log: ${paths.frontdoorLogPath}`);
8448
+ }
8449
+ if (ports.isFrontDoorSupervisor(supervisorPid)) {
8450
+ const stranded = liveSessionsOn(supervisorPid);
8451
+ if (params.replace === true && !replaced) {
8452
+ stopAndAwaitExit(supervisorPid, `the front door (pid ${String(supervisorPid)}) stopped answering and did not exit when asked to`);
8453
+ replaced = true;
8454
+ continue;
8455
+ }
8456
+ if (stranded > 0) {
8457
+ busyDoor = { pid: supervisorPid, sessions: stranded };
8458
+ } else {
8459
+ stopAndAwaitExit(supervisorPid, `the front door (pid ${String(supervisorPid)}) stopped answering and did not exit when asked to`);
8460
+ continue;
8461
+ }
8462
+ } else {
8463
+ distrusted.add(supervisorPid);
8464
+ continue;
8465
+ }
8466
+ }
8467
+ if (state?.lastError !== void 0) {
8468
+ throw new FrontDoorStartError(`the front door reported a fatal error and is not serving: ${state.lastError} (daemon log: ${paths.frontdoorLogPath})`);
8469
+ }
8470
+ } else if (!spawned) {
8471
+ ports.fs.mkdirp(paths.frontdoorDir);
8472
+ const created = ports.fs.writeFileExclusive(paths.frontdoorLockFile, `${JSON.stringify({ pid: params.launcherPid, at: ports.now() })}
8473
+ `);
8474
+ if (created) {
8475
+ ports.spawnSupervisor(paths);
8476
+ spawned = true;
8477
+ } else {
8478
+ const lock = readStartLock(ports.fs, paths.frontdoorLockFile);
8479
+ if (lock === void 0 || !ports.isRunning(lock.pid)) {
8480
+ ports.fs.removeRecursive(paths.frontdoorLockFile);
8481
+ continue;
8482
+ }
8483
+ }
8484
+ }
8485
+ if (ports.now() >= deadline) {
8486
+ const lastError = state?.lastError;
8487
+ throw new FrontDoorStartError(
8488
+ `the front door did not become ready within ${String(FRONTDOOR_START_TIMEOUT_MS)}ms` + (lastError === void 0 ? "" : ` (last error: ${lastError})`) + (lastRejection === void 0 ? "" : ` (${lastRejection})`) + (busyDoor === void 0 ? "" : `. It was not replaced because ${String(busyDoor.sessions)} live session(s) are using it and would lose their connections; run \`agent-shim frontdoor restart\` to replace it deliberately`) + `. Daemon log: ${paths.frontdoorLogPath}`
8489
+ );
8490
+ }
8491
+ ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
8297
8492
  }
8298
- return env;
8299
8493
  }
8300
- var import_node_path36, LOOPBACK_HOSTS, PROVIDER_SESSION_PLACEHOLDER;
8301
- var init_flags = __esm({
8302
- "src/launcher/flags.ts"() {
8494
+ var import_node_crypto10, FRONTDOOR_START_TIMEOUT_MS, FRONTDOOR_LAUNCHER_POLL_MS, FRONTDOOR_PROBE_ATTEMPTS, FRONTDOOR_EXIT_GRACE_MS, FrontDoorStartError;
8495
+ var init_ensure2 = __esm({
8496
+ "src/frontdoor/ensure.ts"() {
8303
8497
  "use strict";
8304
- import_node_path36 = __toESM(require("node:path"), 1);
8305
- init_envBool();
8498
+ import_node_crypto10 = require("node:crypto");
8306
8499
  init_cliError();
8307
- init_conditions();
8308
- init_credential();
8309
- init_headers();
8310
- init_capability();
8311
- init_route();
8312
- LOOPBACK_HOSTS = ["127.0.0.1", "localhost", "::1"];
8313
- PROVIDER_SESSION_PLACEHOLDER = "agent-shim-provider-session";
8500
+ init_state2();
8501
+ init_state();
8502
+ FRONTDOOR_START_TIMEOUT_MS = 3e4;
8503
+ FRONTDOOR_LAUNCHER_POLL_MS = 100;
8504
+ FRONTDOOR_PROBE_ATTEMPTS = 3;
8505
+ FRONTDOOR_EXIT_GRACE_MS = 5e3;
8506
+ FrontDoorStartError = class extends CliError {
8507
+ constructor(message) {
8508
+ super(message);
8509
+ this.name = "FrontDoorStartError";
8510
+ }
8511
+ };
8314
8512
  }
8315
8513
  });
8316
8514
 
8317
- // src/launcher/extraFlags.ts
8318
- function splitExtraFlags(value) {
8319
- if (value === void 0) {
8320
- return [];
8321
- }
8322
- const trimmed = value.trim();
8323
- if (trimmed === "") {
8324
- return [];
8325
- }
8326
- return trimmed.split(/\s+/);
8327
- }
8328
- var init_extraFlags = __esm({
8329
- "src/launcher/extraFlags.ts"() {
8330
- "use strict";
8515
+ // src/launcher/argv.ts
8516
+ function matchValuedFlag(token) {
8517
+ for (const flag of VALUED_FLAGS) {
8518
+ if (token === flag) {
8519
+ return { flag };
8520
+ }
8521
+ if (token.startsWith(`${flag}=`)) {
8522
+ return { flag, inlineValue: token.slice(flag.length + 1) };
8523
+ }
8331
8524
  }
8332
- });
8333
-
8334
- // src/usage/resumeContext.ts
8335
- function projectDirNameOf(cwd) {
8336
- return cwd.replace(/[^A-Za-z0-9]/g, "-");
8525
+ return void 0;
8337
8526
  }
8338
- function resumeTargetOf(passthrough) {
8339
- const end = passthrough.indexOf("--");
8340
- const tokens = end === -1 ? passthrough : passthrough.slice(0, end);
8341
- for (const [index, token] of tokens.entries()) {
8342
- if (token === "--continue" || token === "-c") {
8343
- return { kind: "latest" };
8344
- }
8345
- if (token === "--resume" || token === "-r") {
8346
- const next = tokens[index + 1];
8347
- return next === void 0 || next.startsWith("-") ? void 0 : { kind: "id", id: next };
8527
+ function matchBooleanFlag(token) {
8528
+ for (const { flag, key } of BOOLEAN_FLAGS) {
8529
+ if (token === flag) {
8530
+ return { key, value: true };
8348
8531
  }
8349
- if (token.startsWith("--resume=")) {
8350
- const id = token.slice("--resume=".length);
8351
- return id === "" ? void 0 : { kind: "id", id };
8532
+ if (token === `--no-${flag.slice(2)}`) {
8533
+ return { key, value: false };
8352
8534
  }
8353
8535
  }
8354
8536
  return void 0;
8355
8537
  }
8356
- function countOf(usage, key) {
8357
- const value = key in usage ? Reflect.get(usage, key) : void 0;
8358
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
8359
- }
8360
- function contextTokensOfTranscript(text) {
8361
- const lines = text.split("\n");
8362
- for (let index = lines.length - 1; index >= 0; index -= 1) {
8363
- const line = lines[index];
8364
- if (line === void 0 || line === "") {
8538
+ function parseLauncherArgv(argv) {
8539
+ const first = argv[0];
8540
+ const positionalIdentity = first !== void 0 && first.startsWith("@") && first.length > 1 ? first.slice(1) : void 0;
8541
+ const remaining = positionalIdentity === void 0 ? argv : argv.slice(1);
8542
+ let native = false;
8543
+ let flagIdentity;
8544
+ let configProfile;
8545
+ let provider;
8546
+ let claudeVersion;
8547
+ let delay;
8548
+ const booleans = {};
8549
+ const categoryFlags = [];
8550
+ const shareFlags = [];
8551
+ const hideFlags = [];
8552
+ const rest = [];
8553
+ for (let index = 0; index < remaining.length; index += 1) {
8554
+ const token = remaining[index];
8555
+ if (token === void 0) {
8365
8556
  continue;
8366
8557
  }
8367
- let parsed;
8368
- try {
8369
- parsed = JSON.parse(line);
8370
- } catch {
8558
+ if (token === TERMINATOR) {
8559
+ rest.push(...remaining.slice(index));
8560
+ break;
8561
+ }
8562
+ if (token === "--no-provider") {
8563
+ provider = false;
8371
8564
  continue;
8372
8565
  }
8373
- if (typeof parsed !== "object" || parsed === null || !("type" in parsed) || parsed.type !== "assistant" || !("message" in parsed)) {
8566
+ if (token === NATIVE_FLAG) {
8567
+ native = true;
8374
8568
  continue;
8375
8569
  }
8376
- const { message } = parsed;
8377
- if (typeof message !== "object" || message === null || !("usage" in message) || typeof message.usage !== "object" || message.usage === null) {
8570
+ const booleanFlag = matchBooleanFlag(token);
8571
+ if (booleanFlag !== void 0) {
8572
+ booleans[booleanFlag.key] = booleanFlag.value;
8378
8573
  continue;
8379
8574
  }
8380
- const { usage } = message;
8381
- return countOf(usage, "input_tokens") + countOf(usage, "cache_read_input_tokens") + countOf(usage, "cache_creation_input_tokens");
8575
+ const matched = matchValuedFlag(token);
8576
+ if (matched === void 0) {
8577
+ rest.push(token);
8578
+ continue;
8579
+ }
8580
+ let value;
8581
+ if (matched.inlineValue !== void 0) {
8582
+ value = matched.inlineValue;
8583
+ } else {
8584
+ const next = remaining[index + 1];
8585
+ if (next === void 0 || next === TERMINATOR) {
8586
+ rest.push(token);
8587
+ continue;
8588
+ }
8589
+ value = next;
8590
+ index += 1;
8591
+ }
8592
+ switch (matched.flag) {
8593
+ case "--identity":
8594
+ flagIdentity = value;
8595
+ break;
8596
+ case "--config-profile":
8597
+ configProfile = value;
8598
+ break;
8599
+ case "--provider":
8600
+ provider = value;
8601
+ break;
8602
+ case "--claude-version":
8603
+ claudeVersion = value;
8604
+ break;
8605
+ case "--delay":
8606
+ delay = value;
8607
+ break;
8608
+ case "--category":
8609
+ categoryFlags.push(value);
8610
+ break;
8611
+ case "--share":
8612
+ shareFlags.push(value);
8613
+ break;
8614
+ case "--hide":
8615
+ hideFlags.push(value);
8616
+ break;
8617
+ default:
8618
+ matched.flag;
8619
+ }
8382
8620
  }
8383
- return void 0;
8621
+ if (positionalIdentity !== void 0 && flagIdentity !== void 0 && positionalIdentity !== flagIdentity) {
8622
+ throw new ConflictingIdentityError(positionalIdentity, flagIdentity);
8623
+ }
8624
+ const identity = flagIdentity ?? positionalIdentity;
8625
+ return {
8626
+ ...identity === void 0 ? {} : { identity },
8627
+ ...configProfile === void 0 ? {} : { configProfile },
8628
+ ...provider === void 0 ? {} : { provider },
8629
+ ...claudeVersion === void 0 ? {} : { claudeVersion },
8630
+ ...delay === void 0 ? {} : { delay },
8631
+ ...native ? { native: true } : {},
8632
+ ...booleans,
8633
+ categoryFlags,
8634
+ shareFlags,
8635
+ hideFlags,
8636
+ rest
8637
+ };
8638
+ }
8639
+ var ConflictingIdentityError, VALUED_FLAGS, BOOLEAN_FLAGS, LAUNCHER_FLAG_NAMES, NATIVE_FLAG, TERMINATOR;
8640
+ var init_argv = __esm({
8641
+ "src/launcher/argv.ts"() {
8642
+ "use strict";
8643
+ init_cliError();
8644
+ ConflictingIdentityError = class extends UsageError {
8645
+ constructor(positional, flag) {
8646
+ super(`The launch names two identities: "@${positional}" and "--identity ${flag}". Pass only one.`);
8647
+ this.positional = positional;
8648
+ this.flag = flag;
8649
+ this.name = "ConflictingIdentityError";
8650
+ }
8651
+ positional;
8652
+ flag;
8653
+ };
8654
+ VALUED_FLAGS = ["--identity", "--config-profile", "--provider", "--claude-version", "--delay", "--category", "--share", "--hide"];
8655
+ BOOLEAN_FLAGS = [
8656
+ { flag: "--headroom", key: "headroom" },
8657
+ { flag: "--track-usage", key: "trackUsage" },
8658
+ { flag: "--skip-permissions", key: "skipPermissions" },
8659
+ { flag: "--remote-control", key: "remoteControl" },
8660
+ { flag: "--wait", key: "wait" },
8661
+ { flag: "--pause", key: "pause" },
8662
+ { flag: "--explain", key: "explain" },
8663
+ { flag: "--route-by-name", key: "routeByName" }
8664
+ ];
8665
+ LAUNCHER_FLAG_NAMES = [
8666
+ ...VALUED_FLAGS,
8667
+ "--native",
8668
+ "--no-provider",
8669
+ ...BOOLEAN_FLAGS.flatMap(({ flag }) => [flag, `--no-${flag.slice(2)}`])
8670
+ ];
8671
+ NATIVE_FLAG = "--native";
8672
+ TERMINATOR = "--";
8673
+ }
8674
+ });
8675
+
8676
+ // src/cli/pairs.ts
8677
+ function splitCommas(input) {
8678
+ if (input === "") {
8679
+ return [];
8680
+ }
8681
+ return input.split(",");
8682
+ }
8683
+ function parsePair(input) {
8684
+ const eqIndex = input.indexOf("=");
8685
+ if (eqIndex === -1) {
8686
+ throw new Error(`Expected "<key>=<value>", got "${input}" (no "=" found)`);
8687
+ }
8688
+ const key = input.slice(0, eqIndex);
8689
+ const value = input.slice(eqIndex + 1);
8690
+ if (key === "") {
8691
+ throw new Error(`Expected a non-empty key before "=" in "${input}"`);
8692
+ }
8693
+ return { key, value };
8384
8694
  }
8385
- function newestTranscript(fs13, projectDir) {
8386
- let newest;
8387
- let newestMs = -Infinity;
8388
- for (const name of fs13.readdir(projectDir)) {
8389
- if (!name.endsWith(".jsonl")) {
8390
- continue;
8391
- }
8392
- const candidate = import_node_path37.default.join(projectDir, name);
8393
- const stat = fs13.lstat(candidate);
8394
- if (stat?.kind === "file" && stat.mtimeMs > newestMs) {
8395
- newestMs = stat.mtimeMs;
8396
- newest = candidate;
8397
- }
8695
+ function parseBool(input) {
8696
+ const parsed = parseBoolWord(input);
8697
+ if (parsed === void 0) {
8698
+ throw new Error(`Expected "true", "false", "1" or "0", got "${input}"`);
8398
8699
  }
8399
- return newest;
8700
+ return parsed;
8400
8701
  }
8401
- function resumedContextTokens(fs13, params) {
8402
- const target = resumeTargetOf(params.passthrough);
8403
- if (target === void 0) {
8404
- return void 0;
8702
+ function parseBoolPairList(input) {
8703
+ const result = {};
8704
+ for (const piece of splitCommas(input)) {
8705
+ const { key, value } = parsePair(piece);
8706
+ result[key] = parseBool(value);
8405
8707
  }
8406
- const projectDir = import_node_path37.default.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
8407
- const file = target.kind === "id" ? import_node_path37.default.join(projectDir, `${target.id}.jsonl`) : newestTranscript(fs13, projectDir);
8408
- const text = file === void 0 ? void 0 : fs13.readFileUtf8(file);
8409
- return text === void 0 ? void 0 : contextTokensOfTranscript(text);
8708
+ return result;
8410
8709
  }
8411
- var import_node_path37;
8412
- var init_resumeContext = __esm({
8413
- "src/usage/resumeContext.ts"() {
8710
+ var init_pairs = __esm({
8711
+ "src/cli/pairs.ts"() {
8414
8712
  "use strict";
8415
- import_node_path37 = __toESM(require("node:path"), 1);
8713
+ init_bool();
8416
8714
  }
8417
8715
  });
8418
8716
 
8419
- // src/launcher/claudeSession.ts
8420
- function isFlag(token) {
8421
- return token?.startsWith("-") === true;
8422
- }
8423
- function withConversation(passthrough, conversation, id) {
8424
- const end = passthrough.indexOf(TERMINATOR2);
8425
- const head = end === -1 ? passthrough : passthrough.slice(0, end);
8426
- const tail = end === -1 ? [] : passthrough.slice(end);
8427
- const kept = [];
8428
- for (let index = 0; index < head.length; index += 1) {
8429
- const token = head[index];
8430
- if (token === void 0 || CONTINUE_FLAGS.has(token) || token.startsWith("--resume=") || token.startsWith("--session-id=")) {
8431
- continue;
8717
+ // src/launcher/cliOverride.ts
8718
+ function toCategoryMap(pairs) {
8719
+ const expanded = expandAllCategoryKey(pairs);
8720
+ const result = {};
8721
+ for (const [key, value] of Object.entries(expanded)) {
8722
+ if (!isOverridableCategory(key)) {
8723
+ throw new InvalidCliCategoryError(key);
8432
8724
  }
8433
- if (VALUED_CONVERSATION_FLAGS.has(token)) {
8434
- if (!isFlag(head[index + 1]) && head[index + 1] !== void 0) {
8435
- index += 1;
8436
- }
8437
- continue;
8725
+ result[key] = value;
8726
+ }
8727
+ return result;
8728
+ }
8729
+ function toEntries(pairs) {
8730
+ for (const key of Object.keys(pairs)) {
8731
+ if (!ENTRY_KEY_RE.test(key)) {
8732
+ throw new InvalidCliEntryKeyError(key);
8438
8733
  }
8439
- kept.push(token);
8440
8734
  }
8441
- return [...kept, conversation === "start" ? "--session-id" : "--resume", id, ...tail];
8735
+ return pairs;
8442
8736
  }
8443
- function hasSettingsArgument(passthrough) {
8444
- const end = passthrough.indexOf(TERMINATOR2);
8445
- return (end === -1 ? passthrough : passthrough.slice(0, end)).some((token) => token === "--settings" || token.startsWith("--settings="));
8737
+ function parseOverride(source, raw, parse) {
8738
+ try {
8739
+ return parse(raw);
8740
+ } catch (error) {
8741
+ if (error instanceof Error && !(error instanceof CliError)) {
8742
+ throw new UsageError(`Invalid ${source} value "${raw}": ${error.message}.`);
8743
+ }
8744
+ throw error;
8745
+ }
8446
8746
  }
8447
- function withSupervision(passthrough, supervised) {
8448
- if (supervised.conversation === "as-given") {
8449
- return passthrough;
8747
+ function buildCliOverride(params) {
8748
+ let categoryPairs = {};
8749
+ if (params.env.AGENT_SHIM_CATEGORY_OVERRIDE !== void 0 && params.env.AGENT_SHIM_CATEGORY_OVERRIDE !== "") {
8750
+ categoryPairs = parseOverride("AGENT_SHIM_CATEGORY_OVERRIDE", params.env.AGENT_SHIM_CATEGORY_OVERRIDE, parseBoolPairList);
8450
8751
  }
8451
- const conversed = withConversation(passthrough, supervised.conversation, supervised.sessionId);
8452
- if (supervised.model === void 0) {
8453
- return conversed;
8752
+ for (const flagValue of params.categoryFlags) {
8753
+ const pair = parseOverride("--category", flagValue, (raw) => {
8754
+ const { key, value } = parsePair(raw);
8755
+ return { key, value: parseBool(value) };
8756
+ });
8757
+ categoryPairs[pair.key] = pair.value;
8454
8758
  }
8455
- const end = conversed.indexOf(TERMINATOR2);
8456
- const head = end === -1 ? conversed : conversed.slice(0, end);
8457
- const tail = end === -1 ? [] : conversed.slice(end);
8458
- const kept = [];
8459
- for (let index = 0; index < head.length; index += 1) {
8460
- const token = head[index];
8461
- if (token === "--model") {
8462
- index += 1;
8463
- continue;
8464
- }
8465
- if (token !== void 0 && !token.startsWith("--model=")) {
8466
- kept.push(token);
8467
- }
8759
+ let entryPairs = {};
8760
+ if (params.env.AGENT_SHIM_ENTRY_OVERRIDE !== void 0 && params.env.AGENT_SHIM_ENTRY_OVERRIDE !== "") {
8761
+ entryPairs = parseOverride("AGENT_SHIM_ENTRY_OVERRIDE", params.env.AGENT_SHIM_ENTRY_OVERRIDE, parseBoolPairList);
8468
8762
  }
8469
- return [...kept, "--model", supervised.model, ...tail];
8470
- }
8471
- function withLauncherSettings(passthrough, settings) {
8472
- if (settings === void 0) {
8473
- return passthrough;
8763
+ for (const entryPath of params.shareFlags) {
8764
+ entryPairs[entryPath] = true;
8474
8765
  }
8475
- const end = passthrough.indexOf(TERMINATOR2);
8476
- return end === -1 ? [...passthrough, "--settings", settings] : [...passthrough.slice(0, end), "--settings", settings, ...passthrough.slice(end)];
8477
- }
8478
- function isRecord15(value) {
8479
- return typeof value === "object" && value !== null && !Array.isArray(value);
8480
- }
8481
- function mergeSettings(parts) {
8482
- const merged = {};
8483
- let any = false;
8484
- for (const part of parts) {
8485
- if (part === void 0) {
8486
- continue;
8487
- }
8488
- const parsed = JSON.parse(part);
8489
- if (!isRecord15(parsed)) {
8490
- throw new Error("a launch's settings part is not a JSON object");
8491
- }
8492
- for (const [key, value] of Object.entries(parsed)) {
8493
- if (key in merged) {
8494
- throw new Error(`two launch settings parts both set "${key}"`);
8495
- }
8496
- merged[key] = value;
8497
- }
8498
- any = true;
8766
+ for (const entryPath of params.hideFlags) {
8767
+ entryPairs[entryPath] = false;
8499
8768
  }
8500
- return any ? JSON.stringify(merged) : void 0;
8769
+ const hasCategories = Object.keys(categoryPairs).length > 0;
8770
+ const hasEntries = Object.keys(entryPairs).length > 0;
8771
+ const hasProvider = params.providerFlag !== void 0 && params.providerFlag !== "";
8772
+ if (!hasCategories && !hasEntries && !hasProvider) {
8773
+ return void 0;
8774
+ }
8775
+ return {
8776
+ ...hasCategories ? { categories: toCategoryMap(categoryPairs) } : {},
8777
+ ...hasEntries ? { entries: toEntries(entryPairs) } : {},
8778
+ ...hasProvider ? { launch: { provider: params.providerFlag } } : {}
8779
+ };
8501
8780
  }
8502
- var TERMINATOR2, VALUED_CONVERSATION_FLAGS, CONTINUE_FLAGS;
8503
- var init_claudeSession = __esm({
8504
- "src/launcher/claudeSession.ts"() {
8781
+ var InvalidCliCategoryError, InvalidCliEntryKeyError;
8782
+ var init_cliOverride = __esm({
8783
+ "src/launcher/cliOverride.ts"() {
8505
8784
  "use strict";
8506
- init_resumeContext();
8507
- TERMINATOR2 = "--";
8508
- VALUED_CONVERSATION_FLAGS = /* @__PURE__ */ new Set(["--resume", "-r", "--session-id"]);
8509
- CONTINUE_FLAGS = /* @__PURE__ */ new Set(["--continue", "-c"]);
8785
+ init_pairs();
8786
+ init_schema();
8787
+ init_cliError();
8788
+ InvalidCliCategoryError = class extends CliError {
8789
+ constructor(categoryName) {
8790
+ super(`"${categoryName}" is not a category this launch may toggle (runtime, history, knowledge, settings).`);
8791
+ this.categoryName = categoryName;
8792
+ this.name = "InvalidCliCategoryError";
8793
+ }
8794
+ categoryName;
8795
+ };
8796
+ InvalidCliEntryKeyError = class extends CliError {
8797
+ constructor(key) {
8798
+ super(`"${key}" is not a valid entries key \u2014 it must start with "<category>/", e.g. "knowledge/skills/commit".`);
8799
+ this.key = key;
8800
+ this.name = "InvalidCliEntryKeyError";
8801
+ }
8802
+ key;
8803
+ };
8510
8804
  }
8511
8805
  });
8512
8806
 
8513
- // src/launcher/diagnostics.ts
8514
- function diagnosticLines(diagnostics) {
8515
- const unclassified = [...new Set(diagnostics.filter((diagnostic) => diagnostic.code === "UNCLASSIFIED_ENTRY").map((diagnostic) => diagnostic.subject))];
8516
- const lines = [];
8517
- let unclassifiedReported = false;
8518
- for (const diagnostic of diagnostics) {
8519
- if (diagnostic.severity === "info") {
8807
+ // src/headroom/headers.ts
8808
+ function mergeAnthropicCustomHeaders(existing, additions) {
8809
+ const merged = /* @__PURE__ */ new Map();
8810
+ for (const block of existing) {
8811
+ if (block === void 0) {
8520
8812
  continue;
8521
8813
  }
8522
- if (diagnostic.code === "UNCLASSIFIED_ENTRY") {
8523
- if (!unclassifiedReported) {
8524
- unclassifiedReported = true;
8525
- const names = unclassified.filter((name) => name !== void 0);
8526
- lines.push({ severity: diagnostic.severity, text: `agent-shim: ${diagnostic.code}: ${unclassifiedEntrySummary(names)}
8527
- ${unclassifiedEntryFix(names)}.` });
8814
+ for (const line of block.split("\n")) {
8815
+ const entry = parseCustomHeaderLine(line);
8816
+ if (entry === void 0) {
8817
+ continue;
8528
8818
  }
8529
- continue;
8530
- }
8531
- lines.push({ severity: diagnostic.severity, text: `agent-shim: ${diagnostic.code}: ${diagnostic.message}` });
8532
- }
8533
- return lines;
8534
- }
8535
- function printDiagnosticLines(log, lines, options) {
8536
- for (const line of lines) {
8537
- if (line.severity === "error" && !options.errorsAsWarnings) {
8538
- log.error(line.text);
8539
- } else {
8540
- log.warn(line.text);
8819
+ merged.set(entry.name, entry.value);
8541
8820
  }
8542
8821
  }
8543
- }
8544
- function reportDiagnostics(log, diagnostics, options) {
8545
- printDiagnosticLines(log, diagnosticLines(diagnostics), options);
8546
- }
8547
- var init_diagnostics = __esm({
8548
- "src/launcher/diagnostics.ts"() {
8549
- "use strict";
8550
- init_decide();
8822
+ for (const entry of additions) {
8823
+ merged.set(entry.name, entry.value);
8551
8824
  }
8552
- });
8553
-
8554
- // src/launcher/hold.ts
8555
- function describeDelay(ms) {
8556
- return ms % MS_PER_SECOND7 === 0 ? `${String(ms / MS_PER_SECOND7)}s` : `${String(ms)}ms`;
8825
+ return [...merged].map(([name, value]) => `${name}: ${value}`).join("\n");
8557
8826
  }
8558
- function holdBeforeLaunch(hold, port, log) {
8559
- if (port === void 0 || !port.attended() || !hold.pause && hold.delayMs <= 0) {
8560
- return "go";
8827
+ function parseCustomHeaderLine(line) {
8828
+ const trimmed = line.trim();
8829
+ if (trimmed === "") {
8830
+ return void 0;
8561
8831
  }
8562
- if (hold.pause) {
8563
- log.info("agent-shim: paused before launch; press any key to start, or Ctrl-C to cancel");
8564
- return port.waitForKey() === "interrupt" ? "cancelled" : "go";
8832
+ const colon = trimmed.indexOf(":");
8833
+ if (colon <= 0) {
8834
+ return void 0;
8565
8835
  }
8566
- log.info(`agent-shim: starting in ${describeDelay(hold.delayMs)}`);
8567
- port.sleep(hold.delayMs);
8568
- return "go";
8836
+ return { name: trimmed.slice(0, colon).trim(), value: trimmed.slice(colon + 1).trim() };
8569
8837
  }
8570
- var LAUNCH_CANCELLED_EXIT, MS_PER_SECOND7;
8571
- var init_hold = __esm({
8572
- "src/launcher/hold.ts"() {
8838
+ var init_headers = __esm({
8839
+ "src/headroom/headers.ts"() {
8573
8840
  "use strict";
8574
- LAUNCH_CANCELLED_EXIT = 130;
8575
- MS_PER_SECOND7 = 1e3;
8576
8841
  }
8577
8842
  });
8578
8843
 
8579
- // src/usage/candidateText.ts
8580
- function candidateHeading(candidate) {
8581
- const score = candidate.score === void 0 ? "" : ` score ${candidate.score.toFixed(2)}${candidate.scoreWindow === "fiveHour" ? " by 5h reset" : " by 7d reset"}`;
8582
- const dry = candidate.feasible ? "" : " (5h would run dry)";
8583
- return `[${candidate.class}${score}]${dry}`;
8844
+ // src/launcher/flags.ts
8845
+ function resolveLaunchFlags(params) {
8846
+ return {
8847
+ skipPermissions: params.flags?.skipPermissions ?? parseEnvBool("AGENT_SHIM_SKIP_PERMISSIONS", params.env.AGENT_SHIM_SKIP_PERMISSIONS) ?? params.cascade?.skipPermissions ?? false,
8848
+ remoteControl: params.flags?.remoteControl ?? parseEnvBool("AGENT_SHIM_REMOTE_CONTROL", params.env.AGENT_SHIM_REMOTE_CONTROL) ?? params.cascade?.remoteControl ?? false,
8849
+ headroom: params.flags?.headroom ?? parseEnvBool("AGENT_SHIM_HEADROOM", params.env.AGENT_SHIM_HEADROOM) ?? params.cascade?.headroom ?? false,
8850
+ trackUsage: params.flags?.trackUsage ?? parseEnvBool("AGENT_SHIM_TRACK_USAGE", params.env.AGENT_SHIM_TRACK_USAGE) ?? params.cascade?.trackUsage ?? true,
8851
+ pause: params.flags?.pause ?? parseEnvBool("AGENT_SHIM_PAUSE", params.env.AGENT_SHIM_PAUSE) ?? params.cascade?.pause ?? false,
8852
+ explain: params.flags?.explain ?? parseEnvBool("AGENT_SHIM_EXPLAIN", params.env.AGENT_SHIM_EXPLAIN) ?? params.cascade?.explain ?? false,
8853
+ routeByName: params.flags?.routeByName ?? parseEnvBool("AGENT_SHIM_ROUTE_BY_NAME", params.env.AGENT_SHIM_ROUTE_BY_NAME) ?? params.cascade?.routeByName ?? false,
8854
+ delayMs: resolveDelayMs(params)
8855
+ };
8584
8856
  }
8585
- var init_candidateText = __esm({
8586
- "src/usage/candidateText.ts"() {
8587
- "use strict";
8857
+ function resolveDelayMs(params) {
8858
+ const fromEnv = params.env.AGENT_SHIM_DELAY === "" ? void 0 : params.env.AGENT_SHIM_DELAY;
8859
+ const [literal, source] = params.flags?.delay !== void 0 ? [params.flags.delay, "--delay"] : fromEnv !== void 0 ? [fromEnv, "AGENT_SHIM_DELAY"] : [params.cascade?.delay, "launch.delay"];
8860
+ if (literal === void 0) {
8861
+ return 0;
8588
8862
  }
8589
- });
8590
-
8591
- // src/launcher/launchReport.ts
8592
- function poolDetail(pool) {
8593
- const [reason] = pool.reasons;
8594
- if (pool.movedOff !== void 0) {
8595
- return { detail: `moved off ${pool.movedOff.identity}: ${pool.movedOff.reason}`, ...reason === void 0 ? {} : { notes: [reason] } };
8863
+ try {
8864
+ return parseDuration(literal);
8865
+ } catch (error) {
8866
+ throw new UsageError(`${source}: ${error instanceof Error ? error.message : String(error)}`);
8596
8867
  }
8597
- return reason === void 0 ? {} : { detail: reason };
8598
8868
  }
8599
- function rankingNotes(ranking, picked) {
8600
- return ranking.flatMap((candidate, index) => [
8601
- `${String(index + 1)}. ${candidate.identity} ${candidateHeading(candidate)}${candidate.identity === picked ? " (picked)" : ""}`,
8602
- ` ${candidate.reasons.join("; ")}`
8603
- ]);
8869
+ function buildFlagArgs(flags) {
8870
+ const args = [];
8871
+ if (flags.skipPermissions) {
8872
+ args.push("--dangerously-skip-permissions");
8873
+ }
8874
+ if (flags.remoteControl) {
8875
+ args.push("--remote-control=");
8876
+ }
8877
+ return args;
8604
8878
  }
8605
- function decisionRows(facts) {
8606
- return [
8607
- { label: "identity", value: facts.identity ?? "(none)", detail: facts.identitySource },
8608
- ...facts.pool === void 0 ? [] : [
8609
- {
8610
- label: "pool",
8611
- value: facts.pool.name,
8612
- ...poolDetail(facts.pool),
8613
- ...facts.ranking === void 0 ? {} : { notes: rankingNotes(facts.ranking, facts.identity) }
8614
- }
8615
- ],
8616
- ...facts.profile === void 0 ? [] : [{ label: "profile", value: facts.profile.name, detail: facts.profile.source }],
8617
- ...facts.provider === void 0 ? [] : [{ label: "provider", value: facts.provider.name, detail: `credential ${facts.provider.credential}` }],
8618
- ...facts.identityCredential === void 0 ? [] : [{ label: "credential", value: facts.identityCredential, detail: "the identity's own" }]
8619
- ];
8879
+ function buildArgv(params) {
8880
+ return [...params.toolFlags, ...params.extraFlags, ...params.passthrough];
8620
8881
  }
8621
- function pinnedVersionRow(version, source) {
8622
- return { label: "claude", value: version, detail: `pinned by ${source}` };
8882
+ function withLoopbackHosts(existing) {
8883
+ const listed = (existing ?? "").split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
8884
+ return [...listed, ...LOOPBACK_HOSTS.filter((host) => !listed.includes(host))].join(",");
8623
8885
  }
8624
- function routingRows(facts) {
8625
- if (facts.frontDoor === void 0) {
8626
- return [];
8886
+ function buildEnv(params) {
8887
+ const env = { ...params.baseEnv };
8888
+ const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
8889
+ let providerCustomHeaders;
8890
+ if (!params.configDirEscapeHatch && params.resolvedIdentityName !== void 0) {
8891
+ env.CLAUDE_CONFIG_DIR = import_node_path37.default.join(params.identitiesDir, params.resolvedIdentityName);
8627
8892
  }
8628
- return [
8629
- {
8630
- label: "routing",
8631
- value: `front door 127.0.0.1:${String(facts.frontDoor.port)}`,
8632
- ...facts.provider ? {} : { detail: `OAuth via CONNECT 127.0.0.1:${String(facts.frontDoor.connectPort)}` }
8633
- },
8634
- ...facts.headroom === void 0 ? [] : [{ label: "headroom", value: "on", detail: `project ${facts.headroom.projectId}` }]
8635
- ];
8636
- }
8637
- function farmRow(links, builtDirectories, adopted) {
8638
- const counted = (count, singular, plural) => `${String(count)} ${count === 1 ? singular : plural}`;
8639
- const parts = [counted(links, "link", "links"), counted(builtDirectories, "built directory", "built directories"), ...adopted === 0 ? [] : [`${String(adopted)} adopted`]];
8640
- return { label: "farm", value: "resynced", detail: parts.join(", ") };
8641
- }
8642
- function noteRow(text) {
8643
- return { label: "note", value: text };
8893
+ if (params.provider !== void 0) {
8894
+ const providerEnv = params.provider.definition.kind !== void 0 && params.provider.definition.kind !== "http" ? {} : params.provider.definition.env ?? {};
8895
+ providerCustomHeaders = providerEnv.ANTHROPIC_CUSTOM_HEADERS;
8896
+ env.ANTHROPIC_BASE_URL = void 0;
8897
+ env.AGENT_SHIM_PROVIDER = params.provider.definition.displayName;
8898
+ for (const [key, value] of Object.entries(providerEnv)) {
8899
+ env[key] = value;
8900
+ }
8901
+ }
8902
+ if (params.routeByName) {
8903
+ for (const tier of CLAUDE_TIERS) {
8904
+ const ref = params.tierModels?.[tier];
8905
+ if (ref !== void 0) {
8906
+ env[`ANTHROPIC_DEFAULT_${tier.toUpperCase()}_MODEL`] = ref;
8907
+ }
8908
+ }
8909
+ }
8910
+ if (params.provider !== void 0) {
8911
+ env.ANTHROPIC_AUTH_TOKEN = params.remoteControl ? void 0 : PROVIDER_SESSION_PLACEHOLDER;
8912
+ env.ANTHROPIC_API_KEY = void 0;
8913
+ env.CLAUDE_CODE_OAUTH_TOKEN = void 0;
8914
+ } else if (params.identityCredential !== void 0) {
8915
+ for (const [variable, value] of Object.entries(credentialVariables(params.identityCredential.target, params.identityCredential.token))) {
8916
+ env[variable] = value;
8917
+ }
8918
+ }
8919
+ if (params.frontdoor !== void 0) {
8920
+ env.ANTHROPIC_CUSTOM_HEADERS = mergeAnthropicCustomHeaders(
8921
+ [
8922
+ ...parentCustomHeaders === void 0 ? [] : [parentCustomHeaders],
8923
+ ...providerCustomHeaders === void 0 ? [] : [providerCustomHeaders]
8924
+ ],
8925
+ [
8926
+ ...params.resolvedIdentityName === void 0 ? [] : [{ name: IDENTITY_HEADER, value: params.resolvedIdentityName }],
8927
+ { name: SESSION_HEADER, value: params.sessionId },
8928
+ { name: AUTH_HEADER, value: params.frontdoor.sessionToken },
8929
+ ...params.provider === void 0 ? [] : [{ name: PROVIDER_HEADER, value: params.provider.name }],
8930
+ ...params.routeByName ? [{ name: ROUTE_BY_NAME_HEADER, value: "1" }] : [],
8931
+ ...params.headroom === void 0 ? [] : [
8932
+ { name: HEADROOM_FLAG_HEADER, value: "1" },
8933
+ { name: PROJECT_ID_HEADER, value: params.headroom.projectId }
8934
+ ]
8935
+ ]
8936
+ );
8937
+ env.NODE_EXTRA_CA_CERTS = params.frontdoor.trustBundlePath;
8938
+ env.HTTPS_PROXY = connectProxyUrl(params.frontdoor.connectPort, params.frontdoor.sessionToken);
8939
+ env.NO_PROXY = withLoopbackHosts(env.NO_PROXY);
8940
+ env.no_proxy = withLoopbackHosts(env.no_proxy);
8941
+ }
8942
+ return env;
8644
8943
  }
8645
- var init_launchReport = __esm({
8646
- "src/launcher/launchReport.ts"() {
8944
+ var import_node_path37, LOOPBACK_HOSTS, PROVIDER_SESSION_PLACEHOLDER;
8945
+ var init_flags = __esm({
8946
+ "src/launcher/flags.ts"() {
8647
8947
  "use strict";
8648
- init_candidateText();
8948
+ import_node_path37 = __toESM(require("node:path"), 1);
8949
+ init_envBool();
8950
+ init_cliError();
8951
+ init_conditions();
8952
+ init_schema();
8953
+ init_credential();
8954
+ init_headers();
8955
+ init_capability();
8956
+ init_route();
8957
+ LOOPBACK_HOSTS = ["127.0.0.1", "localhost", "::1"];
8958
+ PROVIDER_SESSION_PLACEHOLDER = "agent-shim-provider-session";
8649
8959
  }
8650
8960
  });
8651
8961
 
8652
- // src/models/identity.ts
8653
- function withoutContextMarker(model) {
8654
- return model.toLowerCase().endsWith(CONTEXT_MARKER_1M) ? model.slice(0, -CONTEXT_MARKER_1M.length) : model;
8962
+ // src/launcher/extraFlags.ts
8963
+ function splitExtraFlags(value) {
8964
+ if (value === void 0) {
8965
+ return [];
8966
+ }
8967
+ const trimmed = value.trim();
8968
+ if (trimmed === "") {
8969
+ return [];
8970
+ }
8971
+ return trimmed.split(/\s+/);
8655
8972
  }
8656
- var CONTEXT_MARKER_1M, VENDOR_BY_NAMESPACE, VENDOR_BY_TOKEN;
8657
- var init_identity2 = __esm({
8658
- "src/models/identity.ts"() {
8973
+ var init_extraFlags = __esm({
8974
+ "src/launcher/extraFlags.ts"() {
8659
8975
  "use strict";
8660
- CONTEXT_MARKER_1M = "[1m]";
8661
- VENDOR_BY_NAMESPACE = Object.freeze({
8662
- anthropic: "anthropic",
8663
- google: "google",
8664
- openai: "openai",
8665
- zai: "zai",
8666
- "z-ai": "zai",
8667
- minimax: "minimax",
8668
- qwen: "qwen",
8669
- deepseek: "deepseek",
8670
- moonshot: "moonshot",
8671
- meta: "meta",
8672
- mistral: "mistral"
8673
- });
8674
- VENDOR_BY_TOKEN = Object.freeze({
8675
- claude: "anthropic",
8676
- gemini: "google",
8677
- antigravity: "google",
8678
- gpt: "openai",
8679
- glm: "zai",
8680
- minimax: "minimax",
8681
- qwen: "qwen",
8682
- deepseek: "deepseek",
8683
- kimi: "moonshot",
8684
- llama: "meta",
8685
- mistral: "mistral",
8686
- mixtral: "mistral"
8687
- });
8688
8976
  }
8689
8977
  });
8690
8978
 
8691
- // src/selection/engine.ts
8692
- var init_engine = __esm({
8693
- "src/selection/engine.ts"() {
8694
- "use strict";
8979
+ // src/usage/resumeContext.ts
8980
+ function projectDirNameOf(cwd) {
8981
+ return cwd.replace(/[^A-Za-z0-9]/g, "-");
8982
+ }
8983
+ function resumeTargetOf(passthrough) {
8984
+ const end = passthrough.indexOf("--");
8985
+ const tokens = end === -1 ? passthrough : passthrough.slice(0, end);
8986
+ for (const [index, token] of tokens.entries()) {
8987
+ if (token === "--continue" || token === "-c") {
8988
+ return { kind: "latest" };
8989
+ }
8990
+ if (token === "--resume" || token === "-r") {
8991
+ const next = tokens[index + 1];
8992
+ return next === void 0 || next.startsWith("-") ? void 0 : { kind: "id", id: next };
8993
+ }
8994
+ if (token.startsWith("--resume=")) {
8995
+ const id = token.slice("--resume=".length);
8996
+ return id === "" ? void 0 : { kind: "id", id };
8997
+ }
8998
+ }
8999
+ return void 0;
9000
+ }
9001
+ function countOf(usage, key) {
9002
+ const value = key in usage ? Reflect.get(usage, key) : void 0;
9003
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
9004
+ }
9005
+ function contextTokensOfTranscript(text) {
9006
+ const lines = text.split("\n");
9007
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
9008
+ const line = lines[index];
9009
+ if (line === void 0 || line === "") {
9010
+ continue;
9011
+ }
9012
+ let parsed;
9013
+ try {
9014
+ parsed = JSON.parse(line);
9015
+ } catch {
9016
+ continue;
9017
+ }
9018
+ if (typeof parsed !== "object" || parsed === null || !("type" in parsed) || parsed.type !== "assistant" || !("message" in parsed)) {
9019
+ continue;
9020
+ }
9021
+ const { message } = parsed;
9022
+ if (typeof message !== "object" || message === null || !("usage" in message) || typeof message.usage !== "object" || message.usage === null) {
9023
+ continue;
9024
+ }
9025
+ const { usage } = message;
9026
+ return countOf(usage, "input_tokens") + countOf(usage, "cache_read_input_tokens") + countOf(usage, "cache_creation_input_tokens");
8695
9027
  }
8696
- });
8697
-
8698
- // src/antigravity/cloudUpstream.ts
8699
- var init_cloudUpstream = __esm({
8700
- "src/antigravity/cloudUpstream.ts"() {
8701
- "use strict";
9028
+ return void 0;
9029
+ }
9030
+ function newestTranscript(fs13, projectDir) {
9031
+ let newest;
9032
+ let newestMs = -Infinity;
9033
+ for (const name of fs13.readdir(projectDir)) {
9034
+ if (!name.endsWith(".jsonl")) {
9035
+ continue;
9036
+ }
9037
+ const candidate = import_node_path38.default.join(projectDir, name);
9038
+ const stat = fs13.lstat(candidate);
9039
+ if (stat?.kind === "file" && stat.mtimeMs > newestMs) {
9040
+ newestMs = stat.mtimeMs;
9041
+ newest = candidate;
9042
+ }
8702
9043
  }
8703
- });
8704
-
8705
- // src/antigravity/quota.ts
8706
- var SECONDS_PER_HOUR, HOURS_PER_FIVE_HOUR_WINDOW, DAYS_PER_WEEK, HOURS_PER_DAY4, FIVE_HOUR_PERIOD_SECONDS, WEEK_PERIOD_SECONDS;
8707
- var init_quota = __esm({
8708
- "src/antigravity/quota.ts"() {
8709
- "use strict";
8710
- init_cloudUpstream();
8711
- SECONDS_PER_HOUR = 3600;
8712
- HOURS_PER_FIVE_HOUR_WINDOW = 5;
8713
- DAYS_PER_WEEK = 7;
8714
- HOURS_PER_DAY4 = 24;
8715
- FIVE_HOUR_PERIOD_SECONDS = HOURS_PER_FIVE_HOUR_WINDOW * SECONDS_PER_HOUR;
8716
- WEEK_PERIOD_SECONDS = DAYS_PER_WEEK * HOURS_PER_DAY4 * SECONDS_PER_HOUR;
9044
+ return newest;
9045
+ }
9046
+ function resumedContextTokens(fs13, params) {
9047
+ const target = resumeTargetOf(params.passthrough);
9048
+ if (target === void 0) {
9049
+ return void 0;
8717
9050
  }
8718
- });
8719
-
8720
- // src/antigravity/signatures.ts
8721
- var init_signatures = __esm({
8722
- "src/antigravity/signatures.ts"() {
9051
+ const projectDir = import_node_path38.default.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
9052
+ const file = target.kind === "id" ? import_node_path38.default.join(projectDir, `${target.id}.jsonl`) : newestTranscript(fs13, projectDir);
9053
+ const text = file === void 0 ? void 0 : fs13.readFileUtf8(file);
9054
+ return text === void 0 ? void 0 : contextTokensOfTranscript(text);
9055
+ }
9056
+ var import_node_path38;
9057
+ var init_resumeContext = __esm({
9058
+ "src/usage/resumeContext.ts"() {
8723
9059
  "use strict";
9060
+ import_node_path38 = __toESM(require("node:path"), 1);
8724
9061
  }
8725
9062
  });
8726
9063
 
8727
- // src/codex/anthropic.ts
8728
- var import_zod29, TextBlockSchema, Base64ImageSourceSchema, UrlImageSourceSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultContentBlockSchema, ToolResultBlockSchema, OtherBlockSchema, ContentBlockSchema, MessageSchema, ToolSchema, ToolChoiceSchema, SystemSchema, MessagesRequestSchema, CountTokensRequestSchema;
8729
- var init_anthropic = __esm({
8730
- "src/codex/anthropic.ts"() {
8731
- "use strict";
8732
- import_zod29 = require("zod");
8733
- TextBlockSchema = import_zod29.z.looseObject({ type: import_zod29.z.literal("text"), text: import_zod29.z.string() });
8734
- Base64ImageSourceSchema = import_zod29.z.looseObject({ type: import_zod29.z.literal("base64"), media_type: import_zod29.z.string().min(1), data: import_zod29.z.string() });
8735
- UrlImageSourceSchema = import_zod29.z.looseObject({ type: import_zod29.z.literal("url"), url: import_zod29.z.string().min(1) });
8736
- ImageBlockSchema = import_zod29.z.looseObject({
8737
- type: import_zod29.z.literal("image"),
8738
- source: import_zod29.z.union([Base64ImageSourceSchema, UrlImageSourceSchema])
8739
- });
8740
- ToolUseBlockSchema = import_zod29.z.looseObject({
8741
- type: import_zod29.z.literal("tool_use"),
8742
- id: import_zod29.z.string().min(1),
8743
- name: import_zod29.z.string().min(1),
8744
- input: import_zod29.z.unknown()
8745
- });
8746
- ToolResultContentBlockSchema = import_zod29.z.union([TextBlockSchema, import_zod29.z.looseObject({ type: import_zod29.z.string() })]);
8747
- ToolResultBlockSchema = import_zod29.z.looseObject({
8748
- type: import_zod29.z.literal("tool_result"),
8749
- tool_use_id: import_zod29.z.string().min(1),
8750
- content: import_zod29.z.union([import_zod29.z.string(), import_zod29.z.array(ToolResultContentBlockSchema)]).optional()
8751
- });
8752
- OtherBlockSchema = import_zod29.z.looseObject({ type: import_zod29.z.string() });
8753
- ContentBlockSchema = import_zod29.z.union([TextBlockSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultBlockSchema, OtherBlockSchema]);
8754
- MessageSchema = import_zod29.z.looseObject({
8755
- role: import_zod29.z.enum(["user", "assistant", "system"]),
8756
- content: import_zod29.z.union([import_zod29.z.string(), import_zod29.z.array(ContentBlockSchema)])
8757
- });
8758
- ToolSchema = import_zod29.z.looseObject({
8759
- name: import_zod29.z.string().min(1),
8760
- description: import_zod29.z.string().optional(),
8761
- input_schema: import_zod29.z.record(import_zod29.z.string(), import_zod29.z.unknown()).optional()
8762
- });
8763
- ToolChoiceSchema = import_zod29.z.union([
8764
- import_zod29.z.looseObject({ type: import_zod29.z.enum(["auto", "none", "any"]) }),
8765
- import_zod29.z.looseObject({ type: import_zod29.z.literal("tool"), name: import_zod29.z.string().min(1) })
8766
- ]);
8767
- SystemSchema = import_zod29.z.union([import_zod29.z.string(), import_zod29.z.array(import_zod29.z.union([TextBlockSchema, OtherBlockSchema]))]);
8768
- MessagesRequestSchema = import_zod29.z.looseObject({
8769
- model: import_zod29.z.string().optional(),
8770
- system: SystemSchema.optional(),
8771
- messages: import_zod29.z.array(MessageSchema),
8772
- tools: import_zod29.z.array(ToolSchema).optional(),
8773
- tool_choice: ToolChoiceSchema.optional(),
8774
- stream: import_zod29.z.boolean().optional(),
8775
- /** `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. */
8776
- metadata: import_zod29.z.looseObject({ user_id: import_zod29.z.string().optional() }).optional(),
8777
- /** Claude Code's effort setting. Any string is accepted; the translator honours only the levels the backend understands. */
8778
- output_config: import_zod29.z.looseObject({ effort: import_zod29.z.string().optional() }).optional()
8779
- });
8780
- CountTokensRequestSchema = import_zod29.z.looseObject({
8781
- system: import_zod29.z.unknown().optional(),
8782
- messages: import_zod29.z.unknown().optional(),
8783
- tools: import_zod29.z.unknown().optional()
8784
- });
9064
+ // src/launcher/claudeSession.ts
9065
+ function isFlag(token) {
9066
+ return token?.startsWith("-") === true;
9067
+ }
9068
+ function withConversation(passthrough, conversation, id) {
9069
+ const end = passthrough.indexOf(TERMINATOR2);
9070
+ const head = end === -1 ? passthrough : passthrough.slice(0, end);
9071
+ const tail = end === -1 ? [] : passthrough.slice(end);
9072
+ const kept = [];
9073
+ for (let index = 0; index < head.length; index += 1) {
9074
+ const token = head[index];
9075
+ if (token === void 0 || CONTINUE_FLAGS.has(token) || token.startsWith("--resume=") || token.startsWith("--session-id=")) {
9076
+ continue;
9077
+ }
9078
+ if (VALUED_CONVERSATION_FLAGS.has(token)) {
9079
+ if (!isFlag(head[index + 1]) && head[index + 1] !== void 0) {
9080
+ index += 1;
9081
+ }
9082
+ continue;
9083
+ }
9084
+ kept.push(token);
8785
9085
  }
8786
- });
8787
-
8788
- // src/antigravity/translate.ts
8789
- function candidatesOf(target) {
8790
- return typeof target === "string" ? [target] : target;
9086
+ return [...kept, conversation === "start" ? "--session-id" : "--resume", id, ...tail];
8791
9087
  }
8792
- function isAntigravityTier(key) {
8793
- return CLAUDE_TIERS.some((tier) => tier === key);
9088
+ function hasSettingsArgument(passthrough) {
9089
+ const end = passthrough.indexOf(TERMINATOR2);
9090
+ return (end === -1 ? passthrough : passthrough.slice(0, end)).some((token) => token === "--settings" || token.startsWith("--settings="));
8794
9091
  }
8795
- function resolveAntigravityConfig(config) {
8796
- const overrides = config?.models ?? {};
8797
- const aliases = /* @__PURE__ */ new Map();
8798
- for (const [key, target] of Object.entries(overrides)) {
8799
- if (!isAntigravityTier(key)) {
8800
- aliases.set(key.toLowerCase(), candidatesOf(target));
9092
+ function withSupervision(passthrough, supervised) {
9093
+ if (supervised.conversation === "as-given") {
9094
+ return passthrough;
9095
+ }
9096
+ const conversed = withConversation(passthrough, supervised.conversation, supervised.sessionId);
9097
+ if (supervised.model === void 0) {
9098
+ return conversed;
9099
+ }
9100
+ const end = conversed.indexOf(TERMINATOR2);
9101
+ const head = end === -1 ? conversed : conversed.slice(0, end);
9102
+ const tail = end === -1 ? [] : conversed.slice(end);
9103
+ const kept = [];
9104
+ for (let index = 0; index < head.length; index += 1) {
9105
+ const token = head[index];
9106
+ if (token === "--model") {
9107
+ index += 1;
9108
+ continue;
9109
+ }
9110
+ if (token !== void 0 && !token.startsWith("--model=")) {
9111
+ kept.push(token);
8801
9112
  }
8802
9113
  }
8803
- const tierModel = (tier) => {
8804
- const target = overrides[tier];
8805
- return target === void 0 ? ANTIGRAVITY_DEFAULT_TIER_MODELS[tier] : candidatesOf(target);
8806
- };
8807
- if (!aliases.has(AUTO_ALIAS)) {
8808
- aliases.set(AUTO_ALIAS, [...new Set(CLAUDE_TIERS.flatMap(tierModel))]);
9114
+ return [...kept, "--model", supervised.model, ...tail];
9115
+ }
9116
+ function withLauncherSettings(passthrough, settings) {
9117
+ if (settings === void 0) {
9118
+ return passthrough;
8809
9119
  }
8810
- return {
8811
- mode: config?.mode ?? ANTIGRAVITY_DEFAULT_MODE,
8812
- defaultModel: config?.defaultModel ?? ANTIGRAVITY_DEFAULT_MODEL,
8813
- models: { fable: tierModel("fable"), opus: tierModel("opus"), sonnet: tierModel("sonnet"), haiku: tierModel("haiku") },
8814
- aliases,
8815
- degradeDownTiers: config?.degradeDownTiers ?? false,
8816
- effort: config?.effort ?? ANTIGRAVITY_DEFAULT_EFFORT,
8817
- cloud: {
8818
- endpoint: config?.cloud?.endpoint,
8819
- projectId: config?.cloud?.projectId,
8820
- location: config?.cloud?.location
8821
- },
8822
- local: {
8823
- command: config?.local?.command,
8824
- socketPath: config?.local?.socketPath
9120
+ const end = passthrough.indexOf(TERMINATOR2);
9121
+ return end === -1 ? [...passthrough, "--settings", settings] : [...passthrough.slice(0, end), "--settings", settings, ...passthrough.slice(end)];
9122
+ }
9123
+ function isRecord15(value) {
9124
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9125
+ }
9126
+ function mergeSettings(parts) {
9127
+ const merged = {};
9128
+ let any = false;
9129
+ for (const part of parts) {
9130
+ if (part === void 0) {
9131
+ continue;
8825
9132
  }
8826
- };
9133
+ const parsed = JSON.parse(part);
9134
+ if (!isRecord15(parsed)) {
9135
+ throw new Error("a launch's settings part is not a JSON object");
9136
+ }
9137
+ for (const [key, value] of Object.entries(parsed)) {
9138
+ if (key in merged) {
9139
+ throw new Error(`two launch settings parts both set "${key}"`);
9140
+ }
9141
+ merged[key] = value;
9142
+ }
9143
+ any = true;
9144
+ }
9145
+ return any ? JSON.stringify(merged) : void 0;
8827
9146
  }
8828
- var AUTO_ALIAS;
8829
- var init_translate = __esm({
8830
- "src/antigravity/translate.ts"() {
9147
+ var TERMINATOR2, VALUED_CONVERSATION_FLAGS, CONTINUE_FLAGS;
9148
+ var init_claudeSession = __esm({
9149
+ "src/launcher/claudeSession.ts"() {
8831
9150
  "use strict";
8832
- init_identity2();
8833
- init_engine();
8834
- init_quota();
8835
- init_signatures();
8836
- init_schema();
8837
- init_anthropic();
8838
- AUTO_ALIAS = "auto";
9151
+ init_resumeContext();
9152
+ TERMINATOR2 = "--";
9153
+ VALUED_CONVERSATION_FLAGS = /* @__PURE__ */ new Set(["--resume", "-r", "--session-id"]);
9154
+ CONTINUE_FLAGS = /* @__PURE__ */ new Set(["--continue", "-c"]);
8839
9155
  }
8840
9156
  });
8841
9157
 
8842
- // src/codex/translate.ts
8843
- function resolveCodexConfig(config) {
8844
- const overrides = config?.models;
8845
- return {
8846
- defaultModel: config?.defaultModel ?? CODEX_DEFAULT_MODEL,
8847
- models: {
8848
- fable: overrides?.fable ?? CODEX_DEFAULT_TIER_MODELS.fable,
8849
- opus: overrides?.opus ?? CODEX_DEFAULT_TIER_MODELS.opus,
8850
- sonnet: overrides?.sonnet ?? CODEX_DEFAULT_TIER_MODELS.sonnet,
8851
- haiku: overrides?.haiku ?? CODEX_DEFAULT_TIER_MODELS.haiku
8852
- },
8853
- effort: config?.effort ?? CODEX_DEFAULT_EFFORT,
8854
- login: config?.login ?? CODEX_DEFAULT_LOGIN
8855
- };
9158
+ // src/launcher/diagnostics.ts
9159
+ function diagnosticLines(diagnostics) {
9160
+ const unclassified = [...new Set(diagnostics.filter((diagnostic) => diagnostic.code === "UNCLASSIFIED_ENTRY").map((diagnostic) => diagnostic.subject))];
9161
+ const lines = [];
9162
+ let unclassifiedReported = false;
9163
+ for (const diagnostic of diagnostics) {
9164
+ if (diagnostic.severity === "info") {
9165
+ continue;
9166
+ }
9167
+ if (diagnostic.code === "UNCLASSIFIED_ENTRY") {
9168
+ if (!unclassifiedReported) {
9169
+ unclassifiedReported = true;
9170
+ const names = unclassified.filter((name) => name !== void 0);
9171
+ lines.push({ severity: diagnostic.severity, text: `agent-shim: ${diagnostic.code}: ${unclassifiedEntrySummary(names)}
9172
+ ${unclassifiedEntryFix(names)}.` });
9173
+ }
9174
+ continue;
9175
+ }
9176
+ lines.push({ severity: diagnostic.severity, text: `agent-shim: ${diagnostic.code}: ${diagnostic.message}` });
9177
+ }
9178
+ return lines;
8856
9179
  }
8857
- var init_translate2 = __esm({
8858
- "src/codex/translate.ts"() {
9180
+ function printDiagnosticLines(log, lines, options) {
9181
+ for (const line of lines) {
9182
+ if (line.severity === "error" && !options.errorsAsWarnings) {
9183
+ log.error(line.text);
9184
+ } else {
9185
+ log.warn(line.text);
9186
+ }
9187
+ }
9188
+ }
9189
+ function reportDiagnostics(log, diagnostics, options) {
9190
+ printDiagnosticLines(log, diagnosticLines(diagnostics), options);
9191
+ }
9192
+ var init_diagnostics = __esm({
9193
+ "src/launcher/diagnostics.ts"() {
8859
9194
  "use strict";
8860
- init_schema();
8861
- init_anthropic();
9195
+ init_decide();
8862
9196
  }
8863
9197
  });
8864
-
8865
- // src/providerCatalogue.ts
8866
- function catalogueCachePath(paths, name) {
8867
- return import_node_path38.default.join(paths.catalogueDir, `${name}.json`);
9198
+
9199
+ // src/launcher/hold.ts
9200
+ function describeDelay(ms) {
9201
+ return ms % MS_PER_SECOND8 === 0 ? `${String(ms / MS_PER_SECOND8)}s` : `${String(ms)}ms`;
8868
9202
  }
8869
- function parseCatalogueCache(text) {
8870
- if (text === void 0) {
8871
- return void 0;
9203
+ function holdBeforeLaunch(hold, port, log) {
9204
+ if (port === void 0 || !port.attended() || !hold.pause && hold.delayMs <= 0) {
9205
+ return "go";
8872
9206
  }
8873
- try {
8874
- const parsed = CatalogueCacheSchema.safeParse(JSON.parse(text));
8875
- return parsed.success ? parsed.data : void 0;
8876
- } catch {
8877
- return void 0;
9207
+ if (hold.pause) {
9208
+ log.info("agent-shim: paused before launch; press any key to start, or Ctrl-C to cancel");
9209
+ return port.waitForKey() === "interrupt" ? "cancelled" : "go";
8878
9210
  }
9211
+ log.info(`agent-shim: starting in ${describeDelay(hold.delayMs)}`);
9212
+ port.sleep(hold.delayMs);
9213
+ return "go";
8879
9214
  }
8880
- function filterCatalogue(models, catalogue) {
8881
- const included = catalogue.include === void 0 ? void 0 : (0, import_picomatch4.default)(catalogue.include, { dot: true });
8882
- const excluded = catalogue.exclude === void 0 ? void 0 : (0, import_picomatch4.default)(catalogue.exclude, { dot: true });
8883
- return models.filter((model) => included?.(model.id) !== false && excluded?.(model.id) !== true);
8884
- }
8885
- var import_node_path38, import_picomatch4, import_zod30, DEFAULT_CANDIDATE_URLS, MS_PER_SECOND8, SECONDS_PER_HOUR2, HOURS_PER_DAY5, MS_PER_HOUR5, HOURS_BETWEEN_RETRIES, CATALOGUE_MAX_AGE_MS, CATALOGUE_RETRY_MS, CATALOGUE_REQUEST_SECONDS, CATALOGUE_REQUEST_TIMEOUT_MS, CATALOGUE_REFRESH_TIMEOUT_MS, CatalogueModelSchema, CatalogueCacheSchema;
8886
- var init_providerCatalogue = __esm({
8887
- "src/providerCatalogue.ts"() {
9215
+ var LAUNCH_CANCELLED_EXIT, MS_PER_SECOND8;
9216
+ var init_hold = __esm({
9217
+ "src/launcher/hold.ts"() {
8888
9218
  "use strict";
8889
- import_node_path38 = __toESM(require("node:path"), 1);
8890
- import_picomatch4 = __toESM(require("picomatch"), 1);
8891
- import_zod30 = require("zod");
8892
- DEFAULT_CANDIDATE_URLS = 2;
9219
+ LAUNCH_CANCELLED_EXIT = 130;
8893
9220
  MS_PER_SECOND8 = 1e3;
8894
- SECONDS_PER_HOUR2 = 3600;
8895
- HOURS_PER_DAY5 = 24;
8896
- MS_PER_HOUR5 = SECONDS_PER_HOUR2 * MS_PER_SECOND8;
8897
- HOURS_BETWEEN_RETRIES = 1;
8898
- CATALOGUE_MAX_AGE_MS = HOURS_PER_DAY5 * MS_PER_HOUR5;
8899
- CATALOGUE_RETRY_MS = HOURS_BETWEEN_RETRIES * MS_PER_HOUR5;
8900
- CATALOGUE_REQUEST_SECONDS = 10;
8901
- CATALOGUE_REQUEST_TIMEOUT_MS = CATALOGUE_REQUEST_SECONDS * MS_PER_SECOND8;
8902
- CATALOGUE_REFRESH_TIMEOUT_MS = DEFAULT_CANDIDATE_URLS * CATALOGUE_REQUEST_TIMEOUT_MS;
8903
- CatalogueModelSchema = import_zod30.z.strictObject({ id: import_zod30.z.string().min(1), name: import_zod30.z.string().min(1).optional() });
8904
- CatalogueCacheSchema = import_zod30.z.strictObject({ fetchedAt: import_zod30.z.number(), url: import_zod30.z.string().min(1), models: import_zod30.z.array(CatalogueModelSchema) });
8905
9221
  }
8906
9222
  });
8907
9223
 
8908
- // src/launcher/modelPicker.ts
8909
- function labelOf(model) {
8910
- return withoutContextMarker(model);
8911
- }
8912
- function describedAs(model, description) {
8913
- return model.toLowerCase().endsWith(CONTEXT_MARKER_1M) ? `${description}; 1M context` : description;
8914
- }
8915
- function joined(parts) {
8916
- const last = parts[parts.length - 1];
8917
- return last === void 0 || parts.length === 1 ? last ?? "" : `${parts.slice(0, -1).join(", ")} and ${last}`;
9224
+ // src/usage/candidateText.ts
9225
+ function candidateHeading(candidate) {
9226
+ const score = candidate.score === void 0 ? "" : ` score ${candidate.score.toFixed(2)}${candidate.scoreWindow === "fiveHour" ? " by 5h reset" : " by 7d reset"}`;
9227
+ const dry = candidate.feasible ? "" : " (5h would run dry)";
9228
+ return `[${candidate.class}${score}]${dry}`;
8918
9229
  }
8919
- function rowOf2(model, reaches) {
8920
- const lead = reaches.find((reach) => reach.standing === "first") ?? reaches[0];
8921
- if (lead === void 0) {
8922
- throw new Error(`model ${model} is reached by no tier`);
9230
+ var init_candidateText = __esm({
9231
+ "src/usage/candidateText.ts"() {
9232
+ "use strict";
8923
9233
  }
8924
- const firsts = reaches.filter((reach) => reach.standing === "first").map((reach) => reach.tier);
8925
- const fallbacks = reaches.filter((reach) => reach.standing === "fallback").map((reach) => reach.tier);
8926
- const serves = firsts.length === 0 ? [] : [`Serves the ${joined(firsts)} tier${firsts.length === 1 ? "" : "s"}`];
8927
- const falls = fallbacks.length === 0 ? [] : [`${serves.length === 0 ? "Fallback" : "fallback"} for ${joined(fallbacks)}`];
8928
- return { model, label: labelOf(model), description: describedAs(model, [...serves, ...falls].join("; ")), behavesAs: TIER_BEHAVES_AS[lead.tier] };
8929
- }
8930
- function rowsOfTable(table) {
8931
- const reachesByModel = /* @__PURE__ */ new Map();
8932
- for (const [tier, candidates] of table) {
8933
- candidates.forEach((model, index) => {
8934
- const reaches = reachesByModel.get(model) ?? [];
8935
- if (!reaches.some((reach) => reach.tier === tier)) {
8936
- reaches.push({ tier, standing: index === 0 ? "first" : "fallback" });
8937
- }
8938
- reachesByModel.set(model, reaches);
8939
- });
9234
+ });
9235
+
9236
+ // src/launcher/launchReport.ts
9237
+ function poolDetail(pool) {
9238
+ const [reason] = pool.reasons;
9239
+ if (pool.movedOff !== void 0) {
9240
+ return { detail: `moved off ${pool.movedOff.identity}: ${pool.movedOff.reason}`, ...reason === void 0 ? {} : { notes: [reason] } };
8940
9241
  }
8941
- return [...reachesByModel].map(([model, reaches]) => rowOf2(model, reaches));
8942
- }
8943
- function antigravityRows(provider) {
8944
- const config = resolveAntigravityConfig(provider.antigravity);
8945
- const tiers = rowsOfTable(CLAUDE_TIERS.map((tier) => [tier, config.models[tier]]));
8946
- const behavesAsOf = new Map(tiers.map((row) => [row.model, row.behavesAs]));
8947
- const aliases = [...config.aliases].flatMap(([alias, candidates]) => {
8948
- const [first] = candidates;
8949
- const behavesAs = first === void 0 ? void 0 : behavesAsOf.get(first);
8950
- const description = alias === AUTO_ALIAS ? `Routes each request to a backend model with quota left, best first (${String(candidates.length)} models)` : `Alias for ${candidates.join(", then ")}`;
8951
- return behavesAs === void 0 ? [] : [{ model: alias, label: labelOf(alias), description, behavesAs }];
8952
- });
8953
- return [...aliases.filter((row) => row.model === AUTO_ALIAS), ...tiers, ...aliases.filter((row) => row.model !== AUTO_ALIAS)];
9242
+ return reason === void 0 ? {} : { detail: reason };
8954
9243
  }
8955
- function codexRows(provider) {
8956
- const config = resolveCodexConfig(provider.codex);
8957
- return rowsOfTable(CLAUDE_TIERS.map((tier) => [tier, [config.models[tier]]]));
9244
+ function rankingNotes(ranking, picked) {
9245
+ return ranking.flatMap((candidate, index) => [
9246
+ `${String(index + 1)}. ${candidate.identity} ${candidateHeading(candidate)}${candidate.identity === picked ? " (picked)" : ""}`,
9247
+ ` ${candidate.reasons.join("; ")}`
9248
+ ]);
8958
9249
  }
8959
- function httpRows(provider) {
8960
- const env = provider.env ?? {};
8961
- const table = CLAUDE_TIERS.flatMap((tier) => {
8962
- const model = env[TIER_ENV_VARIABLES[tier]];
8963
- return model === void 0 || model === "" ? [] : [[tier, [model]]];
8964
- });
8965
- return rowsOfTable(table);
9250
+ function decisionRows(facts) {
9251
+ return [
9252
+ { label: "identity", value: facts.identity ?? "(none)", detail: facts.identitySource },
9253
+ ...facts.pool === void 0 ? [] : [
9254
+ {
9255
+ label: "pool",
9256
+ value: facts.pool.name,
9257
+ ...poolDetail(facts.pool),
9258
+ ...facts.ranking === void 0 ? {} : { notes: rankingNotes(facts.ranking, facts.identity) }
9259
+ }
9260
+ ],
9261
+ ...facts.profile === void 0 ? [] : [{ label: "profile", value: facts.profile.name, detail: facts.profile.source }],
9262
+ ...facts.provider === void 0 ? [] : [{ label: "provider", value: facts.provider.name, detail: `credential ${facts.provider.credential}` }],
9263
+ ...facts.identityCredential === void 0 ? [] : [{ label: "credential", value: facts.identityCredential, detail: "the identity's own" }]
9264
+ ];
8966
9265
  }
8967
- function declaredRow(entry) {
8968
- return {
8969
- model: entry.model,
8970
- label: entry.label ?? labelOf(entry.model),
8971
- description: entry.description ?? describedAs(entry.model, `Declared by the provider for the ${entry.tier} tier`),
8972
- behavesAs: TIER_BEHAVES_AS[entry.tier]
8973
- };
9266
+ function pinnedVersionRow(version, source) {
9267
+ return { label: "claude", value: version, detail: `pinned by ${source}` };
8974
9268
  }
8975
- function catalogueRows(provider, models) {
8976
- if (provider.kind !== void 0 && provider.kind !== "http" || provider.catalogue === void 0) {
9269
+ function routingRows(facts) {
9270
+ if (facts.frontDoor === void 0) {
8977
9271
  return [];
8978
9272
  }
8979
- const { tier } = provider.catalogue;
8980
- return filterCatalogue(models, provider.catalogue).map((model) => ({ model: model.id, label: labelOf(model.id), description: describedAs(model.id, model.name === void 0 ? "Listed by the provider" : `Listed by the provider as ${model.name}`), behavesAs: TIER_BEHAVES_AS[tier] })).sort((left, right) => left.model.localeCompare(right.model));
8981
- }
8982
- function providerModelRows(provider, catalogue = []) {
8983
- const derived = provider.kind === "codex" ? codexRows(provider) : provider.kind === "antigravity" ? antigravityRows(provider) : provider.kind === "router" ? [] : httpRows(provider);
8984
- const declared = provider.kind === "router" ? [] : (provider.pickerModels ?? []).map(declaredRow);
8985
- const declaredModels = new Set(declared.map((row) => row.model));
8986
- const named = [...derived.filter((row) => !declaredModels.has(row.model)), ...declared];
8987
- const taken = new Set(named.map((row) => labelOf(row.model)));
8988
- return [...named, ...catalogueRows(provider, catalogue).filter((row) => !taken.has(labelOf(row.model)))];
8989
- }
8990
- function routedModelRows(models, providers) {
8991
- const hidden = new Set(models.hide ?? []);
8992
- const shown = models.show === void 0 ? void 0 : new Set(models.show);
8993
- const visible = (model) => shown === void 0 ? !hidden.has(model) : shown.has(model);
8994
- const tierOf = (model) => {
8995
- for (const [, provider] of providers) {
8996
- if (provider.kind !== void 0 && provider.kind !== "http") {
8997
- continue;
8998
- }
8999
- const match = Object.entries(provider.env ?? {}).find(([key, value]) => value === model && key.startsWith("ANTHROPIC_DEFAULT_") && key.endsWith("_MODEL"));
9000
- if (match !== void 0) {
9001
- const tier = match[0].replace("ANTHROPIC_DEFAULT_", "").replace("_MODEL", "").toLowerCase();
9002
- return tier === "fable" || tier === "opus" || tier === "sonnet" || tier === "haiku" ? tier : void 0;
9003
- }
9004
- }
9005
- return void 0;
9006
- };
9007
- const virtual = Object.entries(models.virtual ?? {}).flatMap(([name, definition]) => {
9008
- if (!visible(name)) {
9009
- return [];
9010
- }
9011
- const first = definition.members.find((member) => member.includes("/"));
9012
- const tier = first === void 0 ? void 0 : tierOf(first.split("/").slice(1).join("/"));
9013
- const behavesAs = tier === void 0 ? void 0 : TIER_BEHAVES_AS[tier];
9014
- return behavesAs === void 0 ? [] : [{ model: name, label: name, description: `Virtual (${definition.mode})`, behavesAs }];
9015
- });
9016
- const concrete = providers.flatMap(([name, provider]) => providerModelRows(provider).map((row) => ({ ...row, model: `${name}/${row.model}`, label: `${name} / ${row.label}`, description: `${name}: ${row.description}` })));
9017
- return [...virtual, ...concrete.filter((row) => visible(row.model))];
9273
+ return [
9274
+ {
9275
+ label: "routing",
9276
+ value: `front door 127.0.0.1:${String(facts.frontDoor.port)}`,
9277
+ ...facts.provider ? {} : { detail: `OAuth via CONNECT 127.0.0.1:${String(facts.frontDoor.connectPort)}` }
9278
+ },
9279
+ ...facts.headroom === void 0 ? [] : [{ label: "headroom", value: "on", detail: `project ${facts.headroom.projectId}` }]
9280
+ ];
9018
9281
  }
9019
- function modelPickerSettings(provider, catalogue = []) {
9020
- return modelPickerSettingsFromRows(providerModelRows(provider, catalogue), true);
9282
+ function farmRow(links, builtDirectories, adopted) {
9283
+ const counted = (count, singular, plural) => `${String(count)} ${count === 1 ? singular : plural}`;
9284
+ const parts = [counted(links, "link", "links"), counted(builtDirectories, "built directory", "built directories"), ...adopted === 0 ? [] : [`${String(adopted)} adopted`]];
9285
+ return { label: "farm", value: "resynced", detail: parts.join(", ") };
9021
9286
  }
9022
- function modelPickerSettingsFromRows(options, replaceBuiltInOptions) {
9023
- return options.length === 0 ? void 0 : JSON.stringify({ modelPicker: { options, replaceBuiltInOptions } });
9287
+ function noteRow(text) {
9288
+ return { label: "note", value: text };
9024
9289
  }
9025
- var TIER_BEHAVES_AS, TIER_ENV_VARIABLES;
9026
- var init_modelPicker = __esm({
9027
- "src/launcher/modelPicker.ts"() {
9290
+ var init_launchReport = __esm({
9291
+ "src/launcher/launchReport.ts"() {
9028
9292
  "use strict";
9029
- init_translate();
9030
- init_translate2();
9031
- init_providerCatalogue();
9032
- init_schema();
9033
- init_identity2();
9034
- TIER_BEHAVES_AS = Object.freeze({
9035
- fable: "claude-fable-5-1",
9036
- opus: "claude-opus-5-5",
9037
- sonnet: "claude-sonnet-5-5",
9038
- haiku: "claude-haiku-5-5"
9039
- });
9040
- TIER_ENV_VARIABLES = Object.freeze({
9041
- fable: "ANTHROPIC_DEFAULT_FABLE_MODEL",
9042
- opus: "ANTHROPIC_DEFAULT_OPUS_MODEL",
9043
- sonnet: "ANTHROPIC_DEFAULT_SONNET_MODEL",
9044
- haiku: "ANTHROPIC_DEFAULT_HAIKU_MODEL"
9045
- });
9293
+ init_candidateText();
9046
9294
  }
9047
9295
  });
9048
9296
 
@@ -9436,10 +9684,12 @@ function decideLaunch(params, readOnly) {
9436
9684
  }
9437
9685
  const launchCascade = farmContext?.cascade ?? (params.farm === void 0 ? void 0 : params.farm.loadCascade(configProfileDecision.name, cliOverride));
9438
9686
  let cascadeLaunch;
9687
+ let cascadeModels;
9439
9688
  if (launchCascade !== void 0 && params.farm !== void 0) {
9440
9689
  const assembled = assembleCascade(launchCascade);
9441
9690
  const flattened = flattenLayers(assembled.layers, { home: params.farm.home });
9442
9691
  cascadeLaunch = flattened.launch;
9692
+ cascadeModels = flattened.models;
9443
9693
  if (readOnly || farmContext === void 0) {
9444
9694
  reportDiagnostics(log, [...assembled.diagnostics, ...flattened.diagnostics], { errorsAsWarnings: readOnly });
9445
9695
  }
@@ -9468,7 +9718,9 @@ function decideLaunch(params, readOnly) {
9468
9718
  const flags = loginlessProvider === void 0 ? requestedFlags : { ...requestedFlags, remoteControl: false };
9469
9719
  const catalogue = selectedProvider === void 0 ? void 0 : parseCatalogueCache(params.fs.readFileUtf8(catalogueCachePath(paths, selectedProvider.name)));
9470
9720
  const routesByName = flags.routeByName || selectedProvider !== void 0 && isRouterProvider(selectedProvider.definition);
9471
- const pickerSettings = routesByName ? modelPickerSettingsFromRows(routedModelRows(readModels(paths) ?? {}, listProviders(paths).map((entry) => [entry.name, entry.provider])), selectedProvider !== void 0) : selectedProvider === void 0 ? void 0 : modelPickerSettings(selectedProvider.definition, catalogue?.models);
9721
+ const globalModels = loadConfigFile(paths.globalConfigFile, GlobalConfigSchema, params.fs.readConfigFile)?.config.models;
9722
+ const models = launchCascade !== void 0 && params.farm !== void 0 ? cascadeModels : globalModels;
9723
+ const pickerSettings = routesByName ? modelPickerSettingsFromRows(routedModelRows(models ?? {}, listProviders(paths).map((entry) => [entry.name, entry.provider])), selectedProvider !== void 0) : selectedProvider === void 0 ? void 0 : modelPickerSettings(selectedProvider.definition, catalogue?.models);
9472
9724
  const callerSettings = hasSettingsArgument(parsedArgv.rest);
9473
9725
  if (pickerSettings !== void 0 && callerSettings) {
9474
9726
  notes.push("--settings was passed, so /model keeps Claude Code's own model names");
@@ -9506,6 +9758,8 @@ function decideLaunch(params, readOnly) {
9506
9758
  identityCredential,
9507
9759
  pinnedVersion,
9508
9760
  flags,
9761
+ models,
9762
+ globalModels,
9509
9763
  bin: discovered.path,
9510
9764
  args,
9511
9765
  decision
@@ -9572,7 +9826,7 @@ function prepareLaunch(params) {
9572
9826
  }
9573
9827
  const routesByName = resolvedFlags.routeByName || resolvedProvider !== void 0 && isRouterProvider(resolvedProvider.definition);
9574
9828
  if (routesByName) {
9575
- const check = resolveRoutedProviderCredentials({ paths, port: params.fs, env, ...params.credentials === void 0 ? {} : { credentials: params.credentials }, models: loadConfigFile(paths.globalConfigFile, GlobalConfigSchema, params.fs.readConfigFile)?.config.models });
9829
+ const check = resolveRoutedProviderCredentials({ paths, port: params.fs, env, ...params.credentials === void 0 ? {} : { credentials: params.credentials }, models: decided.models, targets: () => targetRefs(paths) });
9576
9830
  if (!check.ok) {
9577
9831
  log.error(check.message);
9578
9832
  proc.exit(check.status);
@@ -9584,7 +9838,10 @@ function prepareLaunch(params) {
9584
9838
  log.error("agent-shim: this launch routes through the front-door daemon, but this launcher has no front-door port wired; refusing to launch without it.");
9585
9839
  proc.exit(1);
9586
9840
  }
9587
- const frontDoor = frontDoorEngaged && frontDoorPort !== void 0 ? frontDoorPort.ensure(env.NODE_EXTRA_CA_CERTS) : void 0;
9841
+ const sessionId = params.supervised?.sessionId ?? (0, import_node_crypto11.randomUUID)();
9842
+ const resolvedModels = decided.models ?? (decided.globalModels === void 0 ? void 0 : {});
9843
+ const sessionModels = (0, import_node_util2.isDeepStrictEqual)(resolvedModels, decided.globalModels) ? void 0 : resolvedModels;
9844
+ const frontDoor = frontDoorEngaged && frontDoorPort !== void 0 ? frontDoorPort.ensure(env.NODE_EXTRA_CA_CERTS, { sessionId, ...sessionModels === void 0 ? {} : { models: sessionModels } }) : void 0;
9588
9845
  if (frontDoor?.trustWarning !== void 0) {
9589
9846
  log.warn(frontDoor.trustWarning);
9590
9847
  }
@@ -9598,7 +9855,6 @@ function prepareLaunch(params) {
9598
9855
  }
9599
9856
  rows.push(...routingRows({ frontDoor, headroom, provider: resolvedProvider !== void 0 }));
9600
9857
  const frontDoorRelease = frontDoor === void 0 ? void 0 : frontDoorPort?.release;
9601
- const sessionId = params.supervised?.sessionId ?? (0, import_node_crypto11.randomUUID)();
9602
9858
  const finalEnv = buildEnv({
9603
9859
  baseEnv: env,
9604
9860
  configDirEscapeHatch: configDirEscapeHatchApplies,
@@ -9610,7 +9866,8 @@ function prepareLaunch(params) {
9610
9866
  ...headroom === void 0 ? {} : { headroom },
9611
9867
  sessionId,
9612
9868
  remoteControl: resolvedFlags.remoteControl,
9613
- routeByName: routesByName
9869
+ routeByName: routesByName,
9870
+ ...decided.models?.tiers === void 0 ? {} : { tierModels: decided.models.tiers }
9614
9871
  });
9615
9872
  const releases = [...headroom === void 0 || headroomPort === void 0 ? [] : [headroomPort.release], ...frontDoorRelease === void 0 ? [] : [frontDoorRelease]];
9616
9873
  const release = () => {
@@ -9672,11 +9929,12 @@ function runLaunchPlan(plan, spawn3) {
9672
9929
  function runLauncher(params) {
9673
9930
  params.proc.exit(runLaunchPlan(prepareLaunch(params), params.spawn));
9674
9931
  }
9675
- var import_node_crypto11, import_node_path39;
9932
+ var import_node_crypto11, import_node_util2, import_node_path39;
9676
9933
  var init_launcher = __esm({
9677
9934
  "src/launcher.ts"() {
9678
9935
  "use strict";
9679
9936
  import_node_crypto11 = require("node:crypto");
9937
+ import_node_util2 = require("node:util");
9680
9938
  import_node_path39 = __toESM(require("node:path"), 1);
9681
9939
  init_package();
9682
9940
  init_envBool();
@@ -9693,7 +9951,6 @@ var init_launcher = __esm({
9693
9951
  init_launchReport();
9694
9952
  init_modelPicker();
9695
9953
  init_providerCatalogue();
9696
- init_modelsStore();
9697
9954
  init_providersStore();
9698
9955
  init_pool();
9699
9956
  init_resumeContext();
@@ -9711,6 +9968,7 @@ var init_launcher = __esm({
9711
9968
  init_read();
9712
9969
  init_claudeVersion();
9713
9970
  init_launchHook();
9971
+ init_targets();
9714
9972
  }
9715
9973
  });
9716
9974
 
@@ -9807,8 +10065,8 @@ function realEnsurePorts(paths, spawnDaemon) {
9807
10065
  }
9808
10066
  function realFrontDoorPort(paths, spawnDaemon) {
9809
10067
  return {
9810
- ensure: (inheritedExtraCaCerts) => {
9811
- const up = ensureFrontDoor({ paths, launcherPid: process.pid, ports: realEnsurePorts(paths, spawnDaemon) });
10068
+ ensure: (inheritedExtraCaCerts, session) => {
10069
+ const up = ensureFrontDoor({ paths, launcherPid: process.pid, ports: realEnsurePorts(paths, spawnDaemon), ...session === void 0 ? {} : { session } });
9812
10070
  const trust = resolveTrustBundle({ caCertFile: paths.frontdoorCaCertFile, bundlesDir: paths.frontdoorCaBundlesDir, variable: "NODE_EXTRA_CA_CERTS", inherited: inheritedExtraCaCerts, fs: realTrustBundleFs });
9813
10071
  return {
9814
10072
  port: up.port,
@@ -15188,8 +15446,8 @@ var ResetRowSchema = import_zod18.z.strictObject({
15188
15446
  var ResetScheduleSchema = import_zod18.z.strictObject({ resets: import_zod18.z.readonly(import_zod18.z.array(ResetRowSchema)) });
15189
15447
 
15190
15448
  // src/frontdoor/controlSchemas.ts
15191
- var import_node_path31 = __toESM(require("node:path"), 1);
15192
- var import_zod23 = require("zod");
15449
+ var import_node_path32 = __toESM(require("node:path"), 1);
15450
+ var import_zod25 = require("zod");
15193
15451
 
15194
15452
  // src/doctorReport.ts
15195
15453
  init_claudeShim();
@@ -15365,7 +15623,7 @@ function removeIdentity(paths, name) {
15365
15623
  // src/doctorReport.ts
15366
15624
  init_realPorts();
15367
15625
  var import_node_fs10 = __toESM(require("node:fs"), 1);
15368
- var import_node_path30 = __toESM(require("node:path"), 1);
15626
+ var import_node_path31 = __toESM(require("node:path"), 1);
15369
15627
  init_signIn();
15370
15628
 
15371
15629
  // src/codex/siwcStore.ts
@@ -15456,6 +15714,8 @@ init_source();
15456
15714
 
15457
15715
  // src/models/doctor.ts
15458
15716
  init_modelsStore();
15717
+ init_families();
15718
+ init_identity2();
15459
15719
  function modelsFindings(input) {
15460
15720
  const findings = [];
15461
15721
  const { models } = input;
@@ -15500,6 +15760,38 @@ function modelsFindings(input) {
15500
15760
  findings.push({ severity: "fail", message: `Tier ${tier} points at "${ref}", which names nothing defined.` });
15501
15761
  }
15502
15762
  }
15763
+ const modelOfRef = (ref) => ref.slice(ref.indexOf("/") + 1);
15764
+ for (const group of models.same ?? []) {
15765
+ for (let outer = 0; outer < group.length; outer += 1) {
15766
+ for (let inner = outer + 1; inner < group.length; inner += 1) {
15767
+ const left = group[outer] ?? "";
15768
+ const right = group[inner] ?? "";
15769
+ if (!left.startsWith("acct:") && !right.startsWith("acct:") && relateModels(modelOfRef(left), modelOfRef(right)) === "distinct") {
15770
+ findings.push({ severity: "warn", message: `"${left}" and "${right}" are asserted to be one model, but their names say they are different models; check the assertion is not a typo.` });
15771
+ }
15772
+ if ((models.distinct ?? []).some(([a, b]) => a === left && b === right || a === right && b === left)) {
15773
+ findings.push({ severity: "fail", message: `"${left}" and "${right}" are asserted to be both one model and two models.` });
15774
+ }
15775
+ }
15776
+ }
15777
+ }
15778
+ for (const [name, model] of Object.entries(models.virtual ?? {})) {
15779
+ const concrete = model.members.filter((member) => memberKindOf(member, models) === "provider" && member.includes("/"));
15780
+ const looksAlike = concrete.flatMap((left, index) => concrete.slice(index + 1).filter((right) => relateModels(modelOfRef(left), modelOfRef(right)) === "same").map((right) => [left, right]));
15781
+ for (const [left, right] of looksAlike) {
15782
+ findings.push({ severity: "warn", message: `Virtual model "${name}" lists "${left}" and "${right}", which look like one model; a member ${FAMILY_PREFIX}${familyKeyOf(modelOfRef(left))} names every target of it.` });
15783
+ }
15784
+ }
15785
+ if (input.targets !== void 0) {
15786
+ const families = buildFamilies(input.targets, models);
15787
+ for (const [name, model] of Object.entries(models.virtual ?? {})) {
15788
+ for (const member of model.members.filter((entry) => entry.startsWith(FAMILY_PREFIX))) {
15789
+ if (!families.some((family) => `${FAMILY_PREFIX}${family.key}` === member)) {
15790
+ findings.push({ severity: "warn", message: `Virtual model "${name}" names ${member}, but no target the providers offer belongs to that family.` });
15791
+ }
15792
+ }
15793
+ }
15794
+ }
15503
15795
  const hidden = new Set(models.hide ?? []);
15504
15796
  const shown = new Set(models.show ?? []);
15505
15797
  for (const ref of hidden) {
@@ -15511,6 +15803,7 @@ function modelsFindings(input) {
15511
15803
  }
15512
15804
 
15513
15805
  // src/doctorReport.ts
15806
+ init_targets();
15514
15807
  init_configProfilesStore();
15515
15808
 
15516
15809
  // src/headroom/allowlistDrift.ts
@@ -15735,7 +16028,7 @@ function tcpPortEraRecord(raw) {
15735
16028
  return (has("port") || has("lastPort")) && !has("socketPath");
15736
16029
  }
15737
16030
  function pushPathResolution(push, resolution) {
15738
- const ownDir = import_node_path30.default.dirname(resolution.ownExecutablePath);
16031
+ const ownDir = import_node_path31.default.dirname(resolution.ownExecutablePath);
15739
16032
  switch (resolution.agentShim.status) {
15740
16033
  case "ok":
15741
16034
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -15839,14 +16132,14 @@ function pushProvider(push, entry, cacheEnv, signIn) {
15839
16132
  }
15840
16133
  function pushLegacyName(push, params) {
15841
16134
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
15842
- if (legacyVariables.length === 0 && import_node_path30.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
16135
+ if (legacyVariables.length === 0 && import_node_path31.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
15843
16136
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
15844
16137
  return;
15845
16138
  }
15846
16139
  for (const name of legacyVariables) {
15847
16140
  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);
15848
16141
  }
15849
- if (import_node_path30.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
16142
+ if (import_node_path31.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
15850
16143
  push(
15851
16144
  "legacy-name",
15852
16145
  "warn",
@@ -16063,7 +16356,7 @@ function runDoctor(params) {
16063
16356
  if (models === void 0) {
16064
16357
  push("models", "pass", "No models block configured.");
16065
16358
  } else {
16066
- for (const finding of modelsFindings({ models, providers: params.providers.map((entry) => entry.name), identities: params.identities.map((entry) => entry.name) })) {
16359
+ for (const finding of modelsFindings({ models, providers: params.providers.map((entry) => entry.name), identities: params.identities.map((entry) => entry.name), ...params.modelTargets === void 0 ? {} : { targets: params.modelTargets } })) {
16067
16360
  push("models", finding.severity, finding.message);
16068
16361
  }
16069
16362
  push("models", "pass", "The models block is consistent.");
@@ -16245,18 +16538,18 @@ function collectDoctorReport(params) {
16245
16538
  const { paths } = params;
16246
16539
  const identityNames = import_node_fs10.default.existsSync(paths.identitiesDir) ? import_node_fs10.default.readdirSync(paths.identitiesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isIdentityDirectoryName(entry.name)).map((entry) => entry.name).sort() : [];
16247
16540
  const identities = identityNames.map((name) => {
16248
- const farmRoot = import_node_path30.default.join(paths.identitiesDir, name);
16249
- const identityPath = import_node_path30.default.join(farmRoot, "identity.json");
16541
+ const farmRoot = import_node_path31.default.join(paths.identitiesDir, name);
16542
+ const identityPath = import_node_path31.default.join(farmRoot, "identity.json");
16250
16543
  return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot, credentialsFilePresent: import_node_fs10.default.existsSync(credentialsFilePath(farmRoot)) };
16251
16544
  });
16252
16545
  const profileNames = import_node_fs10.default.existsSync(paths.configProfilesDir) ? import_node_fs10.default.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
16253
16546
  const configProfiles = profileNames.map((name) => {
16254
- const profilePath = import_node_path30.default.join(paths.configProfilesDir, `${name}.json`);
16547
+ const profilePath = import_node_path31.default.join(paths.configProfilesDir, `${name}.json`);
16255
16548
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
16256
16549
  });
16257
16550
  const providerNames = import_node_fs10.default.existsSync(paths.providersDir) ? import_node_fs10.default.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
16258
16551
  const providers = providerNames.map((name) => {
16259
- const providerPath = import_node_path30.default.join(paths.providersDir, `${name}.json`);
16552
+ const providerPath = import_node_path31.default.join(paths.providersDir, `${name}.json`);
16260
16553
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
16261
16554
  });
16262
16555
  const ownExecutablePath = realOwnExecutablePath();
@@ -16268,12 +16561,12 @@ function collectDoctorReport(params) {
16268
16561
  binaryDiscovery = { ok: false, message: error instanceof Error ? error.message : String(error) };
16269
16562
  }
16270
16563
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
16271
- const pathDirs = (params.env.PATH ?? "").split(import_node_path30.default.delimiter).filter((dir) => dir !== "");
16564
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path31.default.delimiter).filter((dir) => dir !== "");
16272
16565
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
16273
16566
  findPathShadow({
16274
16567
  pathDirs,
16275
- targetDir: import_node_path30.default.dirname(shimState.targetPath),
16276
- targetFilename: import_node_path30.default.basename(shimState.targetPath),
16568
+ targetDir: import_node_path31.default.dirname(shimState.targetPath),
16569
+ targetFilename: import_node_path31.default.basename(shimState.targetPath),
16277
16570
  findExecutableInDir
16278
16571
  }),
16279
16572
  shimState.targetPath,
@@ -16297,6 +16590,7 @@ function collectDoctorReport(params) {
16297
16590
  directoryRules: { path: paths.directoryRulesFile, raw: realFsPort.readFileUtf8(paths.directoryRulesFile) },
16298
16591
  globalConfig: { path: paths.globalConfigFile, raw: realFsPort.readFileUtf8(paths.globalConfigFile) },
16299
16592
  models: parsedModelsOf(paths),
16593
+ modelTargets: targetRefs(paths),
16300
16594
  categoriesLocal: { path: paths.categoriesLocalFile, raw: realFsPort.readFileUtf8(paths.categoriesLocalFile) },
16301
16595
  activeIdentity: { path: paths.activeIdentityFile, raw: realFsPort.readFileUtf8(paths.activeIdentityFile) },
16302
16596
  binaryDiscovery,
@@ -16307,7 +16601,7 @@ function collectDoctorReport(params) {
16307
16601
  agentShim: refinePathShadow(
16308
16602
  findPathShadow({
16309
16603
  pathDirs,
16310
- targetDir: import_node_path30.default.dirname(ownExecutablePath),
16604
+ targetDir: import_node_path31.default.dirname(ownExecutablePath),
16311
16605
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
16312
16606
  findExecutableInDir
16313
16607
  }),
@@ -16348,90 +16642,90 @@ function collectDoctorReport(params) {
16348
16642
  // src/frontdoor/controlSchemas.ts
16349
16643
  init_schema2();
16350
16644
  init_state();
16351
- var UsageListOutputSchema = import_zod23.z.strictObject({ snapshots: import_zod23.z.readonly(import_zod23.z.array(UsageSnapshotSchema)) });
16352
- var UsageWindowsInputSchema = import_zod23.z.strictObject({
16353
- identity: import_zod23.z.string().min(1),
16354
- provider: import_zod23.z.string().min(1).optional()
16645
+ var UsageListOutputSchema = import_zod25.z.strictObject({ snapshots: import_zod25.z.readonly(import_zod25.z.array(UsageSnapshotSchema)) });
16646
+ var UsageWindowsInputSchema = import_zod25.z.strictObject({
16647
+ identity: import_zod25.z.string().min(1),
16648
+ provider: import_zod25.z.string().min(1).optional()
16355
16649
  });
16356
- var EffectiveWindowSchema = import_zod23.z.strictObject({
16650
+ var EffectiveWindowSchema = import_zod25.z.strictObject({
16357
16651
  /** True when the window's reset time has passed, so the recorded observation describes a window that no longer exists. */
16358
- reset: import_zod23.z.boolean(),
16652
+ reset: import_zod25.z.boolean(),
16359
16653
  /** The fraction used: 0 for a reset window, otherwise what was last observed, absent when none was reported. */
16360
- utilization: import_zod23.z.number().optional(),
16654
+ utilization: import_zod25.z.number().optional(),
16361
16655
  /** The reset instant, for a window that has not reset yet and reported one. */
16362
- resetsAtMs: import_zod23.z.number().optional(),
16656
+ resetsAtMs: import_zod25.z.number().optional(),
16363
16657
  /** The window's own status, for a window that has not reset yet. */
16364
- status: import_zod23.z.string().optional()
16658
+ status: import_zod25.z.string().optional()
16365
16659
  });
16366
- var UsageWindowsOutputSchema = import_zod23.z.strictObject({
16367
- identity: import_zod23.z.string(),
16368
- provider: import_zod23.z.string(),
16660
+ var UsageWindowsOutputSchema = import_zod25.z.strictObject({
16661
+ identity: import_zod25.z.string(),
16662
+ provider: import_zod25.z.string(),
16369
16663
  /** When the rate-limit state the windows come from was observed. */
16370
- observedAt: import_zod23.z.iso.datetime().optional(),
16664
+ observedAt: import_zod25.z.iso.datetime().optional(),
16371
16665
  fiveHour: EffectiveWindowSchema.optional(),
16372
16666
  sevenDay: EffectiveWindowSchema.optional()
16373
16667
  });
16374
- var UsageLiveOutputSchema = import_zod23.z.strictObject({
16668
+ var UsageLiveOutputSchema = import_zod25.z.strictObject({
16375
16669
  /** 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. */
16376
16670
  latest: RcLiveRateLimitSchema.optional(),
16377
16671
  /** One observation per session whose stream has filed a rate_limit_event this door generation. */
16378
- sessions: import_zod23.z.readonly(import_zod23.z.array(RcLiveRateLimitSchema))
16672
+ sessions: import_zod25.z.readonly(import_zod25.z.array(RcLiveRateLimitSchema))
16379
16673
  });
16380
- var FrontDoorSessionStatusSchema = import_zod23.z.strictObject({
16381
- pid: import_zod23.z.int().positive(),
16382
- startedAt: import_zod23.z.number(),
16383
- alive: import_zod23.z.boolean()
16674
+ var FrontDoorSessionStatusSchema = import_zod25.z.strictObject({
16675
+ pid: import_zod25.z.int().positive(),
16676
+ startedAt: import_zod25.z.number(),
16677
+ alive: import_zod25.z.boolean()
16384
16678
  });
16385
- var HeadroomSocketTargetSchema = import_zod23.z.union([import_zod23.z.strictObject({ socketPath: import_zod23.z.string() }), import_zod23.z.strictObject({ refused: import_zod23.z.string() })]);
16386
- var FrontDoorStatusOutputSchema = import_zod23.z.strictObject({
16679
+ var HeadroomSocketTargetSchema = import_zod25.z.union([import_zod25.z.strictObject({ socketPath: import_zod25.z.string() }), import_zod25.z.strictObject({ refused: import_zod25.z.string() })]);
16680
+ var FrontDoorStatusOutputSchema = import_zod25.z.strictObject({
16387
16681
  state: FrontDoorStateSchema,
16388
- supervisorAlive: import_zod23.z.boolean(),
16389
- sessions: import_zod23.z.readonly(import_zod23.z.array(FrontDoorSessionStatusSchema)),
16682
+ supervisorAlive: import_zod25.z.boolean(),
16683
+ sessions: import_zod25.z.readonly(import_zod25.z.array(FrontDoorSessionStatusSchema)),
16390
16684
  headroomSocket: HeadroomSocketTargetSchema.optional(),
16391
- logPath: import_zod23.z.string(),
16392
- logExists: import_zod23.z.boolean()
16685
+ logPath: import_zod25.z.string(),
16686
+ logExists: import_zod25.z.boolean()
16393
16687
  });
16394
- var FrontDoorSessionsOutputSchema = import_zod23.z.strictObject({ sessions: import_zod23.z.readonly(import_zod23.z.array(FrontDoorSessionStatusSchema)) });
16395
- var CheckRunInputSchema = import_zod23.z.strictObject({
16396
- path: import_zod23.z.string().min(1),
16397
- identity: import_zod23.z.string().min(1).optional()
16398
- }).refine((input) => import_node_path31.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
16399
- var PoolPickInputSchema = import_zod23.z.strictObject({
16400
- pool: import_zod23.z.string().min(1),
16401
- path: import_zod23.z.string().min(1)
16402
- }).refine((input) => import_node_path31.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
16403
- var DoctorFindingSchema = import_zod23.z.strictObject({
16404
- section: import_zod23.z.enum(DOCTOR_SECTIONS),
16405
- subject: import_zod23.z.string().optional(),
16406
- severity: import_zod23.z.enum(DOCTOR_SEVERITIES),
16407
- message: import_zod23.z.string()
16688
+ var FrontDoorSessionsOutputSchema = import_zod25.z.strictObject({ sessions: import_zod25.z.readonly(import_zod25.z.array(FrontDoorSessionStatusSchema)) });
16689
+ var CheckRunInputSchema = import_zod25.z.strictObject({
16690
+ path: import_zod25.z.string().min(1),
16691
+ identity: import_zod25.z.string().min(1).optional()
16692
+ }).refine((input) => import_node_path32.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
16693
+ var PoolPickInputSchema = import_zod25.z.strictObject({
16694
+ pool: import_zod25.z.string().min(1),
16695
+ path: import_zod25.z.string().min(1)
16696
+ }).refine((input) => import_node_path32.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
16697
+ var DoctorFindingSchema = import_zod25.z.strictObject({
16698
+ section: import_zod25.z.enum(DOCTOR_SECTIONS),
16699
+ subject: import_zod25.z.string().optional(),
16700
+ severity: import_zod25.z.enum(DOCTOR_SEVERITIES),
16701
+ message: import_zod25.z.string()
16408
16702
  });
16409
- var DoctorRunOutputSchema = import_zod23.z.strictObject({
16703
+ var DoctorRunOutputSchema = import_zod25.z.strictObject({
16410
16704
  /** False exactly when any finding is a `fail`; a `warn` never fails the report on its own. */
16411
- ok: import_zod23.z.boolean(),
16412
- findings: import_zod23.z.readonly(import_zod23.z.array(DoctorFindingSchema))
16705
+ ok: import_zod25.z.boolean(),
16706
+ findings: import_zod25.z.readonly(import_zod25.z.array(DoctorFindingSchema))
16413
16707
  });
16414
- var FrontDoorRestartOutputSchema = import_zod23.z.strictObject({
16415
- action: import_zod23.z.literal("restarting"),
16416
- previousPid: import_zod23.z.int().positive()
16708
+ var FrontDoorRestartOutputSchema = import_zod25.z.strictObject({
16709
+ action: import_zod25.z.literal("restarting"),
16710
+ previousPid: import_zod25.z.int().positive()
16417
16711
  });
16418
- var UpdateCheckOutputSchema = import_zod23.z.strictObject({
16419
- current: import_zod23.z.string(),
16420
- latest: import_zod23.z.string(),
16421
- action: import_zod23.z.enum(["current", "available", "updated"])
16712
+ var UpdateCheckOutputSchema = import_zod25.z.strictObject({
16713
+ current: import_zod25.z.string(),
16714
+ latest: import_zod25.z.string(),
16715
+ action: import_zod25.z.enum(["current", "available", "updated"])
16422
16716
  });
16423
- var CodexSignInSchema = import_zod23.z.discriminatedUnion("state", [
16424
- import_zod23.z.strictObject({ state: import_zod23.z.literal("none") }),
16425
- import_zod23.z.strictObject({ state: import_zod23.z.literal("signed-in"), email: import_zod23.z.string().optional(), planScope: import_zod23.z.boolean(), accessTokenExpiresAt: import_zod23.z.number() }),
16426
- import_zod23.z.strictObject({ state: import_zod23.z.literal("unreadable"), message: import_zod23.z.string() })
16717
+ var CodexSignInSchema = import_zod25.z.discriminatedUnion("state", [
16718
+ import_zod25.z.strictObject({ state: import_zod25.z.literal("none") }),
16719
+ import_zod25.z.strictObject({ state: import_zod25.z.literal("signed-in"), email: import_zod25.z.string().optional(), planScope: import_zod25.z.boolean(), accessTokenExpiresAt: import_zod25.z.number() }),
16720
+ import_zod25.z.strictObject({ state: import_zod25.z.literal("unreadable"), message: import_zod25.z.string() })
16427
16721
  ]);
16428
- var CodexStatusOutputSchema = import_zod23.z.strictObject({
16722
+ var CodexStatusOutputSchema = import_zod25.z.strictObject({
16429
16723
  signIn: CodexSignInSchema,
16430
- codexProviders: import_zod23.z.readonly(import_zod23.z.array(import_zod23.z.string()))
16724
+ codexProviders: import_zod25.z.readonly(import_zod25.z.array(import_zod25.z.string()))
16431
16725
  });
16432
- var CodexLogoutOutputSchema = import_zod23.z.strictObject({
16433
- hadGrant: import_zod23.z.boolean(),
16434
- revoked: import_zod23.z.boolean()
16726
+ var CodexLogoutOutputSchema = import_zod25.z.strictObject({
16727
+ hadGrant: import_zod25.z.boolean(),
16728
+ revoked: import_zod25.z.boolean()
16435
16729
  });
16436
16730
 
16437
16731
  // src/frontdoor/codexApi.ts
@@ -16588,144 +16882,144 @@ init_identity();
16588
16882
  init_providersStore();
16589
16883
 
16590
16884
  // src/frontdoor/configSchemas.ts
16591
- var import_zod24 = require("zod");
16885
+ var import_zod26 = require("zod");
16592
16886
  init_schema();
16593
- var RemovalConfirmationSchema = import_zod24.z.boolean();
16594
- var CredentialWriteSchema = (targets) => import_zod24.z.strictObject({
16595
- sources: import_zod24.z.array(RemoteCredentialSourceSchema).min(1).optional(),
16596
- target: import_zod24.z.enum(targets).optional(),
16597
- cache: import_zod24.z.union([import_zod24.z.literal(false), CredentialCacheSchema]).optional()
16887
+ var RemovalConfirmationSchema = import_zod26.z.boolean();
16888
+ var CredentialWriteSchema = (targets) => import_zod26.z.strictObject({
16889
+ sources: import_zod26.z.array(RemoteCredentialSourceSchema).min(1).optional(),
16890
+ target: import_zod26.z.enum(targets).optional(),
16891
+ cache: import_zod26.z.union([import_zod26.z.literal(false), CredentialCacheSchema]).optional()
16598
16892
  });
16599
- var CredentialSummarySchema2 = import_zod24.z.strictObject({
16600
- target: import_zod24.z.enum(CREDENTIAL_TARGETS),
16601
- sources: import_zod24.z.readonly(import_zod24.z.array(
16602
- import_zod24.z.discriminatedUnion("kind", [
16603
- import_zod24.z.strictObject({ kind: import_zod24.z.literal("env"), variable: import_zod24.z.string() }),
16604
- import_zod24.z.strictObject({ kind: import_zod24.z.literal("file"), path: import_zod24.z.string() }),
16605
- import_zod24.z.strictObject({ kind: import_zod24.z.literal("command"), program: import_zod24.z.string() }),
16606
- import_zod24.z.strictObject({ kind: import_zod24.z.literal("op"), reference: import_zod24.z.string() }),
16607
- import_zod24.z.strictObject({ kind: import_zod24.z.literal("keychain"), service: import_zod24.z.string(), account: import_zod24.z.string().optional() }),
16608
- import_zod24.z.strictObject({ kind: import_zod24.z.literal("literal") })
16893
+ var CredentialSummarySchema2 = import_zod26.z.strictObject({
16894
+ target: import_zod26.z.enum(CREDENTIAL_TARGETS),
16895
+ sources: import_zod26.z.readonly(import_zod26.z.array(
16896
+ import_zod26.z.discriminatedUnion("kind", [
16897
+ import_zod26.z.strictObject({ kind: import_zod26.z.literal("env"), variable: import_zod26.z.string() }),
16898
+ import_zod26.z.strictObject({ kind: import_zod26.z.literal("file"), path: import_zod26.z.string() }),
16899
+ import_zod26.z.strictObject({ kind: import_zod26.z.literal("command"), program: import_zod26.z.string() }),
16900
+ import_zod26.z.strictObject({ kind: import_zod26.z.literal("op"), reference: import_zod26.z.string() }),
16901
+ import_zod26.z.strictObject({ kind: import_zod26.z.literal("keychain"), service: import_zod26.z.string(), account: import_zod26.z.string().optional() }),
16902
+ import_zod26.z.strictObject({ kind: import_zod26.z.literal("literal") })
16609
16903
  ])
16610
16904
  )),
16611
16905
  cache: CredentialCacheSchema.optional()
16612
16906
  });
16613
- var mutationOutput = (kind, action) => import_zod24.z.strictObject({ action: import_zod24.z.literal(action), kind: import_zod24.z.literal(kind), name: import_zod24.z.string() });
16614
- var storedMutationOutput = (kind, action, value) => import_zod24.z.strictObject({ action: import_zod24.z.literal(action), kind: import_zod24.z.literal(kind), name: import_zod24.z.string(), value });
16615
- var IdentityValueSchema = import_zod24.z.strictObject({
16616
- name: import_zod24.z.string(),
16617
- defaultConfigProfile: import_zod24.z.string().optional(),
16618
- allowAmbientCredential: import_zod24.z.boolean(),
16907
+ var mutationOutput = (kind, action) => import_zod26.z.strictObject({ action: import_zod26.z.literal(action), kind: import_zod26.z.literal(kind), name: import_zod26.z.string() });
16908
+ var storedMutationOutput = (kind, action, value) => import_zod26.z.strictObject({ action: import_zod26.z.literal(action), kind: import_zod26.z.literal(kind), name: import_zod26.z.string(), value });
16909
+ var IdentityValueSchema = import_zod26.z.strictObject({
16910
+ name: import_zod26.z.string(),
16911
+ defaultConfigProfile: import_zod26.z.string().optional(),
16912
+ allowAmbientCredential: import_zod26.z.boolean(),
16619
16913
  credential: CredentialSummarySchema2.optional(),
16620
- anchors: import_zod24.z.array(AnchorSchema).optional()
16914
+ anchors: import_zod26.z.array(AnchorSchema).optional()
16621
16915
  });
16622
16916
  var ProfileValueSchema = ConfigProfileSchema.omit({ $schema: true });
16623
- var ProviderValueSchema = import_zod24.z.strictObject({
16624
- name: import_zod24.z.string(),
16625
- kind: import_zod24.z.enum(PROVIDER_KINDS),
16626
- displayName: import_zod24.z.string(),
16627
- baseUrl: import_zod24.z.string().optional(),
16917
+ var ProviderValueSchema = import_zod26.z.strictObject({
16918
+ name: import_zod26.z.string(),
16919
+ kind: import_zod26.z.enum(PROVIDER_KINDS),
16920
+ displayName: import_zod26.z.string(),
16921
+ baseUrl: import_zod26.z.string().optional(),
16628
16922
  codex: CodexProviderConfigSchema.optional(),
16629
16923
  credential: CredentialSummarySchema2.optional(),
16630
- env: import_zod24.z.record(import_zod24.z.string(), import_zod24.z.string()).optional()
16924
+ env: import_zod26.z.record(import_zod26.z.string(), import_zod26.z.string()).optional()
16631
16925
  });
16632
- var ConfigNameInputSchema = import_zod24.z.strictObject({ name: import_zod24.z.string().min(1) });
16926
+ var ConfigNameInputSchema = import_zod26.z.strictObject({ name: import_zod26.z.string().min(1) });
16633
16927
  var ConfigIdentityAddOutputSchema = storedMutationOutput("identity", "created", IdentityValueSchema);
16634
- var ConfigIdentitySetInputSchema = import_zod24.z.strictObject({
16635
- name: import_zod24.z.string().min(1),
16636
- defaultConfigProfile: import_zod24.z.union([import_zod24.z.string().min(1), import_zod24.z.literal(false)]).optional(),
16637
- allowAmbientCredential: import_zod24.z.boolean().optional(),
16638
- credential: import_zod24.z.union([import_zod24.z.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
16928
+ var ConfigIdentitySetInputSchema = import_zod26.z.strictObject({
16929
+ name: import_zod26.z.string().min(1),
16930
+ defaultConfigProfile: import_zod26.z.union([import_zod26.z.string().min(1), import_zod26.z.literal(false)]).optional(),
16931
+ allowAmbientCredential: import_zod26.z.boolean().optional(),
16932
+ credential: import_zod26.z.union([import_zod26.z.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
16639
16933
  /** `false` removes the anchors; a list replaces them. */
16640
- anchors: import_zod24.z.union([import_zod24.z.literal(false), import_zod24.z.array(AnchorSchema).min(1)]).optional()
16934
+ anchors: import_zod26.z.union([import_zod26.z.literal(false), import_zod26.z.array(AnchorSchema).min(1)]).optional()
16641
16935
  });
16642
16936
  var ConfigIdentitySetOutputSchema = storedMutationOutput("identity", "updated", IdentityValueSchema);
16643
- var ConfigIdentityRemoveInputSchema = import_zod24.z.strictObject({ name: import_zod24.z.string().min(1), confirm: RemovalConfirmationSchema });
16937
+ var ConfigIdentityRemoveInputSchema = import_zod26.z.strictObject({ name: import_zod26.z.string().min(1), confirm: RemovalConfirmationSchema });
16644
16938
  var ConfigIdentityRemoveOutputSchema = mutationOutput("identity", "removed");
16645
16939
  var ConfigIdentityUseOutputSchema = mutationOutput("identity", "selected");
16646
- var ConfigProfileAddInputSchema = import_zod24.z.strictObject({
16647
- name: import_zod24.z.string().min(1),
16648
- extends: import_zod24.z.array(import_zod24.z.string().min(1)).optional(),
16649
- description: import_zod24.z.string().optional()
16940
+ var ConfigProfileAddInputSchema = import_zod26.z.strictObject({
16941
+ name: import_zod26.z.string().min(1),
16942
+ extends: import_zod26.z.array(import_zod26.z.string().min(1)).optional(),
16943
+ description: import_zod26.z.string().optional()
16650
16944
  });
16651
16945
  var ConfigProfileAddOutputSchema = storedMutationOutput("profile", "created", ProfileValueSchema);
16652
- var ConfigProfileSetInputSchema = import_zod24.z.strictObject({
16653
- name: import_zod24.z.string().min(1),
16654
- category: import_zod24.z.record(import_zod24.z.string(), import_zod24.z.boolean()).optional(),
16655
- entry: import_zod24.z.record(import_zod24.z.string(), import_zod24.z.boolean()).optional(),
16656
- extends: import_zod24.z.union([import_zod24.z.array(import_zod24.z.string().min(1)), import_zod24.z.literal(false)]).optional(),
16657
- description: import_zod24.z.union([import_zod24.z.string(), import_zod24.z.literal(false)]).optional(),
16658
- launch: import_zod24.z.strictObject({
16659
- skipPermissions: import_zod24.z.boolean().optional(),
16660
- remoteControl: import_zod24.z.boolean().optional(),
16661
- headroom: import_zod24.z.boolean().optional(),
16662
- trackUsage: import_zod24.z.boolean().optional(),
16663
- provider: import_zod24.z.union([import_zod24.z.string().min(1), import_zod24.z.literal(false)]).optional(),
16664
- claudeVersion: import_zod24.z.union([import_zod24.z.string().min(1), import_zod24.z.literal(false)]).optional(),
16665
- delay: import_zod24.z.union([import_zod24.z.string().regex(DURATION_RE), import_zod24.z.literal(false)]).optional(),
16666
- pause: import_zod24.z.boolean().optional(),
16667
- explain: import_zod24.z.boolean().optional(),
16668
- routeByName: import_zod24.z.boolean().optional()
16946
+ var ConfigProfileSetInputSchema = import_zod26.z.strictObject({
16947
+ name: import_zod26.z.string().min(1),
16948
+ category: import_zod26.z.record(import_zod26.z.string(), import_zod26.z.boolean()).optional(),
16949
+ entry: import_zod26.z.record(import_zod26.z.string(), import_zod26.z.boolean()).optional(),
16950
+ extends: import_zod26.z.union([import_zod26.z.array(import_zod26.z.string().min(1)), import_zod26.z.literal(false)]).optional(),
16951
+ description: import_zod26.z.union([import_zod26.z.string(), import_zod26.z.literal(false)]).optional(),
16952
+ launch: import_zod26.z.strictObject({
16953
+ skipPermissions: import_zod26.z.boolean().optional(),
16954
+ remoteControl: import_zod26.z.boolean().optional(),
16955
+ headroom: import_zod26.z.boolean().optional(),
16956
+ trackUsage: import_zod26.z.boolean().optional(),
16957
+ provider: import_zod26.z.union([import_zod26.z.string().min(1), import_zod26.z.literal(false)]).optional(),
16958
+ claudeVersion: import_zod26.z.union([import_zod26.z.string().min(1), import_zod26.z.literal(false)]).optional(),
16959
+ delay: import_zod26.z.union([import_zod26.z.string().regex(DURATION_RE), import_zod26.z.literal(false)]).optional(),
16960
+ pause: import_zod26.z.boolean().optional(),
16961
+ explain: import_zod26.z.boolean().optional(),
16962
+ routeByName: import_zod26.z.boolean().optional()
16669
16963
  }).optional()
16670
16964
  });
16671
16965
  var ConfigProfileSetOutputSchema = storedMutationOutput("profile", "updated", ProfileValueSchema);
16672
- var ConfigProfileRemoveInputSchema = import_zod24.z.strictObject({ name: import_zod24.z.string().min(1), confirm: RemovalConfirmationSchema });
16966
+ var ConfigProfileRemoveInputSchema = import_zod26.z.strictObject({ name: import_zod26.z.string().min(1), confirm: RemovalConfirmationSchema });
16673
16967
  var ConfigProfileRemoveOutputSchema = mutationOutput("profile", "removed");
16674
16968
  var ConfigProfileUseOutputSchema = mutationOutput("profile", "selected");
16675
- var PoolMembersInputSchema = import_zod24.z.array(import_zod24.z.string().min(1)).min(1);
16676
- var ConfigPoolAddInputSchema = import_zod24.z.strictObject({
16677
- name: import_zod24.z.string().min(1),
16969
+ var PoolMembersInputSchema = import_zod26.z.array(import_zod26.z.string().min(1)).min(1);
16970
+ var ConfigPoolAddInputSchema = import_zod26.z.strictObject({
16971
+ name: import_zod26.z.string().min(1),
16678
16972
  identities: PoolMembersInputSchema,
16679
- preference: import_zod24.z.enum(POOL_PREFERENCES).optional(),
16680
- resumeOnLimit: import_zod24.z.boolean().optional(),
16681
- compactBeforeLimit: import_zod24.z.boolean().optional(),
16973
+ preference: import_zod26.z.enum(POOL_PREFERENCES).optional(),
16974
+ resumeOnLimit: import_zod26.z.boolean().optional(),
16975
+ compactBeforeLimit: import_zod26.z.boolean().optional(),
16682
16976
  compactAtUtilisation: CompactAtUtilisationSchema.optional()
16683
16977
  });
16684
16978
  var ConfigPoolAddOutputSchema = storedMutationOutput("pool", "created", PoolSchema);
16685
- var ConfigPoolSetInputSchema = import_zod24.z.strictObject({
16686
- name: import_zod24.z.string().min(1),
16979
+ var ConfigPoolSetInputSchema = import_zod26.z.strictObject({
16980
+ name: import_zod26.z.string().min(1),
16687
16981
  identities: PoolMembersInputSchema.optional(),
16688
- preference: import_zod24.z.union([import_zod24.z.enum(POOL_PREFERENCES), import_zod24.z.literal(false)]).optional(),
16689
- resumeOnLimit: import_zod24.z.boolean().optional(),
16690
- compactBeforeLimit: import_zod24.z.boolean().optional(),
16691
- compactAtUtilisation: import_zod24.z.union([CompactAtUtilisationSchema, import_zod24.z.literal(false)]).optional()
16982
+ preference: import_zod26.z.union([import_zod26.z.enum(POOL_PREFERENCES), import_zod26.z.literal(false)]).optional(),
16983
+ resumeOnLimit: import_zod26.z.boolean().optional(),
16984
+ compactBeforeLimit: import_zod26.z.boolean().optional(),
16985
+ compactAtUtilisation: import_zod26.z.union([CompactAtUtilisationSchema, import_zod26.z.literal(false)]).optional()
16692
16986
  });
16693
16987
  var ConfigPoolSetOutputSchema = storedMutationOutput("pool", "updated", PoolSchema);
16694
- var ConfigPoolRemoveInputSchema = import_zod24.z.strictObject({ name: import_zod24.z.string().min(1), confirm: RemovalConfirmationSchema });
16988
+ var ConfigPoolRemoveInputSchema = import_zod26.z.strictObject({ name: import_zod26.z.string().min(1), confirm: RemovalConfirmationSchema });
16695
16989
  var ConfigPoolRemoveOutputSchema = mutationOutput("pool", "removed");
16696
16990
  var ConfigPoolUseOutputSchema = mutationOutput("pool", "selected");
16697
- var ConfigProviderAddInputSchema = import_zod24.z.strictObject({
16698
- name: import_zod24.z.string().min(1),
16699
- kind: import_zod24.z.enum(PROVIDER_KINDS).optional(),
16700
- displayName: import_zod24.z.string().min(1),
16701
- baseUrl: import_zod24.z.string().min(1).optional(),
16991
+ var ConfigProviderAddInputSchema = import_zod26.z.strictObject({
16992
+ name: import_zod26.z.string().min(1),
16993
+ kind: import_zod26.z.enum(PROVIDER_KINDS).optional(),
16994
+ displayName: import_zod26.z.string().min(1),
16995
+ baseUrl: import_zod26.z.string().min(1).optional(),
16702
16996
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).required({ sources: true }),
16703
16997
  codex: CodexProviderConfigSchema.optional()
16704
16998
  });
16705
16999
  var ConfigProviderAddOutputSchema = storedMutationOutput("provider", "created", ProviderValueSchema);
16706
- var ConfigProviderSetInputSchema = import_zod24.z.strictObject({
16707
- name: import_zod24.z.string().min(1),
16708
- displayName: import_zod24.z.string().min(1).optional(),
16709
- baseUrl: import_zod24.z.string().min(1).optional(),
17000
+ var ConfigProviderSetInputSchema = import_zod26.z.strictObject({
17001
+ name: import_zod26.z.string().min(1),
17002
+ displayName: import_zod26.z.string().min(1).optional(),
17003
+ baseUrl: import_zod26.z.string().min(1).optional(),
16710
17004
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).optional(),
16711
17005
  codex: CodexProviderConfigSchema.optional()
16712
17006
  });
16713
17007
  var ConfigProviderSetOutputSchema = storedMutationOutput("provider", "updated", ProviderValueSchema);
16714
- var ConfigProviderRemoveInputSchema = import_zod24.z.strictObject({ name: import_zod24.z.string().min(1), confirm: RemovalConfirmationSchema });
17008
+ var ConfigProviderRemoveInputSchema = import_zod26.z.strictObject({ name: import_zod26.z.string().min(1), confirm: RemovalConfirmationSchema });
16715
17009
  var ConfigProviderRemoveOutputSchema = mutationOutput("provider", "removed");
16716
- var ConfigRuleAddInputSchema = import_zod24.z.strictObject({
16717
- path: import_zod24.z.string().min(1),
16718
- configProfile: import_zod24.z.string().min(1).optional(),
16719
- identity: import_zod24.z.string().min(1).optional()
17010
+ var ConfigRuleAddInputSchema = import_zod26.z.strictObject({
17011
+ path: import_zod26.z.string().min(1),
17012
+ configProfile: import_zod26.z.string().min(1).optional(),
17013
+ identity: import_zod26.z.string().min(1).optional()
16720
17014
  });
16721
17015
  var ConfigRuleAddOutputSchema = storedMutationOutput("rule", "created", DirectoryRuleSchema);
16722
- var ConfigRuleSetInputSchema = import_zod24.z.strictObject({
16723
- path: import_zod24.z.string().min(1),
16724
- configProfile: import_zod24.z.union([import_zod24.z.string().min(1), import_zod24.z.literal(false)]).optional(),
16725
- identity: import_zod24.z.union([import_zod24.z.string().min(1), import_zod24.z.literal(false)]).optional()
17016
+ var ConfigRuleSetInputSchema = import_zod26.z.strictObject({
17017
+ path: import_zod26.z.string().min(1),
17018
+ configProfile: import_zod26.z.union([import_zod26.z.string().min(1), import_zod26.z.literal(false)]).optional(),
17019
+ identity: import_zod26.z.union([import_zod26.z.string().min(1), import_zod26.z.literal(false)]).optional()
16726
17020
  });
16727
17021
  var ConfigRuleSetOutputSchema = storedMutationOutput("rule", "updated", DirectoryRuleSchema);
16728
- var ConfigRuleRemoveInputSchema = import_zod24.z.strictObject({ path: import_zod24.z.string().min(1), confirm: RemovalConfirmationSchema });
17022
+ var ConfigRuleRemoveInputSchema = import_zod26.z.strictObject({ path: import_zod26.z.string().min(1), confirm: RemovalConfirmationSchema });
16729
17023
  var ConfigRuleRemoveOutputSchema = mutationOutput("rule", "removed");
16730
17024
 
16731
17025
  // src/frontdoor/configApi.ts
@@ -17037,43 +17331,43 @@ var import_openapi4 = require("@orpc/openapi");
17037
17331
  var import_server3 = require("@orpc/server");
17038
17332
 
17039
17333
  // src/frontdoor/eventSchemas.ts
17040
- var import_zod25 = require("zod");
17334
+ var import_zod27 = require("zod");
17041
17335
  var DOOR_EVENT_SOURCE_RC = "rc";
17042
17336
  var LAUNCH_EVENT_SOURCE = "launch";
17043
17337
  var USAGE_EVENT_SOURCE = "usage";
17044
17338
  var DOOR_HEALTH_EVENT_SOURCE = "door";
17045
17339
  var QUOTA_EXPIRING_EVENT_SOURCE = "quota-expiring";
17046
- var DoorEventSchema = import_zod25.z.strictObject({
17047
- source: import_zod25.z.string().min(1),
17340
+ var DoorEventSchema = import_zod27.z.strictObject({
17341
+ source: import_zod27.z.string().min(1),
17048
17342
  /** A positive integer because the backbone's counters start at one and only ever increase. */
17049
- sequence: import_zod25.z.number().int().positive(),
17050
- payload: import_zod25.z.unknown()
17343
+ sequence: import_zod27.z.number().int().positive(),
17344
+ payload: import_zod27.z.unknown()
17051
17345
  });
17052
- var DoorEventSourceQuerySchema = import_zod25.z.strictObject({
17053
- sources: import_zod25.z.array(import_zod25.z.string().min(1)).min(1).optional()
17346
+ var DoorEventSourceQuerySchema = import_zod27.z.strictObject({
17347
+ sources: import_zod27.z.array(import_zod27.z.string().min(1)).min(1).optional()
17054
17348
  });
17055
- var LaunchLifecycleEventSchema = import_zod25.z.strictObject({
17056
- kind: import_zod25.z.enum(["registered", "pruned", "ended"]),
17057
- pid: import_zod25.z.number().int().positive(),
17058
- startedAt: import_zod25.z.number(),
17059
- observedAt: import_zod25.z.number()
17349
+ var LaunchLifecycleEventSchema = import_zod27.z.strictObject({
17350
+ kind: import_zod27.z.enum(["registered", "pruned", "ended"]),
17351
+ pid: import_zod27.z.number().int().positive(),
17352
+ startedAt: import_zod27.z.number(),
17353
+ observedAt: import_zod27.z.number()
17060
17354
  });
17061
- var DoorHealthEventSchema = import_zod25.z.discriminatedUnion("kind", [
17062
- import_zod25.z.strictObject({ kind: import_zod25.z.literal("generation"), pid: import_zod25.z.number().int().positive(), providerPort: import_zod25.z.number().int().positive(), connectPort: import_zod25.z.number().int().positive(), directPort: import_zod25.z.number().int().positive(), observedAt: import_zod25.z.number() }),
17063
- import_zod25.z.strictObject({ kind: import_zod25.z.literal("listenerFailed"), pid: import_zod25.z.number().int().positive(), listener: import_zod25.z.enum(["provider", "connect", "direct"]), message: import_zod25.z.string(), observedAt: import_zod25.z.number() }),
17064
- import_zod25.z.strictObject({ kind: import_zod25.z.literal("binaryTurnover"), pid: import_zod25.z.number().int().positive(), observedAt: import_zod25.z.number() }),
17065
- import_zod25.z.strictObject({ kind: import_zod25.z.literal("idleShutdown"), pid: import_zod25.z.number().int().positive(), observedAt: import_zod25.z.number() }),
17066
- import_zod25.z.strictObject({ kind: import_zod25.z.literal("superseded"), pid: import_zod25.z.number().int().positive(), ownerPid: import_zod25.z.number().int().positive(), observedAt: import_zod25.z.number() }),
17067
- import_zod25.z.strictObject({ kind: import_zod25.z.literal("drained"), pid: import_zod25.z.number().int().positive(), observedAt: import_zod25.z.number() })
17355
+ var DoorHealthEventSchema = import_zod27.z.discriminatedUnion("kind", [
17356
+ import_zod27.z.strictObject({ kind: import_zod27.z.literal("generation"), pid: import_zod27.z.number().int().positive(), providerPort: import_zod27.z.number().int().positive(), connectPort: import_zod27.z.number().int().positive(), directPort: import_zod27.z.number().int().positive(), observedAt: import_zod27.z.number() }),
17357
+ import_zod27.z.strictObject({ kind: import_zod27.z.literal("listenerFailed"), pid: import_zod27.z.number().int().positive(), listener: import_zod27.z.enum(["provider", "connect", "direct"]), message: import_zod27.z.string(), observedAt: import_zod27.z.number() }),
17358
+ import_zod27.z.strictObject({ kind: import_zod27.z.literal("binaryTurnover"), pid: import_zod27.z.number().int().positive(), observedAt: import_zod27.z.number() }),
17359
+ import_zod27.z.strictObject({ kind: import_zod27.z.literal("idleShutdown"), pid: import_zod27.z.number().int().positive(), observedAt: import_zod27.z.number() }),
17360
+ import_zod27.z.strictObject({ kind: import_zod27.z.literal("superseded"), pid: import_zod27.z.number().int().positive(), ownerPid: import_zod27.z.number().int().positive(), observedAt: import_zod27.z.number() }),
17361
+ import_zod27.z.strictObject({ kind: import_zod27.z.literal("drained"), pid: import_zod27.z.number().int().positive(), observedAt: import_zod27.z.number() })
17068
17362
  ]);
17069
- var QuotaExpiringEventSchema = import_zod25.z.strictObject({
17070
- identity: import_zod25.z.string().min(1),
17071
- provider: import_zod25.z.string().min(1),
17072
- window: import_zod25.z.enum(["fiveHour", "sevenDay"]),
17363
+ var QuotaExpiringEventSchema = import_zod27.z.strictObject({
17364
+ identity: import_zod27.z.string().min(1),
17365
+ provider: import_zod27.z.string().min(1),
17366
+ window: import_zod27.z.enum(["fiveHour", "sevenDay"]),
17073
17367
  /** 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. */
17074
- utilization: import_zod25.z.number().min(0).max(1),
17075
- resetsAt: import_zod25.z.iso.datetime(),
17076
- observedAt: import_zod25.z.number()
17368
+ utilization: import_zod27.z.number().min(0).max(1),
17369
+ resetsAt: import_zod27.z.iso.datetime(),
17370
+ observedAt: import_zod27.z.number()
17077
17371
  });
17078
17372
 
17079
17373
  // src/frontdoor/eventsApi.ts
@@ -17156,57 +17450,57 @@ var import_openapi6 = require("@orpc/openapi");
17156
17450
  init_cliError();
17157
17451
 
17158
17452
  // src/frontdoor/launchSchemas.ts
17159
- var import_node_path32 = __toESM(require("node:path"), 1);
17160
- var import_zod26 = require("zod");
17453
+ var import_node_path33 = __toESM(require("node:path"), 1);
17454
+ var import_zod28 = require("zod");
17161
17455
  init_claudeVersion();
17162
17456
  init_identity();
17163
- var LaunchResolveInputSchema = import_zod26.z.strictObject({
17164
- path: import_zod26.z.string().min(1),
17457
+ var LaunchResolveInputSchema = import_zod28.z.strictObject({
17458
+ path: import_zod28.z.string().min(1),
17165
17459
  /** `@name`, launch flags, then the arguments for `claude`; empty for a bare launch. */
17166
- argv: import_zod26.z.readonly(import_zod26.z.array(import_zod26.z.string())).optional(),
17460
+ argv: import_zod28.z.readonly(import_zod28.z.array(import_zod28.z.string())).optional(),
17167
17461
  /** 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. */
17168
- env: import_zod26.z.record(import_zod26.z.string(), import_zod26.z.string()).optional()
17169
- }).refine((input) => import_node_path32.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
17170
- var LaunchPoolDecisionSchema = import_zod26.z.strictObject({
17171
- name: import_zod26.z.string(),
17172
- reasons: import_zod26.z.readonly(import_zod26.z.array(import_zod26.z.string())),
17173
- movedOff: import_zod26.z.strictObject({ identity: import_zod26.z.string(), reason: import_zod26.z.string() }).optional()
17462
+ env: import_zod28.z.record(import_zod28.z.string(), import_zod28.z.string()).optional()
17463
+ }).refine((input) => import_node_path33.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
17464
+ var LaunchPoolDecisionSchema = import_zod28.z.strictObject({
17465
+ name: import_zod28.z.string(),
17466
+ reasons: import_zod28.z.readonly(import_zod28.z.array(import_zod28.z.string())),
17467
+ movedOff: import_zod28.z.strictObject({ identity: import_zod28.z.string(), reason: import_zod28.z.string() }).optional()
17174
17468
  });
17175
- var LaunchDecisionSchema = import_zod26.z.strictObject({
17176
- identity: import_zod26.z.string().optional(),
17177
- identitySource: import_zod26.z.enum(IDENTITY_DECISION_SOURCES),
17469
+ var LaunchDecisionSchema = import_zod28.z.strictObject({
17470
+ identity: import_zod28.z.string().optional(),
17471
+ identitySource: import_zod28.z.enum(IDENTITY_DECISION_SOURCES),
17178
17472
  pool: LaunchPoolDecisionSchema.optional(),
17179
- configDirEscapeHatch: import_zod26.z.boolean(),
17180
- configDir: import_zod26.z.string().optional(),
17181
- configProfile: import_zod26.z.string().optional(),
17182
- configProfileSource: import_zod26.z.enum(CONFIG_PROFILE_DECISION_SOURCES),
17183
- provider: import_zod26.z.string().optional()
17473
+ configDirEscapeHatch: import_zod28.z.boolean(),
17474
+ configDir: import_zod28.z.string().optional(),
17475
+ configProfile: import_zod28.z.string().optional(),
17476
+ configProfileSource: import_zod28.z.enum(CONFIG_PROFILE_DECISION_SOURCES),
17477
+ provider: import_zod28.z.string().optional()
17184
17478
  });
17185
- var LaunchFlagsSchema = import_zod26.z.strictObject({
17186
- skipPermissions: import_zod26.z.boolean(),
17187
- remoteControl: import_zod26.z.boolean(),
17188
- headroom: import_zod26.z.boolean(),
17189
- trackUsage: import_zod26.z.boolean(),
17190
- pause: import_zod26.z.boolean(),
17191
- explain: import_zod26.z.boolean(),
17192
- routeByName: import_zod26.z.boolean(),
17479
+ var LaunchFlagsSchema = import_zod28.z.strictObject({
17480
+ skipPermissions: import_zod28.z.boolean(),
17481
+ remoteControl: import_zod28.z.boolean(),
17482
+ headroom: import_zod28.z.boolean(),
17483
+ trackUsage: import_zod28.z.boolean(),
17484
+ pause: import_zod28.z.boolean(),
17485
+ explain: import_zod28.z.boolean(),
17486
+ routeByName: import_zod28.z.boolean(),
17193
17487
  /** How long the launch waits after its own output before it starts claude, in milliseconds. */
17194
- delayMs: import_zod26.z.number()
17488
+ delayMs: import_zod28.z.number()
17195
17489
  });
17196
- var LaunchResolveOutputSchema = import_zod26.z.strictObject({
17490
+ var LaunchResolveOutputSchema = import_zod28.z.strictObject({
17197
17491
  decision: LaunchDecisionSchema,
17198
17492
  flags: LaunchFlagsSchema,
17199
- claudeVersion: import_zod26.z.strictObject({ version: import_zod26.z.string(), source: import_zod26.z.enum(CLAUDE_VERSION_SOURCES) }).optional(),
17493
+ claudeVersion: import_zod28.z.strictObject({ version: import_zod28.z.string(), source: import_zod28.z.enum(CLAUDE_VERSION_SOURCES) }).optional(),
17200
17494
  /** The real `claude` binary the launch would spawn, on the door's host. */
17201
- bin: import_zod26.z.string(),
17495
+ bin: import_zod28.z.string(),
17202
17496
  /** The arguments the launch would pass it: the tool's own flags, then `CLAUDE_EXTRA_FLAGS`, then the caller's own. */
17203
- args: import_zod26.z.readonly(import_zod26.z.array(import_zod26.z.string())),
17497
+ args: import_zod28.z.readonly(import_zod28.z.array(import_zod28.z.string())),
17204
17498
  /** The credential the launch would authenticate with, by target and source kinds. Absent when none applies. */
17205
- credential: import_zod26.z.strictObject({ subject: import_zod26.z.enum(["provider", "identity"]), name: import_zod26.z.string(), summary: CredentialSummarySchema }).optional(),
17206
- routing: import_zod26.z.strictObject({ frontDoor: import_zod26.z.boolean(), headroom: import_zod26.z.boolean(), routeByName: import_zod26.z.boolean() }),
17499
+ credential: import_zod28.z.strictObject({ subject: import_zod28.z.enum(["provider", "identity"]), name: import_zod28.z.string(), summary: CredentialSummarySchema }).optional(),
17500
+ routing: import_zod28.z.strictObject({ frontDoor: import_zod28.z.boolean(), headroom: import_zod28.z.boolean(), routeByName: import_zod28.z.boolean() }),
17207
17501
  /** The names of the environment variables the launch would set or unset, sorted. Values are not reported. */
17208
- environment: import_zod26.z.readonly(import_zod26.z.array(import_zod26.z.string())),
17209
- warnings: import_zod26.z.readonly(import_zod26.z.array(import_zod26.z.string()))
17502
+ environment: import_zod28.z.readonly(import_zod28.z.array(import_zod28.z.string())),
17503
+ warnings: import_zod28.z.readonly(import_zod28.z.array(import_zod28.z.string()))
17210
17504
  });
17211
17505
 
17212
17506
  // src/frontdoor/launchApi.ts
@@ -17242,22 +17536,22 @@ function createLaunchApiRouter(deps) {
17242
17536
  // src/frontdoor/agentTreesApi.ts
17243
17537
  var import_client6 = require("@orpc/client");
17244
17538
  var import_openapi7 = require("@orpc/openapi");
17245
- var import_zod27 = require("zod");
17539
+ var import_zod29 = require("zod");
17246
17540
  init_cliError();
17247
- var AgentTreesListInputSchema = import_zod27.z.strictObject({
17541
+ var AgentTreesListInputSchema = import_zod29.z.strictObject({
17248
17542
  /** Only this identity's sessions. */
17249
- identity: import_zod27.z.string().optional(),
17543
+ identity: import_zod29.z.string().optional(),
17250
17544
  /** Include sessions that spawned no agent and ran no workflow. */
17251
- all: import_zod27.z.boolean().optional()
17545
+ all: import_zod29.z.boolean().optional()
17252
17546
  });
17253
- var AgentTreesListOutputSchema = import_zod27.z.array(SessionSummarySchema);
17254
- var AgentTreesShowInputSchema = import_zod27.z.strictObject({
17547
+ var AgentTreesListOutputSchema = import_zod29.z.array(SessionSummarySchema);
17548
+ var AgentTreesShowInputSchema = import_zod29.z.strictObject({
17255
17549
  /** A session id, or an unambiguous prefix of one. */
17256
- session: import_zod27.z.string().min(1),
17550
+ session: import_zod29.z.string().min(1),
17257
17551
  /** Look only in this identity. */
17258
- identity: import_zod27.z.string().optional()
17552
+ identity: import_zod29.z.string().optional()
17259
17553
  });
17260
- var AgentTreesShowOutputSchema = import_zod27.z.strictObject({ identities: import_zod27.z.array(import_zod27.z.string()), ...MergedAgentTreeSchema.shape });
17554
+ var AgentTreesShowOutputSchema = import_zod29.z.strictObject({ identities: import_zod29.z.array(import_zod29.z.string()), ...MergedAgentTreeSchema.shape });
17261
17555
  function asBadRequest(error) {
17262
17556
  if (error instanceof CliError) {
17263
17557
  throw new import_client6.ORPCError("BAD_REQUEST", { message: error.message });
@@ -17643,11 +17937,11 @@ function createDoorHealthPublisher(hub, now, pid) {
17643
17937
 
17644
17938
  // src/frontdoor/quotaExpiringEvents.ts
17645
17939
  init_schema2();
17646
- var MS_PER_HOUR4 = 36e5;
17940
+ var MS_PER_HOUR5 = 36e5;
17647
17941
  var MS_PER_DAY2 = 864e5;
17648
17942
  var FIVE_HOUR_WINDOW_HOURS = 5;
17649
17943
  var SEVEN_DAY_WINDOW_DAYS = 7;
17650
- var FIVE_HOUR_WINDOW_MS2 = FIVE_HOUR_WINDOW_HOURS * MS_PER_HOUR4;
17944
+ var FIVE_HOUR_WINDOW_MS2 = FIVE_HOUR_WINDOW_HOURS * MS_PER_HOUR5;
17651
17945
  var SEVEN_DAY_WINDOW_MS2 = SEVEN_DAY_WINDOW_DAYS * MS_PER_DAY2;
17652
17946
  var FINAL_SPAN_DENOMINATOR = 30;
17653
17947
  var QUOTA_EXPIRING_WINDOW_FRACTION = 1 / FINAL_SPAN_DENOMINATOR;
@@ -18340,7 +18634,7 @@ async function serveRcConversations(ctx, pathname, method) {
18340
18634
  var RC_SELF_HOST_OAUTH_HOST = "platform.claude.com";
18341
18635
  var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"];
18342
18636
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
18343
- var MS_PER_SECOND5 = 1e3;
18637
+ var MS_PER_SECOND6 = 1e3;
18344
18638
  var HTTP_SERVICE_UNAVAILABLE = 503;
18345
18639
  function isRecord12(value) {
18346
18640
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -18396,7 +18690,7 @@ function createRcSelfHostLocal(deps) {
18396
18690
  }
18397
18691
  if (method === "POST" && pathname.startsWith("/api/eval/")) {
18398
18692
  await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
18399
- answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND5) });
18693
+ answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND6) });
18400
18694
  return true;
18401
18695
  }
18402
18696
  if (method === "GET" && pathname === "/api/oauth/profile") {
@@ -18695,7 +18989,7 @@ var RC_COMPAT_SESSIONS_PATH = "/v1/sessions";
18695
18989
  var RC_SESSION_ID_PREFIX2 = "cse_";
18696
18990
  var RC_SELF_HOST_API_BASE_URL = "https://api.anthropic.com";
18697
18991
  var HTTP_CONFLICT = 409;
18698
- var MS_PER_SECOND6 = 1e3;
18992
+ var MS_PER_SECOND7 = 1e3;
18699
18993
  var HTTP_SERVICE_UNAVAILABLE2 = 503;
18700
18994
  var RC_SELF_HOST_WORKER_JWT_TTL_SECONDS = 46800;
18701
18995
  var RC_SELF_HOST_KEEPALIVE_MS = 15e3;
@@ -18795,7 +19089,7 @@ function parseJsonObject5(body) {
18795
19089
  function mintWorkerJwt(randomToken, issuedAt) {
18796
19090
  const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
18797
19091
  const header = encode({ alg: "HS256", typ: "JWT" });
18798
- const payload = encode({ exp: Math.floor((issuedAt + RC_SELF_HOST_WORKER_JWT_TTL_SECONDS * MS_PER_SECOND6) / MS_PER_SECOND6), iat: Math.floor(issuedAt / MS_PER_SECOND6) });
19092
+ const payload = encode({ exp: Math.floor((issuedAt + RC_SELF_HOST_WORKER_JWT_TTL_SECONDS * MS_PER_SECOND7) / MS_PER_SECOND7), iat: Math.floor(issuedAt / MS_PER_SECOND7) });
18799
19093
  return `${header}.${payload}.${Buffer.from(randomToken(), "utf8").toString("base64url")}`;
18800
19094
  }
18801
19095
  function createRcSelfHostSurface(deps) {
@@ -19338,7 +19632,7 @@ data: ${JSON.stringify(envelope)}
19338
19632
  }
19339
19633
 
19340
19634
  // src/frontdoor/rcSelfHostMint.ts
19341
- var import_node_path33 = __toESM(require("node:path"), 1);
19635
+ var import_node_path34 = __toESM(require("node:path"), 1);
19342
19636
  init_account();
19343
19637
  var CREDENTIALS_FILE2 = ".credentials.json";
19344
19638
  var CLAUDE_JSON2 = ".claude.json";
@@ -19363,7 +19657,7 @@ function readJsonObject(fs13, file) {
19363
19657
  return isRecord14(parsed) ? parsed : void 0;
19364
19658
  }
19365
19659
  function readRcSelfHostRecord(fs13, frontdoorDir) {
19366
- const parsed = readJsonObject(fs13, import_node_path33.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
19660
+ const parsed = readJsonObject(fs13, import_node_path34.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
19367
19661
  if (parsed === void 0) {
19368
19662
  return void 0;
19369
19663
  }
@@ -19377,11 +19671,11 @@ function mintRcSelfHostCredential(deps) {
19377
19671
  if (!isIdentityName(deps.identity)) {
19378
19672
  throw new Error(`"${deps.identity}" is not a valid identity name.`);
19379
19673
  }
19380
- const identityDir = import_node_path33.default.join(deps.identitiesDir, deps.identity);
19381
- const credentialsFile = import_node_path33.default.join(identityDir, CREDENTIALS_FILE2);
19382
- const claudeJsonFile = import_node_path33.default.join(identityDir, CLAUDE_JSON2);
19383
- const recordDir = import_node_path33.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
19384
- const recordFile = import_node_path33.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
19674
+ const identityDir = import_node_path34.default.join(deps.identitiesDir, deps.identity);
19675
+ const credentialsFile = import_node_path34.default.join(identityDir, CREDENTIALS_FILE2);
19676
+ const claudeJsonFile = import_node_path34.default.join(identityDir, CLAUDE_JSON2);
19677
+ const recordDir = import_node_path34.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
19678
+ const recordFile = import_node_path34.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
19385
19679
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
19386
19680
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
19387
19681
  const existingOauth = isRecord14(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
@@ -19397,7 +19691,7 @@ function mintRcSelfHostCredential(deps) {
19397
19691
  const organizationUuid = deps.newUuid();
19398
19692
  const accountUuid = deps.newUuid();
19399
19693
  const mintedAt = new Date(deps.now()).toISOString();
19400
- deps.fs.mkdirPrivate(import_node_path33.default.dirname(credentialsFile));
19694
+ deps.fs.mkdirPrivate(import_node_path34.default.dirname(credentialsFile));
19401
19695
  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)}
19402
19696
  `);
19403
19697
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
@@ -19439,8 +19733,8 @@ init_plan2();
19439
19733
  init_poolPick();
19440
19734
 
19441
19735
  // src/agents/read.ts
19442
- var import_node_path34 = __toESM(require("node:path"), 1);
19443
- var import_zod28 = require("zod");
19736
+ var import_node_path35 = __toESM(require("node:path"), 1);
19737
+ var import_zod30 = require("zod");
19444
19738
  var PROJECTS_DIR = "projects";
19445
19739
  var TASKS_DIR = "tasks";
19446
19740
  var SUBAGENTS_DIR = "subagents";
@@ -19465,15 +19759,15 @@ function parseEntry2(project, entry) {
19465
19759
  }
19466
19760
  function listSessions2(fs13, configDir) {
19467
19761
  const found = [];
19468
- for (const project of fs13.readdir(import_node_path34.default.join(configDir, PROJECTS_DIR))) {
19469
- const projectDir = import_node_path34.default.join(configDir, PROJECTS_DIR, project);
19762
+ for (const project of fs13.readdir(import_node_path35.default.join(configDir, PROJECTS_DIR))) {
19763
+ const projectDir = import_node_path35.default.join(configDir, PROJECTS_DIR, project);
19470
19764
  const entries = /* @__PURE__ */ new Set();
19471
19765
  for (const name of fs13.readdir(projectDir)) {
19472
19766
  if (name.endsWith(TRANSCRIPT_SUFFIX)) {
19473
19767
  entries.add(name.slice(0, -TRANSCRIPT_SUFFIX.length));
19474
19768
  continue;
19475
19769
  }
19476
- const children = fs13.readdir(import_node_path34.default.join(projectDir, name));
19770
+ const children = fs13.readdir(import_node_path35.default.join(projectDir, name));
19477
19771
  if (children.includes(SUBAGENTS_DIR) || children.includes(WORKFLOWS_DIR)) {
19478
19772
  entries.add(name);
19479
19773
  }
@@ -19493,8 +19787,8 @@ function locateAgents(fs13, configDir, relativeDir, workflowRunId, report) {
19493
19787
  const id = name.slice(AGENT_FILE_PREFIX.length, -META_SUFFIX.length);
19494
19788
  located.push({
19495
19789
  id,
19496
- metaPath: import_node_path34.default.join(relativeDir, name),
19497
- transcriptPath: import_node_path34.default.join(relativeDir, `${AGENT_FILE_PREFIX}${id}${TRANSCRIPT_SUFFIX}`),
19790
+ metaPath: import_node_path35.default.join(relativeDir, name),
19791
+ transcriptPath: import_node_path35.default.join(relativeDir, `${AGENT_FILE_PREFIX}${id}${TRANSCRIPT_SUFFIX}`),
19498
19792
  workflowRunId
19499
19793
  });
19500
19794
  }
@@ -19537,7 +19831,7 @@ function describeFailure(error) {
19537
19831
  }
19538
19832
  function readFileOrReport(fs13, configDir, relative, report) {
19539
19833
  try {
19540
- return fs13.readFileUtf8(import_node_path34.default.join(configDir, relative));
19834
+ return fs13.readFileUtf8(import_node_path35.default.join(configDir, relative));
19541
19835
  } catch (error) {
19542
19836
  report({ path: relative, reason: `could not be read: ${describeFailure(error)}` });
19543
19837
  return void 0;
@@ -19545,7 +19839,7 @@ function readFileOrReport(fs13, configDir, relative, report) {
19545
19839
  }
19546
19840
  function listDirOrReport(fs13, configDir, relative, report) {
19547
19841
  try {
19548
- return fs13.readdir(import_node_path34.default.join(configDir, relative));
19842
+ return fs13.readdir(import_node_path35.default.join(configDir, relative));
19549
19843
  } catch (error) {
19550
19844
  report({ path: relative, reason: `could not be listed: ${describeFailure(error)}` });
19551
19845
  return [];
@@ -19559,28 +19853,28 @@ function parseJson2(text) {
19559
19853
  return void 0;
19560
19854
  }
19561
19855
  }
19562
- var TaskFileSchema = import_zod28.z.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: import_zod28.z.array(import_zod28.z.string()).default([]), blockedBy: import_zod28.z.array(import_zod28.z.string()).default([]) });
19563
- var WorkflowRunFileSchema = import_zod28.z.object({
19564
- runId: import_zod28.z.string(),
19565
- workflowName: import_zod28.z.string().optional(),
19566
- status: import_zod28.z.string().optional(),
19567
- startTime: import_zod28.z.number().optional(),
19568
- phases: import_zod28.z.array(import_zod28.z.object({ title: import_zod28.z.string() })).default([]),
19569
- summary: import_zod28.z.string().optional()
19856
+ var TaskFileSchema = import_zod30.z.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: import_zod30.z.array(import_zod30.z.string()).default([]), blockedBy: import_zod30.z.array(import_zod30.z.string()).default([]) });
19857
+ var WorkflowRunFileSchema = import_zod30.z.object({
19858
+ runId: import_zod30.z.string(),
19859
+ workflowName: import_zod30.z.string().optional(),
19860
+ status: import_zod30.z.string().optional(),
19861
+ startTime: import_zod30.z.number().optional(),
19862
+ phases: import_zod30.z.array(import_zod30.z.object({ title: import_zod30.z.string() })).default([]),
19863
+ summary: import_zod30.z.string().optional()
19570
19864
  });
19571
19865
  function summariseSession(fs13, configDir, ref) {
19572
- const sessionRelative = import_node_path34.default.join(PROJECTS_DIR, ref.project, ref.entry);
19573
- const subagentsRelative = import_node_path34.default.join(sessionRelative, SUBAGENTS_DIR);
19574
- const workflowsUnderSubagents = import_node_path34.default.join(subagentsRelative, WORKFLOWS_DIR);
19866
+ const sessionRelative = import_node_path35.default.join(PROJECTS_DIR, ref.project, ref.entry);
19867
+ const subagentsRelative = import_node_path35.default.join(sessionRelative, SUBAGENTS_DIR);
19868
+ const workflowsUnderSubagents = import_node_path35.default.join(subagentsRelative, WORKFLOWS_DIR);
19575
19869
  const isMeta = (name) => name.startsWith(AGENT_FILE_PREFIX) && name.endsWith(META_SUFFIX);
19576
- let agentCount = fs13.readdir(import_node_path34.default.join(configDir, subagentsRelative)).filter(isMeta).length;
19577
- for (const runDir of fs13.readdir(import_node_path34.default.join(configDir, workflowsUnderSubagents))) {
19870
+ let agentCount = fs13.readdir(import_node_path35.default.join(configDir, subagentsRelative)).filter(isMeta).length;
19871
+ for (const runDir of fs13.readdir(import_node_path35.default.join(configDir, workflowsUnderSubagents))) {
19578
19872
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
19579
- agentCount += fs13.readdir(import_node_path34.default.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
19873
+ agentCount += fs13.readdir(import_node_path35.default.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
19580
19874
  }
19581
19875
  }
19582
- const workflowRunCount = fs13.readdir(import_node_path34.default.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
19583
- const transcript = fs13.lstat(import_node_path34.default.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
19876
+ const workflowRunCount = fs13.readdir(import_node_path35.default.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
19877
+ const transcript = fs13.lstat(import_node_path35.default.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
19584
19878
  return { ...ref, agentCount, workflowRunCount, ...transcript === void 0 ? {} : { updatedAt: new Date(transcript.mtimeMs).toISOString() } };
19585
19879
  }
19586
19880
  function readSessionAgentTree(fs13, configDir, ref, options = {}) {
@@ -19588,13 +19882,13 @@ function readSessionAgentTree(fs13, configDir, ref, options = {}) {
19588
19882
  const report = (problem) => {
19589
19883
  problems.push(problem);
19590
19884
  };
19591
- const sessionRelative = import_node_path34.default.join(PROJECTS_DIR, ref.project, ref.entry);
19592
- const subagentsRelative = import_node_path34.default.join(sessionRelative, SUBAGENTS_DIR);
19593
- const workflowsUnderSubagents = import_node_path34.default.join(subagentsRelative, WORKFLOWS_DIR);
19885
+ const sessionRelative = import_node_path35.default.join(PROJECTS_DIR, ref.project, ref.entry);
19886
+ const subagentsRelative = import_node_path35.default.join(sessionRelative, SUBAGENTS_DIR);
19887
+ const workflowsUnderSubagents = import_node_path35.default.join(subagentsRelative, WORKFLOWS_DIR);
19594
19888
  const located = locateAgents(fs13, configDir, subagentsRelative, void 0, report);
19595
19889
  for (const runDir of listDirOrReport(fs13, configDir, workflowsUnderSubagents, report)) {
19596
19890
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
19597
- located.push(...locateAgents(fs13, configDir, import_node_path34.default.join(workflowsUnderSubagents, runDir), runDir, report));
19891
+ located.push(...locateAgents(fs13, configDir, import_node_path35.default.join(workflowsUnderSubagents, runDir), runDir, report));
19598
19892
  }
19599
19893
  }
19600
19894
  const agents = /* @__PURE__ */ new Map();
@@ -19635,7 +19929,7 @@ function readSessionAgentTree(fs13, configDir, ref, options = {}) {
19635
19929
  superseded: ref.superseded,
19636
19930
  agents: roots.sort().map(build),
19637
19931
  tasks: readTasks(fs13, configDir, ownTaskLists(ref.sessionId), [.../* @__PURE__ */ new Set([...teamNames, ...options.taskListIds ?? []])].filter((id) => !ownTaskLists(ref.sessionId).includes(id)), report),
19638
- workflowRuns: readWorkflowRuns(fs13, configDir, import_node_path34.default.join(sessionRelative, WORKFLOWS_DIR), report),
19932
+ workflowRuns: readWorkflowRuns(fs13, configDir, import_node_path35.default.join(sessionRelative, WORKFLOWS_DIR), report),
19639
19933
  problems
19640
19934
  };
19641
19935
  }
@@ -19700,12 +19994,12 @@ function ownTaskLists(sessionId) {
19700
19994
  function readTasks(fs13, configDir, ownLists, sharedLists, report) {
19701
19995
  const tasks = [];
19702
19996
  [...ownLists, ...sharedLists].forEach((scope, index) => {
19703
- const relativeDir = import_node_path34.default.join(TASKS_DIR, scope);
19997
+ const relativeDir = import_node_path35.default.join(TASKS_DIR, scope);
19704
19998
  for (const name of [...listDirOrReport(fs13, configDir, relativeDir, report)].sort()) {
19705
19999
  if (name.startsWith(".") || !name.endsWith(JSON_SUFFIX)) {
19706
20000
  continue;
19707
20001
  }
19708
- const relative = import_node_path34.default.join(relativeDir, name);
20002
+ const relative = import_node_path35.default.join(relativeDir, name);
19709
20003
  const text = readFileOrReport(fs13, configDir, relative, report);
19710
20004
  const parsed = TaskFileSchema.safeParse(text === void 0 ? void 0 : parseJson2(text));
19711
20005
  if (parsed.success) {
@@ -19723,7 +20017,7 @@ function readWorkflowRuns(fs13, configDir, relativeDir, report) {
19723
20017
  if (!name.startsWith(WORKFLOW_RUN_PREFIX) || !name.endsWith(JSON_SUFFIX)) {
19724
20018
  continue;
19725
20019
  }
19726
- const relative = import_node_path34.default.join(relativeDir, name);
20020
+ const relative = import_node_path35.default.join(relativeDir, name);
19727
20021
  const text = readFileOrReport(fs13, configDir, relative, report);
19728
20022
  const parsed = WorkflowRunFileSchema.safeParse(text === void 0 ? void 0 : parseJson2(text));
19729
20023
  if (!parsed.success) {
@@ -19739,7 +20033,7 @@ function readWorkflowRuns(fs13, configDir, relativeDir, report) {
19739
20033
  }
19740
20034
 
19741
20035
  // src/agents/sessions.ts
19742
- var import_node_path35 = __toESM(require("node:path"), 1);
20036
+ var import_node_path36 = __toESM(require("node:path"), 1);
19743
20037
  init_cliError();
19744
20038
  var SessionLookupError = class extends CliError {
19745
20039
  constructor(message) {
@@ -19748,13 +20042,13 @@ var SessionLookupError = class extends CliError {
19748
20042
  }
19749
20043
  };
19750
20044
  function identityConfigDir(identitiesDir, identity) {
19751
- return import_node_path35.default.join(identitiesDir, identity);
20045
+ return import_node_path36.default.join(identitiesDir, identity);
19752
20046
  }
19753
20047
  function historyStores(fs13, identitiesDir, identities) {
19754
20048
  const byRealPath = /* @__PURE__ */ new Map();
19755
20049
  for (const identity of identities) {
19756
20050
  const configDir = identityConfigDir(identitiesDir, identity);
19757
- const real = fs13.realpath(import_node_path35.default.join(configDir, "projects"));
20051
+ const real = fs13.realpath(import_node_path36.default.join(configDir, "projects"));
19758
20052
  if (real === void 0) {
19759
20053
  continue;
19760
20054
  }