claude-use 14.0.4 → 14.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -28517,7 +28517,7 @@ function isRateLimitHeader(name) {
28517
28517
  const lower = name.toLowerCase();
28518
28518
  return lower === "retry-after" || lower.startsWith("anthropic-ratelimit-") || lower.startsWith("x-ratelimit-") || lower.startsWith("ratelimit") || lower.startsWith("x-codex-");
28519
28519
  }
28520
- var USAGE_SCHEMA_VERSION, VersionSchema, InstantSchema, CLIENT_SESSION_ID_PATTERN, TokenCountSchema, TokenUsageSchema, LIMIT_KINDS, LimitClassificationSchema, UsageRecordSchema, QuotaWindowSchema, ExtraUsageSpendSchema, UnifiedRateLimitSchema, RateLimitStateSchema, LimitEventSchema, ProviderQuotaWindowSchema, ProviderAccountSchema, ProviderQuotaSchema, ProviderUsageStateSchema, AccountMetadataSchema, UsageSnapshotSchema;
28520
+ var USAGE_SCHEMA_VERSION, VersionSchema, InstantSchema, CLIENT_SESSION_ID_PATTERN, TokenCountSchema, TokenUsageSchema, LIMIT_KINDS, LimitClassificationSchema, REQUEST_CLASSES, RequestClassSchema, UsageRecordSchema, QuotaWindowSchema, ExtraUsageSpendSchema, UnifiedRateLimitSchema, RateLimitStateSchema, LimitEventSchema, ProviderQuotaWindowSchema, ProviderAccountSchema, ProviderQuotaSchema, ProviderUsageStateSchema, AccountMetadataSchema, UsageSnapshotSchema;
28521
28521
  var init_schema2 = __esm({
28522
28522
  "src/usage/schema.ts"() {
28523
28523
  "use strict";
@@ -28545,6 +28545,8 @@ var init_schema2 = __esm({
28545
28545
  /** The signals the classification rests on, each `<name>=<value>` from a response header or the error body's `type` or `code`. Never the error message. */
28546
28546
  evidence: external_exports.array(external_exports.string())
28547
28547
  });
28548
+ REQUEST_CLASSES = ["main", "subagent", "workflow", "compaction", "auxiliary", "side_reply", "unknown"];
28549
+ RequestClassSchema = external_exports.enum(REQUEST_CLASSES);
28548
28550
  UsageRecordSchema = external_exports.strictObject({
28549
28551
  schemaVersion: VersionSchema,
28550
28552
  /** When the front door received the request. */
@@ -28568,8 +28570,10 @@ var init_schema2 = __esm({
28568
28570
  endpoint: external_exports.string(),
28569
28571
  /** The model the response named. */
28570
28572
  model: external_exports.string().optional(),
28571
- /** The model the session requested when a routing layer chose a different model, or when no response model was available to compare it with. Absent when the response confirms that the requested name was served unchanged. */
28573
+ /** The model name the request asked for, as its body carried it before any routing layer rewrote it: compared with `model`, it tells a choice or tier mapping apart from a name served unchanged. Present when the response served a different model than the name asked for, and when the response names no model (an error response included) and the door had read the request's body; absent when the response confirms the name. */
28572
28574
  requestedModel: external_exports.string().optional(),
28575
+ /** The request's class, as Claude Code stated it in its `x-claude-code-request-class` header: `main` for the conversation's own loop, otherwise `subagent`, `workflow`, `compaction`, `auxiliary` (a hook judge, a title) or `side_reply`; `unknown` when the header carried anything else, so a client-chosen string never reaches the log. `subagent` as well for a request that states no class but carries Claude Code's agent id header, which it sends on every non-main agent request. Absent when the client sent neither. Claude Code derives it from the request's query source, which it does not send, so the query source itself is never recorded. */
28576
+ requestClass: RequestClassSchema.optional(),
28573
28577
  /** The distinct providers the choice could have landed on, present only when there was more than one, so a reader can tell a choice that crossed providers from one that stayed inside a single provider's lineup. */
28574
28578
  candidateProviders: external_exports.array(external_exports.string()).optional(),
28575
28579
  status: external_exports.number().int(),
@@ -31457,6 +31461,9 @@ function readCatalogueStatus(fs38, paths, pid, generation, name) {
31457
31461
  return void 0;
31458
31462
  }
31459
31463
  }
31464
+ function launchKeyOf(launch) {
31465
+ return `${String(launch.pid)}-${String(launch.startedAt)}`;
31466
+ }
31460
31467
  function writeFrontDoorCodexHome(fs38, frontdoorDir, pid, codexHome2, generation) {
31461
31468
  const directory = import_node_path7.default.join(frontdoorDir, "codex-homes");
31462
31469
  fs38.mkdirp(directory);
@@ -31577,8 +31584,43 @@ function pruneDeadFrontDoorDirectRecords(fs38, recordsDir, records, liveness) {
31577
31584
  function recordOf(details) {
31578
31585
  return details === void 0 ? {} : { sessionId: details.sessionId, ...details.identity === void 0 ? {} : { identity: details.identity }, ...details.models === void 0 ? {} : { models: details.models } };
31579
31586
  }
31587
+ function launchRouteStore(fs38, sessionsDir, log) {
31588
+ const failing = /* @__PURE__ */ new Set();
31589
+ const badFacts = /* @__PURE__ */ new Set();
31590
+ return {
31591
+ read: (launch) => readLaunchRoute(fs38, sessionsDir, launch, (message) => {
31592
+ const key = launchKeyOf(launch);
31593
+ if (!badFacts.has(key)) {
31594
+ badFacts.add(key);
31595
+ log(`front door: could not read the facts recorded for launch ${String(launch.pid)}'s main loop (${message}), so its route is used without them`);
31596
+ }
31597
+ }),
31598
+ write: (launch, route) => {
31599
+ writeLaunchRoute(fs38, sessionsDir, launch, route);
31600
+ },
31601
+ // Best effort and the one place that owns its failure: the identity only saves a read, so a stat that cannot be made (no permission, an I/O error, a path that is not a directory) is no identity, never a failed request.
31602
+ identity: (launch) => {
31603
+ const key = launchKeyOf(launch);
31604
+ try {
31605
+ const route = fs38.lstat(import_node_path7.default.join(sessionsDir, launchRouteName(launch.pid)));
31606
+ const facts = fs38.lstat(import_node_path7.default.join(sessionsDir, launchFactsName(launch.pid)));
31607
+ failing.delete(key);
31608
+ const of2 = (stat2) => stat2 === void 0 ? "-" : `${String(stat2.mtimeMs)}:${String(stat2.sizeBytes)}`;
31609
+ return route === void 0 ? void 0 : `${of2(route)}|${of2(facts)}`;
31610
+ } catch (error63) {
31611
+ if (!failing.has(key)) {
31612
+ failing.add(key);
31613
+ log(`front door: could not stat where launch ${String(launch.pid)}'s main loop went, so a route another door writes may go unseen until its next main-loop request: ${error63 instanceof Error ? error63.message : String(error63)}`);
31614
+ }
31615
+ return void 0;
31616
+ }
31617
+ }
31618
+ };
31619
+ }
31580
31620
  function writeFrontDoorSession(fs38, sessionsDir, session) {
31581
31621
  fs38.mkdirPrivate(sessionsDir);
31622
+ fs38.removeRecursive(import_node_path7.default.join(sessionsDir, launchRouteName(session.pid)));
31623
+ fs38.removeRecursive(import_node_path7.default.join(sessionsDir, launchFactsName(session.pid)));
31582
31624
  fs38.writeFilePrivate(import_node_path7.default.join(sessionsDir, sessionRecordName(session.pid)), `${JSON.stringify(session, null, 2)}
31583
31625
  `);
31584
31626
  }
@@ -31586,7 +31628,79 @@ function sessionRecordName(pid) {
31586
31628
  return `${String(pid)}.json`;
31587
31629
  }
31588
31630
  function isSessionRecordName(name) {
31589
- return name.endsWith(".json");
31631
+ return /^[1-9]\d*\.json$/.test(name);
31632
+ }
31633
+ function launchRouteName(pid) {
31634
+ return `${String(pid)}.route.json`;
31635
+ }
31636
+ function launchFactsName(pid) {
31637
+ return `${String(pid)}.context.json`;
31638
+ }
31639
+ function writeLaunchRoute(fs38, sessionsDir, launch, context) {
31640
+ const { facts, route } = splitContext(context);
31641
+ if (readFrontDoorSessionRecord(fs38, sessionsDir, sessionRecordName(launch.pid))?.startedAt !== launch.startedAt) {
31642
+ return;
31643
+ }
31644
+ fs38.mkdirPrivate(sessionsDir);
31645
+ const factsFile = import_node_path7.default.join(sessionsDir, launchFactsName(launch.pid));
31646
+ if (Object.keys(facts).length === 0) {
31647
+ fs38.removeRecursive(factsFile);
31648
+ } else {
31649
+ fs38.writeFilePrivate(factsFile, `${JSON.stringify({ version: LAUNCH_FACTS_FILE_VERSION, startedAt: launch.startedAt, facts })}
31650
+ `);
31651
+ }
31652
+ fs38.writeFilePrivate(import_node_path7.default.join(sessionsDir, launchRouteName(launch.pid)), `${JSON.stringify({ version: LAUNCH_ROUTE_FILE_VERSION, startedAt: launch.startedAt, route })}
31653
+ `);
31654
+ }
31655
+ function splitContext(context) {
31656
+ const facts = ContextFactsSchema.parse({ ...context.credential === void 0 ? {} : { credential: context.credential }, ...context.requestedModel === void 0 ? {} : { requestedModel: context.requestedModel }, ...context.servedModel === void 0 ? {} : { servedModel: context.servedModel } });
31657
+ const route = LaunchRouteSchema.parse(context.kind === "provider" ? { kind: "provider", provider: context.provider } : { kind: "anthropic" });
31658
+ return { route, facts };
31659
+ }
31660
+ function readLaunchRoute(fs38, sessionsDir, launch, factsProblem) {
31661
+ const name = launchRouteName(launch.pid);
31662
+ const text5 = fs38.readFileUtf8(import_node_path7.default.join(sessionsDir, name));
31663
+ if (text5 === void 0) {
31664
+ return void 0;
31665
+ }
31666
+ let json2;
31667
+ try {
31668
+ json2 = JSON.parse(text5);
31669
+ } catch {
31670
+ throw new Error(`${name} is not JSON`);
31671
+ }
31672
+ const version2 = typeof json2 === "object" && json2 !== null && "version" in json2 ? json2.version : void 0;
31673
+ if (typeof version2 === "number" && version2 > LAUNCH_ROUTE_FILE_VERSION) {
31674
+ throw new Error(`${name} is version ${String(version2)}, written by a newer door than this one reads (version ${String(LAUNCH_ROUTE_FILE_VERSION)})`);
31675
+ }
31676
+ const parsed = LaunchRouteFileSchema.safeParse(json2);
31677
+ if (!parsed.success) {
31678
+ throw new Error(`${name} is not a route file this door reads`);
31679
+ }
31680
+ if (parsed.data.startedAt !== launch.startedAt) {
31681
+ return void 0;
31682
+ }
31683
+ return { ...parsed.data.route, ...readLaunchFacts(fs38, sessionsDir, launch, factsProblem) };
31684
+ }
31685
+ function readLaunchFacts(fs38, sessionsDir, launch, factsProblem) {
31686
+ const name = launchFactsName(launch.pid);
31687
+ const text5 = fs38.readFileUtf8(import_node_path7.default.join(sessionsDir, name));
31688
+ if (text5 === void 0) {
31689
+ return {};
31690
+ }
31691
+ let json2;
31692
+ try {
31693
+ json2 = JSON.parse(text5);
31694
+ } catch {
31695
+ factsProblem(`${name} is not JSON`);
31696
+ return {};
31697
+ }
31698
+ const parsed = LaunchFactsFileSchema.safeParse(json2);
31699
+ if (!parsed.success) {
31700
+ factsProblem(`${name} is not a facts file this door reads`);
31701
+ return {};
31702
+ }
31703
+ return parsed.data.startedAt === launch.startedAt ? parsed.data.facts : {};
31590
31704
  }
31591
31705
  function summaryOf(session) {
31592
31706
  return { pid: session.pid, startedAt: session.startedAt, ...session.supervisorPid === void 0 ? {} : { supervisorPid: session.supervisorPid } };
@@ -31609,8 +31723,14 @@ function listFrontDoorSessions(fs38, sessionsDir) {
31609
31723
  }
31610
31724
  return sessions.sort((a10, b) => a10.pid - b.pid);
31611
31725
  }
31726
+ function routeFilePid(name) {
31727
+ const match = /^([1-9]\d*)\.(?:route|context)\.json$/.exec(name);
31728
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
31729
+ }
31612
31730
  function removeFrontDoorSession(fs38, sessionsDir, pid) {
31613
31731
  fs38.removeRecursive(import_node_path7.default.join(sessionsDir, sessionRecordName(pid)));
31732
+ fs38.removeRecursive(import_node_path7.default.join(sessionsDir, launchRouteName(pid)));
31733
+ fs38.removeRecursive(import_node_path7.default.join(sessionsDir, launchFactsName(pid)));
31614
31734
  }
31615
31735
  function pruneDeadFrontDoorSessions(fs38, sessionsDir, listed, isRunning) {
31616
31736
  const removed = [];
@@ -31620,9 +31740,16 @@ function pruneDeadFrontDoorSessions(fs38, sessionsDir, listed, isRunning) {
31620
31740
  removed.push(session.pid);
31621
31741
  }
31622
31742
  }
31743
+ const names = fs38.readdir(sessionsDir);
31744
+ for (const name of names) {
31745
+ const pid = routeFilePid(name);
31746
+ if (pid !== void 0 && !names.includes(sessionRecordName(pid))) {
31747
+ fs38.removeRecursive(import_node_path7.default.join(sessionsDir, name));
31748
+ }
31749
+ }
31623
31750
  return removed;
31624
31751
  }
31625
- var import_node_path7, FRONT_DOOR_PROTOCOL, FRONT_DOOR_HANDOVER_PROTOCOL, FrontDoorSessionSchema, FrontDoorStateSchema, FrontDoorDirectRecordSchema, RECORD_TEMPORARY_FILE;
31752
+ var import_node_path7, FRONT_DOOR_PROTOCOL, FRONT_DOOR_HANDOVER_PROTOCOL, FrontDoorSessionSchema, MAX_CONTEXT_TEXT_LENGTH, ContextText, LaunchRouteSchema, ContextFactsSchema, FrontDoorStateSchema, FrontDoorDirectRecordSchema, RECORD_TEMPORARY_FILE, LAUNCH_ROUTE_FILE_VERSION, LAUNCH_FACTS_FILE_VERSION, LaunchRouteFileSchema, LaunchFactsFileSchema;
31626
31753
  var init_state = __esm({
31627
31754
  "src/frontdoor/state.ts"() {
31628
31755
  "use strict";
@@ -31634,6 +31761,10 @@ var init_state = __esm({
31634
31761
  FRONT_DOOR_PROTOCOL = 8;
31635
31762
  FRONT_DOOR_HANDOVER_PROTOCOL = 6;
31636
31763
  FrontDoorSessionSchema = external_exports.strictObject({ pid: external_exports.number().int().positive(), startedAt: external_exports.number(), token: external_exports.string().min(1), supervisorPid: external_exports.number().int().positive().optional(), sessionId: external_exports.string().min(1).optional(), identity: external_exports.string().min(1).optional(), models: ModelsConfigSchema.optional() });
31764
+ MAX_CONTEXT_TEXT_LENGTH = 256;
31765
+ ContextText = external_exports.string().min(1).max(MAX_CONTEXT_TEXT_LENGTH);
31766
+ LaunchRouteSchema = external_exports.union([external_exports.strictObject({ kind: external_exports.literal("anthropic") }), external_exports.strictObject({ kind: external_exports.literal("provider"), provider: external_exports.string().min(1) })]);
31767
+ ContextFactsSchema = external_exports.strictObject({ credential: ContextText.optional(), requestedModel: ContextText.optional(), servedModel: ContextText.optional() });
31637
31768
  FrontDoorStateSchema = external_exports.strictObject({
31638
31769
  /**
31639
31770
  * 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`).
@@ -31666,6 +31797,10 @@ var init_state = __esm({
31666
31797
  });
31667
31798
  FrontDoorDirectRecordSchema = external_exports.strictObject({ directPort: external_exports.number().int().positive().max(MAX_TCP_PORT) });
31668
31799
  RECORD_TEMPORARY_FILE = /^[1-9]\d*\.json\.([1-9]\d*)\.tmp$/;
31800
+ LAUNCH_ROUTE_FILE_VERSION = 1;
31801
+ LAUNCH_FACTS_FILE_VERSION = 1;
31802
+ LaunchRouteFileSchema = external_exports.strictObject({ version: external_exports.literal(LAUNCH_ROUTE_FILE_VERSION), startedAt: external_exports.number(), route: LaunchRouteSchema });
31803
+ LaunchFactsFileSchema = external_exports.strictObject({ version: external_exports.literal(LAUNCH_FACTS_FILE_VERSION), startedAt: external_exports.number(), facts: ContextFactsSchema });
31669
31804
  }
31670
31805
  });
31671
31806
 
@@ -37099,6 +37234,7 @@ function buildRecord(event, context) {
37099
37234
  ...scan?.model === void 0 ? {} : { model: scan.model },
37100
37235
  ...requestedModel === void 0 ? {} : { requestedModel },
37101
37236
  ...choice !== void 0 && choice.providers.length > 1 ? { candidateProviders: [...choice.providers] } : {},
37237
+ ...event.requestClass === void 0 ? {} : { requestClass: event.requestClass },
37102
37238
  status: event.status,
37103
37239
  latencyMs: Math.max(0, Math.round(context.headAt - event.receivedAt)),
37104
37240
  durationMs: Math.max(0, Math.round(context.endedAt - event.receivedAt)),
@@ -39598,7 +39734,7 @@ function mergeModels(current, layer) {
39598
39734
  }
39599
39735
  if (layer.tiers !== void 0) {
39600
39736
  const tiers = {};
39601
- for (const tier of ["fable", "opus", "sonnet", "haiku"]) {
39737
+ for (const tier of CLAUDE_TIERS) {
39602
39738
  const ref = layer.tiers[tier];
39603
39739
  const inherited = current?.tiers?.[tier];
39604
39740
  if (ref !== null && ref !== void 0) {
@@ -46606,6 +46742,30 @@ var init_catalogueCredential = __esm({
46606
46742
  }
46607
46743
  });
46608
46744
 
46745
+ // src/models/tiers.ts
46746
+ function claudeTierOf(model) {
46747
+ const lower = model.toLowerCase();
46748
+ return CLAUDE_TIERS.find((tier) => lower.includes(tier));
46749
+ }
46750
+ function claudeNameTier(model) {
46751
+ const name = model.toLowerCase().replace(/\[1m\]$/, "");
46752
+ const parts = name.split("-");
46753
+ return parts[0] === "claude" ? CLAUDE_TIERS.find((tier) => parts.includes(tier)) : CLAUDE_TIERS.find((tier) => name === tier);
46754
+ }
46755
+ var TIER_ENV_VARIABLES;
46756
+ var init_tiers = __esm({
46757
+ "src/models/tiers.ts"() {
46758
+ "use strict";
46759
+ init_schema();
46760
+ TIER_ENV_VARIABLES = Object.freeze({
46761
+ fable: "ANTHROPIC_DEFAULT_FABLE_MODEL",
46762
+ opus: "ANTHROPIC_DEFAULT_OPUS_MODEL",
46763
+ sonnet: "ANTHROPIC_DEFAULT_SONNET_MODEL",
46764
+ haiku: "ANTHROPIC_DEFAULT_HAIKU_MODEL"
46765
+ });
46766
+ }
46767
+ });
46768
+
46609
46769
  // src/selection/engine.ts
46610
46770
  function compareMaybe(left, right, preferHigh) {
46611
46771
  if (left === void 0 && right === void 0) {
@@ -47457,7 +47617,7 @@ function resolveName(requested, config2) {
47457
47617
  if (isBackendModelName(stripped)) {
47458
47618
  return { candidates: [stripped], tier: void 0 };
47459
47619
  }
47460
- const tier = CLAUDE_TIERS.find((candidate) => lower.includes(candidate));
47620
+ const tier = claudeTierOf(stripped);
47461
47621
  return tier === void 0 ? { candidates: [config2.defaultModel], tier: void 0 } : { candidates: config2.models[tier], tier };
47462
47622
  }
47463
47623
  function candidateStages(requested, config2) {
@@ -47692,6 +47852,7 @@ var init_translate = __esm({
47692
47852
  "use strict";
47693
47853
  import_node_crypto18 = require("node:crypto");
47694
47854
  init_identity2();
47855
+ init_tiers();
47695
47856
  init_engine();
47696
47857
  init_quota();
47697
47858
  init_signatures();
@@ -47738,8 +47899,7 @@ function mapModel(requested, config2) {
47738
47899
  if (requested.startsWith("gpt-")) {
47739
47900
  return requested;
47740
47901
  }
47741
- const lower = requested.toLowerCase();
47742
- const tier = CLAUDE_TIERS.find((candidate) => lower.includes(candidate));
47902
+ const tier = claudeTierOf(requested);
47743
47903
  return tier === void 0 ? config2.defaultModel : config2.models[tier];
47744
47904
  }
47745
47905
  function isRequestableEffort(value3) {
@@ -47888,6 +48048,7 @@ var init_translate2 = __esm({
47888
48048
  "src/codex/translate.ts"() {
47889
48049
  "use strict";
47890
48050
  import_node_crypto19 = require("node:crypto");
48051
+ init_tiers();
47891
48052
  init_schema();
47892
48053
  init_anthropic();
47893
48054
  REQUESTABLE_EFFORTS = ["low", "medium", "high"];
@@ -48017,7 +48178,7 @@ function safeExpand(name, models) {
48017
48178
  function modelPickerSettingsFromRows(options, replaceBuiltInOptions) {
48018
48179
  return options.length === 0 ? void 0 : JSON.stringify({ modelPicker: { options, replaceBuiltInOptions } });
48019
48180
  }
48020
- var TIER_BEHAVES_AS, TIER_ENV_VARIABLES;
48181
+ var TIER_BEHAVES_AS;
48021
48182
  var init_modelPicker = __esm({
48022
48183
  "src/launcher/modelPicker.ts"() {
48023
48184
  "use strict";
@@ -48028,18 +48189,13 @@ var init_modelPicker = __esm({
48028
48189
  init_identity2();
48029
48190
  init_families();
48030
48191
  init_modelsStore();
48192
+ init_tiers();
48031
48193
  TIER_BEHAVES_AS = Object.freeze({
48032
48194
  fable: "claude-fable-5-1",
48033
48195
  opus: "claude-opus-5-5",
48034
48196
  sonnet: "claude-sonnet-5-5",
48035
48197
  haiku: "claude-haiku-5-5"
48036
48198
  });
48037
- TIER_ENV_VARIABLES = Object.freeze({
48038
- fable: "ANTHROPIC_DEFAULT_FABLE_MODEL",
48039
- opus: "ANTHROPIC_DEFAULT_OPUS_MODEL",
48040
- sonnet: "ANTHROPIC_DEFAULT_SONNET_MODEL",
48041
- haiku: "ANTHROPIC_DEFAULT_HAIKU_MODEL"
48042
- });
48043
48199
  }
48044
48200
  });
48045
48201
 
@@ -74444,7 +74600,7 @@ var init_package = __esm({
74444
74600
  "package.json"() {
74445
74601
  package_default = {
74446
74602
  name: "claude-use",
74447
- version: "14.0.4",
74603
+ version: "14.2.0",
74448
74604
  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.",
74449
74605
  license: "MIT",
74450
74606
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -75776,6 +75932,7 @@ function buildEnv(params) {
75776
75932
  launcherHeaders
75777
75933
  );
75778
75934
  inject("NODE_EXTRA_CA_CERTS", params.frontdoor.trustBundlePath);
75935
+ inject("CLAUDE_CODE_GATEWAY_HINT_HEADERS", "1");
75779
75936
  inject("HTTPS_PROXY", connectProxyUrl(params.frontdoor.connectPort, params.frontdoor.sessionToken));
75780
75937
  const bypassed = [...LOOPBACK_HOSTS, ...params.proxyBypass ?? []];
75781
75938
  for (const list2 of ["NO_PROXY", "no_proxy"]) {
@@ -131452,7 +131609,6 @@ function showSession(fs38, configDirOf, identities, query, onlyIdentity) {
131452
131609
  }
131453
131610
 
131454
131611
  // src/frontdoor/commands.ts
131455
- init_identityStore();
131456
131612
  init_realPorts();
131457
131613
 
131458
131614
  // src/headroom/keeper.ts
@@ -132404,14 +132560,15 @@ init_route();
132404
132560
  function singleValue(value3) {
132405
132561
  return typeof value3 === "string" ? value3 : void 0;
132406
132562
  }
132407
- function admitLaunch(isLiveToken, identityOfToken) {
132563
+ function admitLaunch(isLiveToken, identityOfToken, launchOfToken) {
132408
132564
  return (request7) => {
132409
132565
  const token = singleValue(request7.headers[AUTH_HEADER]);
132410
132566
  if (token === void 0 || !isLiveToken(token)) {
132411
132567
  return { ok: false, message: "agent-shim front door: this request carries no capability from a live agent-shim launch" };
132412
132568
  }
132413
132569
  const identity = identityOfToken(token);
132414
- return identity === void 0 ? { ok: true, headers: { ...request7.forwardable } } : { ok: true, headers: { ...request7.forwardable }, identity };
132570
+ const launch = launchOfToken(token);
132571
+ return { ok: true, headers: { ...request7.forwardable }, ...identity === void 0 ? {} : { identity }, ...launch === void 0 ? {} : { launch } };
132415
132572
  };
132416
132573
  }
132417
132574
  function admitHop(hopSecret, custody) {
@@ -132434,7 +132591,7 @@ function createDoorPipelines(deps) {
132434
132591
  resolveRoute: deps.resolveRoute,
132435
132592
  // The response middleware hook point, where usage tracking registers. The direct listener registers none, because its responses are consumed by headroom, not by the client: the entry the client sees is where observation belongs, and observing both would record every hopped request twice.
132436
132593
  responseObservers: deps.responseObservers,
132437
- admit: admitLaunch(deps.isLiveToken, deps.identityOfToken),
132594
+ admit: admitLaunch(deps.isLiveToken, deps.identityOfToken, deps.launchOfToken),
132438
132595
  headroom: { headroomSocket: deps.headroomSocket, hopSecret: deps.hopSecret, custody: deps.custody, log: deps.log },
132439
132596
  headroomDecision: deps.headroomDecision,
132440
132597
  canonicalProvider: deps.canonicalProvider,
@@ -145236,12 +145393,14 @@ function createLiveSessionRegistry(ports) {
145236
145393
  let tokens = /* @__PURE__ */ new Set();
145237
145394
  let byToken = /* @__PURE__ */ new Map();
145238
145395
  let bySessionId = /* @__PURE__ */ new Map();
145396
+ let launches = /* @__PURE__ */ new Set();
145239
145397
  const recordNames = () => fs38.readdir(sessionsDir).filter(isSessionRecordName);
145240
145398
  const rebuildIndexes = () => {
145241
145399
  const records = [...known.values()].flatMap(({ record: record3 }) => record3 === void 0 ? [] : [record3]);
145242
145400
  tokens = new Set(records.map((record3) => record3.token));
145243
145401
  byToken = new Map(records.map((record3) => [record3.token, record3]));
145244
145402
  bySessionId = new Map(records.flatMap((record3) => record3.sessionId === void 0 ? [] : [[record3.sessionId, record3]]));
145403
+ launches = new Set(records.map(launchKeyOf));
145245
145404
  };
145246
145405
  const load = (name, stat2) => {
145247
145406
  known.set(name, { stat: { mtimeMs: stat2.mtimeMs, sizeBytes: stat2.sizeBytes }, record: readFrontDoorSessionRecord(fs38, sessionsDir, name) });
@@ -145283,6 +145442,11 @@ function createLiveSessionRegistry(ports) {
145283
145442
  const held = bySessionId.get(sessionId) ?? (reconcile() ? bySessionId.get(sessionId) : void 0);
145284
145443
  return held?.models;
145285
145444
  },
145445
+ launchOfToken: (token) => {
145446
+ const held = byToken.get(token) ?? (reconcile() ? byToken.get(token) : void 0);
145447
+ return held?.sessionId === void 0 ? void 0 : { pid: held.pid, startedAt: held.startedAt };
145448
+ },
145449
+ holdsLaunch: (launch) => launches.has(launchKeyOf(launch)) || reconcile() && launches.has(launchKeyOf(launch)),
145286
145450
  rescan: () => {
145287
145451
  known.clear();
145288
145452
  for (const name of recordNames()) {
@@ -145786,6 +145950,387 @@ async function hopOnce(request7, response, target, body, mayRetry) {
145786
145950
  });
145787
145951
  }
145788
145952
 
145953
+ // src/frontdoor/mainLoopRoute.ts
145954
+ var import_node_stream3 = require("node:stream");
145955
+ init_http();
145956
+ init_schema2();
145957
+ init_route();
145958
+
145959
+ // src/frontdoor/topLevelModel.ts
145960
+ var WHITESPACE = /* @__PURE__ */ new Set([" ", " ", "\n", "\r"]);
145961
+ function endOfString(text5, from) {
145962
+ for (let at2 = from + 1; at2 < text5.length; at2 += 1) {
145963
+ if (text5[at2] === "\\") {
145964
+ at2 += 1;
145965
+ } else if (text5[at2] === '"') {
145966
+ return at2 + 1;
145967
+ }
145968
+ }
145969
+ return void 0;
145970
+ }
145971
+ function skipWhitespace(text5, from) {
145972
+ let at2 = from;
145973
+ while (at2 < text5.length && WHITESPACE.has(text5[at2] ?? "")) {
145974
+ at2 += 1;
145975
+ }
145976
+ return at2;
145977
+ }
145978
+ function topLevelModel(text5) {
145979
+ let at2 = skipWhitespace(text5, 0);
145980
+ if (text5[at2] !== "{") {
145981
+ return void 0;
145982
+ }
145983
+ let depth = 0;
145984
+ while (at2 < text5.length) {
145985
+ const character = text5[at2];
145986
+ if (character === '"') {
145987
+ const end = endOfString(text5, at2);
145988
+ if (end === void 0) {
145989
+ return void 0;
145990
+ }
145991
+ const afterKey = skipWhitespace(text5, end);
145992
+ if (depth === 1 && text5[afterKey] === ":" && text5.slice(at2, end) === '"model"') {
145993
+ const valueStart = skipWhitespace(text5, afterKey + 1);
145994
+ if (text5[valueStart] === '"') {
145995
+ const valueEnd = endOfString(text5, valueStart);
145996
+ if (valueEnd === void 0) {
145997
+ return void 0;
145998
+ }
145999
+ const value3 = text5.slice(valueStart + 1, valueEnd - 1);
146000
+ return value3 === "" ? void 0 : { value: value3, start: valueStart, end: valueEnd };
146001
+ }
146002
+ return void 0;
146003
+ }
146004
+ at2 = end;
146005
+ continue;
146006
+ }
146007
+ if (character === "{" || character === "[") {
146008
+ depth += 1;
146009
+ } else if (character === "}" || character === "]") {
146010
+ depth -= 1;
146011
+ if (depth === 0) {
146012
+ return void 0;
146013
+ }
146014
+ }
146015
+ at2 += 1;
146016
+ }
146017
+ return void 0;
146018
+ }
146019
+
146020
+ // src/frontdoor/requestScan.ts
146021
+ var import_node_stream2 = require("node:stream");
146022
+ var import_node_string_decoder = require("node:string_decoder");
146023
+ var BYTES_PER_KIB2 = 1024;
146024
+ var SCAN_KIB = 64;
146025
+ var REQUEST_SCAN_CAP_BYTES = SCAN_KIB * BYTES_PER_KIB2;
146026
+ async function scanRequestHead(request7, wholeBody = false) {
146027
+ const body = request7.body;
146028
+ if (body.readableEnded) {
146029
+ throw new Error("the request body was already read to its end, so its head cannot be scanned again");
146030
+ }
146031
+ const head = [];
146032
+ let seen = 0;
146033
+ let text5 = "";
146034
+ const decoder = new import_node_string_decoder.StringDecoder("utf8");
146035
+ let decided = false;
146036
+ let ended = false;
146037
+ let error63;
146038
+ const replay = new import_node_stream2.PassThrough();
146039
+ replay.on("error", () => void 0);
146040
+ const modelIn = () => topLevelModel(text5)?.value;
146041
+ const settled = new Promise((resolve3) => {
146042
+ const settle2 = () => {
146043
+ const model = modelIn();
146044
+ const hasImage = /"type"\s*:\s*"image"/.test(text5);
146045
+ for (const chunk2 of head) {
146046
+ replay.write(chunk2);
146047
+ }
146048
+ const maxTokens = /"max_tokens"\s*:\s*([0-9]+)/.exec(text5)?.[1];
146049
+ resolve3({
146050
+ ...model === void 0 ? {} : { model },
146051
+ headBytes: seen,
146052
+ hasImage,
146053
+ toolsPresent: /"tools"\s*:\s*\[\s*\{/.test(text5),
146054
+ thinking: /"thinking"\s*:\s*\{\s*"type"\s*:\s*"enabled"/.test(text5),
146055
+ ...maxTokens === void 0 ? {} : { maxTokens: Number(maxTokens) },
146056
+ isCountTokens: request7.url.includes("/v1/messages/count_tokens"),
146057
+ ...wholeBody ? { whole: true, text: text5 } : {},
146058
+ replayed: { ...request7, body: replay }
146059
+ });
146060
+ };
146061
+ body.on("data", (chunk2) => {
146062
+ if (decided) {
146063
+ if (!replay.write(chunk2)) {
146064
+ body.pause();
146065
+ replay.once("drain", () => {
146066
+ body.resume();
146067
+ });
146068
+ }
146069
+ return;
146070
+ }
146071
+ head.push(chunk2);
146072
+ seen += chunk2.length;
146073
+ text5 += decoder.write(chunk2);
146074
+ if (!wholeBody && (modelIn() !== void 0 || seen >= REQUEST_SCAN_CAP_BYTES)) {
146075
+ decided = true;
146076
+ settle2();
146077
+ }
146078
+ });
146079
+ body.on("end", () => {
146080
+ ended = true;
146081
+ text5 += decoder.end();
146082
+ if (!decided) {
146083
+ decided = true;
146084
+ settle2();
146085
+ }
146086
+ replay.end();
146087
+ });
146088
+ body.on("error", (cause) => {
146089
+ error63 = cause;
146090
+ if (!decided) {
146091
+ decided = true;
146092
+ settle2();
146093
+ }
146094
+ replay.destroy(cause);
146095
+ });
146096
+ body.on("close", () => {
146097
+ if (!decided && !ended && error63 === void 0) {
146098
+ decided = true;
146099
+ settle2();
146100
+ }
146101
+ });
146102
+ });
146103
+ return await settled;
146104
+ }
146105
+
146106
+ // src/frontdoor/mainLoopRoute.ts
146107
+ init_tiers();
146108
+ init_state();
146109
+ var REQUEST_CLASS_HEADER = "x-claude-code-request-class";
146110
+ var AGENT_ID_HEADER = "x-claude-code-agent-id";
146111
+ var MAIN_REQUEST_CLASS = "main";
146112
+ function requestClassOf(headers) {
146113
+ const agentId = internalHeaderValue(headers, AGENT_ID_HEADER);
146114
+ const hasAgentId = agentId !== void 0 && agentId !== "";
146115
+ const value3 = internalHeaderValue(headers, REQUEST_CLASS_HEADER);
146116
+ if (value3 === void 0) {
146117
+ return hasAgentId ? "subagent" : void 0;
146118
+ }
146119
+ const parsed = RequestClassSchema.safeParse(value3);
146120
+ const stated = parsed.success ? parsed.data : "unknown";
146121
+ return hasAgentId && stated === MAIN_REQUEST_CLASS ? "subagent" : stated;
146122
+ }
146123
+ function sameContext(a10, b) {
146124
+ return a10.kind === b.kind && (a10.kind !== "provider" || b.kind === "provider" && a10.provider === b.provider) && a10.credential === b.credential && a10.requestedModel === b.requestedModel && a10.servedModel === b.servedModel;
146125
+ }
146126
+ function createMainLoopRouteRecord(ports) {
146127
+ const routes = /* @__PURE__ */ new Map();
146128
+ const failed = /* @__PURE__ */ new Set();
146129
+ const dropEnded = (except) => {
146130
+ for (const [held, entry] of routes) {
146131
+ if (held !== except && !ports.holdsLaunch(entry.launch)) {
146132
+ routes.delete(held);
146133
+ failed.delete(held);
146134
+ }
146135
+ }
146136
+ };
146137
+ const persist = (launch, key, route, persisted) => {
146138
+ if (persisted !== void 0 && sameContext(persisted, route)) {
146139
+ return persisted;
146140
+ }
146141
+ try {
146142
+ ports.stored.write(launch, route);
146143
+ failed.delete(key);
146144
+ return route;
146145
+ } catch (error63) {
146146
+ if (!failed.has(key)) {
146147
+ failed.add(key);
146148
+ ports.log(`front door: could not record where launch ${String(launch.pid)}'s main loop went, so a door restart would send its helpers to the route last stored: ${error63 instanceof Error ? error63.message : String(error63)}`);
146149
+ }
146150
+ return persisted;
146151
+ }
146152
+ };
146153
+ const load = (launch) => {
146154
+ const identity = ports.stored.identity(launch);
146155
+ let stored2;
146156
+ try {
146157
+ stored2 = ports.stored.read(launch);
146158
+ } catch (error63) {
146159
+ ports.log(`front door: could not read where launch ${String(launch.pid)}'s main loop went (${error63 instanceof Error ? error63.message : String(error63)}), so its helpers go the route the launch was launched on until its next main-loop request`);
146160
+ }
146161
+ return { launch, route: stored2, persisted: stored2, identity };
146162
+ };
146163
+ return {
146164
+ record: (launch, route) => {
146165
+ const key = launchKeyOf(launch);
146166
+ dropEnded(key);
146167
+ const before = routes.get(key);
146168
+ const persisted = persist(launch, key, route, before?.persisted);
146169
+ const written = persisted !== void 0 && sameContext(persisted, route) && (before?.persisted === void 0 || !sameContext(before.persisted, route));
146170
+ routes.set(key, { launch, route, persisted, identity: written ? ports.stored.identity(launch) : before?.identity });
146171
+ },
146172
+ routeOf: (launch) => {
146173
+ const key = launchKeyOf(launch);
146174
+ const entry = routes.get(key);
146175
+ if (entry === void 0) {
146176
+ dropEnded(key);
146177
+ const loaded = load(launch);
146178
+ routes.set(key, loaded);
146179
+ return loaded.route;
146180
+ }
146181
+ if (entry.route !== void 0 && (entry.persisted === void 0 || !sameContext(entry.persisted, entry.route))) {
146182
+ const persisted = persist(launch, key, entry.route, entry.persisted);
146183
+ const written = persisted !== void 0 && sameContext(persisted, entry.route);
146184
+ routes.set(key, { ...entry, persisted, identity: written ? ports.stored.identity(launch) : entry.identity });
146185
+ return entry.route;
146186
+ }
146187
+ const current = ports.stored.identity(launch);
146188
+ if (current !== void 0 && current !== entry.identity) {
146189
+ const loaded = load(launch);
146190
+ routes.set(key, loaded);
146191
+ return loaded.route;
146192
+ }
146193
+ return entry.route;
146194
+ }
146195
+ };
146196
+ }
146197
+ function isInferencePath(path101) {
146198
+ return path101 === "/v1/messages" || path101.startsWith("/v1/messages/");
146199
+ }
146200
+ function servedProviderOf(url2) {
146201
+ return parseProviderPath(new URL(url2, "http://127.0.0.1").pathname)?.provider;
146202
+ }
146203
+ var ANTHROPIC_PREFIX = "anthropic/";
146204
+ function isBareClaudeName(model) {
146205
+ return !model.includes("/") && claudeNameTier(model) !== void 0;
146206
+ }
146207
+ function boundedName(text5) {
146208
+ return text5 === void 0 || text5 === "" || text5.length > MAX_CONTEXT_TEXT_LENGTH ? void 0 : text5;
146209
+ }
146210
+ function followingMainLoop(resolve3, deps) {
146211
+ const contextOf = (route, credentialName, requested, served) => {
146212
+ const credential = boundedName(credentialName);
146213
+ const facts = { ...credential === void 0 ? {} : { credential }, ...boundedName(requested) === void 0 ? {} : { requestedModel: boundedName(requested) }, ...boundedName(served) === void 0 ? {} : { servedModel: boundedName(served) } };
146214
+ return { ...route, ...facts };
146215
+ };
146216
+ const toAnthropic = async (base, requested) => {
146217
+ const served = requested.slice(ANTHROPIC_PREFIX.length);
146218
+ const scan = await scanRequestHead(base);
146219
+ const rewritten = withModelInHead(scan.replayed ?? base, scan.headBytes, requested, served);
146220
+ const resolution = await resolve3({ ...rewritten, url: base.url });
146221
+ return { resolution: resolution.ok ? { ...resolution, requestedModel: requested } : resolution, served };
146222
+ };
146223
+ const toProvider = async (base, provider, session) => {
146224
+ const scan = base.body.readableEnded ? { model: void 0, headBytes: 0, replayed: void 0 } : await scanRequestHead(base);
146225
+ const requested = scan.model;
146226
+ const { model: choice, credential } = deps.providerMapping(provider, session, requested ?? "");
146227
+ if (choice.kind === "refused") {
146228
+ return { resolution: { ok: false, status: HTTP_STATUS.badRequest, message: choice.message }, requested, served: void 0, credential };
146229
+ }
146230
+ const replayed = scan.replayed ?? base;
146231
+ const body = choice.kind === "as-is" || requested === void 0 ? replayed : withModelInHead(replayed, scan.headBytes, requested, choice.model);
146232
+ const scoped = { ...body, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(provider)}${base.url}` };
146233
+ const resolution = await resolve3(scoped);
146234
+ if (!resolution.ok) {
146235
+ return { resolution, requested, served: void 0, credential };
146236
+ }
146237
+ if (resolution.request === void 0) {
146238
+ return { resolution: { ok: false, status: HTTP_STATUS.internalServerError, message: "the provider resolver served a request without saying which request it served" }, requested, served: void 0, credential };
146239
+ }
146240
+ return { resolution: { ...resolution, request: resolution.request, ...requested === void 0 ? {} : { requestedModel: requested } }, requested, served: choice.kind === "mapped" ? choice.model : requested, credential };
146241
+ };
146242
+ return async (request7) => {
146243
+ const { launch, provider } = request7.session;
146244
+ const path101 = new URL(request7.url, "http://127.0.0.1").pathname;
146245
+ if (launch === void 0 || provider !== void 0 || !isInferencePath(path101)) {
146246
+ return await resolve3(request7);
146247
+ }
146248
+ const requestClass = requestClassOf(request7.headers);
146249
+ const current = deps.record.routeOf(launch);
146250
+ if (requestClass !== void 0 && requestClass !== MAIN_REQUEST_CLASS) {
146251
+ const scan = await scanRequestHead(request7);
146252
+ const helper = scan.replayed ?? request7;
146253
+ if (scan.model?.startsWith(ANTHROPIC_PREFIX) === true && !deps.definesProvider("anthropic")) {
146254
+ return (await toAnthropic(helper, scan.model)).resolution;
146255
+ }
146256
+ if (current === void 0 || current.kind === "anthropic") {
146257
+ return await resolve3(helper);
146258
+ }
146259
+ return (await toProvider(helper, current.provider, request7.session)).resolution;
146260
+ }
146261
+ const resolution = await resolve3(request7);
146262
+ if (!resolution.ok) {
146263
+ return resolution;
146264
+ }
146265
+ const requested = resolution.requestedModel;
146266
+ const served = servedProviderOf(resolution.request?.url ?? request7.url);
146267
+ if (served === void 0) {
146268
+ const base = resolution.request ?? request7;
146269
+ if (requested?.startsWith(ANTHROPIC_PREFIX) === true && !deps.definesProvider("anthropic")) {
146270
+ const placed = await toAnthropic(base, requested);
146271
+ if (placed.resolution.ok) {
146272
+ deps.record.record(launch, contextOf({ kind: "anthropic" }, deps.loginOf(request7.session), requested, placed.served));
146273
+ }
146274
+ return placed.resolution;
146275
+ }
146276
+ if (current?.kind === "provider") {
146277
+ const placed = await toProvider(base, current.provider, request7.session);
146278
+ if (placed.resolution.ok && requested !== void 0 && isBareClaudeName(requested)) {
146279
+ deps.record.record(launch, contextOf({ kind: "provider", provider: current.provider }, placed.credential, requested, placed.served));
146280
+ }
146281
+ return placed.resolution;
146282
+ }
146283
+ }
146284
+ const route = served === void 0 ? { kind: "anthropic" } : { kind: "provider", provider: served };
146285
+ const qualified = served !== void 0 && requested?.startsWith(`${served}/`) === true ? requested.slice(served.length + 1) : void 0;
146286
+ const servedModel = qualified ?? (served === void 0 ? requested : void 0);
146287
+ const credential = served === void 0 ? deps.loginOf(request7.session) : deps.providerMapping(served, request7.session, "").credential;
146288
+ deps.record.record(launch, contextOf(route, credential, requested, servedModel));
146289
+ return resolution;
146290
+ };
146291
+ }
146292
+ function asBytes(value3) {
146293
+ return Buffer.from(value3, "utf8").toString("latin1");
146294
+ }
146295
+ function withModelInHead(request7, headBytes, from, to2) {
146296
+ const rewriteHead = (head) => {
146297
+ const text5 = head.toString("latin1");
146298
+ const found = topLevelModel(text5);
146299
+ return found?.value === asBytes(from) ? Buffer.from(`${text5.slice(0, found.start)}${asBytes(JSON.stringify(to2))}${text5.slice(found.end)}`, "latin1") : head;
146300
+ };
146301
+ async function* rewritten() {
146302
+ let held = Buffer.alloc(0);
146303
+ let headDone = false;
146304
+ const chunks = request7.body;
146305
+ for await (const piece of chunks) {
146306
+ if (!Buffer.isBuffer(piece)) {
146307
+ throw new TypeError("a request body chunk is not a Buffer");
146308
+ }
146309
+ if (headDone) {
146310
+ yield piece;
146311
+ continue;
146312
+ }
146313
+ held = Buffer.concat([held, piece]);
146314
+ if (held.length >= headBytes) {
146315
+ headDone = true;
146316
+ yield rewriteHead(held.subarray(0, headBytes));
146317
+ yield held.subarray(headBytes);
146318
+ }
146319
+ }
146320
+ if (!headDone) {
146321
+ yield rewriteHead(held);
146322
+ }
146323
+ }
146324
+ const headers = Object.fromEntries(Object.entries(request7.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
146325
+ return { ...request7, headers, body: import_node_stream3.Readable.from(rewritten()) };
146326
+ }
146327
+ function withModel(request7, text5, from, to2) {
146328
+ const found = topLevelModel(text5);
146329
+ const rewritten = found?.value === from ? `${text5.slice(0, found.start)}${JSON.stringify(to2)}${text5.slice(found.end)}` : text5;
146330
+ const headers = Object.fromEntries(Object.entries(request7.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
146331
+ return { ...request7, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
146332
+ }
146333
+
145789
146334
  // src/frontdoor/pipeline.ts
145790
146335
  init_route();
145791
146336
  function errorTypeFor(status) {
@@ -145865,7 +146410,7 @@ function createRoutedResponse(response, context) {
145865
146410
  start: (status, headers) => {
145866
146411
  for (const observe of deps.responseObservers) {
145867
146412
  try {
145868
- const body = observe({ session, route, method: request7.method, path: request7.path, servedPath: context.servedPath, receivedAt: request7.receivedAt, viaHeadroom: request7.viaHeadroom, lineage: request7.thread.lineage, modelChoice: request7.modelChoice.value, requestedModel: request7.requestedModel.value, clientSessionId: request7.clientSessionId, status, headers });
146413
+ const body = observe({ session, route, method: request7.method, path: request7.path, servedPath: context.servedPath, receivedAt: request7.receivedAt, viaHeadroom: request7.viaHeadroom, lineage: request7.thread.lineage, modelChoice: request7.modelChoice.value, requestedModel: request7.requestedModel.value, clientSessionId: request7.clientSessionId, requestClass: request7.requestClass, status, headers });
145869
146414
  if (body !== void 0) {
145870
146415
  bodyObservers.push(body);
145871
146416
  }
@@ -145910,7 +146455,7 @@ function createRoutedResponse(response, context) {
145910
146455
  }
145911
146456
  async function serveRouted(incoming, deps) {
145912
146457
  const request7 = { ...incoming, url: withCanonicalProviderTarget(incoming.url, deps.canonicalProvider) };
145913
- const observed = { method: request7.method, path: pathOf(request7.url), receivedAt: deps.now(), viaHeadroom: false, thread: { lineage: void 0 }, modelChoice: { value: void 0 }, requestedModel: { value: void 0 }, clientSessionId: clientSessionIdOf(incoming.headers) };
146458
+ const observed = { method: request7.method, path: pathOf(request7.url), receivedAt: deps.now(), viaHeadroom: false, thread: { lineage: void 0 }, modelChoice: { value: void 0 }, requestedModel: { value: void 0 }, clientSessionId: clientSessionIdOf(incoming.headers), requestClass: requestClassOf(incoming.headers) };
145914
146459
  const identity = identifyRequest(request7.headers);
145915
146460
  const identified = { ...identity, session: { ...identity.session, provider: identity.session.provider === void 0 ? void 0 : deps.canonicalProvider(identity.session.provider) } };
145916
146461
  const admission = deps.admit({ url: request7.url, headers: request7.headers, forwardable: identified.forwardableHeaders });
@@ -145927,7 +146472,11 @@ async function serveRouted(incoming, deps) {
145927
146472
  headers: admission.headers,
145928
146473
  body: request7.body,
145929
146474
  signal: request7.signal,
145930
- session: identified.session.identity === void 0 && admission.identity !== void 0 ? { ...identified.session, identity: admission.identity } : identified.session
146475
+ session: {
146476
+ ...identified.session,
146477
+ ...identified.session.identity === void 0 && admission.identity !== void 0 ? { identity: admission.identity } : {},
146478
+ ...admission.launch === void 0 ? {} : { launch: admission.launch }
146479
+ }
145931
146480
  };
145932
146481
  const resolution = await deps.resolveRoute(routed);
145933
146482
  if (!resolution.ok) {
@@ -145941,6 +146490,9 @@ async function serveRouted(incoming, deps) {
145941
146490
  if (resolution.modelChoice !== void 0) {
145942
146491
  observed.modelChoice.value = resolution.modelChoice;
145943
146492
  }
146493
+ if (resolution.requestedModel !== void 0) {
146494
+ observed.requestedModel.value = resolution.requestedModel;
146495
+ }
145944
146496
  const wantsHeadroom = headroom !== void 0 && await deps.headroomDecision.decide(identified.session.sessionId, identified.session.headroom, deps.now(), async () => await headroomReady(headroom, request7.signal));
145945
146497
  const viaHeadroom = wantsHeadroom && resolution.route.headroomEligible && deps.headroom !== void 0;
145946
146498
  const response = createRoutedResponse(request7.response, { deps, session: identified.session, route: resolution.route.name, request: { ...observed, viaHeadroom }, servedPath: pathOf(resolution.request?.url ?? request7.url) });
@@ -147651,88 +148203,7 @@ init_engine();
147651
148203
  init_families();
147652
148204
  init_identity2();
147653
148205
  init_route();
147654
- var import_node_stream3 = require("node:stream");
147655
-
147656
- // src/frontdoor/requestScan.ts
147657
- var import_node_stream2 = require("node:stream");
147658
- var BYTES_PER_KIB2 = 1024;
147659
- var SCAN_KIB = 64;
147660
- var REQUEST_SCAN_CAP_BYTES = SCAN_KIB * BYTES_PER_KIB2;
147661
- async function scanRequestHead(request7, wholeBody = false) {
147662
- const body = request7.body;
147663
- const head = [];
147664
- let seen = 0;
147665
- let text5 = "";
147666
- let decided = false;
147667
- let ended = false;
147668
- let error63;
147669
- const replay = new import_node_stream2.PassThrough();
147670
- replay.on("error", () => void 0);
147671
- const modelIn = () => /"model"\s*:\s*"([^"]+)"/.exec(text5)?.[1];
147672
- const settled = new Promise((resolve3) => {
147673
- const settle2 = () => {
147674
- const model = modelIn();
147675
- const hasImage = /"type"\s*:\s*"image"/.test(text5);
147676
- for (const chunk2 of head) {
147677
- replay.write(chunk2);
147678
- }
147679
- const maxTokens = /"max_tokens"\s*:\s*([0-9]+)/.exec(text5)?.[1];
147680
- resolve3({
147681
- ...model === void 0 ? {} : { model },
147682
- hasImage,
147683
- toolsPresent: /"tools"\s*:\s*\[\s*\{/.test(text5),
147684
- thinking: /"thinking"\s*:\s*\{\s*"type"\s*:\s*"enabled"/.test(text5),
147685
- ...maxTokens === void 0 ? {} : { maxTokens: Number(maxTokens) },
147686
- isCountTokens: request7.url.includes("/v1/messages/count_tokens"),
147687
- ...wholeBody ? { whole: true, text: text5 } : {},
147688
- replayed: { ...request7, body: replay }
147689
- });
147690
- };
147691
- body.on("data", (chunk2) => {
147692
- if (decided) {
147693
- if (!replay.write(chunk2)) {
147694
- body.pause();
147695
- replay.once("drain", () => {
147696
- body.resume();
147697
- });
147698
- }
147699
- return;
147700
- }
147701
- head.push(chunk2);
147702
- seen += chunk2.length;
147703
- text5 += chunk2.toString("utf8");
147704
- if (!wholeBody && (modelIn() !== void 0 || seen >= REQUEST_SCAN_CAP_BYTES)) {
147705
- decided = true;
147706
- settle2();
147707
- }
147708
- });
147709
- body.on("end", () => {
147710
- ended = true;
147711
- if (!decided) {
147712
- decided = true;
147713
- settle2();
147714
- }
147715
- replay.end();
147716
- });
147717
- body.on("error", (cause) => {
147718
- error63 = cause;
147719
- if (!decided) {
147720
- decided = true;
147721
- settle2();
147722
- }
147723
- replay.destroy(cause);
147724
- });
147725
- body.on("close", () => {
147726
- if (!decided && !ended && error63 === void 0) {
147727
- decided = true;
147728
- settle2();
147729
- }
147730
- });
147731
- });
147732
- return await settled;
147733
- }
147734
-
147735
- // src/frontdoor/providerRoute.ts
148206
+ init_tiers();
147736
148207
  var COULD_NOT_CONNECT_LOG_INTERVAL_MS = 6e4;
147737
148208
  var isRcSelfHostPath = (path101) => path101 === "/v1/code/sessions" || path101.startsWith("/v1/code/sessions/") || path101 === "/v1/sessions" || path101.startsWith("/v1/sessions/");
147738
148209
  function scopeSessionProviderPath(request7) {
@@ -147996,7 +148467,7 @@ function createProviderRouteResolver(deps) {
147996
148467
  await route.serve({ ...request7, url: rewritten.url, headers: rewritten.headers, body: rewritten.body }, response);
147997
148468
  }
147998
148469
  });
147999
- return async (request7) => {
148470
+ const resolveByName = async (request7, noteRequestedModel) => {
148000
148471
  const scopedRequest = scopeSessionProviderPath(request7);
148001
148472
  const serveScoped = (resolution) => scopedRequest === request7 ? resolution : { ok: true, route: servingRewritten(resolution.route, scopedRequest) };
148002
148473
  let current = scopedRequest;
@@ -148024,6 +148495,7 @@ function createProviderRouteResolver(deps) {
148024
148495
  const resolvesNames = !nameResolved && !isRcSelfHostPath(path101);
148025
148496
  if (resolvesNames) {
148026
148497
  const scan2 = await scanRequestHead(current, true);
148498
+ noteRequestedModel(scan2.model);
148027
148499
  if (scan2.replayed === void 0) {
148028
148500
  const resolution = resolve3(current);
148029
148501
  return resolution.ok && replay !== void 0 ? { ok: true, route: servingRewritten(resolution.route, { ...replay, url: current.url }), request: { ...replay, url: current.url } } : resolution.ok ? serveScoped(resolution) : resolution;
@@ -148054,9 +148526,7 @@ function createProviderRouteResolver(deps) {
148054
148526
  return resolution2.ok ? { ok: true, route: servingRewritten(resolution2.route, { ...replay, url: current.url }), request: { ...replay, url: current.url }, ...modelChoice === void 0 ? {} : { modelChoice } } : resolution2;
148055
148527
  }
148056
148528
  if (requested !== void 0 && routed.model !== requested) {
148057
- const rewritten = (scan2.text ?? "").replace(new RegExp('"model":\\s*"' + requested.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + '"'), '"model":"' + routed.model + '"');
148058
- const headers = Object.fromEntries(Object.entries(replay.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
148059
- replay = { ...replay, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
148529
+ replay = withModel(replay, scan2.text ?? "", requested, routed.model);
148060
148530
  }
148061
148531
  if (routed.provider !== providerName) {
148062
148532
  const scopedPrefix = providerName === void 0 ? void 0 : `${PROVIDER_PATH_PREFIX}${encodeURIComponent(providerName)}`;
@@ -148083,6 +148553,7 @@ function createProviderRouteResolver(deps) {
148083
148553
  })
148084
148554
  );
148085
148555
  const scan = await scanRequestHead(current, whole);
148556
+ noteRequestedModel(scan.model);
148086
148557
  if (scan.replayed === void 0) {
148087
148558
  const resolution = resolve3(current);
148088
148559
  return resolution.ok && replay !== void 0 ? { ok: true, route: servingRewritten(resolution.route, { ...replay, url: current.url }), request: { ...replay, url: current.url } } : resolution.ok ? serveScoped(resolution) : resolution;
@@ -148110,15 +148581,50 @@ function createProviderRouteResolver(deps) {
148110
148581
  return resolution.ok ? { ok: true, route: servingRewritten(resolution.route, { ...replay, url: current.url }), request: { ...replay, url: current.url }, ...modelChoice === void 0 ? {} : { modelChoice } } : resolution;
148111
148582
  }
148112
148583
  if (matched.model !== void 0 && scan.text !== void 0 && scan.model !== void 0) {
148113
- const rewritten = scan.text.replace(new RegExp('"model":\\s*"' + scan.model.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + '"'), '"model":"' + matched.model + '"');
148114
- const headers = Object.fromEntries(Object.entries(replay.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
148115
- replay = { ...replay, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
148584
+ replay = withModel(replay, scan.text, scan.model, matched.model);
148116
148585
  }
148117
148586
  const rest = scoped === void 0 ? path101 : path101.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
148118
148587
  const query = current.url.includes("?") ? current.url.slice(current.url.indexOf("?")) : "";
148119
148588
  current = { ...current, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(matched.provider)}${rest}${query}`, body: replay.body, headers: replay.headers };
148120
148589
  }
148121
148590
  };
148591
+ const providerMapping = (provider, session, requested) => {
148592
+ const asIs = { kind: "as-is" };
148593
+ let definition;
148594
+ try {
148595
+ definition = loadProvider(deps.providersDir, provider, deps.fs);
148596
+ } catch {
148597
+ return { model: asIs, credential: void 0 };
148598
+ }
148599
+ if (definition === void 0) {
148600
+ return { model: asIs, credential: void 0 };
148601
+ }
148602
+ const credential = isRouterProvider(definition) ? void 0 : describeCredential(definition.credential);
148603
+ const tier = requested.includes("/") ? void 0 : claudeNameTier(requested);
148604
+ if (tier === void 0) {
148605
+ return { model: asIs, credential };
148606
+ }
148607
+ if (isHttpProvider(definition)) {
148608
+ const model = definition.env?.[TIER_ENV_VARIABLES[tier]];
148609
+ return { model: model === void 0 || model === "" ? asIs : { kind: "mapped", model: withoutContextMarker(model) }, credential };
148610
+ }
148611
+ if (!isRouterProvider(definition)) {
148612
+ return { model: asIs, credential };
148613
+ }
148614
+ const pointer = deps.models?.(session)?.tiers?.[tier];
148615
+ return { model: pointer === void 0 ? { kind: "refused", message: `provider "${provider}" routes by model name and the models block has no ${tier} tier pointer, so this ${tier}-tier request of the session cannot be routed; set models.tiers.${tier}` } : { kind: "mapped", model: pointer }, credential };
148616
+ };
148617
+ const loginOf = (session) => session.identity === void 0 ? "the launch's login" : `identity ${session.identity} login`;
148618
+ return followingMainLoop(
148619
+ async (request7) => {
148620
+ let requestedModel;
148621
+ const resolution = await resolveByName(request7, (model) => {
148622
+ requestedModel ??= model;
148623
+ });
148624
+ return resolution.ok && requestedModel !== void 0 ? { ...resolution, requestedModel } : resolution;
148625
+ },
148626
+ { record: deps.mainLoopRoutes, providerMapping, loginOf, definesProvider }
148627
+ );
148122
148628
  }
148123
148629
  function providerCredentialHeaders(credential) {
148124
148630
  return credential.target === "apiKey" ? { "x-api-key": credential.token } : { authorization: `Bearer ${credential.token}` };
@@ -152399,7 +152905,8 @@ function realFrontDoorSupervisorPorts(paths, respawnGeneration, lifecycle, track
152399
152905
  accountMoves: async (sessionId, to2, model) => await requestAccountMove({ fs: realFarmFs, paths, runningAmong: realRunningAmong, idOf: (name) => identityIdOf(paths, name), now: () => Date.now() }, sessionId, to2, model),
152400
152906
  ...rcSelfHostSurface === void 0 ? {} : { rcSelfHostRoute: rcSelfHostSurface.route },
152401
152907
  log,
152402
- now: () => Date.now()
152908
+ now: () => Date.now(),
152909
+ mainLoopRoutes: createMainLoopRouteRecord({ holdsLaunch: sessionRegistry.holdsLaunch, stored: launchRouteStore(realFarmFs, paths.frontdoorSessionsDir, log), log })
152403
152910
  }),
152404
152911
  rcTracker,
152405
152912
  rcHub
@@ -152554,6 +153061,7 @@ function realFrontDoorSupervisorPorts(paths, respawnGeneration, lifecycle, track
152554
153061
  resolveRoute,
152555
153062
  isLiveToken,
152556
153063
  identityOfToken: sessionRegistry.identityOf,
153064
+ launchOfToken: sessionRegistry.launchOfToken,
152557
153065
  canonicalProvider,
152558
153066
  responseObservers: [usageMiddleware],
152559
153067
  now: () => Date.now(),
@@ -153042,6 +153550,9 @@ var realHeadroomGet = async (target, requestPath, timeoutMs) => {
153042
153550
 
153043
153551
  // src/statusline/enrich.ts
153044
153552
  init_quota();
153553
+ function lastMainLoopRecord(records, sessionId) {
153554
+ return records.filter((record3) => record3.sessionId === sessionId && (record3.requestClass === void 0 || record3.requestClass === "main")).at(-1);
153555
+ }
153045
153556
  var FULL_PERCENT2 = 100;
153046
153557
  var MS_PER_SECOND18 = 1e3;
153047
153558
  function identityOf(env) {
@@ -157617,7 +158128,7 @@ function registerStatuslineCommand(program2, deps) {
157617
158128
  let modelChoice;
157618
158129
  if (sessionHeader !== void 0) {
157619
158130
  try {
157620
- const last = readUsageLog(realFarmFs, deps.paths.usageLogDir, { sinceMs: nowMs - ROUTED_TARGET_LOOKBACK_MS }).records.filter((record3) => record3.sessionId === sessionHeader).at(-1);
158131
+ const last = lastMainLoopRecord(readUsageLog(realFarmFs, deps.paths.usageLogDir, { sinceMs: nowMs - ROUTED_TARGET_LOOKBACK_MS }).records, sessionHeader);
157621
158132
  if (last?.model !== void 0) {
157622
158133
  if (last.provider !== providerName) {
157623
158134
  routedTarget = `${last.provider}/${last.model}`;