claudish 14.26.1 → 14.27.1

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.
Files changed (2) hide show
  1. package/dist/index.js +2609 -353
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -136,6 +136,7 @@ var init_config = __esm(() => {
136
136
  CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST",
137
137
  CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL: "_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL",
138
138
  CLAUDISH_SET_HOST_ROUTING_VARS: "CLAUDISH_SET_HOST_ROUTING_VARS",
139
+ CLAUDISH_SET_MODEL_VARS: "CLAUDISH_SET_MODEL_VARS",
139
140
  CLAUDISH_MODEL_OPUS: "CLAUDISH_MODEL_OPUS",
140
141
  CLAUDISH_MODEL_SONNET: "CLAUDISH_MODEL_SONNET",
141
142
  CLAUDISH_MODEL_HAIKU: "CLAUDISH_MODEL_HAIKU",
@@ -5153,6 +5154,22 @@ function acquireFileLockSync(path, opts) {
5153
5154
  function sleepSync(ms) {
5154
5155
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
5155
5156
  }
5157
+ async function withFileLock(path, opts, work) {
5158
+ let handle = null;
5159
+ try {
5160
+ handle = await acquireFileLock(path, opts);
5161
+ } catch (err) {
5162
+ if (opts.onUnavailable === "fail")
5163
+ throw err;
5164
+ opts.log?.(`[FileLock] proceeding unlocked: ${err?.message}`);
5165
+ handle = null;
5166
+ }
5167
+ try {
5168
+ return await work(handle);
5169
+ } finally {
5170
+ handle?.release();
5171
+ }
5172
+ }
5156
5173
  var defaultDeps, LOCK_RECORD_WIDTH = 256, FileLockUnavailableError, SYNC_LOCK_POLL_MS = 25;
5157
5174
  var init_file_lock = __esm(() => {
5158
5175
  defaultDeps = {
@@ -5525,7 +5542,7 @@ var init_env_placeholder = __esm(() => {
5525
5542
  });
5526
5543
 
5527
5544
  // src/version.ts
5528
- var VERSION = "14.26.1";
5545
+ var VERSION = "14.27.1";
5529
5546
 
5530
5547
  // src/redact.ts
5531
5548
  function isPlaceholder(value) {
@@ -14128,7 +14145,7 @@ var init_bundled_recommended_list = __esm(() => {
14128
14145
  }
14129
14146
  }
14130
14147
  },
14131
- fetchedAt: "2026-11-16T00:31:40.763Z",
14148
+ fetchedAt: "2026-11-16T12:10:44.345Z",
14132
14149
  format: 1,
14133
14150
  recommendations: {
14134
14151
  contractVersion: 3,
@@ -23334,11 +23351,25 @@ var init_gemini_api_format = __esm(() => {
23334
23351
  init_base_api_format();
23335
23352
  GeminiAPIFormat = class GeminiAPIFormat extends BaseAPIFormat {
23336
23353
  thinkingFromModelName;
23354
+ serverCallIds;
23337
23355
  constructor(modelId, wireFormat, options = {}) {
23338
23356
  super(modelId, wireFormat);
23339
23357
  this.thinkingFromModelName = options.thinkingFromModelName === true;
23358
+ this.serverCallIds = options.serverCallIds === true;
23340
23359
  }
23341
23360
  toolCallMap = new Map;
23361
+ functionResponsePart(toolInfo, text) {
23362
+ if (!this.serverCallIds) {
23363
+ return { functionResponse: { name: toolInfo.name, response: { content: text } } };
23364
+ }
23365
+ return {
23366
+ functionResponse: {
23367
+ ...toolInfo.callId ? { id: toolInfo.callId } : {},
23368
+ name: toolInfo.name,
23369
+ response: { output: text }
23370
+ }
23371
+ };
23372
+ }
23342
23373
  callIdOf = new WeakMap;
23343
23374
  convertMessages(claudeRequest, _filterIdentityFn) {
23344
23375
  const messages = [];
@@ -23429,25 +23460,11 @@ var init_gemini_api_format = __esm(() => {
23429
23460
  textParts.push(item.text);
23430
23461
  }
23431
23462
  }
23432
- parts.push({
23433
- functionResponse: {
23434
- name: toolInfo.name,
23435
- response: {
23436
- content: textParts.join(`
23437
- `) || "OK"
23438
- }
23439
- }
23440
- });
23463
+ parts.push(this.functionResponsePart(toolInfo, textParts.join(`
23464
+ `) || "OK"));
23441
23465
  parts.push(...imageParts);
23442
23466
  } else {
23443
- parts.push({
23444
- functionResponse: {
23445
- name: toolInfo.name,
23446
- response: {
23447
- content: typeof block.content === "string" ? block.content : JSON.stringify(block.content)
23448
- }
23449
- }
23450
- });
23467
+ parts.push(this.functionResponsePart(toolInfo, typeof block.content === "string" ? block.content : JSON.stringify(block.content)));
23451
23468
  }
23452
23469
  for (const part of parts.slice(firstResultPart)) {
23453
23470
  this.callIdOf.set(part, block.tool_use_id);
@@ -23468,12 +23485,14 @@ var init_gemini_api_format = __esm(() => {
23468
23485
  } else if (block.type === "tool_use") {
23469
23486
  const toolInfo = this.toolCallMap.get(block.id);
23470
23487
  let thoughtSignature = toolInfo?.thoughtSignature;
23471
- if (!thoughtSignature) {
23488
+ const sentUnsigned = this.serverCallIds && toolInfo?.fromResponse === true;
23489
+ if (!thoughtSignature && !sentUnsigned) {
23472
23490
  thoughtSignature = "skip_thought_signature_validator";
23473
23491
  log(`[GeminiAPIFormat] Using dummy thoughtSignature for tool ${block.name} (${block.id})`);
23474
23492
  }
23475
23493
  const functionCallPart = {
23476
23494
  functionCall: {
23495
+ ...this.serverCallIds && toolInfo?.callId ? { id: toolInfo.callId } : {},
23477
23496
  name: block.name,
23478
23497
  args: block.input
23479
23498
  }
@@ -23602,8 +23621,8 @@ CRITICAL INSTRUCTION FOR OUTPUT FORMAT:
23602
23621
  return 8192;
23603
23622
  }
23604
23623
  }
23605
- registerToolCall(toolId, name, thoughtSignature) {
23606
- this.toolCallMap.set(toolId, { name, thoughtSignature });
23624
+ registerToolCall(toolId, name, thoughtSignature, callId) {
23625
+ this.toolCallMap.set(toolId, { name, thoughtSignature, callId, fromResponse: true });
23607
23626
  if (thoughtSignature) {
23608
23627
  log(`[GeminiAPIFormat] Captured thoughtSignature for tool ${name} (${toolId})`);
23609
23628
  }
@@ -34165,22 +34184,28 @@ var init_codex2 = __esm(() => {
34165
34184
  function getAgyClientVersion() {
34166
34185
  return version2;
34167
34186
  }
34187
+ function getAgyClientBuild() {
34188
+ return build;
34189
+ }
34168
34190
  function agyClientVersionReadFor(accessToken) {
34169
34191
  return readForToken === accessToken;
34170
34192
  }
34171
- function recordAgyClientVersionRead(read, accessToken) {
34193
+ function recordAgyClientVersionRead(read, accessToken, readBuild = null) {
34172
34194
  readForToken = accessToken;
34173
- if (read === null || read === version2)
34195
+ if (read === null)
34196
+ return false;
34197
+ build = readBuild;
34198
+ if (read === version2)
34174
34199
  return false;
34175
34200
  version2 = read;
34176
34201
  return true;
34177
34202
  }
34178
- var version2 = null, readForToken = null;
34203
+ var version2 = null, readForToken = null, build = null;
34179
34204
 
34180
34205
  // src/auth/antigravity-token.ts
34181
34206
  import { execFileSync } from "child_process";
34182
34207
  import { createHash as createHash3 } from "crypto";
34183
- import { existsSync as existsSync11 } from "fs";
34208
+ import { closeSync as closeSync5, existsSync as existsSync11, openSync as openSync5, readSync, realpathSync as realpathSync3 } from "fs";
34184
34209
  import { homedir as homedir12 } from "os";
34185
34210
  import { join as join12 } from "path";
34186
34211
  function invalidateReadStoreMemo() {
@@ -34268,6 +34293,40 @@ function defaultReadAgyVersion() {
34268
34293
  return null;
34269
34294
  }
34270
34295
  }
34296
+ function readAgyBuildFromBinary(path) {
34297
+ let fd;
34298
+ try {
34299
+ fd = openSync5(path, "r");
34300
+ const chunk = Buffer.alloc(AGY_BUILD_SCAN_CHUNK);
34301
+ let position = 0;
34302
+ for (;; ) {
34303
+ const read = readSync(fd, chunk, 0, chunk.length, position);
34304
+ if (read <= 0)
34305
+ return null;
34306
+ const found = chunk.subarray(0, read).toString("latin1").match(AGY_BUILD_STAMP);
34307
+ if (found)
34308
+ return found[1];
34309
+ if (read < chunk.length)
34310
+ return null;
34311
+ position += read - AGY_BUILD_SCAN_OVERLAP;
34312
+ }
34313
+ } catch {
34314
+ return null;
34315
+ } finally {
34316
+ if (fd !== undefined)
34317
+ closeSync5(fd);
34318
+ }
34319
+ }
34320
+ function defaultReadAgyBuild() {
34321
+ const agy = locateAgyBinary();
34322
+ if (!agy)
34323
+ return null;
34324
+ try {
34325
+ return readAgyBuildFromBinary(realpathSync3(agy));
34326
+ } catch {
34327
+ return null;
34328
+ }
34329
+ }
34271
34330
  function defaultAntigravityTokenDeps() {
34272
34331
  return { ...defaultDeps3 };
34273
34332
  }
@@ -34369,7 +34428,7 @@ function captureAgyClientVersion(accessToken, deps) {
34369
34428
  if (!deps.readAgyVersion || agyClientVersionReadFor(accessToken))
34370
34429
  return;
34371
34430
  const read = deps.readAgyVersion();
34372
- recordAgyClientVersionRead(read, accessToken);
34431
+ recordAgyClientVersionRead(read, accessToken, read ? deps.readAgyBuild?.() ?? null : null);
34373
34432
  if (read) {
34374
34433
  log(`[Antigravity] Client version from agy: ${read}`);
34375
34434
  } else {
@@ -34503,22 +34562,269 @@ function resetObservedTokenState() {
34503
34562
  observedLineage = null;
34504
34563
  invalidateReadStoreMemo();
34505
34564
  }
34506
- var KC_SERVICE = "gemini", KC_ACCOUNT = "antigravity", PREFIX = "go-keyring-base64:", EXPIRY_SKEW_MS = 120000, AGY_REFRESH_TIMEOUT_MS = 12000, AGY_VERSION_TIMEOUT_MS = 5000, READ_STORE_TTL_MS = 3000, cachedRawStore = null, defaultDeps3, KEYCHAIN_LOCKED_EXIT_CODES, cachedHasToken = null, HAS_TOKEN_TTL_MS = 5000, inFlight = null, observedLineage = null, MAX_TRACKED_ACCESS_TOKENS = 8, lineageByAccessToken;
34565
+ var KC_SERVICE = "gemini", KC_ACCOUNT = "antigravity", PREFIX = "go-keyring-base64:", EXPIRY_SKEW_MS = 120000, AGY_REFRESH_TIMEOUT_MS = 12000, AGY_VERSION_TIMEOUT_MS = 5000, READ_STORE_TTL_MS = 3000, cachedRawStore = null, AGY_BUILD_STAMP, AGY_BUILD_SCAN_CHUNK, AGY_BUILD_SCAN_OVERLAP = 64, defaultDeps3, KEYCHAIN_LOCKED_EXIT_CODES, cachedHasToken = null, HAS_TOKEN_TTL_MS = 5000, inFlight = null, observedLineage = null, MAX_TRACKED_ACCESS_TOKENS = 8, lineageByAccessToken;
34507
34566
  var init_antigravity_token = __esm(() => {
34508
34567
  init_logger();
34509
34568
  init_keychain();
34569
+ AGY_BUILD_STAMP = /changelist (\d+) with baseline/;
34570
+ AGY_BUILD_SCAN_CHUNK = 8 << 20;
34510
34571
  defaultDeps3 = {
34511
34572
  readStore: defaultReadStore,
34512
34573
  writeStore: defaultWriteStore,
34513
34574
  deleteStore: defaultDeleteStore,
34514
34575
  runAgyRefresh: defaultRunAgyRefresh,
34515
34576
  readAgyVersion: defaultReadAgyVersion,
34577
+ readAgyBuild: defaultReadAgyBuild,
34516
34578
  now: () => Date.now()
34517
34579
  };
34518
34580
  KEYCHAIN_LOCKED_EXIT_CODES = new Set([36, 51, 128]);
34519
34581
  lineageByAccessToken = new Map;
34520
34582
  });
34521
34583
 
34584
+ // src/providers/transport/antigravity-fetch.ts
34585
+ import http from "http";
34586
+ import https from "https";
34587
+ import { Readable, pipeline } from "stream";
34588
+ import { createGunzip } from "zlib";
34589
+ function nodeHttpWritesOwnHead(bunVersion) {
34590
+ if (!bunVersion)
34591
+ return true;
34592
+ const part = (version) => version.split("-")[0].split(".").map(Number);
34593
+ const have = part(bunVersion);
34594
+ const need = part(FIRST_BUN_WITH_OWN_HTTP_HEAD);
34595
+ for (let i = 0;i < need.length; i++) {
34596
+ const n = have[i];
34597
+ if (!Number.isFinite(n))
34598
+ return false;
34599
+ if (n !== need[i])
34600
+ return n > need[i];
34601
+ }
34602
+ return !bunVersion.includes("-");
34603
+ }
34604
+ function headerRecord(headers) {
34605
+ const out = {};
34606
+ if (!headers)
34607
+ return out;
34608
+ if (headers instanceof Headers) {
34609
+ headers.forEach((value, name) => {
34610
+ out[name] = value;
34611
+ });
34612
+ return out;
34613
+ }
34614
+ for (const [name, value] of Array.isArray(headers) ? headers : Object.entries(headers)) {
34615
+ if (typeof value === "string")
34616
+ out[name] = value;
34617
+ }
34618
+ return out;
34619
+ }
34620
+ function sendsChunked(target) {
34621
+ return target.pathname.includes(":streamGenerateContent");
34622
+ }
34623
+ function antigravityHeaderLines(headers, bodyBytes, chunked) {
34624
+ const given = headerRecord(headers);
34625
+ const find = (lower) => {
34626
+ for (const [name, value] of Object.entries(given)) {
34627
+ if (name.toLowerCase() === lower)
34628
+ return value;
34629
+ }
34630
+ return;
34631
+ };
34632
+ const lines = [];
34633
+ const userAgent = find("user-agent");
34634
+ if (userAgent !== undefined)
34635
+ lines.push(["User-Agent", userAgent]);
34636
+ if (bodyBytes !== null) {
34637
+ lines.push(chunked ? ["Transfer-Encoding", "chunked"] : ["Content-Length", String(bodyBytes)]);
34638
+ }
34639
+ const authorization = find("authorization");
34640
+ if (authorization !== undefined)
34641
+ lines.push(["Authorization", authorization]);
34642
+ const contentType = find("content-type");
34643
+ if (contentType !== undefined)
34644
+ lines.push(["Content-Type", contentType]);
34645
+ lines.push(["Accept-Encoding", "gzip"]);
34646
+ for (const [name, value] of Object.entries(given)) {
34647
+ if (!OWN_HEADERS.has(name.toLowerCase()))
34648
+ lines.push([name, value]);
34649
+ }
34650
+ return lines;
34651
+ }
34652
+ function envValue(...names) {
34653
+ for (const name of names) {
34654
+ const value = process.env[name];
34655
+ if (value)
34656
+ return value;
34657
+ }
34658
+ return;
34659
+ }
34660
+ function bypassesProxy(target) {
34661
+ const list = envValue("NO_PROXY", "no_proxy");
34662
+ if (!list)
34663
+ return false;
34664
+ const name = target.hostname.toLowerCase();
34665
+ const port = target.port || (target.protocol === "https:" ? "443" : "80");
34666
+ return list.split(",").some((raw) => {
34667
+ let entry = raw.trim().toLowerCase();
34668
+ const withPort = entry.match(/^(.*[^:]):(\d+)$/);
34669
+ if (withPort) {
34670
+ if (withPort[2] !== port)
34671
+ return false;
34672
+ entry = withPort[1];
34673
+ }
34674
+ entry = entry.replace(/^\*?\./, "");
34675
+ if (!entry)
34676
+ return false;
34677
+ return entry === "*" || name === entry || name.endsWith(`.${entry}`);
34678
+ });
34679
+ }
34680
+ function proxyFor(target) {
34681
+ if (bypassesProxy(target))
34682
+ return null;
34683
+ const value = target.protocol === "https:" ? envValue("HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy") : envValue("HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy");
34684
+ if (!value)
34685
+ return null;
34686
+ try {
34687
+ return new URL(value);
34688
+ } catch {
34689
+ return null;
34690
+ }
34691
+ }
34692
+ function idleTimeoutError(ms) {
34693
+ return Object.assign(new Error(`The Antigravity backend sent nothing for ${ms} ms`), {
34694
+ code: "ETIMEDOUT"
34695
+ });
34696
+ }
34697
+ async function antigravityFetch(url, init = {}, runtime = {
34698
+ idleTimeoutMs: ANTIGRAVITY_IDLE_TIMEOUT_MS,
34699
+ bunVersion: process.versions.bun
34700
+ }) {
34701
+ if (process.env[ANTIGRAVITY_PLAIN_FETCH_ENV] === "1")
34702
+ return fetch(url, init);
34703
+ if (!nodeHttpWritesOwnHead(runtime.bunVersion))
34704
+ return fetch(url, init);
34705
+ if (init.body != null && typeof init.body !== "string")
34706
+ return fetch(url, init);
34707
+ let target = new URL(url);
34708
+ if (proxyFor(target))
34709
+ return fetch(url, init);
34710
+ let current = init;
34711
+ for (let hop = 0;; hop++) {
34712
+ const response = await sendOnce(target, current, runtime.idleTimeoutMs);
34713
+ const location = response.headers.get("location");
34714
+ const redirected = (response.status === 307 || response.status === 308) && location;
34715
+ if (!redirected || init.redirect === "manual" || hop >= MAX_REDIRECTS)
34716
+ return response;
34717
+ await response.body?.cancel().catch(() => {});
34718
+ if (init.redirect === "error") {
34719
+ throw new TypeError(`The Antigravity backend answered ${response.status} with a redirect`);
34720
+ }
34721
+ const next = new URL(location, target);
34722
+ if (next.origin !== target.origin) {
34723
+ const kept = {};
34724
+ const sent = new Headers(current.headers);
34725
+ sent.forEach((value, name) => {
34726
+ if (name.toLowerCase() !== "authorization")
34727
+ kept[name] = value;
34728
+ });
34729
+ current = { ...current, headers: kept };
34730
+ }
34731
+ target = next;
34732
+ if (proxyFor(target))
34733
+ return fetch(target.href, current);
34734
+ }
34735
+ }
34736
+ async function sendOnce(target, init, idleTimeoutMs) {
34737
+ const secure = target.protocol === "https:";
34738
+ const signal = init.signal ?? undefined;
34739
+ if (signal?.aborted)
34740
+ throw signal.reason;
34741
+ const method = (init.method ?? "GET").toUpperCase();
34742
+ const body = typeof init.body === "string" ? Buffer.from(init.body, "utf8") : null;
34743
+ const chunked = body !== null && sendsChunked(target);
34744
+ return new Promise((resolve, reject) => {
34745
+ const request = (secure ? https : http).request(target, { method, agent: false });
34746
+ try {
34747
+ request.removeHeader("Connection");
34748
+ for (const [name, value] of antigravityHeaderLines(init.headers, body?.length ?? null, chunked)) {
34749
+ request.setHeader(name, value);
34750
+ }
34751
+ } catch (error) {
34752
+ request.once("error", () => {});
34753
+ request.destroy();
34754
+ reject(error);
34755
+ return;
34756
+ }
34757
+ let incoming;
34758
+ request.setTimeout(idleTimeoutMs, () => {
34759
+ const error = idleTimeoutError(idleTimeoutMs);
34760
+ request.destroy(error);
34761
+ incoming?.destroy(error);
34762
+ });
34763
+ const untilResponse = setTimeout(() => request.destroy(idleTimeoutError(idleTimeoutMs)), idleTimeoutMs);
34764
+ const onAbort = () => {
34765
+ request.destroy(signal?.reason);
34766
+ incoming?.destroy(signal?.reason);
34767
+ };
34768
+ const release = () => signal?.removeEventListener("abort", onAbort);
34769
+ signal?.addEventListener("abort", onAbort, { once: true });
34770
+ request.once("error", (error) => {
34771
+ clearTimeout(untilResponse);
34772
+ release();
34773
+ reject(error);
34774
+ });
34775
+ request.once("response", (res) => {
34776
+ clearTimeout(untilResponse);
34777
+ incoming = res;
34778
+ res.once("close", release);
34779
+ const status = res.statusCode ?? 0;
34780
+ const headers = new Headers;
34781
+ for (let i = 0;i + 1 < res.rawHeaders.length; i += 2) {
34782
+ headers.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
34783
+ }
34784
+ let source = res;
34785
+ if (/\bgzip\b/i.test(headers.get("content-encoding") ?? "")) {
34786
+ source = pipeline(res, createGunzip(), () => {});
34787
+ headers.delete("content-encoding");
34788
+ headers.delete("content-length");
34789
+ }
34790
+ const bodiless = method === "HEAD" || status === 204 || status === 304;
34791
+ if (bodiless)
34792
+ res.resume();
34793
+ try {
34794
+ resolve(new Response(bodiless ? null : Readable.toWeb(source), {
34795
+ status,
34796
+ statusText: res.statusMessage ?? "",
34797
+ headers
34798
+ }));
34799
+ } catch (error) {
34800
+ res.destroy();
34801
+ reject(error);
34802
+ }
34803
+ });
34804
+ if (body === null)
34805
+ request.end();
34806
+ else if (chunked) {
34807
+ request.write(body);
34808
+ request.end();
34809
+ } else
34810
+ request.end(body);
34811
+ });
34812
+ }
34813
+ var ANTIGRAVITY_PLAIN_FETCH_ENV = "CLAUDISH_ANTIGRAVITY_PLAIN_FETCH", FIRST_BUN_WITH_OWN_HTTP_HEAD = "1.4.0", OWN_HEADERS, ANTIGRAVITY_IDLE_TIMEOUT_MS = 300000, MAX_REDIRECTS = 5;
34814
+ var init_antigravity_fetch = __esm(() => {
34815
+ OWN_HEADERS = new Set([
34816
+ "host",
34817
+ "accept",
34818
+ "connection",
34819
+ "content-length",
34820
+ "transfer-encoding",
34821
+ "accept-encoding",
34822
+ "user-agent",
34823
+ "authorization",
34824
+ "content-type"
34825
+ ]);
34826
+ });
34827
+
34522
34828
  // src/auth/antigravity-user.ts
34523
34829
  function antigravityHost() {
34524
34830
  const override = process.env.AICODE_ENDPOINT_URL?.trim();
@@ -34540,7 +34846,9 @@ function antigravityClientVersion() {
34540
34846
  return resolveAntigravityClientVersion().version;
34541
34847
  }
34542
34848
  function userAgentFor(version) {
34543
- return `antigravity/cli/${version} (aidev_client; os_type=${process.platform}; arch=${process.arch}; auth_method=consumer)`;
34849
+ const build = version === getAgyClientVersion() ? getAgyClientBuild() : null;
34850
+ const cl = build ? ` cl=${build};` : "";
34851
+ return `antigravity/cli/${version} (aidev_client; os_type=${process.platform}; arch=${process.arch};${cl} auth_method=consumer)`;
34544
34852
  }
34545
34853
  function antigravityUserAgentFor(version) {
34546
34854
  return userAgentFor(version);
@@ -34577,7 +34885,7 @@ function mayPublishFor(lineage) {
34577
34885
  return true;
34578
34886
  }
34579
34887
  async function callLoadCodeAssistAntigravity(accessToken) {
34580
- const res = await fetch(`${apiBase()}:loadCodeAssist`, {
34888
+ const res = await antigravityFetch(`${apiBase()}:loadCodeAssist`, {
34581
34889
  method: "POST",
34582
34890
  headers: {
34583
34891
  Authorization: `Bearer ${accessToken}`,
@@ -34629,7 +34937,7 @@ function getAntigravityTierDisplayName() {
34629
34937
  }
34630
34938
  async function retrieveUserQuota(accessToken, projectId) {
34631
34939
  try {
34632
- const res = await fetch(`${apiBase()}:retrieveUserQuota`, {
34940
+ const res = await antigravityFetch(`${apiBase()}:retrieveUserQuota`, {
34633
34941
  method: "POST",
34634
34942
  headers: {
34635
34943
  Authorization: `Bearer ${accessToken}`,
@@ -34675,7 +34983,7 @@ async function fetchAntigravityAvailableModelsRaw(accessToken, projectId, opts)
34675
34983
  };
34676
34984
  let res;
34677
34985
  try {
34678
- res = await fetch(url, {
34986
+ res = await antigravityFetch(url, {
34679
34987
  method: "POST",
34680
34988
  headers: {
34681
34989
  Authorization: `Bearer ${accessToken}`,
@@ -34744,6 +35052,12 @@ async function getServedAntigravityModels(accessToken, projectId, opts) {
34744
35052
  if (typeof record?.displayName === "string" && record.displayName) {
34745
35053
  entry.displayName = record.displayName;
34746
35054
  }
35055
+ if (typeof record?.model === "string" && record.model) {
35056
+ entry.modelEnum = record.model;
35057
+ }
35058
+ if (typeof record?.thinkingLevel === "number") {
35059
+ entry.thinkingLevel = record.thinkingLevel;
35060
+ }
34747
35061
  meta[id] = entry;
34748
35062
  }
34749
35063
  const excludedIds = new Set;
@@ -34801,6 +35115,7 @@ function peekServedAntigravityModels() {
34801
35115
  var ANTIGRAVITY_DEFAULT_HOST = "https://daily-cloudcode-pa.googleapis.com", SERVED_MODELS_TTL_MS, ANTIGRAVITY_IDE_TYPE = "ANTIGRAVITY", AGY_FALLBACK_CLIENT_VERSION = "1.1.9", cachedAgProjectId = null, cachedAgTierId = null, cachedAgTierName = null, cachedAgLineage = null, agServedCache = null, agServedCacheAt = 0, agServedCacheVersion = null;
34802
35116
  var init_antigravity_user = __esm(() => {
34803
35117
  init_logger();
35118
+ init_antigravity_fetch();
34804
35119
  init_antigravity_token();
34805
35120
  SERVED_MODELS_TTL_MS = 10 * 60 * 1000;
34806
35121
  });
@@ -34937,10 +35252,10 @@ var init_antigravity = __esm(() => {
34937
35252
  // src/auth/credential-file.ts
34938
35253
  import { randomBytes as randomBytes4 } from "crypto";
34939
35254
  import {
34940
- closeSync as closeSync5,
35255
+ closeSync as closeSync6,
34941
35256
  fsyncSync as fsyncSync2,
34942
35257
  mkdirSync as mkdirSync9,
34943
- openSync as openSync5,
35258
+ openSync as openSync6,
34944
35259
  readFileSync as readFileSync16,
34945
35260
  renameSync as renameSync5,
34946
35261
  statSync as statSync6,
@@ -34966,12 +35281,12 @@ function writeCredentialFileAtomic(path, data) {
34966
35281
  mkdirSync9(dirname8(path), { recursive: true });
34967
35282
  const tmp = `${path}.tmp-${process.pid}-${randomBytes4(6).toString("hex")}`;
34968
35283
  try {
34969
- const fd = openSync5(tmp, "wx", 384);
35284
+ const fd = openSync6(tmp, "wx", 384);
34970
35285
  try {
34971
35286
  writeSync5(fd, JSON.stringify(data, null, 2));
34972
35287
  fsyncSync2(fd);
34973
35288
  } finally {
34974
- closeSync5(fd);
35289
+ closeSync6(fd);
34975
35290
  }
34976
35291
  renameSync5(tmp, path);
34977
35292
  } catch (err) {
@@ -48483,12 +48798,12 @@ var init_raw = __esm(() => {
48483
48798
 
48484
48799
  // src/hooks/injection/inbox.ts
48485
48800
  import {
48486
- closeSync as closeSync6,
48801
+ closeSync as closeSync7,
48487
48802
  existsSync as existsSync16,
48488
48803
  fstatSync as fstatSync2,
48489
- openSync as openSync6,
48804
+ openSync as openSync7,
48490
48805
  readFileSync as readFileSync20,
48491
- readSync,
48806
+ readSync as readSync2,
48492
48807
  rmSync as rmSync6,
48493
48808
  statSync as statSync7
48494
48809
  } from "fs";
@@ -48569,7 +48884,7 @@ class FileInbox {
48569
48884
  return [];
48570
48885
  let fd;
48571
48886
  try {
48572
- fd = openSync6(this.path, "r");
48887
+ fd = openSync7(this.path, "r");
48573
48888
  } catch {
48574
48889
  return [];
48575
48890
  }
@@ -48578,7 +48893,7 @@ class FileInbox {
48578
48893
  if (size <= this.offset)
48579
48894
  return [];
48580
48895
  const buf = Buffer.alloc(size - this.offset);
48581
- const n = readSync(fd, buf, 0, buf.length, this.offset);
48896
+ const n = readSync2(fd, buf, 0, buf.length, this.offset);
48582
48897
  const bytes = Buffer.concat([this.partial, buf.subarray(0, n)]);
48583
48898
  const nl = bytes.lastIndexOf(10);
48584
48899
  const complete = nl === -1 ? "" : bytes.subarray(0, nl).toString("utf8");
@@ -48595,7 +48910,7 @@ class FileInbox {
48595
48910
  }
48596
48911
  return out;
48597
48912
  } finally {
48598
- closeSync6(fd);
48913
+ closeSync7(fd);
48599
48914
  }
48600
48915
  }
48601
48916
  }
@@ -48744,7 +49059,7 @@ function createHookInbox(dir, name = HOOK_INBOX_FILE) {
48744
49059
  const path = join20(dir, name);
48745
49060
  try {
48746
49061
  rmSync6(path, { force: true });
48747
- closeSync6(openSync6(path, "wx", 384));
49062
+ closeSync7(openSync7(path, "wx", 384));
48748
49063
  return path;
48749
49064
  } catch {
48750
49065
  return null;
@@ -49327,6 +49642,155 @@ function decideCodexSpeed(speed, modelInfo) {
49327
49642
  }
49328
49643
  var CODEX_SERVICE_TIER_POINTER = "/service_tier";
49329
49644
 
49645
+ // src/providers/antigravity-envelope.ts
49646
+ import { createHash as createHash13, randomBytes as randomBytes7, randomUUID as randomUUID3 } from "crypto";
49647
+
49648
+ class AntigravityConversations {
49649
+ limit;
49650
+ newId;
49651
+ byFirstMessage = new Map;
49652
+ sessionId;
49653
+ constructor(limit = 64, newId = randomUUID3, sessionId = randomSessionId()) {
49654
+ this.limit = limit;
49655
+ this.newId = newId;
49656
+ this.sessionId = sessionId;
49657
+ }
49658
+ of(inner, scope = "") {
49659
+ const key = `${scope}
49660
+ ${firstMessageKey(inner)}`;
49661
+ const known = this.byFirstMessage.get(key);
49662
+ if (known) {
49663
+ this.byFirstMessage.delete(key);
49664
+ this.byFirstMessage.set(key, known);
49665
+ return known;
49666
+ }
49667
+ const created = { cascadeId: this.newId(), trajectoryId: this.newId(), requestCount: 0 };
49668
+ this.byFirstMessage.set(key, created);
49669
+ if (this.byFirstMessage.size > this.limit) {
49670
+ const oldest = this.byFirstMessage.keys().next().value;
49671
+ if (oldest !== undefined)
49672
+ this.byFirstMessage.delete(oldest);
49673
+ }
49674
+ return created;
49675
+ }
49676
+ }
49677
+ function randomSessionId() {
49678
+ return randomBytes7(8).readBigInt64BE().toString();
49679
+ }
49680
+ function firstMessageKey(inner) {
49681
+ const contents = inner?.contents;
49682
+ const first = Array.isArray(contents) && contents.length > 0 ? contents[0] : null;
49683
+ return createHash13("sha256").update(JSON.stringify(first)).digest("hex");
49684
+ }
49685
+ function lastStepIndex(contents) {
49686
+ if (!Array.isArray(contents))
49687
+ return 0;
49688
+ let steps = 0;
49689
+ for (const content of contents.slice(1)) {
49690
+ const parts = Array.isArray(content?.parts) ? content.parts : [];
49691
+ const results = parts.filter((part) => part?.functionResponse !== undefined).length;
49692
+ steps += results > 0 ? results : 1;
49693
+ }
49694
+ return steps;
49695
+ }
49696
+ function toolResultsAsModelEntries(contents) {
49697
+ if (!Array.isArray(contents))
49698
+ return contents;
49699
+ const out = [];
49700
+ for (const content of contents) {
49701
+ const parts = Array.isArray(content?.parts) ? content.parts : [];
49702
+ const results = parts.filter((part) => part?.functionResponse !== undefined);
49703
+ if (results.length === 0) {
49704
+ out.push(content);
49705
+ continue;
49706
+ }
49707
+ const others = parts.filter((part) => part?.functionResponse === undefined);
49708
+ out.push({ ...content, role: "model", parts: results });
49709
+ if (others.length > 0)
49710
+ out.push({ ...content, parts: others });
49711
+ }
49712
+ return out;
49713
+ }
49714
+ function oneToolPerDeclaration(tools) {
49715
+ if (!Array.isArray(tools))
49716
+ return tools;
49717
+ const out = [];
49718
+ for (const entry of tools) {
49719
+ const declarations = entry?.functionDeclarations;
49720
+ if (!Array.isArray(declarations) || declarations.length <= 1) {
49721
+ out.push(entry);
49722
+ continue;
49723
+ }
49724
+ const { functionDeclarations: _all, ...rest } = entry;
49725
+ for (const declaration of declarations) {
49726
+ out.push({ ...rest, functionDeclarations: [declaration] });
49727
+ }
49728
+ }
49729
+ return out;
49730
+ }
49731
+ function labelsFor(model, meta, conversation, stepIndex) {
49732
+ const claude = model.startsWith("claude");
49733
+ const gemini = model.startsWith("gemini");
49734
+ const labels = {
49735
+ cascade_id: conversation.cascadeId,
49736
+ last_step_index: String(stepIndex)
49737
+ };
49738
+ if (meta?.modelEnum)
49739
+ labels.model_enum = meta.modelEnum;
49740
+ labels.request_id = `${conversation.trajectoryId}-${conversation.requestCount}`;
49741
+ labels.root_cascade_id = conversation.cascadeId;
49742
+ labels.trajectory_id = conversation.trajectoryId;
49743
+ labels.used_claude = String(claude);
49744
+ labels.used_claude_conservative = String(claude);
49745
+ labels.used_non_gemini_model = String(!gemini);
49746
+ return labels;
49747
+ }
49748
+ function buildAntigravityEnvelope(input) {
49749
+ const { model, meta, conversation } = input;
49750
+ const inner = input.inner ?? {};
49751
+ const {
49752
+ contents,
49753
+ systemInstruction,
49754
+ tools,
49755
+ generationConfig,
49756
+ labels: _labels,
49757
+ sessionId: _sessionId,
49758
+ ...others
49759
+ } = inner;
49760
+ const stepIndex = lastStepIndex(contents);
49761
+ const request = { contents: toolResultsAsModelEntries(contents) };
49762
+ if (systemInstruction && typeof systemInstruction === "object") {
49763
+ const { role: _role, ...instruction } = systemInstruction;
49764
+ request.systemInstruction = { role: "user", ...instruction };
49765
+ }
49766
+ if (tools !== undefined)
49767
+ request.tools = oneToolPerDeclaration(tools);
49768
+ Object.assign(request, others);
49769
+ request.labels = labelsFor(model, meta, conversation, stepIndex);
49770
+ const {
49771
+ temperature: _temperature,
49772
+ maxOutputTokens,
49773
+ ...config
49774
+ } = generationConfig ?? {};
49775
+ const cap = meta?.maxOutputTokens ?? maxOutputTokens;
49776
+ request.generationConfig = cap === undefined ? config : { maxOutputTokens: cap, ...config };
49777
+ request.sessionId = input.sessionId;
49778
+ const envelope = {
49779
+ project: input.projectId,
49780
+ requestId: `agent/${conversation.cascadeId}/${input.now ?? Date.now()}/${conversation.trajectoryId}/${stepIndex + 1}`,
49781
+ request,
49782
+ model,
49783
+ userAgent: "antigravity",
49784
+ requestType: "agent"
49785
+ };
49786
+ conversation.requestCount += 1;
49787
+ return envelope;
49788
+ }
49789
+ var antigravityConversations;
49790
+ var init_antigravity_envelope = __esm(() => {
49791
+ antigravityConversations = new AntigravityConversations;
49792
+ });
49793
+
49330
49794
  // src/handlers/shared/gemini-queue.ts
49331
49795
  function rejectIfAborted(request) {
49332
49796
  if (request.onAbort)
@@ -50774,16 +51238,19 @@ function mappedAntigravityModelId(req, served, effort) {
50774
51238
  function antigravityCarriesEffortInModelId(sent) {
50775
51239
  return carriesEffortInModelId(sent.trim(), "antigravity");
50776
51240
  }
50777
- function antigravityBodyForModelId(inner, sent) {
51241
+ function antigravityBodyForModelId(inner, sent, backendLevel) {
50778
51242
  const body = inner;
50779
51243
  const thinking = body?.generationConfig?.thinkingConfig;
50780
51244
  if (!thinking || typeof thinking !== "object")
50781
51245
  return inner;
50782
- if (!("thinkingLevel" in thinking) && !("thinkingBudget" in thinking))
50783
- return inner;
50784
51246
  if (!antigravityCarriesEffortInModelId(sent))
50785
51247
  return inner;
51248
+ const level = backendLevel !== undefined && sent.trim().startsWith("gemini") ? BACKEND_THINKING_LEVELS[backendLevel] : undefined;
51249
+ if (!level && !("thinkingLevel" in thinking) && !("thinkingBudget" in thinking))
51250
+ return inner;
50786
51251
  const { thinkingLevel: _level, thinkingBudget: _budget, ...kept } = thinking;
51252
+ if (level)
51253
+ kept.thinkingLevel = level;
50787
51254
  const generationConfig = { ...body?.generationConfig };
50788
51255
  if (Object.keys(kept).length > 0)
50789
51256
  generationConfig.thinkingConfig = kept;
@@ -50853,10 +51320,11 @@ function chooseAntigravityServedModel(requested, served, effort) {
50853
51320
  const id = resolveAntigravityModelId(requested, selectable, defaultId, lookupFamilyDefaultVariant(requested, "antigravity"));
50854
51321
  return existingResolutionChoice(id, effort, decision);
50855
51322
  }
50856
- var REASONING_TIER_RANK;
51323
+ var BACKEND_THINKING_LEVELS, REASONING_TIER_RANK;
50857
51324
  var init_antigravity_model_id = __esm(() => {
50858
51325
  init_model_catalog();
50859
51326
  init_model_id_effort_choice();
51327
+ BACKEND_THINKING_LEVELS = { 1: "LOW", 2: "MEDIUM", 3: "HIGH" };
50860
51328
  REASONING_TIER_RANK = {
50861
51329
  high: 0,
50862
51330
  medium: 1,
@@ -51188,6 +51656,20 @@ var init_wire_request = __esm(() => {
51188
51656
  LIMIT_REQUIRED_APIS = new Set(["anthropic-messages"]);
51189
51657
  });
51190
51658
 
51659
+ // src/providers/transport/conversation-key.ts
51660
+ import { createHash as createHash14, randomBytes as randomBytes8 } from "crypto";
51661
+ function conversationKey(claudeRequest) {
51662
+ const sessionId = extractSessionId(claudeRequest);
51663
+ if (!sessionId)
51664
+ return `claudish_${FALLBACK_CONVERSATION_KEY}`;
51665
+ return `claudish_${createHash14("sha256").update(sessionId).digest("hex").slice(0, 32)}`;
51666
+ }
51667
+ var FALLBACK_CONVERSATION_KEY;
51668
+ var init_conversation_key = __esm(() => {
51669
+ init_harness();
51670
+ FALLBACK_CONVERSATION_KEY = randomBytes8(16).toString("hex");
51671
+ });
51672
+
51191
51673
  // src/providers/transport/antigravity.ts
51192
51674
  var exports_antigravity = {};
51193
51675
  __export(exports_antigravity, {
@@ -51196,7 +51678,6 @@ __export(exports_antigravity, {
51196
51678
  chooseAntigravityServedModel: () => chooseAntigravityServedModel,
51197
51679
  resolveAntigravityServedModel: () => resolveAntigravityServedModel
51198
51680
  });
51199
- import { randomUUID as randomUUID3 } from "crypto";
51200
51681
  function antigravityEndpoint() {
51201
51682
  return `${antigravityHost()}/v1internal:streamGenerateContent?alt=sse`;
51202
51683
  }
@@ -51208,9 +51689,6 @@ function effortOf(claudeRequest, pinned) {
51208
51689
  return "none";
51209
51690
  return isEffortLevel(choices.effort) ? choices.effort : undefined;
51210
51691
  }
51211
- function createActivityRequestId() {
51212
- return Math.random().toString(36).substring(7);
51213
- }
51214
51692
  function classify429(responseBody) {
51215
51693
  try {
51216
51694
  const raw = JSON.parse(responseBody);
@@ -51279,16 +51757,19 @@ class AntigravityProviderTransport {
51279
51757
  return this._displayName;
51280
51758
  }
51281
51759
  streamFormat = "gemini-sse";
51760
+ fetch(url, init) {
51761
+ return antigravityFetch(url, init);
51762
+ }
51282
51763
  modelName;
51283
51764
  servedModelName;
51284
51765
  accessToken = null;
51285
51766
  projectId = null;
51286
- tierId = null;
51287
51767
  cachedAuth = null;
51288
51768
  requests = new WeakMap;
51289
51769
  lastRequest;
51290
51770
  pinnedEffort;
51291
51771
  servedModels = [];
51772
+ modelMeta = {};
51292
51773
  served = {
51293
51774
  servedIds: [],
51294
51775
  defaultId: null
@@ -51317,8 +51798,7 @@ class AntigravityProviderTransport {
51317
51798
  buildLocalHeaders() {
51318
51799
  return {
51319
51800
  Authorization: `Bearer ${this.accessToken}`,
51320
- "User-Agent": buildAntigravityUserAgent(),
51321
- "x-activity-request-id": createActivityRequestId()
51801
+ "User-Agent": buildAntigravityUserAgent()
51322
51802
  };
51323
51803
  }
51324
51804
  async refreshAuth() {
@@ -51326,12 +51806,12 @@ class AntigravityProviderTransport {
51326
51806
  model: this.modelName
51327
51807
  });
51328
51808
  this.accessToken = await getValidAntigravityAccessToken();
51329
- const { projectId, tierId } = await setupAntigravityUser(this.accessToken);
51809
+ const { projectId } = await setupAntigravityUser(this.accessToken);
51330
51810
  this.projectId = projectId;
51331
- this.tierId = tierId;
51332
51811
  this._displayName = getAntigravityTierDisplayName();
51333
51812
  const served = await getServedAntigravityModels(this.accessToken, this.projectId);
51334
51813
  this.served = served;
51814
+ this.modelMeta = served.meta ?? {};
51335
51815
  this.servedModels = served.servedIds;
51336
51816
  this.servedModelName = resolveAntigravityServedModel(this.modelName, served, this.pinnedEffort);
51337
51817
  log(`[Antigravity] Auth refreshed, project: ${this.projectId}, tier: ${this._displayName}, ` + `model: ${this.modelName} -> ${this.servedModelName}, served: ${this.servedModels.join(",") || "(none)"}`);
@@ -51357,17 +51837,24 @@ class AntigravityProviderTransport {
51357
51837
  }
51358
51838
  transformPayload(payload, claudeRequest) {
51359
51839
  let choice;
51840
+ const conversationScope = conversationKey(claudeRequest);
51360
51841
  const request = {
51361
51842
  effort: effortOf(claudeRequest, this.pinnedEffort),
51362
51843
  onModelChoice: (decided) => {
51363
51844
  choice = decided;
51364
- }
51845
+ },
51846
+ conversationScope
51365
51847
  };
51366
51848
  const envelope = this.cachedAuth?.transformPayload ? this.cachedAuth.transformPayload(payload, request) : this.buildLocalEnvelope(payload, request);
51367
51849
  if (typeof envelope?.model === "string" && envelope.model) {
51368
51850
  this.servedModelName = envelope.model;
51369
51851
  }
51370
- const state = { payload, sentId: this.servedModelName, choice };
51852
+ const state = {
51853
+ payload,
51854
+ sentId: this.servedModelName,
51855
+ choice,
51856
+ conversationScope
51857
+ };
51371
51858
  if (envelope && typeof envelope === "object")
51372
51859
  this.requests.set(envelope, state);
51373
51860
  this.lastRequest = envelope ? state : undefined;
@@ -51378,19 +51865,17 @@ class AntigravityProviderTransport {
51378
51865
  buildLocalEnvelope(payload, request) {
51379
51866
  const choice = chooseAntigravityServedModel(this.modelName, this.served, request.effort);
51380
51867
  request.onModelChoice?.(choice);
51381
- return this.buildEnvelope(antigravityBodyForModelId(payload, choice.id), choice.id);
51868
+ return this.buildEnvelope(antigravityBodyForModelId(payload, choice.id, this.modelMeta[choice.id]?.thinkingLevel), choice.id, request.conversationScope);
51382
51869
  }
51383
- buildEnvelope(innerPayload, model) {
51384
- const envelope = {
51870
+ buildEnvelope(innerPayload, model, conversationScope) {
51871
+ return buildAntigravityEnvelope({
51872
+ inner: innerPayload,
51385
51873
  model,
51386
- project: this.projectId,
51387
- user_prompt_id: randomUUID3(),
51388
- request: innerPayload
51389
- };
51390
- if (this.tierId && this.tierId !== "free-tier") {
51391
- envelope.enabled_credit_types = ["GOOGLE_ONE_AI"];
51392
- }
51393
- return envelope;
51874
+ projectId: this.projectId,
51875
+ meta: this.modelMeta[model],
51876
+ conversation: antigravityConversations.of(innerPayload, conversationScope),
51877
+ sessionId: antigravityConversations.sessionId
51878
+ });
51394
51879
  }
51395
51880
  async enqueueRequest(fetchFn, opts) {
51396
51881
  const queue = GeminiRequestQueue.getInstance();
@@ -51466,7 +51951,7 @@ class AntigravityProviderTransport {
51466
51951
  if (choice)
51467
51952
  logModelIdChoice("Antigravity", this.modelName, { ...choice, id: fallbackModel });
51468
51953
  tried.push(fallbackModel);
51469
- const fallbackEnvelope = this.buildEnvelope(antigravityBodyForModelId(originalPayload, fallbackModel), fallbackModel);
51954
+ const fallbackEnvelope = this.buildEnvelope(antigravityBodyForModelId(originalPayload, fallbackModel, this.modelMeta[fallbackModel]?.thinkingLevel), fallbackModel, request.conversationScope);
51470
51955
  const headers = this.buildLocalHeaders();
51471
51956
  headers["Content-Type"] = "application/json";
51472
51957
  const fallbackResponse = await this.fetchCapacityCandidate(queue, endpoint, headers, fallbackEnvelope, signal);
@@ -51502,8 +51987,8 @@ class AntigravityProviderTransport {
51502
51987
  fetchCapacityCandidate(queue, endpoint, headers, envelope, signal) {
51503
51988
  const init = { method: "POST", headers, body: JSON.stringify(envelope) };
51504
51989
  if (!signal)
51505
- return queue.enqueue(() => fetch(endpoint, init));
51506
- return queue.enqueue(() => signal.aborted ? Promise.reject(callAbortError()) : fetch(endpoint, { ...init, signal }), { signal });
51990
+ return queue.enqueue(() => antigravityFetch(endpoint, init));
51991
+ return queue.enqueue(() => signal.aborted ? Promise.reject(callAbortError()) : antigravityFetch(endpoint, { ...init, signal }), { signal });
51507
51992
  }
51508
51993
  rewriteModelNotFound(response, sentId, capacityFallbacksExhausted = false) {
51509
51994
  const served = this.servedModels;
@@ -51635,9 +52120,12 @@ var init_antigravity2 = __esm(() => {
51635
52120
  init_call_context();
51636
52121
  init_gemini_queue();
51637
52122
  init_logger();
52123
+ init_antigravity_envelope();
51638
52124
  init_antigravity_model_id();
51639
52125
  init_model_id_effort_choice();
51640
52126
  init_wire_request();
52127
+ init_antigravity_fetch();
52128
+ init_conversation_key();
51641
52129
  init_provider_model_discovery();
51642
52130
  init_antigravity_model_id();
51643
52131
  });
@@ -51656,11 +52144,6 @@ function redactSecrets2(text) {
51656
52144
  }
51657
52145
 
51658
52146
  // src/auth/credentials/antigravity-credential.ts
51659
- import { randomUUID as randomUUID4 } from "crypto";
51660
- function createActivityRequestId2() {
51661
- return Math.random().toString(36).substring(7);
51662
- }
51663
-
51664
52147
  class AntigravityCredentialProvider {
51665
52148
  catalogName = "antigravity";
51666
52149
  async describeReadiness() {
@@ -51686,33 +52169,31 @@ ${antigravityHost()}` : undefined;
51686
52169
  }
51687
52170
  async getRequestAuth(ctx) {
51688
52171
  const token = await getValidAntigravityAccessToken();
51689
- const { projectId, tierId } = await setupAntigravityUser(token);
52172
+ const { projectId } = await setupAntigravityUser(token);
51690
52173
  const served = await getServedAntigravityModels(token, projectId);
51691
52174
  return {
51692
52175
  headers: {
51693
52176
  Authorization: `Bearer ${token}`,
51694
- "User-Agent": buildAntigravityUserAgent(),
51695
- "x-activity-request-id": createActivityRequestId2()
52177
+ "User-Agent": buildAntigravityUserAgent()
51696
52178
  },
51697
52179
  transformPayload: (inner, request) => {
51698
52180
  const choice = chooseAntigravityServedModel(ctx.model, served, request?.effort);
51699
52181
  request?.onModelChoice?.(choice);
51700
52182
  const model = choice.id;
51701
- const env = {
52183
+ return buildAntigravityEnvelope({
52184
+ inner: antigravityBodyForModelId(inner, model, served.meta?.[model]?.thinkingLevel),
51702
52185
  model,
51703
- project: projectId,
51704
- user_prompt_id: randomUUID4(),
51705
- request: antigravityBodyForModelId(inner, model)
51706
- };
51707
- if (tierId && tierId !== "free-tier") {
51708
- env.enabled_credit_types = ["GOOGLE_ONE_AI"];
51709
- }
51710
- return env;
52186
+ projectId,
52187
+ meta: served.meta?.[model],
52188
+ conversation: antigravityConversations.of(inner, request?.conversationScope),
52189
+ sessionId: antigravityConversations.sessionId
52190
+ });
51711
52191
  }
51712
52192
  };
51713
52193
  }
51714
52194
  }
51715
52195
  var init_antigravity_credential = __esm(() => {
52196
+ init_antigravity_envelope();
51716
52197
  init_antigravity2();
51717
52198
  init_antigravity_token();
51718
52199
  init_antigravity_user();
@@ -54388,7 +54869,7 @@ var init_dist12 = __esm(() => {
54388
54869
 
54389
54870
  // src/auth/codex-pkce.ts
54390
54871
  import { exec as exec4 } from "child_process";
54391
- import { createHash as createHash13, randomBytes as randomBytes7 } from "crypto";
54872
+ import { createHash as createHash15, randomBytes as randomBytes9 } from "crypto";
54392
54873
  import { createServer } from "http";
54393
54874
  import { promisify as promisify3 } from "util";
54394
54875
  function loginClaims(idToken) {
@@ -54499,9 +54980,9 @@ function waitForCallback(options, deps) {
54499
54980
  }
54500
54981
  async function loginCodexPkce(deps = {}) {
54501
54982
  log("[CodexOAuth] Starting OAuth login flow");
54502
- const verifier = randomBytes7(64).toString("base64url");
54503
- const challenge = createHash13("sha256").update(verifier).digest("base64url");
54504
- const state = randomBytes7(32).toString("base64url");
54983
+ const verifier = randomBytes9(64).toString("base64url");
54984
+ const challenge = createHash15("sha256").update(verifier).digest("base64url");
54985
+ const state = randomBytes9(32).toString("base64url");
54505
54986
  const options = {
54506
54987
  port: 1455,
54507
54988
  timeoutMs: 5 * 60 * 1000,
@@ -55093,7 +55574,7 @@ var init_codex_oauth = __esm(() => {
55093
55574
  });
55094
55575
 
55095
55576
  // src/auth/accounts/management.ts
55096
- import { randomBytes as randomBytes8 } from "crypto";
55577
+ import { randomBytes as randomBytes10 } from "crypto";
55097
55578
  import { accessSync, constants as fsConstants, lstatSync as lstatSync3, readFileSync as readFileSync23 } from "fs";
55098
55579
  function legacyMoveDeferredMessage(outcome, env = process.env) {
55099
55580
  return `Could not move the existing Codex login into the macOS Keychain (${outcome.reason}: ` + `${redactSecrets(outcome.detail)}). The login was not moved; ${legacyCodexCredentialsPath(env)} was kept. ` + MOVE_HINTS[outcome.reason];
@@ -55275,7 +55756,7 @@ class CodexAccountManagement {
55275
55756
  }
55276
55757
  newId(entry, reserved) {
55277
55758
  for (let attempt = 0;attempt < 16; attempt++) {
55278
- const id = this.deps.newId?.() ?? randomBytes8(6).toString("hex");
55759
+ const id = this.deps.newId?.() ?? randomBytes10(6).toString("hex");
55279
55760
  if (!ACCOUNT_ID_PATTERN.test(id))
55280
55761
  throw new Error("The account id generator returned an invalid id.");
55281
55762
  if (id !== reserved && !entry.accounts.some((row) => row.id === id))
@@ -55365,7 +55846,7 @@ class CodexAccountManagement {
55365
55846
  fingerprint: fingerprintOf(credentials2.refresh_token),
55366
55847
  journal: null,
55367
55848
  updatedAt: this.now(),
55368
- writeId: randomBytes8(16).toString("hex")
55849
+ writeId: randomBytes10(16).toString("hex")
55369
55850
  };
55370
55851
  }
55371
55852
  async run(command) {
@@ -55803,7 +56284,7 @@ class CodexAccountManagement {
55803
56284
  const existing = await dest.read(row, { uncached: true });
55804
56285
  const record = {
55805
56286
  ...material,
55806
- writeId: randomBytes8(16).toString("hex"),
56287
+ writeId: randomBytes10(16).toString("hex"),
55807
56288
  updatedAt: this.now()
55808
56289
  };
55809
56290
  const resumed = existing !== null && sameDurableRecord(existing, material);
@@ -56012,14 +56493,14 @@ var init_management = __esm(() => {
56012
56493
  });
56013
56494
 
56014
56495
  // src/auth/accounts/legacy-move.ts
56015
- import { lstatSync as lstatSync4, realpathSync as realpathSync3 } from "fs";
56496
+ import { lstatSync as lstatSync4, realpathSync as realpathSync4 } from "fs";
56016
56497
  import { join as join23, resolve as resolve2 } from "path";
56017
56498
  function legacyMoveKeychainBlocked(env = process.env) {
56018
56499
  return env.CLAUDISH_DISABLE_KEYCHAIN === "1" || !isKeychainSupported();
56019
56500
  }
56020
56501
  function canonical(path) {
56021
56502
  try {
56022
- return realpathSync3(path);
56503
+ return realpathSync4(path);
56023
56504
  } catch {
56024
56505
  return resolve2(path);
56025
56506
  }
@@ -56448,12 +56929,12 @@ var init_grok_credential = __esm(() => {
56448
56929
 
56449
56930
  // src/auth/kimi-oauth.ts
56450
56931
  import { exec as exec5 } from "child_process";
56451
- import { randomBytes as randomBytes9 } from "crypto";
56932
+ import { randomBytes as randomBytes11 } from "crypto";
56452
56933
  import {
56453
- closeSync as closeSync7,
56934
+ closeSync as closeSync8,
56454
56935
  existsSync as existsSync19,
56455
56936
  mkdirSync as mkdirSync12,
56456
- openSync as openSync7,
56937
+ openSync as openSync8,
56457
56938
  readFileSync as readFileSync25,
56458
56939
  unlinkSync as unlinkSync7,
56459
56940
  writeSync as writeSync6
@@ -56535,13 +57016,13 @@ class KimiOAuth {
56535
57016
  log(`[KimiOAuth] Failed to load device ID: ${e.message}`);
56536
57017
  }
56537
57018
  }
56538
- const deviceId = randomBytes9(16).toString("hex").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
57019
+ const deviceId = randomBytes11(16).toString("hex").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
56539
57020
  try {
56540
- const fd = openSync7(deviceIdPath, "w", 384);
57021
+ const fd = openSync8(deviceIdPath, "w", 384);
56541
57022
  try {
56542
57023
  writeSync6(fd, deviceId, 0, "utf-8");
56543
57024
  } finally {
56544
- closeSync7(fd);
57025
+ closeSync8(fd);
56545
57026
  }
56546
57027
  log(`[KimiOAuth] New device ID created: ${deviceId}`);
56547
57028
  } catch (e) {
@@ -57887,14 +58368,14 @@ var init_vertex_credential = __esm(() => {
57887
58368
  });
57888
58369
 
57889
58370
  // src/providers/dynamic-models-catalog-store.ts
57890
- import { createHmac, randomBytes as randomBytes10 } from "crypto";
58371
+ import { createHmac, randomBytes as randomBytes12 } from "crypto";
57891
58372
  import {
57892
- closeSync as closeSync8,
58373
+ closeSync as closeSync9,
57893
58374
  fsyncSync as fsyncSync3,
57894
58375
  linkSync as linkSync2,
57895
58376
  lstatSync as lstatSync5,
57896
58377
  mkdirSync as mkdirSync15,
57897
- openSync as openSync8,
58378
+ openSync as openSync9,
57898
58379
  readFileSync as readFileSync29,
57899
58380
  readdirSync as readdirSync3,
57900
58381
  rmSync as rmSync9,
@@ -57963,13 +58444,13 @@ function readSecret(path) {
57963
58444
  function createSecret(path) {
57964
58445
  const dir = dirname13(path);
57965
58446
  mkdirSync15(dir, { recursive: true, mode: 448 });
57966
- const temp = join29(dir, `.dynamic-models-catalog.key.${process.pid}.${randomBytes10(6).toString("hex")}`);
57967
- const fd = openSync8(temp, "wx", 384);
58447
+ const temp = join29(dir, `.dynamic-models-catalog.key.${process.pid}.${randomBytes12(6).toString("hex")}`);
58448
+ const fd = openSync9(temp, "wx", 384);
57968
58449
  try {
57969
- writeSync7(fd, randomBytes10(32).toString("hex"));
58450
+ writeSync7(fd, randomBytes12(32).toString("hex"));
57970
58451
  fsyncSync3(fd);
57971
58452
  } finally {
57972
- closeSync8(fd);
58453
+ closeSync9(fd);
57973
58454
  }
57974
58455
  try {
57975
58456
  linkSync2(temp, path);
@@ -58197,7 +58678,7 @@ var init_dynamic_models_catalog_store = __esm(() => {
58197
58678
  });
58198
58679
 
58199
58680
  // src/providers/dynamic-models-catalog.ts
58200
- import { createHmac as createHmac2, randomBytes as randomBytes11 } from "crypto";
58681
+ import { createHmac as createHmac2, randomBytes as randomBytes13 } from "crypto";
58201
58682
  function nowOf2(opts) {
58202
58683
  return opts?.now ? opts.now() : Date.now();
58203
58684
  }
@@ -58367,6 +58848,20 @@ async function refreshAccountModelsList(provider, trigger, opts) {
58367
58848
  };
58368
58849
  }
58369
58850
  }
58851
+ async function liveOrStoredModelsCatalog(provider, trigger) {
58852
+ const result = await refreshAccountModelsList(provider, trigger, {
58853
+ minAgeMs: LIVE_MS
58854
+ });
58855
+ if (result.kind === "refreshed") {
58856
+ return result.outcome.kind === "served" ? servedOutcomeOf(result.outcome.models) : result.outcome;
58857
+ }
58858
+ if (result.reason === "too-recent") {
58859
+ const list = await readAccountModelsList(provider);
58860
+ if (list)
58861
+ return servedOutcomeOf(list.models);
58862
+ }
58863
+ return discoverProviderModelsCatalog(provider);
58864
+ }
58370
58865
  function sweepAccountModelsLists(trigger, opts) {
58371
58866
  const run = async (provider) => {
58372
58867
  const readiness = await credentials.describeReadiness(provider, { allowOpPrompt: false });
@@ -58401,7 +58896,7 @@ var init_dynamic_models_catalog = __esm(() => {
58401
58896
  init_dynamic_models_catalog_store();
58402
58897
  init_model_discovery();
58403
58898
  init_provider_definitions();
58404
- processSecret = randomBytes11(32);
58899
+ processSecret = randomBytes13(32);
58405
58900
  identityMemo = new Map;
58406
58901
  liveMemory = new Map;
58407
58902
  inFlight4 = new Map;
@@ -59324,14 +59819,14 @@ var init_proto_codec = __esm(() => {
59324
59819
  });
59325
59820
 
59326
59821
  // src/providers/devin/devin-request.ts
59327
- import { randomUUID as randomUUID5 } from "crypto";
59822
+ import { randomUUID as randomUUID4 } from "crypto";
59328
59823
  function encodeChatMetadata(meta) {
59329
59824
  const version = meta.clientVersion ?? DEVIN_CLI_VERSION;
59330
59825
  return msg(bytes(1, "devin-cli"), bytes(2, version), bytes(3, meta.apiKey), bytes(4, "en"), bytes(5, meta.platform ?? process.platform), bytes(7, version), bytes(12, "chisel"), bytes(28, "chisel"));
59331
59826
  }
59332
59827
  function encodeMessage(message) {
59333
59828
  const parts = [
59334
- bytes(1, message.id ?? randomUUID5()),
59829
+ bytes(1, message.id ?? randomUUID4()),
59335
59830
  vint(2, DEVIN_ROLE[message.role])
59336
59831
  ];
59337
59832
  if (message.text)
@@ -59394,7 +59889,7 @@ var init_devin_request = __esm(() => {
59394
59889
  });
59395
59890
 
59396
59891
  // src/providers/devin/devin-models.ts
59397
- import { createHash as createHash14 } from "crypto";
59892
+ import { createHash as createHash16 } from "crypto";
59398
59893
  function unaryMetadata(apiKey) {
59399
59894
  return msg(bytes(1, "chisel"), bytes(2, DEVIN_CLI_VERSION), bytes(3, apiKey), bytes(4, "en"), bytes(5, process.platform), bytes(7, DEVIN_CLI_VERSION));
59400
59895
  }
@@ -59583,7 +60078,7 @@ function decodeAllowedUids(body) {
59583
60078
  return uids;
59584
60079
  }
59585
60080
  function hashApiKey(apiKey) {
59586
- return createHash14("sha256").update(apiKey).digest("hex");
60081
+ return createHash16("sha256").update(apiKey).digest("hex");
59587
60082
  }
59588
60083
  async function getServedDevinModels(opts) {
59589
60084
  const now = Date.now();
@@ -60160,7 +60655,7 @@ var init_model_discovery_builtins = __esm(() => {
60160
60655
  });
60161
60656
 
60162
60657
  // src/providers/model-discovery.ts
60163
- import { createHash as createHash15 } from "crypto";
60658
+ import { createHash as createHash17 } from "crypto";
60164
60659
  function toModelsCatalogEntry(model) {
60165
60660
  const { id, ...rest } = model;
60166
60661
  return { wireId: id, ...rest };
@@ -60173,7 +60668,7 @@ function getModelDiscoveryFetcher(format) {
60173
60668
  }
60174
60669
  async function accountFingerprint(providerName) {
60175
60670
  const identity = await credentials.accountIdentity(providerName, { allowOpPrompt: false });
60176
- return identity ? createHash15("sha256").update(identity).digest("hex") : undefined;
60671
+ return identity ? createHash17("sha256").update(identity).digest("hex") : undefined;
60177
60672
  }
60178
60673
  function recordFailure(failure) {
60179
60674
  _failures.set(failure.provider, failure);
@@ -61145,7 +61640,7 @@ function reduceEvent(state, event) {
61145
61640
  }
61146
61641
 
61147
61642
  // src/session-events/transcript-tailer.ts
61148
- import { closeSync as closeSync9, openSync as openSync9, readSync as readSync2, statSync as statSync12 } from "fs";
61643
+ import { closeSync as closeSync10, openSync as openSync10, readSync as readSync3, statSync as statSync12 } from "fs";
61149
61644
 
61150
61645
  class TranscriptTailer {
61151
61646
  filePath;
@@ -61198,16 +61693,16 @@ class TranscriptTailer {
61198
61693
  }
61199
61694
  if (size === this.offset)
61200
61695
  return;
61201
- const fd = openSync9(this.filePath, "r");
61696
+ const fd = openSync10(this.filePath, "r");
61202
61697
  let chunk;
61203
61698
  try {
61204
61699
  chunk = Buffer.alloc(size - this.offset);
61205
- const bytesRead = readSync2(fd, chunk, 0, chunk.length, this.offset);
61700
+ const bytesRead = readSync3(fd, chunk, 0, chunk.length, this.offset);
61206
61701
  this.offset += bytesRead;
61207
61702
  if (bytesRead < chunk.length)
61208
61703
  chunk = chunk.subarray(0, bytesRead);
61209
61704
  } finally {
61210
- closeSync9(fd);
61705
+ closeSync10(fd);
61211
61706
  }
61212
61707
  this.buffer += this.decoder.decode(chunk, { stream: true });
61213
61708
  const lines = this.buffer.split(`
@@ -61716,7 +62211,7 @@ function formatOtlpBatch(events, resource) {
61716
62211
  }
61717
62212
 
61718
62213
  // src/telemetry.ts
61719
- import { randomBytes as randomBytes12 } from "crypto";
62214
+ import { randomBytes as randomBytes14 } from "crypto";
61720
62215
  function getVersion() {
61721
62216
  return VERSION;
61722
62217
  }
@@ -61985,7 +62480,7 @@ function initTelemetry(_config) {
61985
62480
  } catch {
61986
62481
  consentEnabled = false;
61987
62482
  }
61988
- sessionId = randomBytes12(8).toString("hex");
62483
+ sessionId = randomBytes14(8).toString("hex");
61989
62484
  claudishVersion = getVersion();
61990
62485
  installMethod = detectInstallMethod();
61991
62486
  }
@@ -64880,7 +65375,7 @@ data: ${JSON.stringify(data)}
64880
65375
  };
64881
65376
  toolCalls.set(toolIdx, t);
64882
65377
  if (opts.onToolCall) {
64883
- opts.onToolCall(toolId, part.functionCall.name, part.thoughtSignature);
65378
+ opts.onToolCall(toolId, part.functionCall.name, part.thoughtSignature, typeof part.functionCall.id === "string" ? part.functionCall.id : undefined);
64884
65379
  }
64885
65380
  send("content_block_start", {
64886
65381
  type: "content_block_start",
@@ -67756,6 +68251,9 @@ function computeCacheReadDiscount(pricing, billedInputTokens, detail) {
67756
68251
  function computeTurnCost(pricing, inputTokens, outputTokens, detail) {
67757
68252
  return inputTokens / 1e6 * pricing.inputCostPer1M + outputTokens / 1e6 * pricing.outputCostPer1M - computeCacheReadDiscount(pricing, inputTokens, detail);
67758
68253
  }
68254
+ function clearTokenFileTotals(path) {
68255
+ tokenFileTotals.delete(path);
68256
+ }
67759
68257
 
67760
68258
  class TokenTracker {
67761
68259
  port;
@@ -67773,6 +68271,13 @@ class TokenTracker {
67773
68271
  startedAt = Date.now();
67774
68272
  sessionBilledInputTokens = 0;
67775
68273
  sessionCacheReadTokens = 0;
68274
+ reported = {
68275
+ totalCost: 0,
68276
+ billedInputTokens: 0,
68277
+ outputTokens: 0,
68278
+ totalTokens: 0,
68279
+ toolCalls: new Map
68280
+ };
67776
68281
  constructor(port, config) {
67777
68282
  this.port = port;
67778
68283
  this.config = config;
@@ -67939,11 +68444,47 @@ class TokenTracker {
67939
68444
  return "OpenAI";
67940
68445
  return name.charAt(0).toUpperCase() + name.slice(1);
67941
68446
  }
67942
- writeFile(inputTokens, outputTokens, isEstimate, requestPricing) {
68447
+ addToFileTotals(path, inputTokens) {
68448
+ let totals = tokenFileTotals.get(path);
68449
+ if (!totals) {
68450
+ totals = {
68451
+ totalCost: 0,
68452
+ billedInputTokens: 0,
68453
+ outputTokens: 0,
68454
+ totalTokens: 0,
68455
+ toolCalls: new Map,
68456
+ startedAt: this.startedAt
68457
+ };
68458
+ tokenFileTotals.set(path, totals);
68459
+ }
68460
+ totals.startedAt = Math.min(totals.startedAt, this.startedAt);
68461
+ totals.totalCost += this.sessionTotalCost - this.reported.totalCost;
68462
+ totals.billedInputTokens += this.sessionBilledInputTokens - this.reported.billedInputTokens;
68463
+ totals.outputTokens += this.sessionOutputTokens - this.reported.outputTokens;
68464
+ const ownTotalTokens = inputTokens + this.sessionOutputTokens;
68465
+ totals.totalTokens += ownTotalTokens - this.reported.totalTokens;
68466
+ for (const [name, count] of this.toolCallsByName) {
68467
+ const delta = count - (this.reported.toolCalls.get(name) ?? 0);
68468
+ if (delta !== 0)
68469
+ totals.toolCalls.set(name, (totals.toolCalls.get(name) ?? 0) + delta);
68470
+ }
68471
+ this.reported = {
68472
+ totalCost: this.sessionTotalCost,
68473
+ billedInputTokens: this.sessionBilledInputTokens,
68474
+ outputTokens: this.sessionOutputTokens,
68475
+ totalTokens: ownTotalTokens,
68476
+ toolCalls: new Map(this.toolCallsByName)
68477
+ };
68478
+ return totals;
68479
+ }
68480
+ writeFile(inputTokens, _outputTokens, isEstimate, requestPricing) {
67943
68481
  if (this.config.writesTokenFile === false)
67944
68482
  return;
67945
68483
  try {
67946
- const total = inputTokens + outputTokens;
68484
+ const outPath = resolveTokenFilePath(this.port);
68485
+ const totals = this.addToFileTotals(outPath, inputTokens);
68486
+ const outputTokens = totals.outputTokens;
68487
+ const total = totals.totalTokens;
67947
68488
  const cw = this.config.contextWindow;
67948
68489
  const leftPct = cw > 0 ? Math.max(0, Math.min(100, Math.round((cw - inputTokens) / cw * 100))) : -1;
67949
68490
  const pricing = requestPricing ?? this.getPricing();
@@ -67952,16 +68493,16 @@ class TokenTracker {
67952
68493
  input_tokens: inputTokens,
67953
68494
  output_tokens: outputTokens,
67954
68495
  total_tokens: total,
67955
- total_cost: this.sessionTotalCost,
68496
+ total_cost: totals.totalCost,
67956
68497
  context_window: cw > 0 ? cw : "unknown",
67957
68498
  context_left_percent: leftPct,
67958
68499
  provider_name: this.getDisplayName(),
67959
68500
  updated_at: Date.now(),
67960
68501
  is_free: isFreeModel,
67961
68502
  is_estimated: isEstimate || false,
67962
- started_at: this.startedAt,
67963
- tool_calls: this.getToolCalls(),
67964
- billed_input_tokens: this.sessionBilledInputTokens,
68503
+ started_at: totals.startedAt,
68504
+ tool_calls: [...totals.toolCalls].filter(([, count]) => count > 0).map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)),
68505
+ billed_input_tokens: totals.billedInputTokens,
67965
68506
  input_per_m: pricing.inputCostPer1M,
67966
68507
  output_per_m: pricing.outputCostPer1M
67967
68508
  };
@@ -67985,7 +68526,6 @@ class TokenTracker {
67985
68526
  gapEndSec: allowance.gapEndSec
67986
68527
  };
67987
68528
  }
67988
- const outPath = resolveTokenFilePath(this.port);
67989
68529
  mkdirSync18(dirname15(outPath), { recursive: true });
67990
68530
  writeFileSync13(outPath, JSON.stringify(data), "utf-8");
67991
68531
  } catch (e) {
@@ -67993,7 +68533,7 @@ class TokenTracker {
67993
68533
  }
67994
68534
  }
67995
68535
  }
67996
- var ALLOWANCE_LABEL_STALE_MS;
68536
+ var ALLOWANCE_LABEL_STALE_MS, tokenFileTotals;
67997
68537
  var init_token_tracker = __esm(() => {
67998
68538
  init_tool_name_utils();
67999
68539
  init_types2();
@@ -68002,6 +68542,7 @@ var init_token_tracker = __esm(() => {
68002
68542
  init_token_file();
68003
68543
  init_remote_provider_types();
68004
68544
  ALLOWANCE_LABEL_STALE_MS = 10 * 60 * 1000;
68545
+ tokenFileTotals = new Map;
68005
68546
  });
68006
68547
 
68007
68548
  // src/handlers/shared/upstream-error-capture.ts
@@ -68034,7 +68575,7 @@ var init_upstream_error_capture = __esm(() => {
68034
68575
  });
68035
68576
 
68036
68577
  // src/handlers/composed-handler.ts
68037
- import { randomUUID as randomUUID6 } from "crypto";
68578
+ import { randomUUID as randomUUID5 } from "crypto";
68038
68579
  function startAllowanceFlight() {
68039
68580
  try {
68040
68581
  return getAllowanceService().requestStarted();
@@ -68555,7 +69096,7 @@ class ComposedHandler {
68555
69096
  overload: { attempts: 0 },
68556
69097
  deadlineAt: tier1DeadlineAt(c),
68557
69098
  payloadVersion: 0,
68558
- requestId: randomUUID6(),
69099
+ requestId: randomUUID5(),
68559
69100
  outcomes: new Map,
68560
69101
  observedResponses: new WeakSet,
68561
69102
  ledger
@@ -69071,7 +69612,8 @@ class ComposedHandler {
69071
69612
  const fetchCurrent = () => {
69072
69613
  if (callSignal?.aborted)
69073
69614
  return Promise.reject(callAbortError());
69074
- return fetch(activeEndpoint, mergeSignalIntoInit({
69615
+ const send = this.provider.fetch ? (url, init) => this.provider.fetch(url, init) : fetch;
69616
+ return send(activeEndpoint, mergeSignalIntoInit({
69075
69617
  method: "POST",
69076
69618
  headers: activeHeaders,
69077
69619
  body: serialized.body,
@@ -70034,9 +70576,9 @@ class ComposedHandler {
70034
70576
  onToolCallObserved: observeToolCall
70035
70577
  });
70036
70578
  case "gemini-sse": {
70037
- const onToolCall = (toolId, name, thoughtSignature) => {
70579
+ const onToolCall = (toolId, name, thoughtSignature, callId) => {
70038
70580
  if (typeof adapter.registerToolCall === "function") {
70039
- adapter.registerToolCall(toolId, name, thoughtSignature);
70581
+ adapter.registerToolCall(toolId, name, thoughtSignature, callId);
70040
70582
  }
70041
70583
  };
70042
70584
  return createGeminiSseStream(c, response, {
@@ -71020,20 +71562,6 @@ var init_ollamacloud = __esm(() => {
71020
71562
  init_probe_discovery();
71021
71563
  });
71022
71564
 
71023
- // src/providers/transport/conversation-key.ts
71024
- import { createHash as createHash16, randomBytes as randomBytes13 } from "crypto";
71025
- function conversationKey(claudeRequest) {
71026
- const sessionId = extractSessionId(claudeRequest);
71027
- if (!sessionId)
71028
- return `claudish_${FALLBACK_CONVERSATION_KEY}`;
71029
- return `claudish_${createHash16("sha256").update(sessionId).digest("hex").slice(0, 32)}`;
71030
- }
71031
- var FALLBACK_CONVERSATION_KEY;
71032
- var init_conversation_key = __esm(() => {
71033
- init_harness();
71034
- FALLBACK_CONVERSATION_KEY = randomBytes13(16).toString("hex");
71035
- });
71036
-
71037
71565
  // src/providers/transport/openai-codex.ts
71038
71566
  var OpenAICodexTransport;
71039
71567
  var init_openai_codex = __esm(() => {
@@ -72279,7 +72807,10 @@ var init_provider_profiles = __esm(() => {
72279
72807
  antigravityProfile = {
72280
72808
  createHandler(ctx) {
72281
72809
  const transport = new AntigravityProviderTransport(ctx.modelName);
72282
- const adapter = new GeminiAPIFormat(ctx.modelName, undefined, { thinkingFromModelName: true });
72810
+ const adapter = new GeminiAPIFormat(ctx.modelName, undefined, {
72811
+ thinkingFromModelName: true,
72812
+ serverCallIds: true
72813
+ });
72283
72814
  const handler = new ComposedHandler(transport, ctx.targetModel, ctx.modelName, ctx.port, {
72284
72815
  adapter,
72285
72816
  unwrapGeminiResponse: true,
@@ -73648,7 +74179,100 @@ function getLegacySyntaxWarning(parsed) {
73648
74179
  return `Deprecation warning: "${parsed.original}" uses legacy prefix syntax.
73649
74180
  ` + ` Consider using: ${newSyntax}`;
73650
74181
  }
73651
- var AUTO_ROUTE_PROVIDER = "auto-route", PROVIDER_SHORTCUTS, PROVIDER_PREFIX, LOCAL_PROVIDERS, NATIVE_MODEL_PATTERNS, LEGACY_PREFIX_PATTERNS, MODEL_CHAIN_SEPARATOR = "+", MODE_MARKER_SEGMENT;
74182
+ function parseListingEntry(value) {
74183
+ const match = LISTING_ENTRY.exec(value.trim());
74184
+ if (!match)
74185
+ return null;
74186
+ return { shortcut: match[1].toLowerCase(), scope: match[2] ? "all" : "recommended" };
74187
+ }
74188
+ function modelValueForMessage(value) {
74189
+ return parseModelChain(value).map((element) => {
74190
+ const parsed = parseModelSpec(element);
74191
+ if (parsed.provider !== "custom-url")
74192
+ return element;
74193
+ try {
74194
+ return `<a raw URL at ${new URL(parsed.model).origin}>`;
74195
+ } catch {
74196
+ return "<a raw URL>";
74197
+ }
74198
+ }).join("+");
74199
+ }
74200
+ function pinnedSpecRefusal(spec) {
74201
+ const parsed = parseModelSpec(spec);
74202
+ if (parsed.provider === "custom-url") {
74203
+ return `--model ${modelValueForMessage(spec)}: a raw URL cannot be listed in /model. Declare the endpoint under customEndpoints and list it by name (--model <name>@).`;
74204
+ }
74205
+ if (parsed.provider === "native-anthropic") {
74206
+ return `--model ${spec}: a Claude model cannot be listed beside the start model, because Claude Code lists Claude's own models in /model already. Drop it, or give it as the last --model to start on it.`;
74207
+ }
74208
+ if (!parsed.isExplicitProvider) {
74209
+ if (parsed.provider === "unknown") {
74210
+ return `--model ${spec}: "${spec}" names no claudish provider to list. Use <provider>@${spec}, for example openrouter@${spec}.`;
74211
+ }
74212
+ return `--model ${spec}: a bare model name names no provider to list. Use <provider>@${spec}, or give it as the last --model to start on it.`;
74213
+ }
74214
+ return null;
74215
+ }
74216
+ function parseModelFlags(values) {
74217
+ const listings = [];
74218
+ const fullSpecs = [];
74219
+ const raw = [];
74220
+ for (const value of values) {
74221
+ const entry = parseListingEntry(value);
74222
+ if (entry) {
74223
+ const earlier = listings.find((l) => l.shortcut === entry.shortcut);
74224
+ if (earlier) {
74225
+ if (entry.scope === "all")
74226
+ earlier.scope = "all";
74227
+ } else {
74228
+ listings.push(entry);
74229
+ }
74230
+ continue;
74231
+ }
74232
+ fullSpecs.push(parseModelChain(value).map(normalizeNativeModelSpec));
74233
+ raw.push(value);
74234
+ }
74235
+ if (listings.length === 0) {
74236
+ const last = fullSpecs[fullSpecs.length - 1];
74237
+ if (!last)
74238
+ return { ok: true, value: { pinned: [], listings: [], hasLineup: false } };
74239
+ return {
74240
+ ok: true,
74241
+ value: {
74242
+ start: last[0],
74243
+ ...last.length > 1 ? { chain: last } : {},
74244
+ pinned: [],
74245
+ listings: [],
74246
+ hasLineup: false
74247
+ }
74248
+ };
74249
+ }
74250
+ for (let i = 0;i < fullSpecs.length; i++) {
74251
+ if (fullSpecs[i].length > 1) {
74252
+ return {
74253
+ ok: false,
74254
+ message: `--model ${modelValueForMessage(raw[i])}: a + routing chain cannot be combined with a listing entry. Give one model per --model.`
74255
+ };
74256
+ }
74257
+ }
74258
+ const specs = fullSpecs.map((chain) => chain[0]);
74259
+ const pinned = specs.slice(0, -1);
74260
+ for (const spec of pinned) {
74261
+ const refusal = pinnedSpecRefusal(spec);
74262
+ if (refusal)
74263
+ return { ok: false, message: refusal };
74264
+ }
74265
+ return {
74266
+ ok: true,
74267
+ value: {
74268
+ ...specs.length > 0 ? { start: specs[specs.length - 1] } : {},
74269
+ pinned,
74270
+ listings,
74271
+ hasLineup: true
74272
+ }
74273
+ };
74274
+ }
74275
+ var AUTO_ROUTE_PROVIDER = "auto-route", PROVIDER_SHORTCUTS, PROVIDER_PREFIX, LOCAL_PROVIDERS, NATIVE_MODEL_PATTERNS, LEGACY_PREFIX_PATTERNS, MODEL_CHAIN_SEPARATOR = "+", MODE_MARKER_SEGMENT, LISTING_ENTRY;
73652
74276
  var init_model_parser = __esm(() => {
73653
74277
  init_claude_code_aliases();
73654
74278
  init_provider_definitions();
@@ -73663,6 +74287,7 @@ var init_model_parser = __esm(() => {
73663
74287
  NATIVE_MODEL_PATTERNS = getNativeModelPatterns();
73664
74288
  LEGACY_PREFIX_PATTERNS = getLegacyPrefixPatterns();
73665
74289
  MODE_MARKER_SEGMENT = /^(pro|standard)(#[a-z]+)?(:\d+)?$/i;
74290
+ LISTING_ENTRY = /^([^@\s/:+#]+)@(\*)?$/;
73666
74291
  });
73667
74292
 
73668
74293
  // src/providers/predefined-catalog.ts
@@ -87210,7 +87835,7 @@ function herdrPaneEnv(env = process.env) {
87210
87835
  }
87211
87836
 
87212
87837
  // src/auth/claude-code-facts.ts
87213
- import { createHash as createHash17 } from "crypto";
87838
+ import { createHash as createHash18 } from "crypto";
87214
87839
  import { homedir as homedir35 } from "os";
87215
87840
  import { isAbsolute as isAbsolute2, resolve as resolve4 } from "path";
87216
87841
  function defaultConfigDir(env) {
@@ -87223,7 +87848,7 @@ function claudeCodeConfigDir(env = process.env) {
87223
87848
  return isAbsolute2(raw) ? resolve4(raw) : resolve4(process.cwd(), raw);
87224
87849
  }
87225
87850
  function configDirHash(configDir) {
87226
- return createHash17("sha256").update(configDir).digest("hex").slice(0, 8);
87851
+ return createHash18("sha256").update(configDir).digest("hex").slice(0, 8);
87227
87852
  }
87228
87853
  function claudeCodeSecureStorageServices(kind, env = process.env) {
87229
87854
  const base = `${BASE_KEYCHAIN_SERVICE}${kind}`;
@@ -89236,7 +89861,7 @@ var init_slot_steps = __esm(() => {
89236
89861
  });
89237
89862
 
89238
89863
  // src/pane/subagent-ledger.ts
89239
- import { createHash as createHash18 } from "crypto";
89864
+ import { createHash as createHash19 } from "crypto";
89240
89865
  function str4(v) {
89241
89866
  return typeof v === "string" && v.length > 0 ? v : null;
89242
89867
  }
@@ -89248,7 +89873,7 @@ function subagentDescription(v) {
89248
89873
  return line ? line.slice(0, SUBAGENT_DESCRIPTION_MAX) : null;
89249
89874
  }
89250
89875
  function digest(text) {
89251
- return createHash18("sha256").update(text).digest("base64");
89876
+ return createHash19("sha256").update(text).digest("base64");
89252
89877
  }
89253
89878
  function userText(r) {
89254
89879
  const c = r.message?.content;
@@ -89564,14 +90189,14 @@ var init_subagent_ledger = __esm(() => {
89564
90189
 
89565
90190
  // src/pane/transcript-follower.ts
89566
90191
  import {
89567
- closeSync as closeSync10,
90192
+ closeSync as closeSync11,
89568
90193
  existsSync as existsSync27,
89569
90194
  fstatSync as fstatSync3,
89570
- openSync as openSync10,
90195
+ openSync as openSync11,
89571
90196
  readFileSync as readFileSync36,
89572
- readSync as readSync3,
90197
+ readSync as readSync4,
89573
90198
  readdirSync as readdirSync6,
89574
- realpathSync as realpathSync4,
90199
+ realpathSync as realpathSync5,
89575
90200
  statSync as statSync13
89576
90201
  } from "fs";
89577
90202
  import { join as join39 } from "path";
@@ -89591,7 +90216,7 @@ function initialFollowerState(resolvePath = safeRealpath) {
89591
90216
  }
89592
90217
  function safeRealpath(p) {
89593
90218
  try {
89594
- return realpathSync4(p);
90219
+ return realpathSync5(p);
89595
90220
  } catch {
89596
90221
  return p;
89597
90222
  }
@@ -90079,7 +90704,7 @@ class Tail {
90079
90704
  read() {
90080
90705
  let fd;
90081
90706
  try {
90082
- fd = openSync10(this.path, "r");
90707
+ fd = openSync11(this.path, "r");
90083
90708
  } catch {
90084
90709
  return [];
90085
90710
  }
@@ -90088,7 +90713,7 @@ class Tail {
90088
90713
  if (size <= this.offset)
90089
90714
  return [];
90090
90715
  const chunk = Buffer.alloc(size - this.offset);
90091
- const got = readSync3(fd, chunk, 0, chunk.length, this.offset);
90716
+ const got = readSync4(fd, chunk, 0, chunk.length, this.offset);
90092
90717
  this.offset += got;
90093
90718
  const fresh = chunk.subarray(0, got);
90094
90719
  const buf = this.rest.length ? Buffer.concat([this.rest, fresh]) : fresh;
@@ -90105,7 +90730,7 @@ class Tail {
90105
90730
  this.rest = Buffer.from(buf.subarray(start));
90106
90731
  return out;
90107
90732
  } finally {
90108
- closeSync10(fd);
90733
+ closeSync11(fd);
90109
90734
  }
90110
90735
  }
90111
90736
  }
@@ -90366,7 +90991,7 @@ __export(exports_session_discovery, {
90366
90991
  transcriptPathFor: () => transcriptPathFor
90367
90992
  });
90368
90993
  import { execFile as execFile4, execFileSync as execFileSync2 } from "child_process";
90369
- import { closeSync as closeSync11, openSync as openSync11, readSync as readSync4, readdirSync as readdirSync7, realpathSync as realpathSync5, statSync as statSync14 } from "fs";
90994
+ import { closeSync as closeSync12, openSync as openSync12, readSync as readSync5, readdirSync as readdirSync7, realpathSync as realpathSync6, statSync as statSync14 } from "fs";
90370
90995
  import { basename as basename3, join as join41 } from "path";
90371
90996
  function projectsDir(env = process.env) {
90372
90997
  return join41(claudeConfigDir(env), "projects");
@@ -90377,7 +91002,7 @@ function slugForPath(absPath) {
90377
91002
  function transcriptPathFor(cwd, sessionUuid, projectsRoot = projectsDir()) {
90378
91003
  let real = cwd;
90379
91004
  try {
90380
- real = realpathSync5(cwd);
91005
+ real = realpathSync6(cwd);
90381
91006
  } catch {}
90382
91007
  return join41(projectsRoot, slugForPath(real), `${sessionUuid}.jsonl`);
90383
91008
  }
@@ -90616,16 +91241,16 @@ function readChunk(file, pos, len) {
90616
91241
  return "";
90617
91242
  let fd = null;
90618
91243
  try {
90619
- fd = openSync11(file, "r");
91244
+ fd = openSync12(file, "r");
90620
91245
  const buf = Buffer.allocUnsafe(len);
90621
- const n = readSync4(fd, buf, 0, len, pos);
91246
+ const n = readSync5(fd, buf, 0, len, pos);
90622
91247
  return buf.subarray(0, n).toString("utf-8");
90623
91248
  } catch {
90624
91249
  return "";
90625
91250
  } finally {
90626
91251
  if (fd !== null) {
90627
91252
  try {
90628
- closeSync11(fd);
91253
+ closeSync12(fd);
90629
91254
  } catch {}
90630
91255
  }
90631
91256
  }
@@ -91895,11 +92520,11 @@ var init_magmux_binary = () => {};
91895
92520
  // src/launcher/magmux-wrapper.ts
91896
92521
  import {
91897
92522
  chmodSync as chmodSync3,
91898
- closeSync as closeSync12,
92523
+ closeSync as closeSync13,
91899
92524
  existsSync as existsSync30,
91900
92525
  mkdirSync as mkdirSync20,
91901
92526
  mkdtempSync,
91902
- openSync as openSync12,
92527
+ openSync as openSync13,
91903
92528
  rmSync as rmSync11,
91904
92529
  writeFileSync as writeFileSync16
91905
92530
  } from "fs";
@@ -91975,11 +92600,11 @@ function planMagmuxWrap(input) {
91975
92600
  const scriptPath = join44(scriptDir, "claude-launch.sh");
91976
92601
  const parentEnv = input.parentEnv ?? process.env;
91977
92602
  const deltas = envDeltas(parentEnv, input.childEnv);
91978
- const fd = openSync12(scriptPath, "wx", 384);
92603
+ const fd = openSync13(scriptPath, "wx", 384);
91979
92604
  try {
91980
92605
  writeFileSync16(fd, buildLauncherScript(input.claudeBinary, input.claudeArgs, deltas));
91981
92606
  } finally {
91982
- closeSync12(fd);
92607
+ closeSync13(fd);
91983
92608
  }
91984
92609
  const env = { ...input.childEnv };
91985
92610
  for (const k of STRIPPED_CHILD_VARS)
@@ -92086,6 +92711,80 @@ var init_magmux_wrapper = __esm(() => {
92086
92711
  STRIPPED_CHILD_VARS = ["CLAUDECODE", "CLAUDE_CODE_CHILD_SESSION"];
92087
92712
  });
92088
92713
 
92714
+ // src/model-vars-env.ts
92715
+ function recordModelVars(env, set) {
92716
+ const record = {};
92717
+ for (const name of MODEL_VAR_NAMES) {
92718
+ const value = set[name];
92719
+ if (typeof value !== "string" || value.length === 0)
92720
+ continue;
92721
+ env[name] = value;
92722
+ record[name] = value;
92723
+ }
92724
+ if (Object.keys(record).length > 0) {
92725
+ env[ENV.CLAUDISH_SET_MODEL_VARS] = JSON.stringify(record);
92726
+ }
92727
+ }
92728
+ function readRecord(env) {
92729
+ const raw = env[ENV.CLAUDISH_SET_MODEL_VARS];
92730
+ if (typeof raw !== "string" || raw.length === 0)
92731
+ return {};
92732
+ try {
92733
+ const parsed = JSON.parse(raw);
92734
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
92735
+ return {};
92736
+ const record = {};
92737
+ for (const name of MODEL_VAR_NAMES) {
92738
+ const value = parsed[name];
92739
+ if (typeof value === "string")
92740
+ record[name] = value;
92741
+ }
92742
+ return record;
92743
+ } catch {
92744
+ return {};
92745
+ }
92746
+ }
92747
+ function isModelVarSetByClaudish(env, name) {
92748
+ const value = env[name];
92749
+ return typeof value === "string" && value.length > 0 && readRecord(env)[name] === value;
92750
+ }
92751
+ function isClaudishProviderSpec(value) {
92752
+ const parsed = parseModelSpec(value);
92753
+ return parsed.isExplicitProvider && parsed.provider !== "native-anthropic";
92754
+ }
92755
+ function scrubInheritedModelVars(env, keep, opts = {}) {
92756
+ const record = readRecord(env);
92757
+ const removed = [];
92758
+ const survived = [];
92759
+ for (const name of MODEL_VAR_NAMES) {
92760
+ if (name === "ANTHROPIC_MODEL" ? keep.model : keep.smallFast)
92761
+ continue;
92762
+ const value = env[name];
92763
+ if (typeof value !== "string" || value.length === 0)
92764
+ continue;
92765
+ const setByClaudish = record[name] === value;
92766
+ if (setByClaudish || opts.keepsLogin === true && isClaudishProviderSpec(value)) {
92767
+ delete env[name];
92768
+ removed.push(name);
92769
+ } else {
92770
+ survived.push({ name, value });
92771
+ }
92772
+ }
92773
+ if (ENV.CLAUDISH_SET_MODEL_VARS in env)
92774
+ delete env[ENV.CLAUDISH_SET_MODEL_VARS];
92775
+ const haiku = env[ENV.ANTHROPIC_DEFAULT_HAIKU_MODEL];
92776
+ if (typeof haiku === "string" && haiku.length > 0) {
92777
+ survived.push({ name: ENV.ANTHROPIC_DEFAULT_HAIKU_MODEL, value: haiku });
92778
+ }
92779
+ return { removed, survived };
92780
+ }
92781
+ var MODEL_VAR_NAMES;
92782
+ var init_model_vars_env = __esm(() => {
92783
+ init_config();
92784
+ init_model_parser();
92785
+ MODEL_VAR_NAMES = ["ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL"];
92786
+ });
92787
+
92089
92788
  // src/providers/cache-ttl.ts
92090
92789
  var FIREBASE_CACHE_TTL_HOURS = 24, FIREBASE_CACHE_TTL_MS;
92091
92790
  var init_cache_ttl = __esm(() => {
@@ -94128,19 +94827,8 @@ function storedOutcome(provider, displayName, list, catalog) {
94128
94827
  const outcome = outcomeFromModelsCatalog(provider, displayName, servedOutcomeOf(list.models), servedModelsForProvider(provider, catalog));
94129
94828
  return outcome.kind === "rows" ? { ...outcome, listFetchedAt: list.fetchedAt } : null;
94130
94829
  }
94131
- async function liveAccountModelsCatalog(provider) {
94132
- const result = await refreshAccountModelsList(provider, "picker-provider", {
94133
- minAgeMs: LIVE_MS
94134
- });
94135
- if (result.kind === "refreshed") {
94136
- return result.outcome.kind === "served" ? servedOutcomeOf(result.outcome.models) : result.outcome;
94137
- }
94138
- if (result.reason === "too-recent") {
94139
- const list = await readAccountModelsList(provider);
94140
- if (list)
94141
- return servedOutcomeOf(list.models);
94142
- }
94143
- return discoverProviderModelsCatalog(provider);
94830
+ function pickerLiveModelsCatalog(provider) {
94831
+ return liveOrStoredModelsCatalog(provider, "picker-provider");
94144
94832
  }
94145
94833
  function createPickerDataSource() {
94146
94834
  const catalog = createCatalogClient();
@@ -94228,7 +94916,7 @@ function createPickerDataSource() {
94228
94916
  return [...stored.rows, ...fromCatalog.filter((m) => !listed.has(m.id))];
94229
94917
  },
94230
94918
  discoverModelsCatalog(provider) {
94231
- return buildDiscoveredModelOutcome(provider, names.get(provider) ?? provider, catalog, isPersistedListProvider(provider) ? liveAccountModelsCatalog : undefined);
94919
+ return buildDiscoveredModelOutcome(provider, names.get(provider) ?? provider, catalog, isPersistedListProvider(provider) ? pickerLiveModelsCatalog : undefined);
94232
94920
  },
94233
94921
  cachedModelsCatalog(provider) {
94234
94922
  return cachedOutcome(provider);
@@ -106971,9 +107659,9 @@ var init_seam_hooks = __esm(() => {
106971
107659
  });
106972
107660
 
106973
107661
  // src/hooks/seam-tap.ts
106974
- import { randomUUID as randomUUID7 } from "crypto";
107662
+ import { randomUUID as randomUUID6 } from "crypto";
106975
107663
  function newRequestId() {
106976
- return randomUUID7();
107664
+ return randomUUID6();
106977
107665
  }
106978
107666
 
106979
107667
  class EndLine {
@@ -107454,14 +108142,16 @@ async function createProxyServer(port, _openrouterApiKey, model, monitorMode = f
107454
108142
  return out.markers && (out.markers.mode || out.markers.speed) ? new WireMarkerHandler(handler, out.markers) : handler;
107455
108143
  };
107456
108144
  const requestProbeHopOrigin = (c) => probeHopOriginOf(c.req.header(PROBE_HOP_ORIGIN_HEADER), options.probeProxy);
108145
+ const lineupSpecs = new Set((options.modelLineup ?? []).map((row) => row.model));
107457
108146
  const resolveHandlerForRequest = async (requestedModel, out, probeHopOrigin) => {
107458
108147
  if (monitorMode)
107459
108148
  return nativeHandler;
107460
108149
  let target = requestedModel;
107461
108150
  let wasFromModelMap = false;
107462
108151
  let targetFromLaunch = false;
108152
+ const lineupMatched = lineupSpecs.has(requestedModel);
107463
108153
  let slotMatched = false;
107464
- const slot = options.slotMap?.get(requestedModel);
108154
+ const slot = lineupMatched ? undefined : options.slotMap?.get(requestedModel);
107465
108155
  if (slot) {
107466
108156
  target = slot.provider != null && slot.provider !== "" ? `${slot.provider}@${slot.model}` : slot.model;
107467
108157
  slotMatched = true;
@@ -107470,8 +108160,9 @@ async function createProxyServer(port, _openrouterApiKey, model, monitorMode = f
107470
108160
  logStderr(`[Serve] slot ${requestedModel} \u2192 ${target}`);
107471
108161
  }
107472
108162
  }
108163
+ const claudeRowPicked = options.claudeRowsAsPicked === true && nativeRouteFor(requestedModel) !== null;
107473
108164
  const req = requestedModel.toLowerCase();
107474
- if (slotMatched) {} else if (modelMap) {
108165
+ if (slotMatched || lineupMatched) {} else if (modelMap) {
107475
108166
  if (req.includes("opus") && modelMap.opus) {
107476
108167
  target = modelMap.opus;
107477
108168
  wasFromModelMap = true;
@@ -107481,10 +108172,10 @@ async function createProxyServer(port, _openrouterApiKey, model, monitorMode = f
107481
108172
  } else if (req.includes("haiku") && modelMap.haiku) {
107482
108173
  target = modelMap.haiku;
107483
108174
  wasFromModelMap = true;
107484
- } else if (model)
108175
+ } else if (model && !claudeRowPicked)
107485
108176
  target = model;
107486
- targetFromLaunch = wasFromModelMap || Boolean(model);
107487
- } else if (model) {
108177
+ targetFromLaunch = wasFromModelMap || Boolean(model) && !claudeRowPicked;
108178
+ } else if (model && !claudeRowPicked) {
107488
108179
  target = model;
107489
108180
  targetFromLaunch = true;
107490
108181
  }
@@ -107701,7 +108392,18 @@ ${plan.hint}` : `[Route] ${plan.reason}`;
107701
108392
  }
107702
108393
  return [...seen];
107703
108394
  })();
108395
+ const lineupModels = () => (options.modelLineup ?? []).map((row) => ({
108396
+ id: row.model,
108397
+ type: "model",
108398
+ object: "model",
108399
+ display_name: redactForClient(row.label),
108400
+ created: MODEL_LIST_CREATED,
108401
+ owned_by: "claudish"
108402
+ }));
107704
108403
  app.get("/v1/models", (c) => {
108404
+ if (servedSlotIds.length === 0 && options.modelLineup !== undefined) {
108405
+ return c.json({ object: "list", has_more: false, data: lineupModels() });
108406
+ }
107705
108407
  const ids = servedSlotIds.length > 0 ? servedSlotIds : discoverableModelIds;
107706
108408
  return c.json({
107707
108409
  object: "list",
@@ -107710,7 +108412,7 @@ ${plan.hint}` : `[Route] ${plan.reason}`;
107710
108412
  id,
107711
108413
  object: "model",
107712
108414
  type: "model",
107713
- created: 1716000000,
108415
+ created: MODEL_LIST_CREATED,
107714
108416
  owned_by: "claudish"
107715
108417
  }))
107716
108418
  });
@@ -107849,6 +108551,7 @@ ${plan.hint}` : `[Route] ${plan.reason}`;
107849
108551
  if (advisorRuntime)
107850
108552
  await shutdownAdvisorChains(advisorRuntime.chains.values());
107851
108553
  closeAllEpisodes();
108554
+ clearTokenFileTotals(resolveTokenFilePath(port));
107852
108555
  },
107853
108556
  invalidateHandlerCache: (providerSlug) => {
107854
108557
  if (!providerSlug) {
@@ -107871,7 +108574,7 @@ ${plan.hint}` : `[Route] ${plan.reason}`;
107871
108574
  }
107872
108575
  };
107873
108576
  }
107874
- var RoutingError, classifierCaptureDirReady = false;
108577
+ var RoutingError, classifierCaptureDirReady = false, MODEL_LIST_CREATED = 1716000000;
107875
108578
  var init_proxy_server = __esm(() => {
107876
108579
  init_dist13();
107877
108580
  init_cors();
@@ -107891,6 +108594,7 @@ var init_proxy_server = __esm(() => {
107891
108594
  init_anthropic_forward();
107892
108595
  init_call_context();
107893
108596
  init_hop_decision();
108597
+ init_token_tracker();
107894
108598
  init_hooks();
107895
108599
  init_response_seam();
107896
108600
  init_logger();
@@ -107913,6 +108617,7 @@ var init_proxy_server = __esm(() => {
107913
108617
  init_coordinator();
107914
108618
  init_redact();
107915
108619
  init_pricing_cache();
108620
+ init_token_file();
107916
108621
  init_test_upstream();
107917
108622
  RoutingError = class RoutingError extends Error {
107918
108623
  constructor(message) {
@@ -108096,7 +108801,7 @@ async function parseArgs(args) {
108096
108801
  const anthropicModel = process.env[ENV.ANTHROPIC_MODEL];
108097
108802
  if (claudishModel) {
108098
108803
  config.model = claudishModel;
108099
- } else if (anthropicModel) {
108804
+ } else if (anthropicModel && !isModelVarSetByClaudish(process.env, "ANTHROPIC_MODEL")) {
108100
108805
  config.model = anthropicModel;
108101
108806
  }
108102
108807
  const tierSources = {};
@@ -108160,6 +108865,7 @@ async function parseArgs(args) {
108160
108865
  if (config.debug && config.logLevel === "info") {
108161
108866
  config.logLevel = "debug";
108162
108867
  }
108868
+ const modelValues = [];
108163
108869
  let i = 0;
108164
108870
  while (i < args.length) {
108165
108871
  const arg = args[i];
@@ -108174,6 +108880,9 @@ async function parseArgs(args) {
108174
108880
  config.model = chain[0];
108175
108881
  if (chain.length > 1)
108176
108882
  config.modelChain = chain;
108883
+ else
108884
+ delete config.modelChain;
108885
+ modelValues.push(modelArg);
108177
108886
  } else if (arg === "--model-pinned") {
108178
108887
  config.modelPinned = true;
108179
108888
  } else if (arg === "--claude-subscription-pin") {
@@ -108517,6 +109226,16 @@ Usage: claudish --models --provider <slug>`);
108517
109226
  }
108518
109227
  i++;
108519
109228
  }
109229
+ if (modelValues.some((value) => parseListingEntry(value) !== null)) {
109230
+ const flags = parseModelFlags(modelValues);
109231
+ if (!flags.ok) {
109232
+ console.error(`[claudish] Error: ${redactSecrets(flags.message)}`);
109233
+ process.exit(1);
109234
+ }
109235
+ config.model = flags.value.start;
109236
+ delete config.modelChain;
109237
+ config._modelFlags = flags.value;
109238
+ }
108520
109239
  if (!config._hasPositionalPrompt && !config.stdin && !config._hasPrintFlag) {
108521
109240
  config.interactive = true;
108522
109241
  }
@@ -109296,6 +110015,9 @@ ${shortcutTable}
109296
110015
  ${h("OPTIONS")}
109297
110016
  ${green("-i, --interactive")} Run in interactive mode (default when no prompt given)
109298
110017
  ${green("-m, --model")} ${yellow("<model>")} Model to use (required for single-shot mode)
110018
+ ${dim("--model <provider>@ (no model) lists that provider's models in /model;")}
110019
+ ${dim("--model '<provider>@*' lists every model a gateway serves. Repeat --model")}
110020
+ ${dim("to list several; the last <provider>@<model> starts the session.")}
109299
110021
  ${green("--profile")} ${yellow("<name>")} Use named profile for model mapping (default profile if omitted)
109300
110022
  ${green("--default-provider")} ${yellow("<name>")} Fallback provider for bare model names (claudish provider or customEndpoints key)
109301
110023
  ${dim('"" disables it. Precedence: this flag > CLAUDISH_DEFAULT_PROVIDER env > config.json')}
@@ -109687,6 +110409,7 @@ var init_cli = __esm(() => {
109687
110409
  init_logger();
109688
110410
  init_model_loader();
109689
110411
  init_model_selector();
110412
+ init_model_vars_env();
109690
110413
  init_probe_chain();
109691
110414
  init_probe_results_printer();
109692
110415
  init_probe_tui_runtime();
@@ -109708,6 +110431,7 @@ var init_cli = __esm(() => {
109708
110431
  init_routing_rules();
109709
110432
  init_recommended_listing();
109710
110433
  init_settings();
110434
+ init_redact();
109711
110435
  init_ansi();
109712
110436
  init_provider_resolver();
109713
110437
  __filename2 = fileURLToPath2(import.meta.url);
@@ -110207,7 +110931,7 @@ var init_process_identity = __esm(() => {
110207
110931
 
110208
110932
  // src/pane/pane-launch.ts
110209
110933
  import { spawn } from "child_process";
110210
- import { randomBytes as randomBytes14 } from "crypto";
110934
+ import { randomBytes as randomBytes15 } from "crypto";
110211
110935
  import {
110212
110936
  chmodSync as chmodSync4,
110213
110937
  lstatSync as lstatSync7,
@@ -110268,7 +110992,7 @@ function ensureSockRoot(given = sockRootFor()) {
110268
110992
  }
110269
110993
  function mintPaneId(kind, label) {
110270
110994
  const head = `c${process.pid}-${OWNER_START36}-${kind}`;
110271
- const tail = `-${randomBytes14(3).toString("hex")}`;
110995
+ const tail = `-${randomBytes15(3).toString("hex")}`;
110272
110996
  const room = Math.max(0, 40 - head.length - tail.length);
110273
110997
  const clean = label.replace(/[^A-Za-z0-9_]/g, "").slice(0, room);
110274
110998
  const id = `${head}${clean}${tail}`;
@@ -111425,14 +112149,14 @@ var init_terminal_isolation = __esm(() => {
111425
112149
 
111426
112150
  // src/claude-runner.ts
111427
112151
  import { spawn as spawn2 } from "child_process";
111428
- import { randomUUID as randomUUID8 } from "crypto";
112152
+ import { randomUUID as randomUUID7 } from "crypto";
111429
112153
  import {
111430
112154
  chmodSync as chmodSync5,
111431
- closeSync as closeSync13,
112155
+ closeSync as closeSync14,
111432
112156
  existsSync as existsSync37,
111433
112157
  mkdirSync as mkdirSync26,
111434
112158
  mkdtempSync as mkdtempSync3,
111435
- openSync as openSync13,
112159
+ openSync as openSync14,
111436
112160
  readFileSync as readFileSync43,
111437
112161
  readdirSync as readdirSync9,
111438
112162
  rmSync as rmSync12,
@@ -111457,7 +112181,17 @@ function hasNativeAnthropicMapping(config) {
111457
112181
  config.modelHaiku,
111458
112182
  config.modelSubagent
111459
112183
  ];
111460
- return models.some((m) => m && nativeRouteFor(m) !== null);
112184
+ return models.some((m) => m && nativeRouteFor(m) !== null) || startsOnClaudeSubscription(config);
112185
+ }
112186
+ function startsOnClaudeSubscription(config) {
112187
+ if ((config.modelListings?.length ?? 0) === 0)
112188
+ return false;
112189
+ if (config.monitor)
112190
+ return false;
112191
+ if (config.model || (config.modelChain?.length ?? 0) > 0)
112192
+ return false;
112193
+ const tiers = [config.modelOpus, config.modelSonnet, config.modelHaiku, config.modelSubagent];
112194
+ return !tiers.some((m) => typeof m === "string" && m.length > 0);
111461
112195
  }
111462
112196
  function claudeLaunchAuthLine(launch, env, keySource) {
111463
112197
  const state = (name) => {
@@ -111646,6 +112380,17 @@ function settingsArgOccurrences(args) {
111646
112380
  }
111647
112381
  return out;
111648
112382
  }
112383
+ function settingsArgScopeOf(config) {
112384
+ return config.modelLineup?.picker ? "every" : "first";
112385
+ }
112386
+ function settingsArgValues(claudeArgs, scope) {
112387
+ if (scope === "every") {
112388
+ return settingsArgOccurrences(claudeArgs).flatMap((o) => o.value ? [o.value] : []);
112389
+ }
112390
+ const idx = claudeArgs.indexOf("--settings");
112391
+ const value = idx === -1 ? undefined : claudeArgs[idx + 1];
112392
+ return value ? [value] : [];
112393
+ }
111649
112394
  function customHeaderAuthNames(value) {
111650
112395
  const names = new Set;
111651
112396
  if (typeof value !== "string" || !value)
@@ -111809,6 +112554,42 @@ function settingsClaudeLoginToken(config, env = process.env, deps = {}) {
111809
112554
  }
111810
112555
  return "absent";
111811
112556
  }
112557
+ function modelPickerSources(config, env = process.env, deps = {}) {
112558
+ let user = null;
112559
+ let userRank = -1;
112560
+ let managed = null;
112561
+ const availableModels = [];
112562
+ claudeSettingsLayers(config, env, deps).forEach((layer, index) => {
112563
+ const settings = layer.settings;
112564
+ if (settings === null)
112565
+ return;
112566
+ const where = layer.file ?? layer.where;
112567
+ if ("availableModels" in settings)
112568
+ availableModels.push(where);
112569
+ if (!("modelPicker" in settings))
112570
+ return;
112571
+ if (layer.tier === "managed") {
112572
+ managed = where;
112573
+ return;
112574
+ }
112575
+ const rank = NON_MANAGED_TIER_RANK[layer.tier] * 1e4 + index;
112576
+ if (rank < userRank)
112577
+ return;
112578
+ userRank = rank;
112579
+ const picker = settings.modelPicker;
112580
+ const record = picker && typeof picker === "object" && !Array.isArray(picker) ? picker : {};
112581
+ user = {
112582
+ where,
112583
+ options: Array.isArray(record.options) ? record.options : [],
112584
+ ..."replaceBuiltInOptions" in record ? { replaceBuiltInOptions: record.replaceBuiltInOptions } : {}
112585
+ };
112586
+ });
112587
+ return { user, managed, availableModels };
112588
+ }
112589
+ function unreadableSettingsArgs(config, deps = {}) {
112590
+ const readFile = deps.readFile ?? ((path) => readFileSync43(path, "utf-8"));
112591
+ return settingsArgOccurrences(config.claudeArgs ?? []).flatMap((occurrence, i) => occurrence.value && readSettingsSource(occurrence.value, readFile) === null ? [i + 1] : []);
112592
+ }
111812
112593
  function enabledSettingSources(args) {
111813
112594
  let value;
111814
112595
  for (let i = 0;i < args.length; i++) {
@@ -111842,7 +112623,7 @@ function readSettingsSource(source, readFile) {
111842
112623
  try {
111843
112624
  const raw = isInlineSettings(source) ? source : readFile(source);
111844
112625
  const parsed = JSON.parse(raw);
111845
- return parsed && typeof parsed === "object" ? parsed : null;
112626
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
111846
112627
  } catch {
111847
112628
  return null;
111848
112629
  }
@@ -112111,12 +112892,9 @@ function userSettingsFileCandidates(cwd) {
112111
112892
  join53(cwd, ".claude", "settings.local.json")
112112
112893
  ];
112113
112894
  }
112114
- function discoverUserStatusLineCommand(claudeArgs = [], cwd = process.cwd()) {
112895
+ function discoverUserStatusLineCommand(claudeArgs = [], cwd = process.cwd(), scope = "first") {
112115
112896
  const sources = userSettingsFileCandidates(cwd).filter((file) => existsSync37(file));
112116
- const idx = claudeArgs.indexOf("--settings");
112117
- const settingsArg = idx === -1 ? undefined : claudeArgs[idx + 1];
112118
- if (settingsArg)
112119
- sources.push(settingsArg);
112897
+ sources.push(...settingsArgValues(claudeArgs, scope));
112120
112898
  let effective;
112121
112899
  for (const source of sources) {
112122
112900
  const layer = parseSettingsArgSafe(source);
@@ -112147,7 +112925,7 @@ function buildChainedStatusCommand(userCommand, claudishBody, claudishSegment) {
112147
112925
  const emit = `if [ -n "$USER_OUT" ]; then LAST="\${USER_OUT##*$'\\n'}"; if [ "$LAST" = "$USER_OUT" ]; then printf '%s%s%s\\n' "$USER_OUT" "$SEP" "$SEG"; else printf '%s\\n%s%s%s\\n' "\${USER_OUT%$'\\n'*}" "$LAST" "$SEP" "$SEG"; fi; else printf '%s\\n' "$SEG"; fi`;
112148
112926
  return `JSON=$(cat); ${runUser}; ${claudishBody}; SEG=$(${claudishSegment}); ${separator}; ${emit}`;
112149
112927
  }
112150
- function createTempSettingsFile(_modelDisplay, port, proxyAuthMode, userStatusLineCommand) {
112928
+ function createTempSettingsFile(_modelDisplay, port, proxyAuthMode, userStatusLineCommand, modelPicker) {
112151
112929
  const homeDir = process.env.HOME || process.env.USERPROFILE || tmpdir2();
112152
112930
  const claudishDir = join53(homeDir, ".claudish");
112153
112931
  try {
@@ -112192,7 +112970,7 @@ function createTempSettingsFile(_modelDisplay, port, proxyAuthMode, userStatusLi
112192
112970
  command: statusCommand,
112193
112971
  padding: 0
112194
112972
  };
112195
- const settings = buildClaudishSettingsOverlay(statusLine, proxyAuthMode);
112973
+ const settings = buildClaudishSettingsOverlay(statusLine, proxyAuthMode, isPaneChild(), modelPicker);
112196
112974
  writeFileSync20(tempPath, JSON.stringify(settings, null, 2), { encoding: "utf-8", mode: 384 });
112197
112975
  return { path: tempPath, statusLine, tokenFilePath };
112198
112976
  }
@@ -112204,7 +112982,7 @@ function scrubChildEnv(env, opts) {
112204
112982
  for (const key of PANE_LAUNCH_VARS)
112205
112983
  delete env[key];
112206
112984
  }
112207
- function buildClaudishSettingsOverlay(statusLine, proxyAuthMode, paneChild = isPaneChild()) {
112985
+ function buildClaudishSettingsOverlay(statusLine, proxyAuthMode, paneChild = isPaneChild(), modelPicker) {
112208
112986
  const settings = { statusLine, disableClaudeAiConnectors: true };
112209
112987
  if (proxyAuthMode) {
112210
112988
  settings.forceLoginMethod = "console";
@@ -112215,9 +112993,36 @@ function buildClaudishSettingsOverlay(statusLine, proxyAuthMode, paneChild = isP
112215
112993
  settings.wheelScrollAccelerationEnabled = false;
112216
112994
  settings.tui = "fullscreen";
112217
112995
  }
112996
+ if (modelPicker)
112997
+ settings.modelPicker = modelPicker;
112218
112998
  return settings;
112219
112999
  }
112220
- function mergeUserSettingsIfPresent(config, tempSettingsPath, statusLine, proxyAuthMode, paneChild = isPaneChild()) {
113000
+ function applyClaudishSettingsKeys(userSettings, statusLine, proxyAuthMode, paneChild) {
113001
+ userSettings.statusLine = statusLine;
113002
+ if (!("disableClaudeAiConnectors" in userSettings)) {
113003
+ userSettings.disableClaudeAiConnectors = true;
113004
+ }
113005
+ if (proxyAuthMode && !("forceLoginMethod" in userSettings)) {
113006
+ userSettings.forceLoginMethod = "console";
113007
+ }
113008
+ if (paneChild && !("skipDangerousModePermissionPrompt" in userSettings)) {
113009
+ userSettings.skipDangerousModePermissionPrompt = true;
113010
+ }
113011
+ if (paneChild) {
113012
+ userSettings.editorMode = "normal";
113013
+ }
113014
+ if (paneChild) {
113015
+ userSettings.wheelScrollAccelerationEnabled = false;
113016
+ }
113017
+ if (paneChild) {
113018
+ userSettings.tui = "fullscreen";
113019
+ }
113020
+ }
113021
+ function mergeUserSettingsIfPresent(config, tempSettingsPath, statusLine, proxyAuthMode, paneChild = isPaneChild(), modelPicker) {
113022
+ if (modelPicker) {
113023
+ mergeEverySettingsArg(config, tempSettingsPath, statusLine, proxyAuthMode, paneChild, modelPicker);
113024
+ return;
113025
+ }
112221
113026
  const idx = config.claudeArgs.indexOf("--settings");
112222
113027
  if (idx === -1 || !config.claudeArgs[idx + 1]) {
112223
113028
  return;
@@ -112225,25 +113030,7 @@ function mergeUserSettingsIfPresent(config, tempSettingsPath, statusLine, proxyA
112225
113030
  const userSettingsValue = config.claudeArgs[idx + 1];
112226
113031
  try {
112227
113032
  const userSettings = parseSettingsArg(userSettingsValue);
112228
- userSettings.statusLine = statusLine;
112229
- if (!("disableClaudeAiConnectors" in userSettings)) {
112230
- userSettings.disableClaudeAiConnectors = true;
112231
- }
112232
- if (proxyAuthMode && !("forceLoginMethod" in userSettings)) {
112233
- userSettings.forceLoginMethod = "console";
112234
- }
112235
- if (paneChild && !("skipDangerousModePermissionPrompt" in userSettings)) {
112236
- userSettings.skipDangerousModePermissionPrompt = true;
112237
- }
112238
- if (paneChild) {
112239
- userSettings.editorMode = "normal";
112240
- }
112241
- if (paneChild) {
112242
- userSettings.wheelScrollAccelerationEnabled = false;
112243
- }
112244
- if (paneChild) {
112245
- userSettings.tui = "fullscreen";
112246
- }
113033
+ applyClaudishSettingsKeys(userSettings, statusLine, proxyAuthMode, paneChild);
112247
113034
  chmodSync5(tempSettingsPath, 384);
112248
113035
  writeFileSync20(tempSettingsPath, JSON.stringify(userSettings, null, 2), {
112249
113036
  encoding: "utf-8",
@@ -112256,6 +113043,45 @@ function mergeUserSettingsIfPresent(config, tempSettingsPath, statusLine, proxyA
112256
113043
  }
112257
113044
  config.claudeArgs.splice(idx, 2);
112258
113045
  }
113046
+ function mergeEverySettingsArg(config, tempSettingsPath, statusLine, proxyAuthMode, paneChild, modelPicker) {
113047
+ const occurrences = settingsArgOccurrences(config.claudeArgs);
113048
+ if (occurrences.length === 0)
113049
+ return;
113050
+ const merged = {};
113051
+ let mergedAny = false;
113052
+ occurrences.forEach((occurrence, i) => {
113053
+ if (!occurrence.value)
113054
+ return;
113055
+ const label = occurrences.length > 1 ? `--settings (occurrence ${i + 1})` : "--settings";
113056
+ const parsed = parseSettingsArgSafe(occurrence.value);
113057
+ if (parsed === null || Array.isArray(parsed)) {
113058
+ if (!config.quiet)
113059
+ console.warn(`[claudish] Warning: could not merge user settings: ${label}`);
113060
+ return;
113061
+ }
113062
+ Object.assign(merged, parsed);
113063
+ mergedAny = true;
113064
+ });
113065
+ if (mergedAny) {
113066
+ applyClaudishSettingsKeys(merged, statusLine, proxyAuthMode, paneChild);
113067
+ merged.modelPicker = modelPicker;
113068
+ try {
113069
+ chmodSync5(tempSettingsPath, 384);
113070
+ writeFileSync20(tempSettingsPath, JSON.stringify(merged, null, 2), {
113071
+ encoding: "utf-8",
113072
+ mode: 384
113073
+ });
113074
+ } catch {
113075
+ if (!config.quiet) {
113076
+ console.warn("[claudish] Warning: could not write the merged --settings file");
113077
+ }
113078
+ }
113079
+ }
113080
+ for (const occurrence of [...occurrences].reverse()) {
113081
+ const width = occurrence.spelling === "separate" && occurrence.value !== undefined ? 2 : 1;
113082
+ config.claudeArgs.splice(occurrence.index, width);
113083
+ }
113084
+ }
112259
113085
  async function resolveLocalContextWindow(spec, cachePath) {
112260
113086
  const parsed = parseModelSpec(spec);
112261
113087
  let provider = parsed.provider;
@@ -112336,12 +113162,9 @@ function resolveAdvisorToolEnv(config, processEnv = process.env) {
112336
113162
  return { vars: {}, source: "inherited" };
112337
113163
  return { vars: { [ADVISOR_TOOL_ENV_VAR]: "1" }, source: "claudish" };
112338
113164
  }
112339
- function discoverUserAdvisorModel(claudeArgs = [], cwd = process.cwd()) {
113165
+ function discoverUserAdvisorModel(claudeArgs = [], cwd = process.cwd(), scope = "first") {
112340
113166
  const sources = userSettingsFileCandidates(cwd).filter((file) => existsSync37(file));
112341
- const idx = claudeArgs.indexOf("--settings");
112342
- const settingsArg = idx === -1 ? undefined : claudeArgs[idx + 1];
112343
- if (settingsArg)
112344
- sources.push(settingsArg);
113167
+ sources.push(...settingsArgValues(claudeArgs, scope));
112345
113168
  const managed = managedSettingsPath();
112346
113169
  if (existsSync37(managed))
112347
113170
  sources.push(managed);
@@ -112358,7 +113181,7 @@ function discoverUserAdvisorModel(claudeArgs = [], cwd = process.cwd()) {
112358
113181
  function resolveAdvisorModelArg(config, cwd = process.cwd()) {
112359
113182
  if (!config.advisor)
112360
113183
  return { args: [], source: "off" };
112361
- const userChoice = discoverUserAdvisorModel(config.claudeArgs, cwd);
113184
+ const userChoice = discoverUserAdvisorModel(config.claudeArgs, cwd, settingsArgScopeOf(config));
112362
113185
  if (userChoice)
112363
113186
  return { args: [], model: userChoice, source: "inherited" };
112364
113187
  return {
@@ -112407,10 +113230,29 @@ function relayChildStderr(stream) {
112407
113230
  logStderr(`child stderr relay ended: ${err}`);
112408
113231
  });
112409
113232
  }
112410
- async function runClaudeWithProxy(config, proxyUrl, onCleanup) {
113233
+ function childModelIdOf(config) {
112411
113234
  const hasProfileMappings = config.modelOpus || config.modelSonnet || config.modelHaiku || config.modelSubagent;
113235
+ return config.model || (hasProfileMappings || config.monitor || isAdvisorNativeSession(config) || startsOnClaudeSubscription(config) ? undefined : "unknown");
113236
+ }
113237
+ function childModelVarsFor(config) {
113238
+ const modelId = childModelIdOf(config);
113239
+ const id = config.monitor || isAdvisorNativeSession(config) ? config.claudeLaunchModel ?? modelId : modelId;
113240
+ if (!id)
113241
+ return {};
113242
+ if ((config.modelListings?.length ?? 0) > 0)
113243
+ return { ANTHROPIC_MODEL: id };
113244
+ return { ANTHROPIC_MODEL: id, ANTHROPIC_SMALL_FAST_MODEL: id };
113245
+ }
113246
+ function childKeepsLogin(config) {
113247
+ return !isProxyAuthMode(config) && config.claudeLaunch !== "api";
113248
+ }
113249
+ function scrubChildModelVars(config, env) {
113250
+ const set = childModelVarsFor(config);
113251
+ return scrubInheritedModelVars(env, { model: Boolean(set.ANTHROPIC_MODEL), smallFast: Boolean(set.ANTHROPIC_SMALL_FAST_MODEL) }, { keepsLogin: childKeepsLogin(config) });
113252
+ }
113253
+ async function runClaudeWithProxy(config, proxyUrl, onCleanup, hooks = {}) {
112412
113254
  const advisorNativeSession = isAdvisorNativeSession(config);
112413
- const modelId = config.model || (hasProfileMappings || config.monitor || advisorNativeSession ? undefined : "unknown");
113255
+ const modelId = childModelIdOf(config);
112414
113256
  const portMatch = proxyUrl.match(/:(\d+)/);
112415
113257
  const port = portMatch ? portMatch[1] : "unknown";
112416
113258
  const proxyAuthMode = isProxyAuthMode(config);
@@ -112434,15 +113276,16 @@ async function runClaudeWithProxy(config, proxyUrl, onCleanup) {
112434
113276
  if (!gatewayEligible && globalConfig.harnessGateway !== undefined) {
112435
113277
  log(gatewayHeldOff ? `[claude-runner] harnessGateway ignored: ${HARNESS_GATEWAY_OFF_VAR}=1` : "[claude-runner] harnessGateway ignored: a monitor session keeps the proxy URL");
112436
113278
  }
112437
- const userStatusLineCommand = discoverUserStatusLineCommand(config.claudeArgs);
113279
+ const userStatusLineCommand = discoverUserStatusLineCommand(config.claudeArgs, process.cwd(), settingsArgScopeOf(config));
112438
113280
  const advisorModelArg = resolveAdvisorModelArg(config);
113281
+ const modelPicker = config.modelLineup?.picker;
112439
113282
  const {
112440
113283
  path: tempSettingsPath,
112441
113284
  statusLine,
112442
113285
  tokenFilePath
112443
- } = createTempSettingsFile(modelId ?? "default", port, forceConsoleLogin, userStatusLineCommand);
112444
- const signalShutdown = setupSignalHandlers(tempSettingsPath, config.quiet, onCleanup);
112445
- mergeUserSettingsIfPresent(config, tempSettingsPath, statusLine, forceConsoleLogin);
113286
+ } = createTempSettingsFile(modelId ?? "default", port, forceConsoleLogin, userStatusLineCommand, modelPicker);
113287
+ const signalShutdown = setupSignalHandlers(tempSettingsPath, config.quiet, onCleanup, hooks.onDeadline);
113288
+ mergeUserSettingsIfPresent(config, tempSettingsPath, statusLine, forceConsoleLogin, isPaneChild(), modelPicker);
112446
113289
  const claudeArgs = [];
112447
113290
  claudeArgs.push("--settings", tempSettingsPath);
112448
113291
  claudeArgs.push(...advisorModelArg.args);
@@ -112513,6 +113356,11 @@ async function runClaudeWithProxy(config, proxyUrl, onCleanup) {
112513
113356
  if (!config.interactive && env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC === undefined) {
112514
113357
  env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
112515
113358
  }
113359
+ const childModelVars = childModelVarsFor(config);
113360
+ const inheritedModelVars = scrubChildModelVars(config, env);
113361
+ if (inheritedModelVars.removed.length > 0) {
113362
+ log(`[claude-runner] Removed inherited model variables claudish set: ${inheritedModelVars.removed.join(", ")}`);
113363
+ }
112516
113364
  if (config.monitor || advisorNativeSession) {
112517
113365
  delete env.ANTHROPIC_API_KEY;
112518
113366
  delete env.ANTHROPIC_AUTH_TOKEN;
@@ -112522,19 +113370,12 @@ async function runClaudeWithProxy(config, proxyUrl, onCleanup) {
112522
113370
  env.ANTHROPIC_AUTH_TOKEN = CLAUDISH_PLACEHOLDER_AUTH_TOKEN;
112523
113371
  applyHostManagedMarker(env);
112524
113372
  }
112525
- const launchModelId = config.claudeLaunchModel ?? modelId;
112526
- if (launchModelId) {
112527
- env[ENV.ANTHROPIC_MODEL] = launchModelId;
112528
- env[ENV.ANTHROPIC_SMALL_FAST_MODEL] = launchModelId;
112529
- }
113373
+ recordModelVars(env, childModelVars);
112530
113374
  if (config.claudeLaunch) {
112531
113375
  log(claudeLaunchAuthLine(config.claudeLaunch, env, config.claudeLaunchKeySource));
112532
113376
  }
112533
113377
  } else {
112534
- if (modelId) {
112535
- env[ENV.ANTHROPIC_MODEL] = modelId;
112536
- env[ENV.ANTHROPIC_SMALL_FAST_MODEL] = modelId;
112537
- }
113378
+ recordModelVars(env, childModelVars);
112538
113379
  if (shouldPreserveNativeAuth(config)) {
112539
113380
  const scrubbed = scrubInheritedClaudishPlaceholders(env);
112540
113381
  if (scrubbed.removed.length > 0) {
@@ -112556,7 +113397,7 @@ async function runClaudeWithProxy(config, proxyUrl, onCleanup) {
112556
113397
  applyProxyPlaceholderAuth(env);
112557
113398
  applyProxyFastModeGates(env);
112558
113399
  applyHostRouting(env);
112559
- const realWindow = await computeMainThreadContextWindow(config);
113400
+ const realWindow = config.mainThreadWindow ?? await computeMainThreadContextWindow(config);
112560
113401
  const contextEnv = resolveContextWindowEnv(realWindow, process.env);
112561
113402
  seedTokenFileWindow(resolveTokenFilePath(port), realWindow);
112562
113403
  Object.assign(env, contextEnv.vars);
@@ -112600,6 +113441,7 @@ async function runClaudeWithProxy(config, proxyUrl, onCleanup) {
112600
113441
  `);
112601
113442
  }
112602
113443
  const claudeBinary = await findClaudeBinary();
113444
+ await hooks.beforeSpawn?.(tempSettingsPath);
112603
113445
  const stoppedBeforeSpawn = signalShutdownExitCode();
112604
113446
  if (stoppedBeforeSpawn !== null) {
112605
113447
  signalShutdown.removeSettingsFile();
@@ -112622,11 +113464,11 @@ Or set CLAUDE_PATH to your custom installation:`);
112622
113464
  const childWantsTty = config.interactive && !process.stdout.isTTY && Boolean(process.stdin.isTTY);
112623
113465
  if (childWantsTty) {
112624
113466
  try {
112625
- const fd = openSync13("/dev/fd/0", "r+");
113467
+ const fd = openSync14("/dev/fd/0", "r+");
112626
113468
  if (isatty(fd)) {
112627
113469
  ttyFd = fd;
112628
113470
  } else {
112629
- closeSync13(fd);
113471
+ closeSync14(fd);
112630
113472
  }
112631
113473
  } catch {
112632
113474
  ttyFd = undefined;
@@ -112645,7 +113487,7 @@ Or set CLAUDE_PATH to your custom installation:`);
112645
113487
  const sessionFlags = sessionFlagsOf(config.claudeArgs);
112646
113488
  let driverLaunch = null;
112647
113489
  if (surfaces.driver) {
112648
- const minted = sessionFlags.sessionId || sessionFlags.resumes ? null : randomUUID8();
113490
+ const minted = sessionFlags.sessionId || sessionFlags.resumes ? null : randomUUID7();
112649
113491
  const turnDir = mkdtempSync3(join53(tmpdir2(), "claudish-turns-"));
112650
113492
  chmodSync5(turnDir, 448);
112651
113493
  claudeArgs.unshift(...driverLeadingArgs({ mintedSessionId: minted, turnDir }));
@@ -112668,6 +113510,13 @@ Or set CLAUDE_PATH to your custom installation:`);
112668
113510
  shell: needsShell
112669
113511
  });
112670
113512
  signalShutdown.attachClaudeCode(proc);
113513
+ if (proc.pid !== undefined) {
113514
+ try {
113515
+ hooks.onChildSpawned?.(proc.pid);
113516
+ } catch (err) {
113517
+ log2(`[claudish] onChildSpawned hook failed: ${err}`);
113518
+ }
113519
+ }
112671
113520
  if (wrap) {
112672
113521
  wrap.watch(proc);
112673
113522
  }
@@ -112730,7 +113579,7 @@ Or set CLAUDE_PATH to your custom installation:`);
112730
113579
  const fdToClose = ttyFd;
112731
113580
  proc.on("spawn", () => {
112732
113581
  try {
112733
- closeSync13(fdToClose);
113582
+ closeSync14(fdToClose);
112734
113583
  } catch {}
112735
113584
  });
112736
113585
  }
@@ -112767,7 +113616,7 @@ function sessionOutcomeOf(exitCode) {
112767
113616
  function signalShutdownExitCode() {
112768
113617
  return signalShutdownCode;
112769
113618
  }
112770
- function setupSignalHandlers(tempSettingsPath, quiet, onCleanup) {
113619
+ function setupSignalHandlers(tempSettingsPath, quiet, onCleanup, onDeadline) {
112771
113620
  const signals = isWindows2() ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"];
112772
113621
  let shuttingDown = null;
112773
113622
  let claudeCode = null;
@@ -112806,6 +113655,9 @@ function setupSignalHandlers(tempSettingsPath, quiet, onCleanup) {
112806
113655
  const armDeadline = (code) => {
112807
113656
  const deadline = setTimeout(() => {
112808
113657
  log(`[claudish] Signal shutdown passed ${SIGNAL_SHUTDOWN_BUDGET_MS} ms; exiting`);
113658
+ try {
113659
+ onDeadline?.();
113660
+ } catch {}
112809
113661
  try {
112810
113662
  onCleanup?.();
112811
113663
  } catch {}
@@ -112914,7 +113766,7 @@ async function checkClaudeInstalled() {
112914
113766
  const binary = await findClaudeBinary();
112915
113767
  return binary !== null;
112916
113768
  }
112917
- var restoreTerminal = null, SETTINGS_TIER_ORDER, STALE_TOKEN_FILE_MS, MAX_TOKEN_FILES_SCANNED = 4000, CLAUDE_CODE_DEFAULT_MAX_CONTEXT = 200000, USER_STATUS_LINE_TIMEOUT_SECONDS = 3, MIN_AUTO_COMPACT_WINDOW = 200000, MAX_AUTO_COMPACT_WINDOW = 1e6, ADVISOR_TOOL_ENV_VAR = "CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL", CLAUDISH_CHILD_ADVISOR_MODEL = "sonnet", CHILD_STDERR_NOISE, SIGNAL_CHILD_EXIT_GRACE_MS = 2000, SIGNAL_CHILD_KILL_WAIT_MS = 500, SIGNAL_DESCENDANT_READ_MS = 200, SIGNAL_SHUTDOWN_BUDGET_MS = 4500, signalShutdownCode = null;
113769
+ var restoreTerminal = null, SETTINGS_TIER_ORDER, NON_MANAGED_TIER_RANK, STALE_TOKEN_FILE_MS, MAX_TOKEN_FILES_SCANNED = 4000, CLAUDE_CODE_DEFAULT_MAX_CONTEXT = 200000, USER_STATUS_LINE_TIMEOUT_SECONDS = 3, MIN_AUTO_COMPACT_WINDOW = 200000, MAX_AUTO_COMPACT_WINDOW = 1e6, ADVISOR_TOOL_ENV_VAR = "CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL", CLAUDISH_CHILD_ADVISOR_MODEL = "sonnet", CHILD_STDERR_NOISE, SIGNAL_CHILD_EXIT_GRACE_MS = 2000, SIGNAL_CHILD_KILL_WAIT_MS = 500, SIGNAL_DESCENDANT_READ_MS = 200, SIGNAL_SHUTDOWN_BUDGET_MS = 4500, signalShutdownCode = null;
112918
113770
  var init_claude_runner = __esm(() => {
112919
113771
  init_model_catalog();
112920
113772
  init_claude_code_login();
@@ -112930,6 +113782,7 @@ var init_claude_runner = __esm(() => {
112930
113782
  init_host_routing_env();
112931
113783
  init_magmux_wrapper();
112932
113784
  init_logger();
113785
+ init_model_vars_env();
112933
113786
  init_child_env();
112934
113787
  init_pane_launch();
112935
113788
  init_process_tree();
@@ -112949,6 +113802,12 @@ var init_claude_runner = __esm(() => {
112949
113802
  init_terminal_isolation();
112950
113803
  init_theme_mode();
112951
113804
  SETTINGS_TIER_ORDER = ["managed", "cli", "local", "project", "user"];
113805
+ NON_MANAGED_TIER_RANK = {
113806
+ user: 0,
113807
+ project: 1,
113808
+ local: 2,
113809
+ cli: 3
113810
+ };
112952
113811
  STALE_TOKEN_FILE_MS = 7 * 24 * 60 * 60 * 1000;
112953
113812
  CHILD_STDERR_NOISE = [/^\[claude-code:unrecognized_model\]/];
112954
113813
  });
@@ -113036,7 +113895,7 @@ var init_contract = __esm(() => {
113036
113895
  });
113037
113896
 
113038
113897
  // src/pane/reason-detail.ts
113039
- import { closeSync as closeSync14, fstatSync as fstatSync4, openSync as openSync14, readSync as readSync5 } from "fs";
113898
+ import { closeSync as closeSync15, fstatSync as fstatSync4, openSync as openSync15, readSync as readSync6 } from "fs";
113040
113899
  function reasonDetail(input, upstreamRecords = []) {
113041
113900
  if (!isTerminalState(input.state) || input.state === "COMPLETED")
113042
113901
  return null;
@@ -113117,11 +113976,11 @@ function isObject3(v) {
113117
113976
  function readTailLines(path, maxBytes) {
113118
113977
  let fd = null;
113119
113978
  try {
113120
- fd = openSync14(path, "r");
113979
+ fd = openSync15(path, "r");
113121
113980
  const size = fstatSync4(fd).size;
113122
113981
  const start = Math.max(0, size - maxBytes);
113123
113982
  const buf = Buffer.alloc(size - start);
113124
- readSync5(fd, buf, 0, buf.length, start);
113983
+ readSync6(fd, buf, 0, buf.length, start);
113125
113984
  const lines = buf.toString("utf-8").split(`
113126
113985
  `);
113127
113986
  if (start > 0)
@@ -113132,7 +113991,7 @@ function readTailLines(path, maxBytes) {
113132
113991
  } finally {
113133
113992
  if (fd !== null) {
113134
113993
  try {
113135
- closeSync14(fd);
113994
+ closeSync15(fd);
113136
113995
  } catch {}
113137
113996
  }
113138
113997
  }
@@ -113750,7 +114609,7 @@ var init_token_watch = __esm(() => {
113750
114609
  });
113751
114610
 
113752
114611
  // src/view/view-claims.ts
113753
- import { randomBytes as randomBytes15 } from "crypto";
114612
+ import { randomBytes as randomBytes16 } from "crypto";
113754
114613
  function ownerOf(caller) {
113755
114614
  return caller.kind === "mcp" ? "mcp" : caller.connId;
113756
114615
  }
@@ -113782,7 +114641,7 @@ class ViewClaims {
113782
114641
  const same = cur?.owner === by;
113783
114642
  const next = {
113784
114643
  ...who,
113785
- claimId: same && cur ? cur.claimId : randomBytes15(8).toString("hex"),
114644
+ claimId: same && cur ? cur.claimId : randomBytes16(8).toString("hex"),
113786
114645
  owner: by,
113787
114646
  since: same && cur ? cur.since : new Date(now).toISOString(),
113788
114647
  expiresAt: now + CLAUDE_CODE_CLAIM_TTL_MS
@@ -113873,14 +114732,14 @@ var init_view_claims = __esm(() => {
113873
114732
  });
113874
114733
 
113875
114734
  // src/team-orchestrator.ts
113876
- import { randomBytes as randomBytes16, randomUUID as randomUUID9 } from "crypto";
114735
+ import { randomBytes as randomBytes17, randomUUID as randomUUID8 } from "crypto";
113877
114736
  import {
113878
114737
  existsSync as existsSync39,
113879
114738
  lstatSync as lstatSync8,
113880
114739
  mkdirSync as mkdirSync27,
113881
114740
  readFileSync as readFileSync45,
113882
114741
  readdirSync as readdirSync11,
113883
- realpathSync as realpathSync6,
114742
+ realpathSync as realpathSync7,
113884
114743
  rmSync as rmSync14,
113885
114744
  statSync as statSync21,
113886
114745
  writeFileSync as writeFileSync22
@@ -114420,13 +115279,13 @@ function answerFailureDetail(v, answer, requirePattern, outcomes) {
114420
115279
  function readWrittenFile(path, root) {
114421
115280
  let realRoot;
114422
115281
  try {
114423
- realRoot = realpathSync6(root);
115282
+ realRoot = realpathSync7(root);
114424
115283
  } catch {
114425
115284
  realRoot = resolve7(root);
114426
115285
  }
114427
115286
  let real;
114428
115287
  try {
114429
- real = realpathSync6(resolve7(root, path));
115288
+ real = realpathSync7(resolve7(root, path));
114430
115289
  } catch {
114431
115290
  return { skip: "missing" };
114432
115291
  }
@@ -114498,11 +115357,11 @@ function validateSessionPath(sessionPath) {
114498
115357
  }
114499
115358
  let real;
114500
115359
  try {
114501
- real = join56(realpathSync6(existing), ...tail);
115360
+ real = join56(realpathSync7(existing), ...tail);
114502
115361
  } catch {
114503
115362
  throw outside();
114504
115363
  }
114505
- const cwd = realpathSync6(process.cwd());
115364
+ const cwd = realpathSync7(process.cwd());
114506
115365
  if (real !== cwd && !real.startsWith(cwd + sep)) {
114507
115366
  throw outside();
114508
115367
  }
@@ -114603,7 +115462,7 @@ async function preflightTeamRun(opts) {
114603
115462
  throw new Error(`pane_limit: ${live} live panes for this user, ${opts.slots} more would exceed ${MAX_LIVE_PANES}`);
114604
115463
  }
114605
115464
  function mintRunId(path, startMs) {
114606
- return `${basename6(path)}-${startMs.toString(36)}-${randomBytes16(3).toString("hex")}`;
115465
+ return `${basename6(path)}-${startMs.toString(36)}-${randomBytes17(3).toString("hex")}`;
114607
115466
  }
114608
115467
  function startModels(sessionPath, opts = {}) {
114609
115468
  const flight = { aborted: false };
@@ -115004,7 +115863,7 @@ async function startModelsIn(flight, sessionPath, opts) {
115004
115863
  stopReason: null
115005
115864
  };
115006
115865
  entries.set(id, e);
115007
- const uuid = randomUUID9();
115866
+ const uuid = randomUUID8();
115008
115867
  const transcriptPath = transcriptPathFor(cwd, uuid, projects);
115009
115868
  updateModelStatus(id, {
115010
115869
  state: "STARTING",
@@ -115563,16 +116422,16 @@ var init_scrollback_buffer = __esm(() => {
115563
116422
  });
115564
116423
 
115565
116424
  // src/mcp-session/session-manager.ts
115566
- import { randomUUID as randomUUID10 } from "crypto";
116425
+ import { randomUUID as randomUUID9 } from "crypto";
115567
116426
  import {
115568
116427
  appendFileSync as appendFileSync7,
115569
- closeSync as closeSync15,
116428
+ closeSync as closeSync16,
115570
116429
  createWriteStream,
115571
116430
  existsSync as existsSync41,
115572
116431
  mkdirSync as mkdirSync28,
115573
- openSync as openSync15,
116432
+ openSync as openSync16,
115574
116433
  readFileSync as readFileSync47,
115575
- readSync as readSync6,
116434
+ readSync as readSync7,
115576
116435
  renameSync as renameSync10,
115577
116436
  rmSync as rmSync15,
115578
116437
  statSync as statSync23,
@@ -115691,15 +116550,15 @@ function readTailText(path, maxBytes) {
115691
116550
  const start = Math.max(0, size - maxBytes);
115692
116551
  const length = size - start;
115693
116552
  const buf = Buffer.alloc(length);
115694
- fd = openSync15(path, "r");
115695
- readSync6(fd, buf, 0, length, start);
116553
+ fd = openSync16(path, "r");
116554
+ readSync7(fd, buf, 0, length, start);
115696
116555
  return { text: buf.toString("utf-8"), truncated: start > 0 };
115697
116556
  } catch {
115698
116557
  return null;
115699
116558
  } finally {
115700
116559
  if (fd !== null) {
115701
116560
  try {
115702
- closeSync15(fd);
116561
+ closeSync16(fd);
115703
116562
  } catch {}
115704
116563
  }
115705
116564
  }
@@ -115839,7 +116698,7 @@ class SessionManager {
115839
116698
  let id = "";
115840
116699
  let dir = "";
115841
116700
  for (let attempt = 0;; attempt++) {
115842
- id = `team-${randomUUID10().replace(/-/g, "").slice(0, 8)}`;
116701
+ id = `team-${randomUUID9().replace(/-/g, "").slice(0, 8)}`;
115843
116702
  dir = join58(this.sessionsDir, id);
115844
116703
  try {
115845
116704
  mkdirSync28(dir);
@@ -115966,8 +116825,8 @@ class SessionManager {
115966
116825
  }
115967
116826
  }
115968
116827
  recordSession(opts, inheritedLayer) {
115969
- const sessionId = opts.sessionId ?? randomUUID10().slice(0, 8);
115970
- const claudeSessionId = randomUUID10();
116828
+ const sessionId = opts.sessionId ?? randomUUID9().slice(0, 8);
116829
+ const claudeSessionId = randomUUID9();
115971
116830
  const timeout = normaliseTimeoutSeconds(opts.timeoutSeconds);
115972
116831
  const agentRequested = requestedAgentOf(opts.claudishFlags ?? []);
115973
116832
  const startedAt = new Date().toISOString();
@@ -117046,7 +117905,7 @@ var init_session_manager = __esm(() => {
117046
117905
  });
117047
117906
 
117048
117907
  // src/view/history.ts
117049
- import { closeSync as closeSync16, openSync as openSync16, readSync as readSync7, readdirSync as readdirSync12, statSync as statSync24 } from "fs";
117908
+ import { closeSync as closeSync17, openSync as openSync17, readSync as readSync8, readdirSync as readdirSync12, statSync as statSync24 } from "fs";
117050
117909
  import { join as join59 } from "path";
117051
117910
  function finishedDetail(promptSummary) {
117052
117911
  return {
@@ -117068,15 +117927,15 @@ function readJson(path) {
117068
117927
  function readHead(path, bytes) {
117069
117928
  let fd = null;
117070
117929
  try {
117071
- fd = openSync16(path, "r");
117930
+ fd = openSync17(path, "r");
117072
117931
  const buf = Buffer.alloc(bytes);
117073
- const n = readSync7(fd, buf, 0, bytes, 0);
117932
+ const n = readSync8(fd, buf, 0, bytes, 0);
117074
117933
  return buf.subarray(0, n).toString("utf8");
117075
117934
  } catch {
117076
117935
  return null;
117077
117936
  } finally {
117078
117937
  if (fd !== null)
117079
- closeSync16(fd);
117938
+ closeSync17(fd);
117080
117939
  }
117081
117940
  }
117082
117941
  function runDirs(sessionsDir) {
@@ -117792,7 +118651,7 @@ function writeRecord(root, rec) {
117792
118651
  `, { mode: 384 });
117793
118652
  renameSync12(tmp, p);
117794
118653
  }
117795
- function readRecord(root, paneId) {
118654
+ function readRecord2(root, paneId) {
117796
118655
  if (!isValidPaneId(paneId))
117797
118656
  return null;
117798
118657
  try {
@@ -117802,7 +118661,7 @@ function readRecord(root, paneId) {
117802
118661
  }
117803
118662
  }
117804
118663
  function updateRecord(root, paneId, patch) {
117805
- const rec = readRecord(root, paneId);
118664
+ const rec = readRecord2(root, paneId);
117806
118665
  if (rec)
117807
118666
  writeRecord(root, { ...rec, ...patch });
117808
118667
  }
@@ -117859,7 +118718,7 @@ function readRecords(root) {
117859
118718
  }
117860
118719
  const out = [];
117861
118720
  for (const n of names) {
117862
- const rec = readRecord(root, n.slice(0, -".json".length));
118721
+ const rec = readRecord2(root, n.slice(0, -".json".length));
117863
118722
  if (rec)
117864
118723
  out.push(rec);
117865
118724
  }
@@ -118294,7 +119153,7 @@ var init_pane_registry = __esm(() => {
118294
119153
  });
118295
119154
 
118296
119155
  // src/pane/gate-binding.ts
118297
- import { realpathSync as realpathSync7 } from "fs";
119156
+ import { realpathSync as realpathSync8 } from "fs";
118298
119157
  import { basename as basename8, dirname as dirname26, join as join62, resolve as resolve10 } from "path";
118299
119158
  function normaliseTranscriptPath(p) {
118300
119159
  const abs = resolve10(p);
@@ -118302,7 +119161,7 @@ function normaliseTranscriptPath(p) {
118302
119161
  let cur = abs;
118303
119162
  for (;; ) {
118304
119163
  try {
118305
- return tail.length ? join62(realpathSync7(cur), ...tail.reverse()) : realpathSync7(cur);
119164
+ return tail.length ? join62(realpathSync8(cur), ...tail.reverse()) : realpathSync8(cur);
118306
119165
  } catch {
118307
119166
  const parent = dirname26(cur);
118308
119167
  if (parent === cur)
@@ -118728,7 +119587,7 @@ var init_view_socket = __esm(() => {
118728
119587
  });
118729
119588
 
118730
119589
  // src/pane/pane-session.ts
118731
- import { readFileSync as readFileSync51, realpathSync as realpathSync8, rmSync as rmSync18, statSync as statSync25, writeFileSync as writeFileSync26 } from "fs";
119590
+ import { readFileSync as readFileSync51, realpathSync as realpathSync9, rmSync as rmSync18, statSync as statSync25, writeFileSync as writeFileSync26 } from "fs";
118732
119591
  import { join as join64 } from "path";
118733
119592
  function iso3(ms) {
118734
119593
  return new Date(ms).toISOString();
@@ -121323,7 +122182,7 @@ function preparePane(o, root, parentEnv) {
121323
122182
  try {
121324
122183
  const paneId = mintPaneId(o.kind, o.label);
121325
122184
  const sockPath = sockPathOf(root, paneId);
121326
- const cwd = realpathSync8(o.cwd);
122185
+ const cwd = realpathSync9(o.cwd);
121327
122186
  const launch = o.claudishSpawn ?? resolveClaudishLaunch(parentEnv);
121328
122187
  dirs = createLaunchDirs(root);
121329
122188
  const argv = buildClaudishPaneArgv(o.spawnModel, o.sessionUuid, dirs.turnDir, o.callerFlags, o.spawnPinned === true);
@@ -122495,14 +123354,14 @@ var init_transcript_redaction = __esm(() => {
122495
123354
  // src/pane/transcript-page.ts
122496
123355
  import {
122497
123356
  constants as constants5,
122498
- closeSync as closeSync17,
123357
+ closeSync as closeSync18,
122499
123358
  fstatSync as fstatSync5,
122500
123359
  lstatSync as lstatSync10,
122501
- openSync as openSync17,
122502
- readSync as readSync8,
123360
+ openSync as openSync18,
123361
+ readSync as readSync9,
122503
123362
  readdirSync as readdirSync15,
122504
123363
  readlinkSync,
122505
- realpathSync as realpathSync9,
123364
+ realpathSync as realpathSync10,
122506
123365
  statSync as statSync26
122507
123366
  } from "fs";
122508
123367
  import { basename as basename9, dirname as dirname27, join as join66, sep as sep3 } from "path";
@@ -122552,7 +123411,7 @@ class LineScanner {
122552
123411
  return null;
122553
123412
  const n = Math.min(READ_CHUNK, this.size - at);
122554
123413
  const b = Buffer.alloc(n);
122555
- const got = readSync8(this.fd, b, 0, n, at);
123414
+ const got = readSync9(this.fd, b, 0, n, at);
122556
123415
  if (got <= 0)
122557
123416
  return null;
122558
123417
  this.chunk = got < n ? b.subarray(0, got) : b;
@@ -122587,7 +123446,7 @@ function absentPage(from) {
122587
123446
  }
122588
123447
  function closeQuietly(fd) {
122589
123448
  try {
122590
- closeSync17(fd);
123449
+ closeSync18(fd);
122591
123450
  } catch {}
122592
123451
  }
122593
123452
  function readTranscriptPageFd(fd, from, limits) {
@@ -122600,7 +123459,7 @@ function readTranscriptPageFd(fd, from, limits) {
122600
123459
  throw new ContractErrorException("invalid_args", "'since' is past the end of the transcript");
122601
123460
  if (from.offset > 0) {
122602
123461
  const b = Buffer.alloc(1);
122603
- const got = readSync8(fd, b, 0, 1, from.offset - 1);
123462
+ const got = readSync9(fd, b, 0, 1, from.offset - 1);
122604
123463
  if (got !== 1 || b[0] !== 10)
122605
123464
  throw new ContractErrorException("invalid_args", "'since' is not at a line start");
122606
123465
  }
@@ -122717,8 +123576,8 @@ function openContainedTranscript(path, uuid, projectsRoot) {
122717
123576
  let real;
122718
123577
  let root;
122719
123578
  try {
122720
- real = realpathSync9(path);
122721
- root = realpathSync9(projectsRoot);
123579
+ real = realpathSync10(path);
123580
+ root = realpathSync10(projectsRoot);
122722
123581
  } catch (e) {
122723
123582
  if (!isEnoent(e))
122724
123583
  logRejection(path, errText(e));
@@ -122730,7 +123589,7 @@ function openContainedTranscript(path, uuid, projectsRoot) {
122730
123589
  }
122731
123590
  let fd;
122732
123591
  try {
122733
- fd = openSync17(real, OPEN_FLAGS);
123592
+ fd = openSync18(real, OPEN_FLAGS);
122734
123593
  } catch (e) {
122735
123594
  if (e?.code === "ELOOP")
122736
123595
  logRejection(path, "the transcript became a symlink");
@@ -122747,7 +123606,7 @@ function openContainedTranscript(path, uuid, projectsRoot) {
122747
123606
  }
122748
123607
  const parent = dirname27(real);
122749
123608
  const named = lstatSync10(real);
122750
- if (realpathSync9(parent) !== parent || !named.isFile() || named.dev !== st.dev || named.ino !== st.ino || !kernelPathMatches(fd, real)) {
123609
+ if (realpathSync10(parent) !== parent || !named.isFile() || named.dev !== st.dev || named.ino !== st.ino || !kernelPathMatches(fd, real)) {
122751
123610
  logRejection(path, "the opened file is not the one under the projects directory");
122752
123611
  closeQuietly(fd);
122753
123612
  return null;
@@ -122778,7 +123637,7 @@ function transcriptHeadCwd(path, uuid, projectsRoot) {
122778
123637
  let text;
122779
123638
  try {
122780
123639
  const buf = Buffer.alloc(HEAD_CWD_MAX_BYTES);
122781
- const n = readSync8(fd, buf, 0, HEAD_CWD_MAX_BYTES, 0);
123640
+ const n = readSync9(fd, buf, 0, HEAD_CWD_MAX_BYTES, 0);
122782
123641
  text = buf.toString("utf8", 0, n);
122783
123642
  } catch {
122784
123643
  return null;
@@ -122890,7 +123749,7 @@ var init_pane = __esm(() => {
122890
123749
  });
122891
123750
 
122892
123751
  // src/view/kernel-lock.ts
122893
- import { constants as constants6, closeSync as closeSync18, fstatSync as fstatSync6, openSync as openSync18, statSync as statSync27, unlinkSync as unlinkSync13 } from "fs";
123752
+ import { constants as constants6, closeSync as closeSync19, fstatSync as fstatSync6, openSync as openSync19, statSync as statSync27, unlinkSync as unlinkSync13 } from "fs";
122894
123753
  function bindFlock() {
122895
123754
  const library = process.platform === "darwin" ? "libSystem.B.dylib" : process.platform === "linux" ? "libc.so.6" : null;
122896
123755
  if (!library)
@@ -122933,7 +123792,7 @@ function lockOf(fd, path) {
122933
123792
  return;
122934
123793
  open = false;
122935
123794
  try {
122936
- closeSync18(fd);
123795
+ closeSync19(fd);
122937
123796
  } catch {}
122938
123797
  }
122939
123798
  };
@@ -122943,10 +123802,10 @@ function tryAcquire(path) {
122943
123802
  if (!lib)
122944
123803
  throw new KernelLockUnavailable("flock is not available in this process");
122945
123804
  for (let attempt = 0;attempt < 5; attempt++) {
122946
- const fd = openSync18(path, constants6.O_RDWR | constants6.O_CREAT | O_CLOEXEC, 384);
123805
+ const fd = openSync19(path, constants6.O_RDWR | constants6.O_CREAT | O_CLOEXEC, 384);
122947
123806
  if (lib.flock(fd, LOCK_EX | LOCK_NB) !== 0) {
122948
123807
  const errno = lib.errno();
122949
- closeSync18(fd);
123808
+ closeSync19(fd);
122950
123809
  if (errno === EWOULDBLOCK)
122951
123810
  return null;
122952
123811
  throw new KernelLockUnavailable(`flock ${path}: errno ${errno}`);
@@ -122959,7 +123818,7 @@ function tryAcquire(path) {
122959
123818
  }
122960
123819
  if (same)
122961
123820
  return lockOf(fd, path);
122962
- closeSync18(fd);
123821
+ closeSync19(fd);
122963
123822
  }
122964
123823
  throw new KernelLockUnavailable(`flock ${path}: the file keeps being replaced`);
122965
123824
  }
@@ -123148,7 +124007,7 @@ var init_peer_link = __esm(() => {
123148
124007
  });
123149
124008
 
123150
124009
  // src/view/replay-registry.ts
123151
- import { randomBytes as randomBytes17 } from "crypto";
124010
+ import { randomBytes as randomBytes18 } from "crypto";
123152
124011
  import { readFileSync as readFileSync52, readdirSync as readdirSync16, renameSync as renameSync13, rmSync as rmSync20, writeFileSync as writeFileSync28 } from "fs";
123153
124012
  import { join as join67 } from "path";
123154
124013
  function parseEntry(raw) {
@@ -123221,7 +124080,7 @@ class ReplayRegistry {
123221
124080
  }
123222
124081
  writeLocked(uuid, entry) {
123223
124082
  const path = this.entryPathOf(uuid);
123224
- const tmp = `${path}.${randomBytes17(4).toString("hex")}.tmp`;
124083
+ const tmp = `${path}.${randomBytes18(4).toString("hex")}.tmp`;
123225
124084
  writeFileSync28(tmp, `${JSON.stringify(entry)}
123226
124085
  `, { mode: 384, flag: "wx" });
123227
124086
  try {
@@ -123313,8 +124172,8 @@ var init_replay_registry = __esm(() => {
123313
124172
  });
123314
124173
 
123315
124174
  // src/mcp-session/replay-manager.ts
123316
- import { randomBytes as randomBytes18, randomUUID as randomUUID11 } from "crypto";
123317
- import { constants as constants7, accessSync as accessSync3, closeSync as closeSync19, existsSync as existsSync43, realpathSync as realpathSync10, statSync as statSync28 } from "fs";
124175
+ import { randomBytes as randomBytes19, randomUUID as randomUUID10 } from "crypto";
124176
+ import { constants as constants7, accessSync as accessSync3, closeSync as closeSync20, existsSync as existsSync43, realpathSync as realpathSync11, statSync as statSync28 } from "fs";
123318
124177
  import { dirname as dirname28, resolve as resolve11 } from "path";
123319
124178
  function unavailable2(reason, message) {
123320
124179
  return new ContractErrorException("replay_unavailable", message, reason);
@@ -123329,10 +124188,10 @@ function replayCwd(own) {
123329
124188
  if (own) {
123330
124189
  try {
123331
124190
  if (statSync28(own).isDirectory())
123332
- return realpathSync10(own);
124191
+ return realpathSync11(own);
123333
124192
  } catch {}
123334
124193
  }
123335
- return realpathSync10(process.cwd());
124194
+ return realpathSync11(process.cwd());
123336
124195
  }
123337
124196
  async function replayClaudeBinary(env) {
123338
124197
  const named = env.CLAUDE_PATH ? resolve11(env.CLAUDE_PATH) : "";
@@ -123633,11 +124492,11 @@ class ReplayManager {
123633
124492
  return entry;
123634
124493
  }
123635
124494
  mintReplayId() {
123636
- return `replay-${randomBytes18(8).toString("hex")}`;
124495
+ return `replay-${randomBytes19(8).toString("hex")}`;
123637
124496
  }
123638
124497
  async spawn(slot, target, size, opener, lock, replayId, paneId) {
123639
124498
  const uuid = slot.uuid;
123640
- const forkUuid = randomUUID11();
124499
+ const forkUuid = randomUUID10();
123641
124500
  const cwd = replayCwd(target.cwd);
123642
124501
  const projectsRoot = resolve11(target.projectsRoot);
123643
124502
  const forkPath = transcriptPathFor(cwd, forkUuid, projectsRoot);
@@ -123969,7 +124828,7 @@ class ReplayManager {
123969
124828
  const fd = openContainedTranscript(path, uuid, target.projectsRoot);
123970
124829
  if (fd === null)
123971
124830
  throw noRecord("the session's Claude Code record is gone");
123972
- closeSync19(fd);
124831
+ closeSync20(fd);
123973
124832
  return uuid;
123974
124833
  }
123975
124834
  itemOf(e) {
@@ -124211,6 +125070,15 @@ function launchSigningFor(config, deps = {}) {
124211
125070
  const wantsApiBilling = deps.wantsApiBilling ?? ((c) => wantsAnthropicApiBilling(c));
124212
125071
  return wantsApiBilling(config) ? undefined : LOGIN_ONLY_SIGNING;
124213
125072
  }
125073
+ function claudeRowsAsPicked(config) {
125074
+ if ((config.modelListings?.length ?? 0) === 0)
125075
+ return false;
125076
+ if (isProxyAuthMode(config))
125077
+ return false;
125078
+ if (typeof config.model !== "string" || config.model.length === 0)
125079
+ return true;
125080
+ return nativeRouteFor(config.model) !== null;
125081
+ }
124214
125082
  function advisorKeyLookupAllowed(config, deps = {}) {
124215
125083
  const tiers = [config.modelOpus, config.modelSonnet, config.modelHaiku, config.modelSubagent];
124216
125084
  const hasMainModel = (config.modelChain?.length ?? 0) > 0 || Boolean(config.model) || tiers.some((m) => typeof m === "string" && m.length > 0);
@@ -124261,6 +125129,11 @@ function subscriptionPrefix(cause) {
124261
125129
  return cause ? `${CLAUDE_SUBSCRIPTION_LABEL}, ${cause}` : CLAUDE_SUBSCRIPTION_LABEL;
124262
125130
  }
124263
125131
  function subscriptionCause(config) {
125132
+ if (startsOnClaudeSubscription(config)) {
125133
+ const typed = (config.modelListings ?? []).map((listing) => listing.typed);
125134
+ const verb = typed.length === 1 ? "names" : "name";
125135
+ return `because --model ${typed.join(", ")} ${verb} no start model, so the session starts on Claude's default model`;
125136
+ }
124264
125137
  const main = typeof config.model === "string" ? config.model : undefined;
124265
125138
  if (main && nativeRouteFor(main) !== null)
124266
125139
  return;
@@ -124369,7 +125242,8 @@ function decideClaudeLaunch(config, deps = {}) {
124369
125242
  }
124370
125243
  if (!isClaudeSubscriptionSpec2(main))
124371
125244
  return { ok: true };
124372
- if (deps.paneChild ?? isPaneChild()) {
125245
+ const hasListings = (config.modelListings?.length ?? 0) > 0;
125246
+ if (hasListings || (deps.paneChild ?? isPaneChild())) {
124373
125247
  config.model = normalizeNativeModelSpec(claudeSubscriptionInner(main));
124374
125248
  config.claudeSubscriptionPin = true;
124375
125249
  return { ok: true };
@@ -124381,6 +125255,113 @@ function decideClaudeLaunch(config, deps = {}) {
124381
125255
  config.claudeLaunch = "subscription";
124382
125256
  return { ok: true };
124383
125257
  }
125258
+ function listingProviderRefusal(typed, provider) {
125259
+ if (provider === "native-anthropic") {
125260
+ return `--model ${typed}: Claude Code lists the Claude subscription's models in /model already, so claude@ cannot be a listing entry.`;
125261
+ }
125262
+ if (provider === "custom-url") {
125263
+ return `--model ${typed}: a raw URL has no model list. Declare the endpoint under customEndpoints and list it by name (--model <name>@).`;
125264
+ }
125265
+ return null;
125266
+ }
125267
+ function unknownShortcutRefusal(shortcut, typed) {
125268
+ const { reason, hint } = describeUnknownShortcut(shortcut, "", undefined, typed);
125269
+ return `${reason} ${hint}`;
125270
+ }
125271
+ function unreadableSettingsRefusal(config, deps) {
125272
+ const unreadable = (deps.unreadableSettings ?? ((c) => unreadableSettingsArgs(c)))(config);
125273
+ if (unreadable.length === 0)
125274
+ return null;
125275
+ const which = unreadable.length === 1 ? `occurrence ${unreadable[0]}` : `occurrences ${unreadable.join(", ")}`;
125276
+ return `claudish cannot read --settings (${which}); a /model lineup merges every --settings into ` + `one file. Fix or remove ${unreadable.length === 1 ? "it" : "them"}.`;
125277
+ }
125278
+ function settingsBaseUrlRefusal(config, deps) {
125279
+ const keepsLogin = deps.keepsLogin ?? ((c) => !isProxyAuthMode(c));
125280
+ if (!keepsLogin(config))
125281
+ return null;
125282
+ const findingsOf = deps.settingsFindings ?? ((c) => settingsCredentialFindings(c, process.env));
125283
+ const files = [
125284
+ ...new Set(findingsOf(config).filter((finding) => finding.kind === "base-url").map((finding) => finding.where))
125285
+ ];
125286
+ if (files.length === 0)
125287
+ return null;
125288
+ const classifierOn = deps.classifierPassthrough ?? ((c) => classifierPassthroughEnabled(c));
125289
+ const classifierIsCause = !hasNativeAnthropicMapping(config) && classifierOn(config);
125290
+ const remedy = classifierIsCause ? "launch without classifier passthrough." : "start on a foreign model (--model <provider>@<id>), whose launch claudish routes.";
125291
+ return `${files.join(", ")} ${files.length === 1 ? "sets" : "set"} ANTHROPIC_BASE_URL, so /model picks ` + `would bypass claudish. Remove ${files.length === 1 ? "it" : "them"}, or ${remedy}`;
125292
+ }
125293
+ function decideModelListings(config, parsed, deps = {}) {
125294
+ if (!parsed?.hasLineup)
125295
+ return { ok: true };
125296
+ const isKnown = deps.isKnownProvider ?? isKnownProviderName;
125297
+ if (config.monitor) {
125298
+ return {
125299
+ ok: false,
125300
+ message: "--monitor cannot be combined with a listing entry (--model <provider>@): a monitor session sends every request to Anthropic, so no listed model could be routed."
125301
+ };
125302
+ }
125303
+ const start = parsed.start;
125304
+ if (start && isClaudeApiSpec(start)) {
125305
+ return {
125306
+ ok: false,
125307
+ message: `--model ${start} starts a Claude API session that forwards every request to Anthropic, so no listed model could be routed. Start on another model, or drop the listing entries.`
125308
+ };
125309
+ }
125310
+ const byProvider = new Map;
125311
+ const add = (provider, typed, scope) => {
125312
+ const existing = byProvider.get(provider);
125313
+ if (existing) {
125314
+ if (scope === "all")
125315
+ existing.scope = "all";
125316
+ return existing;
125317
+ }
125318
+ const listing = { provider, typed, scope, pinnedSpecs: [] };
125319
+ byProvider.set(provider, listing);
125320
+ return listing;
125321
+ };
125322
+ if (start) {
125323
+ const parsedStart = parseModelSpec(start);
125324
+ if (parsedStart.isExplicitProvider && listingProviderRefusal(start, parsedStart.provider) === null && isKnown(typedShortcutOf(start))) {
125325
+ add(parsedStart.provider, start, "recommended").pinnedSpecs.push(start);
125326
+ }
125327
+ }
125328
+ for (const entry of parsed.listings) {
125329
+ const typed = `${entry.shortcut}@${entry.scope === "all" ? "*" : ""}`;
125330
+ if (!isKnown(entry.shortcut)) {
125331
+ return { ok: false, message: unknownShortcutRefusal(entry.shortcut, typed) };
125332
+ }
125333
+ const provider = parseModelSpec(`${entry.shortcut}@x`).provider;
125334
+ const refusal = listingProviderRefusal(typed, provider);
125335
+ if (refusal)
125336
+ return { ok: false, message: refusal };
125337
+ const listing = add(provider, typed, entry.scope);
125338
+ if (listing.typed === start)
125339
+ listing.typed = typed;
125340
+ }
125341
+ for (const spec of parsed.pinned) {
125342
+ const shortcut = typedShortcutOf(spec);
125343
+ if (!isKnown(shortcut)) {
125344
+ const parsedPin = parseModelSpec(spec);
125345
+ const { reason, hint } = describeUnknownShortcut(shortcut, parsedPin.model, undefined, spec);
125346
+ return { ok: false, message: `${reason} ${hint}` };
125347
+ }
125348
+ const provider = parseModelSpec(spec).provider;
125349
+ const refusal = listingProviderRefusal(spec, provider);
125350
+ if (refusal)
125351
+ return { ok: false, message: refusal };
125352
+ add(provider, spec, "recommended").pinnedSpecs.push(spec);
125353
+ }
125354
+ const settingsRefusal = unreadableSettingsRefusal(config, deps);
125355
+ if (settingsRefusal)
125356
+ return { ok: false, message: settingsRefusal };
125357
+ config.modelListings = [...byProvider.values()];
125358
+ const baseUrlRefusal = settingsBaseUrlRefusal(config, deps);
125359
+ if (baseUrlRefusal) {
125360
+ delete config.modelListings;
125361
+ return { ok: false, message: baseUrlRefusal };
125362
+ }
125363
+ return { ok: true };
125364
+ }
124384
125365
  function effectiveStartupCredential(config, env, deps) {
124385
125366
  const credentialOf = deps.claudeCodeCredential ?? ((e) => claudeCodeStartupCredential({ env: e }));
124386
125367
  const fromSettings = (deps.settingsLoginToken ?? settingsClaudeLoginToken)(config, env);
@@ -124528,6 +125509,7 @@ var init_claude_launch = __esm(() => {
124528
125509
  init_model_parser();
124529
125510
  init_native_route();
124530
125511
  init_shadowed_endpoint();
125512
+ init_unknown_shortcut();
124531
125513
  init_redact();
124532
125514
  TIER_FIELDS = [
124533
125515
  ["opus", "modelOpus"],
@@ -124567,6 +125549,7 @@ function claudeCodePrintEnv(parent) {
124567
125549
  scrubInheritedFastModeGates(env);
124568
125550
  scrubInheritedHostRouting(env);
124569
125551
  scrubInheritedHarnessGatewayTarget(env);
125552
+ scrubInheritedModelVars(env, { model: false, smallFast: false }, { keepsLogin: true });
124570
125553
  return env;
124571
125554
  }
124572
125555
  function isFrame(v) {
@@ -124772,6 +125755,7 @@ var init_run_prompt_claude_code = __esm(() => {
124772
125755
  init_harness_gateway();
124773
125756
  init_host_routing_env();
124774
125757
  init_claude_launch();
125758
+ init_model_vars_env();
124775
125759
  init_child_env();
124776
125760
  init_pane_launch();
124777
125761
  init_redact();
@@ -132312,7 +133296,7 @@ __export(exports_subscription_probe_command, {
132312
133296
  runProbeWith: () => runProbeWith,
132313
133297
  subscriptionProbeCommand: () => subscriptionProbeCommand
132314
133298
  });
132315
- import { randomUUID as randomUUID12 } from "crypto";
133299
+ import { randomUUID as randomUUID11 } from "crypto";
132316
133300
  function probeExitCodeFor(failure) {
132317
133301
  if (failure.class === "internal") {
132318
133302
  return CALLER_CODES.includes(failure.code) ? PROBE_EXIT.usage : PROBE_EXIT.internal;
@@ -132455,13 +133439,13 @@ async function runProbeWith(deps, facts, secrets, requestFileMessage, determine)
132455
133439
  }
132456
133440
  return result.exitCode;
132457
133441
  }
132458
- function buildProbeEnvelopeBody(model, projectId, tierId, requestText, userPromptId = randomUUID12()) {
132459
- const head = JSON.stringify({ model, project: projectId, user_prompt_id: userPromptId });
132460
- const credits = tierId && tierId !== "free-tier" ? `,"enabled_credit_types":${JSON.stringify(["GOOGLE_ONE_AI"])}` : "";
132461
- return `${head.slice(0, -1)},"request":${requestText}${credits}}`;
133442
+ function firstRequestId() {
133443
+ return `agent/${randomUUID11()}/${Date.now()}/${randomUUID11()}/1`;
132462
133444
  }
132463
- function createActivityRequestId3() {
132464
- return Math.random().toString(36).substring(7);
133445
+ function buildProbeEnvelopeBody(model, projectId, requestText, requestId = firstRequestId()) {
133446
+ const head = JSON.stringify({ project: projectId, requestId });
133447
+ const tail = JSON.stringify({ model, userAgent: "antigravity", requestType: "agent" });
133448
+ return `${head.slice(0, -1)},"request":${requestText},${tail.slice(1)}`;
132465
133449
  }
132466
133450
  async function determineAntigravity2(deps, secrets, facts, args) {
132467
133451
  const request = await readRequestFileChecked(deps.readRequestFile, args.requestFile);
@@ -132481,15 +133465,14 @@ async function determineAntigravity2(deps, secrets, facts, args) {
132481
133465
  try {
132482
133466
  let res;
132483
133467
  try {
132484
- res = await fetch(url, {
133468
+ res = await antigravityFetch(url, {
132485
133469
  method: "POST",
132486
133470
  headers: {
132487
133471
  Authorization: `Bearer ${session.accessToken}`,
132488
133472
  "Content-Type": "application/json",
132489
- "User-Agent": antigravityUserAgentFor(version.version),
132490
- "x-activity-request-id": createActivityRequestId3()
133473
+ "User-Agent": antigravityUserAgentFor(version.version)
132491
133474
  },
132492
- body: buildProbeEnvelopeBody(args.model, session.projectId, session.tierId, request.text),
133475
+ body: buildProbeEnvelopeBody(args.model, session.projectId, request.text),
132493
133476
  signal: controller.signal,
132494
133477
  redirect: "manual"
132495
133478
  });
@@ -132554,6 +133537,7 @@ var PROBE_FAILURE_CODES, PROBE_EXIT, CALLER_CODES, SUBSCRIPTION_PROBE_USAGE = "u
132554
133537
  var init_subscription_probe_command = __esm(() => {
132555
133538
  init_antigravity_token();
132556
133539
  init_antigravity_user();
133540
+ init_antigravity_fetch();
132557
133541
  init_subscription_antigravity_session();
132558
133542
  init_subscription_dispatch();
132559
133543
  init_subscription_secret_guard();
@@ -141565,6 +142549,578 @@ var init_tui = __esm(() => {
141565
142549
  }
141566
142550
  });
141567
142551
 
142552
+ // src/launcher/model-lineup.ts
142553
+ function redactAndTruncate(text, max) {
142554
+ const redacted = redactSecrets(text);
142555
+ if (redacted.length <= max)
142556
+ return redacted;
142557
+ let cut = max - 1;
142558
+ for (const marker of REDACTION_MARKERS) {
142559
+ let at = redacted.indexOf(marker);
142560
+ while (at >= 0 && at < cut) {
142561
+ if (at + marker.length > cut) {
142562
+ cut = at;
142563
+ break;
142564
+ }
142565
+ at = redacted.indexOf(marker, at + marker.length);
142566
+ }
142567
+ }
142568
+ return `${redacted.slice(0, cut).trimEnd()}\u2026`;
142569
+ }
142570
+ function rowKey(spec) {
142571
+ const parsed = parseModelSpec(spec);
142572
+ return [
142573
+ parsed.provider,
142574
+ parsed.model,
142575
+ parsed.mode ?? "",
142576
+ parsed.speed ?? "",
142577
+ parsed.concurrency ?? ""
142578
+ ].join("\x00");
142579
+ }
142580
+ function lineupSpecFor(provider, wireId) {
142581
+ const spec = buildExplicitModelSpec(provider, wireId);
142582
+ const parsed = parseModelSpec(spec);
142583
+ if (parsed.isExplicitProvider && parsed.provider === provider)
142584
+ return spec;
142585
+ return `${provider}@${wireId}`;
142586
+ }
142587
+ function lineupProviderName(provider) {
142588
+ try {
142589
+ const choice = buildProviderChoices().find((c) => c.value === provider);
142590
+ if (choice)
142591
+ return choice.name;
142592
+ } catch {}
142593
+ return getDisplayName(provider);
142594
+ }
142595
+ function priceLabel2(provider, isLocal, model) {
142596
+ if (isLocal)
142597
+ return "local";
142598
+ if (displayBillingOf(provider) === "sub")
142599
+ return "SUB";
142600
+ const price = resolveProviderDisplayPrice(provider, model);
142601
+ return price && price !== "N/A" ? price : undefined;
142602
+ }
142603
+ function rowFrom(provider, providerName, isLocal, spec, model, fallbackLabel) {
142604
+ const contextLength = model?.contextLength && model.contextLength > 0 ? model.contextLength : undefined;
142605
+ const parts = [providerName];
142606
+ if (contextLength)
142607
+ parts.push(`${formatContextLength(contextLength)} context`);
142608
+ const price = model ? priceLabel2(provider, isLocal, model) : isLocal ? "local" : undefined;
142609
+ if (price)
142610
+ parts.push(price);
142611
+ else if (!model && displayBillingOf(provider) === "sub")
142612
+ parts.push("SUB");
142613
+ return {
142614
+ model: spec,
142615
+ label: redactAndTruncate(model?.name || fallbackLabel, LINEUP_LABEL_MAX),
142616
+ description: redactAndTruncate(parts.join(" \xB7 "), LINEUP_DESCRIPTION_MAX),
142617
+ provider,
142618
+ ...contextLength ? { contextLength } : {}
142619
+ };
142620
+ }
142621
+ function declaredModelInfo(id, providerName) {
142622
+ return { id, name: id, description: "", provider: providerName };
142623
+ }
142624
+ function allScopeHint(listing) {
142625
+ const at = listing.typed.indexOf("@");
142626
+ const shortcut = at > 0 ? listing.typed.slice(0, at) : listing.provider;
142627
+ return `'${shortcut}@*'`;
142628
+ }
142629
+ function discoveryEmptyReason(outcome) {
142630
+ switch (outcome.kind) {
142631
+ case "rows":
142632
+ return;
142633
+ case "failed":
142634
+ return describeDiscoveryFailure(outcome.failure);
142635
+ case "empty-models-catalog":
142636
+ return describeDiscoveryFailure(outcome.failure);
142637
+ case "all-filtered":
142638
+ return outcome.servedCount === 1 ? "it serves 1 model, not a chat model" : `it serves ${outcome.servedCount} models, none of them a chat model`;
142639
+ case "collapsed-empty":
142640
+ return "its model list yielded no rows";
142641
+ case "unsupported":
142642
+ return "it publishes no model list";
142643
+ }
142644
+ }
142645
+ function lineupRowsForProvider(input) {
142646
+ const { listing, tier, declared } = input;
142647
+ const source = candidateSource(input);
142648
+ let { candidates, emptyReason } = source;
142649
+ const isGatewayRecommended = tier === "gateway" && listing.scope === "recommended" && declared === null;
142650
+ if (isGatewayRecommended && (candidates.length > 0 || input.recommendedIds === null)) {
142651
+ const narrowed = recommendedCandidates(input, candidates);
142652
+ candidates = narrowed.candidates;
142653
+ emptyReason = narrowed.emptyReason ?? emptyReason;
142654
+ }
142655
+ const rows = assembleRows(input, candidates.filter((m) => m.supportsTools !== false));
142656
+ if (rows.length > 0)
142657
+ return { rows };
142658
+ return { rows, emptyReason: emptyReason ?? "it lists no chat models" };
142659
+ }
142660
+ function candidateSource(input) {
142661
+ const { listing, discovered, catalogRows, declared } = input;
142662
+ const provider = listing.provider;
142663
+ if (declared && declared.length > 0) {
142664
+ const providerName = lineupProviderName(provider);
142665
+ return { candidates: declared.map((id) => declaredModelInfo(id, providerName)) };
142666
+ }
142667
+ const isCustomEndpoint = declared !== null;
142668
+ if (isCustomEndpoint && listing.scope === "recommended") {
142669
+ return {
142670
+ candidates: [],
142671
+ emptyReason: `declare models for ${provider}, or use ${allScopeHint(listing)}`
142672
+ };
142673
+ }
142674
+ if (discovered) {
142675
+ return discovered.kind === "rows" ? { candidates: [...discovered.rows] } : { candidates: [], emptyReason: discoveryEmptyReason(discovered) };
142676
+ }
142677
+ if (isCustomEndpoint)
142678
+ return { candidates: [], emptyReason: `${provider} has no model list` };
142679
+ return { candidates: [...catalogRows] };
142680
+ }
142681
+ function recommendedCandidates(input, candidates) {
142682
+ const { listing, discovered, catalogRows, recommendedIds } = input;
142683
+ if (recommendedIds === null) {
142684
+ return {
142685
+ candidates: [],
142686
+ emptyReason: `recommended list unavailable; ${allScopeHint(listing)} lists every model it serves`
142687
+ };
142688
+ }
142689
+ const rank = new Map;
142690
+ if (discovered?.kind === "rows") {
142691
+ const catalogById = new Map(catalogRows.map((m) => [m.id, m]));
142692
+ recommendedIds.forEach((id, i) => {
142693
+ const row = catalogById.get(id);
142694
+ if (!row)
142695
+ return;
142696
+ const wire = resolveProviderExternalId(listing.provider, row);
142697
+ if (!rank.has(wire))
142698
+ rank.set(wire, i);
142699
+ });
142700
+ } else {
142701
+ recommendedIds.forEach((id, i) => {
142702
+ if (!rank.has(id))
142703
+ rank.set(id, i);
142704
+ });
142705
+ }
142706
+ const kept = candidates.filter((m) => rank.has(m.id)).sort((a, b) => (rank.get(a.id) ?? 0) - (rank.get(b.id) ?? 0));
142707
+ if (kept.length > 0)
142708
+ return { candidates: kept };
142709
+ return {
142710
+ candidates: [],
142711
+ emptyReason: `it serves none of the recommended models; ${allScopeHint(listing)} lists every model it serves`
142712
+ };
142713
+ }
142714
+ function assembleRows(input, candidates) {
142715
+ const { listing, isLocal, discovered, declared } = input;
142716
+ const provider = listing.provider;
142717
+ const providerName = lineupProviderName(provider);
142718
+ const idIsWire = discovered?.kind === "rows" || declared !== null && declared.length > 0;
142719
+ const listed = new Map;
142720
+ for (const m of candidates) {
142721
+ const spec = lineupSpecFor(provider, idIsWire ? m.id : resolveProviderExternalId(provider, m));
142722
+ const key = rowKey(spec);
142723
+ if (!listed.has(key))
142724
+ listed.set(key, { spec, model: m });
142725
+ }
142726
+ const rows = [];
142727
+ const seen = new Set;
142728
+ for (const pinned of listing.pinnedSpecs) {
142729
+ const key = rowKey(pinned);
142730
+ if (seen.has(key))
142731
+ continue;
142732
+ seen.add(key);
142733
+ const match = listed.get(key)?.model;
142734
+ rows.push(rowFrom(provider, providerName, isLocal, pinned, match, parseModelSpec(pinned).model));
142735
+ }
142736
+ for (const [key, { spec, model }] of listed) {
142737
+ if (seen.has(key))
142738
+ continue;
142739
+ seen.add(key);
142740
+ rows.push(rowFrom(provider, providerName, isLocal, spec, model, model.id));
142741
+ }
142742
+ return rows;
142743
+ }
142744
+ function stageSentence(stage, deadlineMs) {
142745
+ const seconds = `${Math.round(deadlineMs / 1000)} s`;
142746
+ switch (stage) {
142747
+ case "credential":
142748
+ return `no answer within ${seconds} while resolving its credential (a 1Password unlock may be waiting)`;
142749
+ case "list":
142750
+ return `no answer within ${seconds} while fetching its model list`;
142751
+ case "recommended":
142752
+ return `no answer within ${seconds} while reading the recommended list`;
142753
+ }
142754
+ }
142755
+ function notReadyReason(provider) {
142756
+ const def = getProviderByName(provider);
142757
+ if (def?.oauthLoginSlug) {
142758
+ return `not signed in \u2014 run \`claudish login ${def.oauthLoginSlug}\``;
142759
+ }
142760
+ if (def && def.apiKeyEnvVar === "" && def.isLocal !== true) {
142761
+ return `no ${lineupProviderName(provider)} sign-in found on this machine`;
142762
+ }
142763
+ return describeMissingCredential(provider);
142764
+ }
142765
+ function credentialCheck(provider, outcome) {
142766
+ if (outcome.kind !== "failed")
142767
+ return;
142768
+ const kind = outcome.failure.kind;
142769
+ if (kind !== "unauthorized" && kind !== "no-credentials")
142770
+ return;
142771
+ const envVar = getProviderByName(provider)?.apiKeyEnvVar;
142772
+ return envVar ? `check ${envVar} (a value in your shell overrides stored credentials)` : undefined;
142773
+ }
142774
+ function recommendedIdsOf(doc) {
142775
+ const tierIndex = new Map(RECOMMENDATION_SECTIONS.map((s, i) => [s.recommendationTier, i]));
142776
+ const ranked = doc.models.map((m, i) => ({ m, i })).filter(({ m }) => tierIndex.has(m.recommendationTier)).sort((a, b) => (tierIndex.get(a.m.recommendationTier) ?? 0) - (tierIndex.get(b.m.recommendationTier) ?? 0) || (a.m.priority ?? 0) - (b.m.priority ?? 0) || a.i - b.i);
142777
+ const ids = [];
142778
+ for (const { m } of ranked)
142779
+ if (!ids.includes(m.id))
142780
+ ids.push(m.id);
142781
+ return ids;
142782
+ }
142783
+ function defaultDeps7() {
142784
+ let catalog = null;
142785
+ const catalogOf = () => {
142786
+ catalog ??= createCatalogClient({ readSlimCache: () => readAllModelsCache() });
142787
+ return catalog;
142788
+ };
142789
+ return {
142790
+ ready: (provider) => pickerProviderReady(provider),
142791
+ storedList: (provider) => readAccountModelsList(provider),
142792
+ liveList: (provider) => liveOrStoredModelsCatalog(provider, "launch-lineup"),
142793
+ catalogRows: (provider) => {
142794
+ try {
142795
+ return servedModelsForProvider(provider, catalogOf());
142796
+ } catch {
142797
+ return [];
142798
+ }
142799
+ },
142800
+ catalogIsBundled: () => bundledListActive(),
142801
+ ensureCatalog: (ms) => ensureCatalogReady(Math.max(0, ms)).catch(() => {
142802
+ return;
142803
+ }),
142804
+ recommended: async () => {
142805
+ if (bundledListActive())
142806
+ return bundledRecommendedModelsDoc();
142807
+ try {
142808
+ await Promise.resolve().then(() => init_model_loader());
142809
+ const doc = await getRecommendedModels();
142810
+ if (doc)
142811
+ return doc;
142812
+ } catch {}
142813
+ return bundledListActive() ? bundledRecommendedModelsDoc() : null;
142814
+ },
142815
+ declaredModels: (provider) => {
142816
+ try {
142817
+ const endpoints = loadConfig().customEndpoints ?? {};
142818
+ if (!Object.prototype.hasOwnProperty.call(endpoints, provider))
142819
+ return null;
142820
+ const models = endpoints[provider].models;
142821
+ return Array.isArray(models) ? models.filter((m) => typeof m === "string") : [];
142822
+ } catch {
142823
+ return null;
142824
+ }
142825
+ },
142826
+ tier: (provider) => getProviderByName(provider)?.tier ?? "gateway",
142827
+ hasDiscovery: (provider) => Boolean(getProviderByName(provider)?.modelDiscovery),
142828
+ now: () => Date.now()
142829
+ };
142830
+ }
142831
+ function within(promise, ms, fallback) {
142832
+ if (ms <= 0)
142833
+ return Promise.resolve(fallback);
142834
+ return new Promise((resolve) => {
142835
+ const timer = setTimeout(() => resolve(fallback), ms);
142836
+ promise.then((value) => {
142837
+ clearTimeout(timer);
142838
+ resolve(value);
142839
+ }, () => {
142840
+ clearTimeout(timer);
142841
+ resolve(fallback);
142842
+ });
142843
+ });
142844
+ }
142845
+ async function buildModelLineup(listings, opts = {}) {
142846
+ const deadlineMs = opts.deadlineMs ?? LINEUP_WAIT_MS;
142847
+ const deps = { ...defaultDeps7(), ...opts.deps };
142848
+ const startedAt = deps.now();
142849
+ const remaining = () => Math.max(0, deadlineMs - (deps.now() - startedAt));
142850
+ const tiers = new Map(listings.map((l) => [l.provider, safeTier(deps, l.provider)]));
142851
+ const needsRecommended = listings.some((l) => tiers.get(l.provider) === "gateway" && l.scope === "recommended" && safeDeclared(deps, l.provider) === null);
142852
+ const recommendedPromise = needsRecommended ? deps.recommended().catch(() => null) : null;
142853
+ const stages = new Map;
142854
+ const settled = new Map;
142855
+ const one = async (listing) => {
142856
+ const provider = listing.provider;
142857
+ const notListed = (reason) => settled.set(provider, { rows: [], outcome: { kind: "not-listed", provider, reason } });
142858
+ try {
142859
+ stages.set(provider, "credential");
142860
+ const ready = await deps.ready(provider).catch(() => false);
142861
+ if (!ready) {
142862
+ notListed(notReadyReason(provider));
142863
+ return;
142864
+ }
142865
+ const tier = tiers.get(provider) ?? "gateway";
142866
+ const isLocal = getProviderByName(provider)?.isLocal === true;
142867
+ const declared = safeDeclared(deps, provider);
142868
+ stages.set(provider, "list");
142869
+ let discovered = null;
142870
+ let source = "catalog";
142871
+ let storedAt;
142872
+ if (declared && declared.length > 0) {
142873
+ source = "declared";
142874
+ } else if (deps.hasDiscovery(provider) && (declared === null || listing.scope === "all")) {
142875
+ const asked = await discoverFor(provider, deps, remaining());
142876
+ discovered = asked.discovered;
142877
+ source = asked.source;
142878
+ storedAt = asked.storedAt;
142879
+ if (discovered.kind !== "rows" && listing.pinnedSpecs.length === 0) {
142880
+ const check = credentialCheck(provider, discovered);
142881
+ const reason = discoveryEmptyReason(discovered) ?? "it lists no chat models";
142882
+ notListed(check ? `${reason}; ${check}` : reason);
142883
+ return;
142884
+ }
142885
+ } else if (declared === null) {
142886
+ await deps.ensureCatalog(remaining());
142887
+ }
142888
+ const catalogRows = declared === null ? deps.catalogRows(provider) : [];
142889
+ if (source === "catalog" && declared === null && deps.catalogIsBundled())
142890
+ source = "bundled";
142891
+ let recommendedIds = null;
142892
+ if (tier === "gateway" && listing.scope === "recommended" && declared === null) {
142893
+ stages.set(provider, "recommended");
142894
+ const doc = recommendedPromise ? await within(recommendedPromise, remaining(), null) : null;
142895
+ recommendedIds = doc ? recommendedIdsOf(doc) : null;
142896
+ }
142897
+ const built = lineupRowsForProvider({
142898
+ listing,
142899
+ tier,
142900
+ isLocal,
142901
+ discovered,
142902
+ catalogRows,
142903
+ recommendedIds,
142904
+ declared
142905
+ });
142906
+ if (built.rows.length === 0) {
142907
+ notListed(built.emptyReason ?? "it lists no chat models");
142908
+ return;
142909
+ }
142910
+ const servedTotal = tier === "gateway" && listing.scope === "recommended" && declared === null ? discovered?.kind === "rows" ? discovered.rows.length : catalogRows.length : undefined;
142911
+ settled.set(provider, {
142912
+ rows: built.rows,
142913
+ outcome: {
142914
+ kind: "listed",
142915
+ provider,
142916
+ count: built.rows.length,
142917
+ source,
142918
+ ...storedAt !== undefined ? { storedAt } : {},
142919
+ ...servedTotal !== undefined && servedTotal > built.rows.length ? { servedTotal } : {}
142920
+ }
142921
+ });
142922
+ } catch (err) {
142923
+ notListed(redactSecrets(err instanceof Error ? err.message : String(err)));
142924
+ } finally {
142925
+ stages.delete(provider);
142926
+ }
142927
+ };
142928
+ const all = Promise.all(listings.map(one)).then(() => {
142929
+ return;
142930
+ });
142931
+ const result = await within(all, remaining(), TIMED_OUT2);
142932
+ if (result === TIMED_OUT2)
142933
+ log(`[model-lineup] deadline of ${deadlineMs} ms reached`);
142934
+ const rows = [];
142935
+ const outcomes = [];
142936
+ for (const listing of listings) {
142937
+ const done = settled.get(listing.provider);
142938
+ if (done) {
142939
+ rows.push(...done.rows);
142940
+ outcomes.push(done.outcome);
142941
+ continue;
142942
+ }
142943
+ const stage = stages.get(listing.provider) ?? "credential";
142944
+ outcomes.push({
142945
+ kind: "not-listed",
142946
+ provider: listing.provider,
142947
+ reason: stageSentence(stage, deadlineMs)
142948
+ });
142949
+ }
142950
+ return { rows, outcomes };
142951
+ }
142952
+ async function discoverFor(provider, deps, remainingMs) {
142953
+ const catalogWarm = deps.ensureCatalog(remainingMs);
142954
+ const stored = await deps.storedList(provider).catch(() => null);
142955
+ let outcome;
142956
+ if (stored) {
142957
+ outcome = servedOutcomeOf(stored.models);
142958
+ deps.liveList(provider).catch(() => {
142959
+ return;
142960
+ });
142961
+ } else {
142962
+ outcome = await deps.liveList(provider);
142963
+ }
142964
+ await catalogWarm;
142965
+ const discovered = outcomeFromModelsCatalog(provider, lineupProviderName(provider), outcome, deps.catalogRows(provider));
142966
+ return stored ? { discovered, source: "stored", storedAt: stored.fetchedAt } : { discovered, source: "live" };
142967
+ }
142968
+ function safeTier(deps, provider) {
142969
+ try {
142970
+ return deps.tier(provider);
142971
+ } catch {
142972
+ return "gateway";
142973
+ }
142974
+ }
142975
+ function safeDeclared(deps, provider) {
142976
+ try {
142977
+ return deps.declaredModels(provider);
142978
+ } catch {
142979
+ return null;
142980
+ }
142981
+ }
142982
+ function sessionWindow(env, computedWindow) {
142983
+ const raw = env.CLAUDE_CODE_MAX_CONTEXT_TOKENS;
142984
+ const user = raw ? Number.parseInt(raw, 10) : Number.NaN;
142985
+ if (Number.isFinite(user) && user > 0)
142986
+ return user;
142987
+ if (computedWindow > 0)
142988
+ return computedWindow;
142989
+ return CLAUDE_CODE_DEFAULT_MAX_CONTEXT;
142990
+ }
142991
+ function lineupReport(lineup, ctx) {
142992
+ const listed = lineup.outcomes.filter((o) => o.kind === "listed");
142993
+ const lines = [summaryLine(lineup.rows.length, listed)];
142994
+ for (const o of lineup.outcomes) {
142995
+ if (o.kind !== "not-listed")
142996
+ continue;
142997
+ lines.push(`${PREFIX2}/model: ${lineupProviderName(o.provider)} not listed \u2014 ${redactSecrets(o.reason)}`);
142998
+ }
142999
+ for (const o of listed) {
143000
+ if (o.source !== "bundled")
143001
+ continue;
143002
+ lines.push(`${PREFIX2}/model: ${lineupProviderName(o.provider)} list is partial (the cloud models catalog was unreachable; it lists recommended models only)`);
143003
+ }
143004
+ const windowLine = smallerWindowLine(lineup.rows, ctx.sizedFor);
143005
+ if (windowLine)
143006
+ lines.push(windowLine);
143007
+ for (const notice of ctx.settingsNotices)
143008
+ lines.push(`${PREFIX2}/model: ${redactSecrets(notice)}`);
143009
+ if (ctx.posture === "foreign-start") {
143010
+ lines.push(`${PREFIX2}/model: this session starts on a foreign model, so a Claude row runs that start model`);
143011
+ } else if (ctx.posture === "tiers") {
143012
+ lines.push(`${PREFIX2}/model: Claude rows run your mapped tiers; an unmapped Claude row is not served on this launch`);
143013
+ }
143014
+ for (const { name } of ctx.inheritedModelVars) {
143015
+ lines.push(name === "ANTHROPIC_MODEL" ? `${PREFIX2}starts on the model ANTHROPIC_MODEL names in your environment` : `${PREFIX2}${name} from your environment still applies`);
143016
+ }
143017
+ return lines;
143018
+ }
143019
+ function summaryLine(rowCount, listed) {
143020
+ if (rowCount === 0) {
143021
+ return `${PREFIX2}/model lists no claudish models this session; Claude's own models only`;
143022
+ }
143023
+ const parts = listed.map((o) => {
143024
+ const name = lineupProviderName(o.provider);
143025
+ if (o.servedTotal === undefined)
143026
+ return `${name} ${o.count}`;
143027
+ return `${name} ${o.count} (recommended; '${shortestShortcut(o.provider)}@*' lists ${o.servedTotal})`;
143028
+ });
143029
+ const noun = rowCount === 1 ? "model" : "models";
143030
+ return `${PREFIX2}/model lists ${rowCount} ${noun} after Claude's own: ${parts.join(" \xB7 ")}`;
143031
+ }
143032
+ function smallerWindowLine(rows, sizedFor) {
143033
+ const smaller = rows.filter((r) => r.contextLength !== undefined && r.contextLength < sizedFor);
143034
+ if (smaller.length === 0)
143035
+ return null;
143036
+ const smallest = smaller.reduce((a, b) => (a.contextLength ?? 0) <= (b.contextLength ?? 0) ? a : b);
143037
+ const verb = smaller.length === 1 ? "model has" : "models have";
143038
+ return `${PREFIX2}/model: ${smaller.length} listed ${verb} a smaller context window than this session assumes (${formatContextLength(sizedFor)}; smallest: ${smallest.label} ${formatContextLength(smallest.contextLength)})`;
143039
+ }
143040
+ function shortestShortcut(provider) {
143041
+ const def = getProviderByName(provider);
143042
+ return def?.shortestPrefix || def?.shortcuts?.[0] || provider;
143043
+ }
143044
+ function userOption(entry) {
143045
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
143046
+ return null;
143047
+ const record = entry;
143048
+ const { model, label } = record;
143049
+ if (typeof model !== "string" || model.length === 0)
143050
+ return null;
143051
+ return { ...record, model, label: typeof label === "string" ? label : model };
143052
+ }
143053
+ function isRoutableClaudishSpec(model) {
143054
+ if (nativeRouteFor(model) !== null)
143055
+ return false;
143056
+ const parsed = parseModelSpec(model);
143057
+ if (!parsed.isExplicitProvider || parsed.isLegacySyntax)
143058
+ return false;
143059
+ if (parsed.provider === "custom-url" || parsed.provider === "native-anthropic")
143060
+ return false;
143061
+ return getProviderByName(parsed.provider) !== undefined;
143062
+ }
143063
+ function routedUserRows(options, rows) {
143064
+ const listed = new Set(rows.map((row) => row.model));
143065
+ const out = [];
143066
+ for (const option of options) {
143067
+ if (listed.has(option.model) || !isRoutableClaudishSpec(option.model))
143068
+ continue;
143069
+ listed.add(option.model);
143070
+ out.push({ model: option.model, label: option.label });
143071
+ }
143072
+ return out;
143073
+ }
143074
+ function modelPickerSetting(rows, sources) {
143075
+ const options = [];
143076
+ const seen = new Set;
143077
+ for (const entry of sources.user?.options ?? []) {
143078
+ const option = userOption(entry);
143079
+ if (!option || seen.has(option.model))
143080
+ continue;
143081
+ seen.add(option.model);
143082
+ options.push(option);
143083
+ }
143084
+ for (const row of rows) {
143085
+ if (seen.has(row.model))
143086
+ continue;
143087
+ seen.add(row.model);
143088
+ options.push({ model: row.model, label: row.label, description: row.description });
143089
+ }
143090
+ const notices = [];
143091
+ if (sources.user && sources.user.replaceBuiltInOptions === true) {
143092
+ notices.push(`${sources.user.where} sets modelPicker.replaceBuiltInOptions; claudish keeps Claude's own rows in /model for this session`);
143093
+ }
143094
+ if (sources.managed) {
143095
+ notices.push(`${sources.managed} sets modelPicker, which Claude Code applies over claudish's rows; listed models may be missing from /model`);
143096
+ }
143097
+ for (const where of sources.availableModels) {
143098
+ notices.push(`${where} sets availableModels, which may hide listed models from /model`);
143099
+ }
143100
+ return { setting: { options }, notices };
143101
+ }
143102
+ var LINEUP_WAIT_MS = 6000, LINEUP_LABEL_MAX = 60, LINEUP_DESCRIPTION_MAX = 100, REDACTION_MARKERS, TIMED_OUT2, PREFIX2 = "[claudish] ", MODEL_RESTORE_PROMISE = `/model: Enter saves a pick as Claude Code's default; claudish puts your setting back at exit ("s" picks for this session only)`;
143103
+ var init_model_lineup = __esm(() => {
143104
+ init_claude_runner();
143105
+ init_logger();
143106
+ init_model_loader();
143107
+ init_model_selector();
143108
+ init_profile_config();
143109
+ init_all_models_cache();
143110
+ init_bundled_list();
143111
+ init_catalog_client();
143112
+ init_dynamic_models_catalog();
143113
+ init_model_catalog2();
143114
+ init_model_discovery();
143115
+ init_model_parser();
143116
+ init_native_route();
143117
+ init_picker_readiness();
143118
+ init_provider_definitions();
143119
+ init_redact();
143120
+ REDACTION_MARKERS = ["***REDACTED***", "[redacted]"];
143121
+ TIMED_OUT2 = Symbol("timed-out");
143122
+ });
143123
+
141568
143124
  // src/diag-output.ts
141569
143125
  import { createWriteStream as createWriteStream2, mkdirSync as mkdirSync32, unlinkSync as unlinkSync15, writeFileSync as writeFileSync32 } from "fs";
141570
143126
  import { homedir as homedir47 } from "os";
@@ -141988,7 +143544,7 @@ var init_advisor_startup = __esm(() => {
141988
143544
  });
141989
143545
 
141990
143546
  // src/session/conversation.ts
141991
- import { closeSync as closeSync20, openSync as openSync19, readSync as readSync9, statSync as statSync31 } from "fs";
143547
+ import { closeSync as closeSync21, openSync as openSync20, readSync as readSync10, statSync as statSync31 } from "fs";
141992
143548
  import { StringDecoder } from "string_decoder";
141993
143549
  function looksLikeTurn(line) {
141994
143550
  const assistant = line.includes('"type":"assistant"');
@@ -142044,7 +143600,7 @@ function readConversation(file, opts = {}) {
142044
143600
  let fd = null;
142045
143601
  try {
142046
143602
  const size = statSync31(file).size;
142047
- fd = openSync19(file, "r");
143603
+ fd = openSync20(file, "r");
142048
143604
  const buf = Buffer.allocUnsafe(chunkBytes);
142049
143605
  const decoder = new StringDecoder("utf-8");
142050
143606
  let pending = "";
@@ -142076,7 +143632,7 @@ function readConversation(file, opts = {}) {
142076
143632
  take({ role: raw.role, text, elided });
142077
143633
  };
142078
143634
  while (pos < size) {
142079
- const n = readSync9(fd, buf, 0, Math.min(chunkBytes, size - pos), pos);
143635
+ const n = readSync10(fd, buf, 0, Math.min(chunkBytes, size - pos), pos);
142080
143636
  if (n <= 0)
142081
143637
  break;
142082
143638
  pos += n;
@@ -142100,7 +143656,7 @@ function readConversation(file, opts = {}) {
142100
143656
  } catch {} finally {
142101
143657
  if (fd !== null) {
142102
143658
  try {
142103
- closeSync20(fd);
143659
+ closeSync21(fd);
142104
143660
  } catch {}
142105
143661
  }
142106
143662
  }
@@ -143667,6 +145223,611 @@ var init_resume_picker_run = __esm(() => {
143667
145223
  init_session_discovery();
143668
145224
  });
143669
145225
 
145226
+ // src/launcher/model-setting-ledger-path.ts
145227
+ import { homedir as homedir48 } from "os";
145228
+ import { join as join77 } from "path";
145229
+ function modelSettingLedgerPath(env = process.env) {
145230
+ const home = env.HOME && env.HOME.length > 0 ? env.HOME : homedir48();
145231
+ return join77(home, ".claudish", MODEL_SETTING_LEDGER_FILE);
145232
+ }
145233
+ var MODEL_SETTING_LEDGER_FILE = "model-setting-restore.json";
145234
+ var init_model_setting_ledger_path = () => {};
145235
+
145236
+ // src/launcher/model-setting-restore.ts
145237
+ import { randomUUID as randomUUID12 } from "crypto";
145238
+ import {
145239
+ closeSync as closeSync22,
145240
+ fchmodSync as fchmodSync2,
145241
+ fsyncSync as fsyncSync4,
145242
+ openSync as openSync21,
145243
+ readFileSync as readFileSync59,
145244
+ readdirSync as readdirSync20,
145245
+ realpathSync as realpathSync12,
145246
+ renameSync as renameSync15,
145247
+ rmSync as rmSync22,
145248
+ statSync as statSync32,
145249
+ unlinkSync as unlinkSync16,
145250
+ writeSync as writeSync8
145251
+ } from "fs";
145252
+ import { homedir as homedir49 } from "os";
145253
+ import { basename as basename10, dirname as dirname31, join as join78, resolve as resolve15 } from "path";
145254
+ function canonicalSettingsPath(path) {
145255
+ let head = resolve15(path);
145256
+ const rest = [];
145257
+ for (;; ) {
145258
+ try {
145259
+ return join78(realpathSync12.native(head), ...rest);
145260
+ } catch {
145261
+ const parent = dirname31(head);
145262
+ if (parent === head)
145263
+ return join78(head, ...rest);
145264
+ rest.unshift(basename10(head));
145265
+ head = parent;
145266
+ }
145267
+ }
145268
+ }
145269
+ function restoreDecision(current, entry) {
145270
+ if (typeof current !== "string" || !entry.listed.includes(current))
145271
+ return { action: "leave" };
145272
+ if (entry.original.present && entry.original.value === current)
145273
+ return { action: "leave" };
145274
+ return entry.original.present ? { action: "set", value: entry.original.value } : { action: "delete" };
145275
+ }
145276
+ function errnoOf(err) {
145277
+ return err?.code;
145278
+ }
145279
+ function toFileStat(s) {
145280
+ return { dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs, mode: s.mode };
145281
+ }
145282
+ function sameStat(a, b) {
145283
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.mode === b.mode;
145284
+ }
145285
+ function writeWholeSync(fd, data, write = (f, b, o, l) => writeSync8(f, b, o, l)) {
145286
+ const bytes = Buffer.from(data, "utf8");
145287
+ let offset = 0;
145288
+ while (offset < bytes.length) {
145289
+ const n = write(fd, bytes, offset, bytes.length - offset);
145290
+ if (!(n > 0)) {
145291
+ throw new Error(`short write: ${offset} of ${bytes.length} bytes, then no progress`);
145292
+ }
145293
+ offset += n;
145294
+ }
145295
+ }
145296
+ function detectIndent(text) {
145297
+ if (!text.trim().includes(`
145298
+ `))
145299
+ return;
145300
+ const m = text.match(/^\{\s*?\n([ \t]+)\S/);
145301
+ return m?.[1] ? m[1] : 2;
145302
+ }
145303
+ function isPlainObject8(value) {
145304
+ return value !== null && typeof value === "object" && !Array.isArray(value);
145305
+ }
145306
+ function restoreSettingsFile(settingsKey, entry, deps = realRestoreFs, fence = () => true) {
145307
+ let target;
145308
+ try {
145309
+ target = deps.realpath(settingsKey);
145310
+ } catch (err) {
145311
+ return errnoOf(err) === "ENOENT" ? "absent" : "not-writable";
145312
+ }
145313
+ for (let round = 0;round < RESTORE_ROUNDS; round++) {
145314
+ const outcome = restoreRound(settingsKey, target, entry, deps, fence);
145315
+ if (outcome !== "retry")
145316
+ return outcome;
145317
+ }
145318
+ return "changed-under-us";
145319
+ }
145320
+ function nextSettingsText(text, entry) {
145321
+ let parsed;
145322
+ try {
145323
+ parsed = JSON.parse(text);
145324
+ } catch {
145325
+ return { outcome: "unparsable" };
145326
+ }
145327
+ if (!isPlainObject8(parsed))
145328
+ return { outcome: "unparsable" };
145329
+ const decision = restoreDecision(parsed.model, entry);
145330
+ if (decision.action === "leave")
145331
+ return { outcome: "left" };
145332
+ if (decision.action === "set")
145333
+ parsed.model = decision.value;
145334
+ else
145335
+ delete parsed.model;
145336
+ const newline = text.endsWith(`
145337
+ `) ? `
145338
+ ` : "";
145339
+ return { next: `${JSON.stringify(parsed, null, detectIndent(text))}${newline}` };
145340
+ }
145341
+ function unlinkQuietly(deps, path) {
145342
+ try {
145343
+ deps.unlink(path);
145344
+ } catch {}
145345
+ }
145346
+ function restoreRound(settingsKey, target, entry, deps, fence) {
145347
+ let bytesA;
145348
+ let statA;
145349
+ try {
145350
+ bytesA = deps.readFile(target);
145351
+ statA = deps.stat(target);
145352
+ } catch (err) {
145353
+ return errnoOf(err) === "ENOENT" ? "absent" : "not-writable";
145354
+ }
145355
+ const text = bytesA.toString("utf8");
145356
+ const planned = nextSettingsText(text, entry);
145357
+ if ("outcome" in planned)
145358
+ return planned.outcome;
145359
+ const temp = join78(dirname31(target), `${TEMP_PREFIX}${deps.pid ?? process.pid}-${randomUUID12()}`);
145360
+ try {
145361
+ deps.writeNew(temp, planned.next, statA.mode & 4095);
145362
+ } catch {
145363
+ unlinkQuietly(deps, temp);
145364
+ return "not-writable";
145365
+ }
145366
+ deps.beforeRename?.();
145367
+ let unchanged = false;
145368
+ try {
145369
+ unchanged = deps.realpath(settingsKey) === target && sameStat(deps.stat(target), statA) && deps.readFile(target).equals(bytesA);
145370
+ } catch {
145371
+ unchanged = false;
145372
+ }
145373
+ if (!unchanged) {
145374
+ unlinkQuietly(deps, temp);
145375
+ return "retry";
145376
+ }
145377
+ if (!fence()) {
145378
+ unlinkQuietly(deps, temp);
145379
+ return "fenced";
145380
+ }
145381
+ try {
145382
+ deps.rename(temp, target);
145383
+ } catch {
145384
+ unlinkQuietly(deps, temp);
145385
+ return "not-writable";
145386
+ }
145387
+ return "restored";
145388
+ }
145389
+ function readLedger2(path) {
145390
+ let text;
145391
+ try {
145392
+ text = readFileSync59(path, "utf8");
145393
+ } catch (err) {
145394
+ if (errnoOf(err) === "ENOENT")
145395
+ return { ok: true, ledger: { version: 1, entries: {} } };
145396
+ log(`[model-restore] ledger unreadable (${path}): ${errnoOf(err) ?? String(err)}`);
145397
+ return { ok: false, reason: "unreadable" };
145398
+ }
145399
+ let parsed;
145400
+ try {
145401
+ parsed = JSON.parse(text);
145402
+ } catch (err) {
145403
+ log(`[model-restore] ledger unparsable (${path}): ${err.message}`);
145404
+ return { ok: false, reason: "unparsable" };
145405
+ }
145406
+ if (parsed?.version !== 1 || !isPlainObject8(parsed.entries)) {
145407
+ log(`[model-restore] ledger of unknown shape (${path})`);
145408
+ return { ok: false, reason: "unknown-shape" };
145409
+ }
145410
+ return { ok: true, ledger: parsed };
145411
+ }
145412
+ function reportUnreadableLedger(ctx, reason) {
145413
+ if (reportedUnreadableLedgers.has(ctx.ledgerPath))
145414
+ return;
145415
+ reportedUnreadableLedgers.add(ctx.ledgerPath);
145416
+ const why = reason === "unreadable" ? "cannot be read" : reason === "unparsable" ? "is not valid JSON" : "has a version or shape this claudish does not read";
145417
+ ctx.report(`${ctx.ledgerPath} ${why}, so claudish cannot put back your Claude Code default model; delete that file`);
145418
+ }
145419
+ function writeLedger(path, ledger, fence) {
145420
+ if (!fence()) {
145421
+ log(`[model-restore] ledger lock taken by another claudish; ${path} not written`);
145422
+ return false;
145423
+ }
145424
+ if (Object.keys(ledger.entries).length === 0) {
145425
+ rmSync22(path, { force: true });
145426
+ return true;
145427
+ }
145428
+ atomicWriteFileSync(path, `${JSON.stringify(ledger, null, 2)}
145429
+ `, {
145430
+ mode: 384,
145431
+ dirMode: 448
145432
+ });
145433
+ return true;
145434
+ }
145435
+ function fenceOf(handle) {
145436
+ return () => handle?.holdsLock() ?? false;
145437
+ }
145438
+ function lockPathOf(ledgerPath) {
145439
+ return `${ledgerPath}.lock`;
145440
+ }
145441
+ function markLive(mark, table) {
145442
+ if (table === null || mark.startedEpochMs === null)
145443
+ return pidMayBeAlive(mark.pid);
145444
+ const row = table.find((r) => r.pid === mark.pid);
145445
+ return row !== undefined && startedAt(row, mark.startedEpochMs);
145446
+ }
145447
+ function settingsWriterLive(session, table) {
145448
+ if (session.settingsArg) {
145449
+ const needle = `--settings ${session.settingsArg}`;
145450
+ return table.some((r) => r.command.includes(needle));
145451
+ }
145452
+ const nameNeedle = `/.claudish/settings-${session.launcher.pid}-`;
145453
+ const since = session.launcher.startedEpochMs;
145454
+ return table.some((r) => r.command.includes("--settings ") && r.command.includes(nameNeedle) && (since === null || r.startMs === undefined || r.startMs >= since - 2000));
145455
+ }
145456
+ function sessionLiveness(session, table) {
145457
+ if (markLive(session.launcher, table))
145458
+ return "live";
145459
+ if (session.child !== "pending")
145460
+ return markLive(session.child, table) ? "live" : "ended";
145461
+ if (table === null)
145462
+ return "unknown";
145463
+ return settingsWriterLive(session, table) ? "live" : "ended";
145464
+ }
145465
+ function contextOf(deps) {
145466
+ const fs = deps.fs ?? realRestoreFs;
145467
+ const withHooks = {
145468
+ ...fs,
145469
+ ...deps.beforeRename ? { beforeRename: deps.beforeRename } : {},
145470
+ ...deps.pid !== undefined ? { pid: deps.pid } : {}
145471
+ };
145472
+ return {
145473
+ ledgerPath: deps.ledgerPath ?? modelSettingLedgerPath(deps.env ?? process.env),
145474
+ fs: withHooks,
145475
+ now: deps.now ?? Date.now,
145476
+ report: deps.report ?? logStderr,
145477
+ processTable: deps.processTable ?? readProcessTable
145478
+ };
145479
+ }
145480
+ function statOrNull3(ctx, key) {
145481
+ try {
145482
+ return ctx.fs.stat(ctx.fs.realpath(key));
145483
+ } catch {
145484
+ return null;
145485
+ }
145486
+ }
145487
+ function settleEntry(ctx, ledger, key, silent, fence) {
145488
+ const entry = ledger.entries[key];
145489
+ if (!entry)
145490
+ return;
145491
+ const outcome = restoreSettingsFile(key, entry, ctx.fs, fence);
145492
+ log(`[model-restore] ${key}: ${outcome}`);
145493
+ switch (outcome) {
145494
+ case "fenced":
145495
+ return;
145496
+ case "restored":
145497
+ ctx.report(`Put back your Claude Code default model in ${key}`);
145498
+ delete ledger.entries[key];
145499
+ return;
145500
+ case "left":
145501
+ case "absent":
145502
+ delete ledger.entries[key];
145503
+ return;
145504
+ case "changed-under-us":
145505
+ entry.sessions = [];
145506
+ if (!silent) {
145507
+ ctx.report(`${key} kept changing while claudish put back your default model; it will try again at the next launch`);
145508
+ }
145509
+ return;
145510
+ case "unparsable":
145511
+ case "not-writable": {
145512
+ entry.sessions = [];
145513
+ if (!entry.failure) {
145514
+ entry.failure = {
145515
+ outcome,
145516
+ firstAt: ctx.now(),
145517
+ stat: statOrNull3(ctx, key),
145518
+ reported: true
145519
+ };
145520
+ const why = outcome === "unparsable" ? "is not valid JSON" : "cannot be written";
145521
+ ctx.report(`${key} ${why}, so claudish did not put back your default model; set or remove "model" in ${key} by hand`);
145522
+ } else {
145523
+ entry.failure.stat = statOrNull3(ctx, key);
145524
+ }
145525
+ return;
145526
+ }
145527
+ }
145528
+ }
145529
+ function removeOrphanTemps(ctx, key, table) {
145530
+ const dirs = new Set([dirname31(key)]);
145531
+ try {
145532
+ dirs.add(dirname31(ctx.fs.realpath(key)));
145533
+ } catch {}
145534
+ for (const dir of dirs) {
145535
+ let names;
145536
+ try {
145537
+ names = readdirSync20(dir);
145538
+ } catch {
145539
+ continue;
145540
+ }
145541
+ for (const name of names) {
145542
+ if (!name.startsWith(TEMP_PREFIX))
145543
+ continue;
145544
+ const pid = Number(name.slice(TEMP_PREFIX.length).split("-")[0]);
145545
+ if (!Number.isInteger(pid) || pid <= 0)
145546
+ continue;
145547
+ const live = table === null ? pidMayBeAlive(pid) : table.some((r) => r.pid === pid);
145548
+ if (live)
145549
+ continue;
145550
+ try {
145551
+ unlinkSync16(join78(dir, name));
145552
+ } catch {}
145553
+ }
145554
+ }
145555
+ }
145556
+ function sweepLedger(ctx, ledger, fence) {
145557
+ const table = ctx.processTable();
145558
+ const now = ctx.now();
145559
+ for (const key of Object.keys(ledger.entries)) {
145560
+ const entry = ledger.entries[key];
145561
+ if (!entry)
145562
+ continue;
145563
+ removeOrphanTemps(ctx, key, table);
145564
+ const kept = [];
145565
+ let unknownOnly = true;
145566
+ for (const session of entry.sessions) {
145567
+ const liveness = sessionLiveness(session, table);
145568
+ if (liveness === "ended")
145569
+ continue;
145570
+ kept.push(session);
145571
+ if (liveness === "live" || now - session.startedAt <= GIVE_UP_AFTER_MS)
145572
+ unknownOnly = false;
145573
+ }
145574
+ entry.sessions = kept;
145575
+ if (kept.length > 0) {
145576
+ if (!unknownOnly)
145577
+ continue;
145578
+ ctx.report(`Gave up putting back your Claude Code default model in ${key}: no process table for 14 days`);
145579
+ delete ledger.entries[key];
145580
+ continue;
145581
+ }
145582
+ if (entry.failure) {
145583
+ if (now - entry.failure.firstAt > GIVE_UP_AFTER_MS) {
145584
+ ctx.report(`Gave up putting back your Claude Code default model in ${key}; set or remove "model" there by hand`);
145585
+ delete ledger.entries[key];
145586
+ continue;
145587
+ }
145588
+ const stat = statOrNull3(ctx, key);
145589
+ const unchanged = stat !== null && entry.failure.stat !== null && sameStat(stat, entry.failure.stat);
145590
+ if (unchanged)
145591
+ continue;
145592
+ settleEntry(ctx, ledger, key, true, fence);
145593
+ continue;
145594
+ }
145595
+ settleEntry(ctx, ledger, key, false, fence);
145596
+ }
145597
+ }
145598
+ async function sweepModelSettingLedger(deps = {}) {
145599
+ const ctx = contextOf(deps);
145600
+ try {
145601
+ await withFileLock(lockPathOf(ctx.ledgerPath), {
145602
+ timeoutMs: LOCK_TIMEOUT_MS,
145603
+ staleMs: LOCK_STALE_MS,
145604
+ heartbeatMs: LOCK_HEARTBEAT_MS,
145605
+ onUnavailable: "fail"
145606
+ }, async (handle) => {
145607
+ const read = readLedger2(ctx.ledgerPath);
145608
+ if (!read.ok) {
145609
+ reportUnreadableLedger(ctx, read.reason);
145610
+ return;
145611
+ }
145612
+ const fence = fenceOf(handle);
145613
+ sweepLedger(ctx, read.ledger, fence);
145614
+ writeLedger(ctx.ledgerPath, read.ledger, fence);
145615
+ });
145616
+ } catch (err) {
145617
+ log(`[model-restore] sweep skipped: ${err instanceof Error ? err.message : String(err)}`);
145618
+ }
145619
+ }
145620
+ function readOriginal(ctx, key) {
145621
+ let text;
145622
+ try {
145623
+ text = ctx.fs.readFile(ctx.fs.realpath(key)).toString("utf8");
145624
+ } catch (err) {
145625
+ return errnoOf(err) === "ENOENT" ? { present: false } : null;
145626
+ }
145627
+ try {
145628
+ const parsed = JSON.parse(text);
145629
+ if (!isPlainObject8(parsed))
145630
+ return null;
145631
+ return "model" in parsed ? { present: true, value: parsed.model } : { present: false };
145632
+ } catch {
145633
+ return null;
145634
+ }
145635
+ }
145636
+ function selfStartEpochMs() {
145637
+ return Math.round(Date.now() - process.uptime() * 1000);
145638
+ }
145639
+ async function beginModelSettingWatch(listedSpecs, deps = {}) {
145640
+ const ctx = contextOf(deps);
145641
+ const env = deps.env ?? process.env;
145642
+ const settingsFile = deps.settingsFile ?? userSettingsFile(env.CLAUDE_CONFIG_DIR, env.HOME && env.HOME.length > 0 ? env.HOME : homedir49(), deps.cwd ?? process.cwd());
145643
+ const key = canonicalSettingsPath(settingsFile);
145644
+ const lockPath = lockPathOf(ctx.ledgerPath);
145645
+ const lockOpts = {
145646
+ timeoutMs: LOCK_TIMEOUT_MS,
145647
+ staleMs: LOCK_STALE_MS,
145648
+ heartbeatMs: LOCK_HEARTBEAT_MS,
145649
+ onUnavailable: "fail"
145650
+ };
145651
+ const sessionId = randomUUID12();
145652
+ const launcherPid = deps.pid ?? process.pid;
145653
+ const noRestore = "so claudish will not put back your Claude Code default model after this session";
145654
+ let registered = false;
145655
+ try {
145656
+ registered = await withFileLock(lockPath, lockOpts, async (handle) => {
145657
+ const read = readLedger2(ctx.ledgerPath);
145658
+ if (!read.ok) {
145659
+ reportUnreadableLedger(ctx, read.reason);
145660
+ return false;
145661
+ }
145662
+ const unreadableAtLaunch = () => {
145663
+ log(`[model-restore] ${key} unreadable at launch; no restore for this session`);
145664
+ ctx.report(`${key} cannot be read or is not a JSON object, ${noRestore}`);
145665
+ return false;
145666
+ };
145667
+ let entry = read.ledger.entries[key];
145668
+ if (!entry) {
145669
+ const original = readOriginal(ctx, key);
145670
+ if (original === null)
145671
+ return unreadableAtLaunch();
145672
+ entry = { original, listed: [], sessions: [] };
145673
+ read.ledger.entries[key] = entry;
145674
+ } else if (entry.failure) {
145675
+ if (readOriginal(ctx, key) === null)
145676
+ return unreadableAtLaunch();
145677
+ delete entry.failure;
145678
+ }
145679
+ for (const spec of listedSpecs)
145680
+ if (!entry.listed.includes(spec))
145681
+ entry.listed.push(spec);
145682
+ entry.sessions.push({
145683
+ id: sessionId,
145684
+ launcher: { pid: launcherPid, startedEpochMs: selfStartEpochMs() },
145685
+ child: "pending",
145686
+ settingsArg: null,
145687
+ startedAt: ctx.now()
145688
+ });
145689
+ if (!writeLedger(ctx.ledgerPath, read.ledger, fenceOf(handle))) {
145690
+ ctx.report(`${lockPath} was taken by another claudish, ${noRestore}`);
145691
+ return false;
145692
+ }
145693
+ return true;
145694
+ });
145695
+ } catch (err) {
145696
+ log(`[model-restore] watch not begun: ${err instanceof Error ? err.message : String(err)}`);
145697
+ ctx.report(err instanceof FileLockUnavailableError && err.reason !== "unwritable" ? `${lockPath} is held by another claudish, ${noRestore}` : `${ctx.ledgerPath} cannot be written, ${noRestore}`);
145698
+ }
145699
+ if (!registered)
145700
+ return INERT_WATCH;
145701
+ let childMark = null;
145702
+ let ended = false;
145703
+ const updateRow = (fence, update) => {
145704
+ const read = readLedger2(ctx.ledgerPath);
145705
+ if (!read.ok)
145706
+ return;
145707
+ const session = read.ledger.entries[key]?.sessions.find((s) => s.id === sessionId);
145708
+ if (!session)
145709
+ return;
145710
+ update(session);
145711
+ writeLedger(ctx.ledgerPath, read.ledger, fence);
145712
+ };
145713
+ const exitTransaction = (fence) => {
145714
+ const read = readLedger2(ctx.ledgerPath);
145715
+ if (!read.ok)
145716
+ return;
145717
+ const entry = read.ledger.entries[key];
145718
+ if (!entry)
145719
+ return;
145720
+ const index = entry.sessions.findIndex((s) => s.id === sessionId);
145721
+ if (index < 0)
145722
+ return;
145723
+ const table = ctx.processTable();
145724
+ if (childMark && markLive(childMark, table))
145725
+ return;
145726
+ entry.sessions.splice(index, 1);
145727
+ const othersLive = entry.sessions.some((s) => sessionLiveness(s, table) !== "ended");
145728
+ if (!othersLive) {
145729
+ entry.sessions = [];
145730
+ settleEntry(ctx, read.ledger, key, false, fence);
145731
+ }
145732
+ writeLedger(ctx.ledgerPath, read.ledger, fence);
145733
+ };
145734
+ return {
145735
+ registered: true,
145736
+ recordSettingsArg: async (settingsPath) => {
145737
+ try {
145738
+ await withFileLock(lockPath, lockOpts, async (handle) => updateRow(fenceOf(handle), (s) => {
145739
+ s.settingsArg = settingsPath;
145740
+ }));
145741
+ } catch (err) {
145742
+ log(`[model-restore] settings path not recorded: ${err?.message ?? err}`);
145743
+ }
145744
+ },
145745
+ recordChild: (pid) => {
145746
+ const mark = { pid, startedEpochMs: Date.now() };
145747
+ childMark = mark;
145748
+ const apply = (handle) => updateRow(fenceOf(handle), (s) => {
145749
+ s.child = mark;
145750
+ });
145751
+ try {
145752
+ const handle = acquireFileLockSync(lockPath, {
145753
+ staleMs: LOCK_STALE_MS,
145754
+ waitMs: SYNC_LOCK_WAIT_MS
145755
+ });
145756
+ try {
145757
+ apply(handle);
145758
+ } finally {
145759
+ handle.release();
145760
+ }
145761
+ } catch {
145762
+ withFileLock(lockPath, lockOpts, async (handle) => apply(handle)).catch((err) => log(`[model-restore] child not recorded: ${err?.message ?? err}`));
145763
+ }
145764
+ },
145765
+ end: async () => {
145766
+ if (ended)
145767
+ return;
145768
+ ended = true;
145769
+ try {
145770
+ await withFileLock(lockPath, lockOpts, async (handle) => exitTransaction(fenceOf(handle)));
145771
+ } catch (err) {
145772
+ log(`[model-restore] exit skipped: ${err?.message ?? err}`);
145773
+ }
145774
+ },
145775
+ endSync: () => {
145776
+ if (ended)
145777
+ return;
145778
+ ended = true;
145779
+ try {
145780
+ const handle = acquireFileLockSync(lockPath, {
145781
+ staleMs: LOCK_STALE_MS,
145782
+ waitMs: SYNC_LOCK_WAIT_MS
145783
+ });
145784
+ try {
145785
+ exitTransaction(fenceOf(handle));
145786
+ } finally {
145787
+ handle.release();
145788
+ }
145789
+ } catch (err) {
145790
+ log(`[model-restore] deadline exit skipped: ${err?.message ?? err}`);
145791
+ }
145792
+ }
145793
+ };
145794
+ }
145795
+ var LOCK_TIMEOUT_MS = 2000, LOCK_HEARTBEAT_MS = 2000, SYNC_LOCK_WAIT_MS = 250, LOCK_STALE_MS = 1e4, RESTORE_ROUNDS = 3, GIVE_UP_AFTER_MS, TEMP_PREFIX = ".settings.json.claudish-", realRestoreFs, reportedUnreadableLedgers, INERT_WATCH;
145796
+ var init_model_setting_restore = __esm(() => {
145797
+ init_atomic_write();
145798
+ init_file_lock();
145799
+ init_claude_runner();
145800
+ init_logger();
145801
+ init_process_identity();
145802
+ init_model_setting_ledger_path();
145803
+ GIVE_UP_AFTER_MS = 14 * 24 * 60 * 60 * 1000;
145804
+ realRestoreFs = {
145805
+ realpath: (path) => realpathSync12.native(path),
145806
+ readFile: (path) => readFileSync59(path),
145807
+ stat: (path) => toFileStat(statSync32(path)),
145808
+ writeNew: (path, data, mode) => {
145809
+ const fd = openSync21(path, "wx", mode);
145810
+ try {
145811
+ fchmodSync2(fd, mode);
145812
+ writeWholeSync(fd, data);
145813
+ fsyncSync4(fd);
145814
+ } finally {
145815
+ closeSync22(fd);
145816
+ }
145817
+ },
145818
+ rename: (from, to) => renameSync15(from, to),
145819
+ unlink: (path) => unlinkSync16(path)
145820
+ };
145821
+ reportedUnreadableLedgers = new Set;
145822
+ INERT_WATCH = {
145823
+ registered: false,
145824
+ recordSettingsArg: async () => {},
145825
+ recordChild: () => {},
145826
+ end: async () => {},
145827
+ endSync: () => {}
145828
+ };
145829
+ });
145830
+
143670
145831
  // src/session/baseline-pricing.ts
143671
145832
  function resolveBaseline(alias, label) {
143672
145833
  const entry = findEntryByAlias(alias);
@@ -143702,11 +145863,11 @@ var exports_session_stats = {};
143702
145863
  __export(exports_session_stats, {
143703
145864
  readSessionStats: () => readSessionStats
143704
145865
  });
143705
- import { readFileSync as readFileSync59 } from "fs";
145866
+ import { readFileSync as readFileSync60 } from "fs";
143706
145867
  function readSessionStats(port, opts) {
143707
145868
  let raw;
143708
145869
  try {
143709
- raw = JSON.parse(readFileSync59(resolveTokenFilePath(port), "utf-8"));
145870
+ raw = JSON.parse(readFileSync60(resolveTokenFilePath(port), "utf-8"));
143710
145871
  } catch {
143711
145872
  return null;
143712
145873
  }
@@ -144093,12 +146254,12 @@ init_launch_env();
144093
146254
  init_op_source();
144094
146255
  init_startup_trace();
144095
146256
  init_picker_cancelled();
144096
- import { existsSync as existsSync50, readFileSync as readFileSync60 } from "fs";
144097
- import { join as join77, resolve as resolve15 } from "path";
146257
+ import { existsSync as existsSync50, readFileSync as readFileSync61 } from "fs";
146258
+ import { join as join79, resolve as resolve16 } from "path";
144098
146259
 
144099
146260
  // src/tui/runtime/should-open-picker.ts
144100
146261
  function noModelConfigured(gate) {
144101
- return !gate.monitor && !gate.advisorNativeSession && !gate.model && !gate.hasProfileTiers;
146262
+ return !gate.monitor && !gate.advisorNativeSession && !gate.hasModelListings && !gate.model && !gate.hasProfileTiers;
144102
146263
  }
144103
146264
  function shouldOpenPicker(gate, tty) {
144104
146265
  return noModelConfigured(gate) && Boolean(gate.interactive) && tty;
@@ -144111,7 +146272,7 @@ function requiresExplicitModel(gate, tty) {
144111
146272
  var autoloadDropped = [...droppedAtLaunch, ...takeLauncherDropped(process.env)];
144112
146273
  var dotenvText;
144113
146274
  try {
144114
- dotenvText = readFileSync60(join77(process.cwd(), ".env"));
146275
+ dotenvText = readFileSync61(join79(process.cwd(), ".env"));
144115
146276
  } catch {}
144116
146277
  if (dotenvText !== undefined) {
144117
146278
  await Promise.resolve().then(() => init_dotenv_allowlist());
@@ -144228,7 +146389,7 @@ async function applyOpImport() {
144228
146389
  async function applyConfigOverride() {
144229
146390
  await Promise.resolve();
144230
146391
  const plan = planConfigOverride(process.argv.slice(2), process.env, {
144231
- resolve: resolve15,
146392
+ resolve: resolve16,
144232
146393
  exists: existsSync50
144233
146394
  });
144234
146395
  if (plan.kind === "none")
@@ -144423,6 +146584,35 @@ if (isMcpMode) {
144423
146584
  } else {
144424
146585
  runCli();
144425
146586
  }
146587
+ async function reportModelLineup(config, lineup) {
146588
+ await Promise.resolve().then(() => init_model_lineup());
146589
+ await Promise.resolve().then(() => init_claude_runner());
146590
+ await Promise.resolve().then(() => init_native_route());
146591
+ await Promise.resolve().then(() => init_redact());
146592
+ await Promise.resolve().then(() => init_logger());
146593
+ const computed = await computeMainThreadContextWindow(config);
146594
+ config.mainThreadWindow = computed;
146595
+ const picker = modelPickerSetting(lineup.rows, modelPickerSources(config, process.env));
146596
+ const inherited = scrubChildModelVars(config, { ...process.env });
146597
+ const posture = startsOnClaudeSubscription(config) ? "claude-start" : typeof config.model === "string" ? nativeRouteFor(config.model) !== null ? "claude-model-start" : "foreign-start" : isProxyAuthMode(config) ? "tiers" : "claude-model-start";
146598
+ const lines = lineupReport(lineup, {
146599
+ sizedFor: sessionWindow(process.env, computed),
146600
+ settingsNotices: picker.notices,
146601
+ posture,
146602
+ inheritedModelVars: inherited.survived
146603
+ });
146604
+ if (inherited.removed.length > 0) {
146605
+ lines.push(`[claudish] /model: removed ${inherited.removed.join(", ")}, set by a parent claudish session, from this session`);
146606
+ }
146607
+ for (const line of lines)
146608
+ logStderr(redactSecrets(line.replace(/^\[claudish\] /, "")));
146609
+ const userRows = routedUserRows(picker.setting.options, lineup.rows);
146610
+ config.modelLineup = {
146611
+ rows: lineup.rows,
146612
+ picker: picker.setting,
146613
+ ...userRows.length > 0 ? { userRows } : {}
146614
+ };
146615
+ }
144426
146616
  async function runCli() {
144427
146617
  const endImports = beginSpan("startup:cli-imports");
144428
146618
  await Promise.resolve().then(() => init_claude_runner());
@@ -144470,17 +146660,25 @@ async function runCli() {
144470
146660
  await Promise.resolve().then(() => init_endpoint_registration());
144471
146661
  ensureEndpointsRegistered();
144472
146662
  });
146663
+ if (cliConfig._modelFlags?.hasLineup) {
146664
+ await Promise.resolve().then(() => init_claude_launch());
146665
+ const decision = decideModelListings(cliConfig, cliConfig._modelFlags);
146666
+ if (!decision.ok) {
146667
+ console.error(`[claudish] Error: ${decision.message}`);
146668
+ process.exit(1);
146669
+ }
146670
+ }
144473
146671
  if (cliConfig.team && cliConfig.team.length > 0) {
144474
146672
  let prompt = cliConfig.claudeArgs.join(" ");
144475
146673
  if (cliConfig.inputFile) {
144476
- prompt = readFileSync60(cliConfig.inputFile, "utf-8");
146674
+ prompt = readFileSync61(cliConfig.inputFile, "utf-8");
144477
146675
  }
144478
146676
  if (!prompt.trim()) {
144479
146677
  console.error("Error: --team requires a prompt (positional args or -f <file>)");
144480
146678
  process.exit(1);
144481
146679
  }
144482
146680
  const mode = cliConfig.teamMode ?? "default";
144483
- const sessionPath = join77(process.cwd(), `.claudish-team-${Date.now()}`);
146681
+ const sessionPath = join79(process.cwd(), `.claudish-team-${Date.now()}`);
144484
146682
  if (mode === "json") {
144485
146683
  await Promise.resolve().then(() => init_pane());
144486
146684
  await Promise.resolve().then(() => init_team_orchestrator());
@@ -144500,9 +146698,9 @@ async function runCli() {
144500
146698
  const status = await runModels(sessionPath);
144501
146699
  const result = { ...status, responses: {} };
144502
146700
  for (const anonId of Object.keys(status.models)) {
144503
- const responsePath = join77(sessionPath, `response-${anonId}.md`);
146701
+ const responsePath = join79(sessionPath, `response-${anonId}.md`);
144504
146702
  try {
144505
- const raw = readFileSync60(responsePath, "utf-8").trim();
146703
+ const raw = readFileSync61(responsePath, "utf-8").trim();
144506
146704
  try {
144507
146705
  result.responses[anonId] = JSON.parse(raw);
144508
146706
  } catch {
@@ -144619,6 +146817,7 @@ Team Status`);
144619
146817
  interactive: cliConfig.interactive,
144620
146818
  monitor: cliConfig.monitor,
144621
146819
  advisorNativeSession,
146820
+ hasModelListings: (cliConfig.modelListings?.length ?? 0) > 0,
144622
146821
  model: cliConfig.model,
144623
146822
  hasProfileTiers
144624
146823
  });
@@ -144740,6 +146939,20 @@ Team Status`);
144740
146939
  `);
144741
146940
  }
144742
146941
  const launchSigning = preparedLaunch.signing;
146942
+ const lineupListings = cliConfig.modelListings ?? [];
146943
+ let lineupPromise = null;
146944
+ if (lineupListings.length > 0 && cliConfig.interactive) {
146945
+ lineupPromise = Promise.resolve().then(() => (init_model_lineup(), {})).then((m) => traceSpan("startup:model-lineup", () => buildModelLineup(lineupListings))).catch((err) => ({
146946
+ rows: [],
146947
+ outcomes: lineupListings.map((l) => ({
146948
+ kind: "not-listed",
146949
+ provider: l.provider,
146950
+ reason: err instanceof Error ? err.message : String(err)
146951
+ }))
146952
+ }));
146953
+ } else if (lineupListings.length > 0) {
146954
+ log("[model-lineup] print mode: listing entries accepted, no /model list is fetched");
146955
+ }
144743
146956
  let advisorRuntime;
144744
146957
  if (cliConfig.advisor) {
144745
146958
  await Promise.resolve().then(() => init_advisor_startup());
@@ -144809,9 +147022,23 @@ Team Status`);
144809
147022
  if (cliConfig.contextWindow !== undefined) {
144810
147023
  process.env.CLAUDISH_CONTEXT_WINDOW = String(cliConfig.contextWindow);
144811
147024
  }
147025
+ if (lineupPromise) {
147026
+ const lineup = await lineupPromise;
147027
+ await reportModelLineup(cliConfig, lineup);
147028
+ }
144812
147029
  const proxy = await traceSpan("startup:proxy-start", () => createProxyServer(port, cliConfig.monitor ? undefined : cliConfig.openrouterApiKey, cliConfig.monitor ? undefined : explicitModel, cliConfig.monitor, launchSigning ? undefined : cliConfig.anthropicApiKey, modelMap, {
144813
147030
  ...launchSigning ? { nativeSigning: launchSigning } : {},
144814
147031
  ...cliConfig.claudeLaunch === "api" && cliConfig.claudeLaunchModel ? { claudeApiMainModel: cliConfig.claudeLaunchModel } : {},
147032
+ ...cliConfig.modelLineup ? {
147033
+ modelLineup: [
147034
+ ...cliConfig.modelLineup.rows,
147035
+ ...cliConfig.modelLineup.userRows ?? []
147036
+ ].map((row) => ({
147037
+ model: row.model,
147038
+ label: row.label
147039
+ }))
147040
+ } : {},
147041
+ ...claudeRowsAsPicked(cliConfig) ? { claudeRowsAsPicked: true } : {},
144815
147042
  apiBillingOptIn: wantsAnthropicApiBilling(cliConfig),
144816
147043
  advisorKeyLookup: advisorKeyLookupAllowed(cliConfig),
144817
147044
  summarizeTools: cliConfig.summarizeTools,
@@ -144829,6 +147056,30 @@ Team Status`);
144829
147056
  codeMode: cliConfig.codeMode,
144830
147057
  hostMode: isPaneChild() ? "pane-child" : cliConfig.interactive ? "interactive" : "other"
144831
147058
  }));
147059
+ let modelSettingWatch = null;
147060
+ if (cliConfig.interactive) {
147061
+ await Promise.resolve().then(() => init_model_setting_ledger_path());
147062
+ const { statSync } = await import("fs");
147063
+ let ledgerPending = false;
147064
+ try {
147065
+ ledgerPending = statSync(modelSettingLedgerPath(process.env), { throwIfNoEntry: false }) !== undefined;
147066
+ } catch {
147067
+ ledgerPending = false;
147068
+ }
147069
+ if (ledgerPending || cliConfig.modelLineup) {
147070
+ const restore = await Promise.resolve().then(() => (init_model_setting_restore(), {}));
147071
+ if (ledgerPending)
147072
+ await sweepModelSettingLedger();
147073
+ if (cliConfig.modelLineup) {
147074
+ modelSettingWatch = await beginModelSettingWatch(cliConfig.modelLineup.rows.map((row) => row.model));
147075
+ if (modelSettingWatch.registered && cliConfig.modelLineup.rows.length > 0) {
147076
+ await Promise.resolve().then(() => init_model_lineup());
147077
+ await Promise.resolve().then(() => init_logger());
147078
+ logStderr(MODEL_RESTORE_PROMISE);
147079
+ }
147080
+ }
147081
+ }
147082
+ }
144832
147083
  const diag = createDiagOutput({
144833
147084
  interactive: cliConfig.interactive,
144834
147085
  diagMode: cliConfig.diagMode
@@ -144846,7 +147097,11 @@ Team Status`);
144846
147097
  diag.cleanup();
144847
147098
  };
144848
147099
  try {
144849
- exitCode = await runClaudeWithProxy(cliConfig, proxy.url, cleanupDiag);
147100
+ exitCode = await runClaudeWithProxy(cliConfig, proxy.url, cleanupDiag, modelSettingWatch ? {
147101
+ beforeSpawn: modelSettingWatch.recordSettingsArg,
147102
+ onChildSpawned: modelSettingWatch.recordChild,
147103
+ onDeadline: modelSettingWatch.endSync
147104
+ } : {});
144850
147105
  } finally {
144851
147106
  setDiagOutput(null);
144852
147107
  cleanupDiag();
@@ -144856,6 +147111,7 @@ Team Status`);
144856
147111
  [claudish] Shutting down proxy server...`);
144857
147112
  }
144858
147113
  await proxy.shutdown();
147114
+ await modelSettingWatch?.end();
144859
147115
  }
144860
147116
  if (!cliConfig.quiet) {
144861
147117
  const write = cliConfig.interactive ? console.log : console.error;