claudish 7.52.0 → 7.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1257 -471
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -729,7 +729,7 @@ var init_onepassword_config = __esm(() => {
729
729
  });
730
730
 
731
731
  // src/version.ts
732
- var VERSION = "7.52.0";
732
+ var VERSION = "7.54.0";
733
733
 
734
734
  // src/logger.ts
735
735
  var exports_logger = {};
@@ -28161,6 +28161,26 @@ var init_provider_definitions = __esm(() => {
28161
28161
  nativeModelPatterns: [{ pattern: /^x-ai\//i }, { pattern: /^grok-/i }],
28162
28162
  isDirectApi: true
28163
28163
  },
28164
+ {
28165
+ name: "grok-subscription",
28166
+ displayName: "Grok Build (subscription)",
28167
+ transport: "grok-subscription",
28168
+ tokenStrategy: "delta-aware",
28169
+ baseUrl: "https://cli-chat-proxy.grok.com",
28170
+ baseUrlEnvVars: ["GROK_PROXY_URL"],
28171
+ apiPath: "/v1/chat/completions",
28172
+ apiKeyEnvVar: "",
28173
+ apiKeyDescription: "Grok subscription OAuth (`claudish login grok`, or an existing `grok login`)",
28174
+ apiKeyUrl: "https://x.ai/cli",
28175
+ oauthLoginSlug: "grok",
28176
+ oauthFallback: "grok-oauth.json",
28177
+ shortcuts: ["gk", "grok-subscription"],
28178
+ shortestPrefix: "gk",
28179
+ legacyPrefixes: [{ prefix: "gk/", stripPrefix: true }],
28180
+ modelDiscovery: { path: "/v1/models", format: "openai-models-list" },
28181
+ isDirectApi: true,
28182
+ description: "Grok on your SuperGrok or X Premium+ plan (gk@)"
28183
+ },
28164
28184
  {
28165
28185
  name: "minimax",
28166
28186
  displayName: "MiniMax",
@@ -28934,7 +28954,8 @@ var init_remote_provider_types = __esm(() => {
28934
28954
  "qwen-cloud",
28935
28955
  "devin",
28936
28956
  "antigravity",
28937
- "sakana-subscription"
28957
+ "sakana-subscription",
28958
+ "grok-subscription"
28938
28959
  ]);
28939
28960
  PROVIDER_ALIAS = {
28940
28961
  google: "gemini",
@@ -30167,6 +30188,9 @@ function parseRecord(raw) {
30167
30188
  return null;
30168
30189
  }
30169
30190
  }
30191
+ function encodeRecord(rec) {
30192
+ return PREFIX + Buffer.from(JSON.stringify(rec), "utf8").toString("base64");
30193
+ }
30170
30194
  function readSharedAntigravityToken(deps = defaultDeps) {
30171
30195
  const rec = parseRecord(deps.readStore());
30172
30196
  return rec ? rec.token : null;
@@ -30184,6 +30208,15 @@ function hasSharedAntigravityToken(deps = defaultDeps) {
30184
30208
  cachedHasToken = { at: now, value };
30185
30209
  return value;
30186
30210
  }
30211
+ function writeSharedAntigravityToken(tok, deps = defaultDeps) {
30212
+ const existing = parseRecord(deps.readStore());
30213
+ const base = existing ?? { token: tok };
30214
+ const merged = {
30215
+ ...base,
30216
+ token: { ...base.token, ...tok }
30217
+ };
30218
+ deps.writeStore(encodeRecord(merged));
30219
+ }
30187
30220
  function deleteSharedAntigravityToken(deps = defaultDeps) {
30188
30221
  (deps.deleteStore ?? defaultDeleteStore)();
30189
30222
  _resetAntigravityTokenState();
@@ -30222,6 +30255,31 @@ function getValidAntigravityAccessToken(deps = defaultDeps) {
30222
30255
  });
30223
30256
  return inFlight;
30224
30257
  }
30258
+ async function forceRefreshAntigravityToken(deps = defaultDeps) {
30259
+ if (process.platform !== "darwin") {
30260
+ throw new Error("[Antigravity] The shared Antigravity token store is macOS-only for now. " + "Use g@<model> with GEMINI_API_KEY on this platform.");
30261
+ }
30262
+ _resetAntigravityTokenState();
30263
+ const rec = parseRecord(deps.readStore());
30264
+ if (!rec) {
30265
+ throw new Error("[Antigravity] No Antigravity session found. Sign in with `claudish login antigravity`, " + "or use g@<model> with GEMINI_API_KEY " + "(get one at https://aistudio.google.com/app/apikey).");
30266
+ }
30267
+ const original = rec.token;
30268
+ log("[Antigravity] Upstream rejected the current token \u2014 asking the Antigravity CLI to re-mint.");
30269
+ writeSharedAntigravityToken({ ...original, expiry: new Date(deps.now() - 1000).toISOString() }, deps);
30270
+ deps.runAgyRefresh();
30271
+ const refreshed = parseRecord(deps.readStore());
30272
+ const token = refreshed?.token;
30273
+ if (token && token.access_token !== original.access_token && !needsRefresh(token, deps.now())) {
30274
+ log("[Antigravity] Shared token re-minted by the Antigravity CLI.");
30275
+ return token.access_token;
30276
+ }
30277
+ if (!refreshed || refreshed.token.access_token === original.access_token) {
30278
+ writeSharedAntigravityToken(original, deps);
30279
+ }
30280
+ _resetAntigravityTokenState();
30281
+ throw new Error("[Antigravity] The Antigravity session was rejected upstream and could not be re-minted. " + "Run `claudish login antigravity` to sign in again.");
30282
+ }
30225
30283
  function _resetAntigravityTokenState() {
30226
30284
  inFlight = null;
30227
30285
  cachedHasToken = null;
@@ -30248,6 +30306,13 @@ function makeTerminalSetupError(message) {
30248
30306
  function buildAntigravityUserAgent() {
30249
30307
  return `antigravity/cli/1.1.9 (aidev_client; os_type=${process.platform}; arch=${process.arch}; auth_method=consumer)`;
30250
30308
  }
30309
+ function resetAntigravityUserCache() {
30310
+ cachedAgProjectId = null;
30311
+ cachedAgTierId = null;
30312
+ cachedAgTierName = null;
30313
+ agServedCache = null;
30314
+ agServedCacheAt = 0;
30315
+ }
30251
30316
  async function callLoadCodeAssistAntigravity(accessToken) {
30252
30317
  const res = await fetch(`${ANTIGRAVITY_API_BASE}:loadCodeAssist`, {
30253
30318
  method: "POST",
@@ -30632,6 +30697,22 @@ class AntigravityProviderTransport {
30632
30697
  this.servedModelName = resolveAntigravityModelId(this.modelName, this.servedModels, this.defaultServedModel, lookupFamilyDefaultVariant(this.modelName, "antigravity"));
30633
30698
  log(`[Antigravity] Auth refreshed, project: ${this.projectId}, tier: ${this._displayName}, ` + `model: ${this.modelName} -> ${this.servedModelName}, served: ${this.servedModels.join(",") || "(none)"}`);
30634
30699
  }
30700
+ async forceRefreshAuth() {
30701
+ await forceRefreshAntigravityToken();
30702
+ resetAntigravityUserCache();
30703
+ this.cachedAuth = null;
30704
+ await this.refreshAuth();
30705
+ }
30706
+ classifyTerminalError(status, bodyText) {
30707
+ if (status !== 429)
30708
+ return;
30709
+ const classification = classify429(bodyText);
30710
+ if (!classification)
30711
+ return;
30712
+ if (classification.reason === "MODEL_CAPACITY_EXHAUSTED")
30713
+ return false;
30714
+ return classification.terminal;
30715
+ }
30635
30716
  transformPayload(payload) {
30636
30717
  const envelope = this.cachedAuth?.transformPayload ? this.cachedAuth.transformPayload(payload) : this.buildEnvelope(payload, this.servedModelName);
30637
30718
  this.lastEnvelope = envelope;
@@ -30672,8 +30753,7 @@ class AntigravityProviderTransport {
30672
30753
  return this.handleCapacityExhausted(response, queue);
30673
30754
  }
30674
30755
  if (classification.terminal) {
30675
- logStderr(`[Antigravity] Quota exhausted (${classification.reason || "daily limit"}). Check plan limits.`);
30676
- return response;
30756
+ return await this.explainTerminalQuota(response, bodyText, classification.reason);
30677
30757
  }
30678
30758
  if (attempt < MAX_RETRY_ATTEMPTS) {
30679
30759
  const delay = classification.retryDelayMs ?? DEFAULT_RATE_LIMIT_DELAY_MS;
@@ -30768,6 +30848,53 @@ class AntigravityProviderTransport {
30768
30848
  headers: { "Content-Type": "application/json" }
30769
30849
  });
30770
30850
  }
30851
+ async quotaRemainingForServedModel() {
30852
+ if (!this.accessToken || !this.projectId)
30853
+ return;
30854
+ let timer;
30855
+ const data = await Promise.race([
30856
+ retrieveUserQuota(this.accessToken, this.projectId).catch(() => null),
30857
+ new Promise((resolve) => {
30858
+ timer = setTimeout(() => resolve(null), QUOTA_CHECK_TIMEOUT_MS);
30859
+ })
30860
+ ]).finally(() => {
30861
+ if (timer)
30862
+ clearTimeout(timer);
30863
+ });
30864
+ const buckets = data?.buckets;
30865
+ if (!buckets?.length)
30866
+ return;
30867
+ const bucket = buckets.find((b) => b.modelId === this.servedModelName) ?? buckets.find((b) => b.modelId === this.modelName);
30868
+ return typeof bucket?.remainingFraction === "number" ? bucket.remainingFraction : undefined;
30869
+ }
30870
+ async explainTerminalQuota(response, bodyText, reason) {
30871
+ const remaining = await this.quotaRemainingForServedModel();
30872
+ const model = this.servedModelName;
30873
+ let advice;
30874
+ if (remaining !== undefined && remaining > 0) {
30875
+ advice = `your Antigravity plan still reports ${(remaining * 100).toFixed(1)}% of the ${model} ` + "allowance available, so this is probably NOT an exhausted plan. The usual cause is an " + "Antigravity session Google invalidated server-side; run `claudish login antigravity`.";
30876
+ } else if (remaining === undefined) {
30877
+ advice = "claudish could not read your Antigravity quota to confirm this. If your plan is not " + "actually spent, the session may be stale \u2014 run `claudish login antigravity`.";
30878
+ } else {
30879
+ advice = `your Antigravity plan reports no remaining ${model} allowance; it refills on Google's own schedule.`;
30880
+ }
30881
+ logStderr(`[Antigravity] Terminal 429 (${reason || "daily limit"}) \u2014 ${advice}`);
30882
+ let parsed;
30883
+ try {
30884
+ parsed = JSON.parse(bodyText);
30885
+ } catch {
30886
+ return response;
30887
+ }
30888
+ const target = Array.isArray(parsed) ? parsed[0]?.error : parsed?.error;
30889
+ if (!target || typeof target !== "object")
30890
+ return response;
30891
+ const upstream = typeof target.message === "string" && target.message.length > 0 ? target.message : "Resource has been exhausted";
30892
+ target.message = `${upstream} \u2014 ${advice}`;
30893
+ return new Response(JSON.stringify(parsed), {
30894
+ status: 429,
30895
+ headers: { "Content-Type": "application/json" }
30896
+ });
30897
+ }
30771
30898
  async logQuotaInfo() {
30772
30899
  if (!this.accessToken || !this.projectId)
30773
30900
  return;
@@ -30817,7 +30944,7 @@ ${lines.join(`
30817
30944
  }
30818
30945
  }
30819
30946
  }
30820
- var ANTIGRAVITY_BASE = "https://cloudcode-pa.googleapis.com", ANTIGRAVITY_ENDPOINT, MAX_RETRY_ATTEMPTS = 3, DEFAULT_RATE_LIMIT_DELAY_MS = 1e4, REASONING_TIER_RANK;
30947
+ var ANTIGRAVITY_BASE = "https://cloudcode-pa.googleapis.com", ANTIGRAVITY_ENDPOINT, MAX_RETRY_ATTEMPTS = 3, DEFAULT_RATE_LIMIT_DELAY_MS = 1e4, QUOTA_CHECK_TIMEOUT_MS = 3000, REASONING_TIER_RANK;
30821
30948
  var init_antigravity = __esm(() => {
30822
30949
  init_model_catalog();
30823
30950
  init_antigravity_token();
@@ -31557,14 +31684,613 @@ var init_devin_credential = __esm(() => {
31557
31684
  init_devin_credentials();
31558
31685
  });
31559
31686
 
31560
- // src/auth/kimi-oauth.ts
31687
+ // src/auth/oauth-manager.ts
31561
31688
  import { exec as exec2 } from "child_process";
31562
- import { randomBytes as randomBytes2 } from "crypto";
31563
- import { closeSync as closeSync3, existsSync as existsSync10, openSync as openSync3, readFileSync as readFileSync9, unlinkSync as unlinkSync3, writeSync as writeSync3 } from "fs";
31564
- import { homedir as homedir13, hostname as hostname3, platform, release as release2 } from "os";
31689
+ import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
31690
+ import {
31691
+ closeSync as closeSync3,
31692
+ existsSync as existsSync10,
31693
+ mkdirSync as mkdirSync7,
31694
+ openSync as openSync3,
31695
+ readFileSync as readFileSync9,
31696
+ unlinkSync as unlinkSync3,
31697
+ writeSync as writeSync3
31698
+ } from "fs";
31699
+ import { homedir as homedir13 } from "os";
31565
31700
  import { join as join13 } from "path";
31566
31701
  import { promisify as promisify2 } from "util";
31567
31702
 
31703
+ class OAuthManager {
31704
+ credentials = null;
31705
+ refreshPromise = null;
31706
+ tokenRefreshMargin = 5 * 60 * 1000;
31707
+ static ensureClaudishDir() {
31708
+ const dir = join13(homedir13(), ".claudish");
31709
+ if (!existsSync10(dir)) {
31710
+ mkdirSync7(dir, { recursive: true });
31711
+ }
31712
+ return dir;
31713
+ }
31714
+ getCredentialsPath() {
31715
+ return join13(homedir13(), ".claudish", this.credentialFile);
31716
+ }
31717
+ loadCredentials() {
31718
+ const credPath = this.getCredentialsPath();
31719
+ if (!existsSync10(credPath))
31720
+ return null;
31721
+ try {
31722
+ const data = JSON.parse(readFileSync9(credPath, "utf-8"));
31723
+ if (!this.validateCredentials(data)) {
31724
+ log(`[${this.providerName}] Invalid credentials file structure`);
31725
+ return null;
31726
+ }
31727
+ log(`[${this.providerName}] Loaded credentials from file`);
31728
+ return data;
31729
+ } catch (e) {
31730
+ log(`[${this.providerName}] Failed to load credentials: ${e.message}`);
31731
+ return null;
31732
+ }
31733
+ }
31734
+ saveCredentials(credentials2) {
31735
+ OAuthManager.ensureClaudishDir();
31736
+ const credPath = this.getCredentialsPath();
31737
+ const fd = openSync3(credPath, "w", 384);
31738
+ try {
31739
+ writeSync3(fd, JSON.stringify(credentials2, null, 2), 0, "utf-8");
31740
+ } finally {
31741
+ closeSync3(fd);
31742
+ }
31743
+ log(`[${this.providerName}] Credentials saved to ${credPath}`);
31744
+ }
31745
+ deleteCredentials() {
31746
+ const credPath = this.getCredentialsPath();
31747
+ if (existsSync10(credPath)) {
31748
+ unlinkSync3(credPath);
31749
+ log(`[${this.providerName}] Credentials deleted`);
31750
+ }
31751
+ }
31752
+ hasCredentials() {
31753
+ return this.credentials !== null && !!this.credentials.refresh_token;
31754
+ }
31755
+ async getAccessToken() {
31756
+ if (this.refreshPromise) {
31757
+ log(`[${this.providerName}] Waiting for in-progress refresh`);
31758
+ return this.refreshPromise;
31759
+ }
31760
+ if (!this.credentials) {
31761
+ throw new Error(`No ${this.providerName} credentials found. Please run \`${this.loginHint}\` first.`);
31762
+ }
31763
+ if (this.isTokenValid()) {
31764
+ return this.credentials.access_token;
31765
+ }
31766
+ this.refreshPromise = this.doRefreshToken().finally(() => {
31767
+ this.refreshPromise = null;
31768
+ });
31769
+ return this.refreshPromise;
31770
+ }
31771
+ async refreshToken() {
31772
+ if (!this.credentials) {
31773
+ throw new Error(`No ${this.providerName} credentials found. Please run \`${this.loginHint}\` first.`);
31774
+ }
31775
+ await this.doRefreshToken();
31776
+ }
31777
+ isTokenValid() {
31778
+ if (!this.credentials)
31779
+ return false;
31780
+ return Date.now() < this.credentials.expires_at - this.tokenRefreshMargin;
31781
+ }
31782
+ generateCodeVerifier() {
31783
+ return randomBytes2(64).toString("base64url");
31784
+ }
31785
+ generateCodeChallenge(verifier) {
31786
+ return createHash3("sha256").update(verifier).digest("base64url");
31787
+ }
31788
+ async openBrowser(url2, message) {
31789
+ try {
31790
+ if (process.platform === "darwin") {
31791
+ await execAsync2(`open "${url2}"`);
31792
+ } else if (process.platform === "win32") {
31793
+ await execAsync2(`start "${url2}"`);
31794
+ } else {
31795
+ await execAsync2(`xdg-open "${url2}"`);
31796
+ }
31797
+ if (message !== undefined) {
31798
+ console.log(message);
31799
+ } else {
31800
+ console.log(`
31801
+ Opening browser for authentication...`);
31802
+ console.log(`If the browser doesn't open, visit this URL:
31803
+ ${url2}
31804
+ `);
31805
+ }
31806
+ } catch {
31807
+ console.log(`
31808
+ Please open this URL in your browser to authenticate:`);
31809
+ console.log(url2);
31810
+ console.log("");
31811
+ }
31812
+ }
31813
+ async copyToClipboard(text) {
31814
+ const commands = process.platform === "darwin" ? ["pbcopy"] : process.platform === "win32" ? ["clip"] : ["wl-copy", "xclip -selection clipboard", "xsel --clipboard --input"];
31815
+ for (const command of commands) {
31816
+ try {
31817
+ const child = (await import("child_process")).spawn(command, {
31818
+ shell: true,
31819
+ stdio: ["pipe", "ignore", "ignore"]
31820
+ });
31821
+ child.stdin.write(text);
31822
+ child.stdin.end();
31823
+ const ok = await new Promise((resolve) => {
31824
+ child.on("close", (code) => resolve(code === 0));
31825
+ child.on("error", () => resolve(false));
31826
+ });
31827
+ if (ok)
31828
+ return true;
31829
+ } catch {}
31830
+ }
31831
+ return false;
31832
+ }
31833
+ presentAuthUrl(url2) {
31834
+ const stdin = process.stdin;
31835
+ const interactive = Boolean(stdin.isTTY && typeof stdin.setRawMode === "function");
31836
+ if (!interactive) {
31837
+ console.log(` URL: ${url2}
31838
+ `);
31839
+ return () => {};
31840
+ }
31841
+ console.log(` URL: ${url2}`);
31842
+ console.log(` (press c to copy the URL, or open it manually)
31843
+ `);
31844
+ const onKey = (chunk) => {
31845
+ const key = chunk.toString();
31846
+ if (key === "\x03") {
31847
+ cleanup();
31848
+ process.exit(130);
31849
+ }
31850
+ if (key.toLowerCase() === "c") {
31851
+ this.copyToClipboard(url2).then((ok) => {
31852
+ console.log(ok ? " \u2713 URL copied to clipboard" : " \u2717 No clipboard tool available");
31853
+ });
31854
+ }
31855
+ };
31856
+ let disposed = false;
31857
+ const cleanup = () => {
31858
+ if (disposed)
31859
+ return;
31860
+ disposed = true;
31861
+ stdin.off("data", onKey);
31862
+ try {
31863
+ stdin.setRawMode(false);
31864
+ } catch {}
31865
+ stdin.pause();
31866
+ };
31867
+ stdin.setRawMode(true);
31868
+ stdin.resume();
31869
+ stdin.on("data", onKey);
31870
+ return cleanup;
31871
+ }
31872
+ async logout() {
31873
+ this.deleteCredentials();
31874
+ this.credentials = null;
31875
+ }
31876
+ }
31877
+ var execAsync2;
31878
+ var init_oauth_manager = __esm(() => {
31879
+ init_logger();
31880
+ execAsync2 = promisify2(exec2);
31881
+ });
31882
+
31883
+ // src/auth/grok-oauth.ts
31884
+ var GROK_ISSUER = "https://auth.x.ai", DEVICE_CODE_ENDPOINT, TOKEN_ENDPOINT, REVOKE_ENDPOINT, GROK_PUBLIC_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828", GROK_SCOPES, DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code", DEFAULT_POLL_INTERVAL_S = 5, GrokOAuth;
31885
+ var init_grok_oauth = __esm(() => {
31886
+ init_logger();
31887
+ init_oauth_manager();
31888
+ DEVICE_CODE_ENDPOINT = `${GROK_ISSUER}/oauth2/device/code`;
31889
+ TOKEN_ENDPOINT = `${GROK_ISSUER}/oauth2/token`;
31890
+ REVOKE_ENDPOINT = `${GROK_ISSUER}/oauth2/revoke`;
31891
+ GROK_SCOPES = [
31892
+ "openid",
31893
+ "profile",
31894
+ "email",
31895
+ "offline_access",
31896
+ "grok-cli:access",
31897
+ "api:access",
31898
+ "conversations:read",
31899
+ "conversations:write",
31900
+ "workspaces:read",
31901
+ "workspaces:write"
31902
+ ].join(" ");
31903
+ GrokOAuth = class GrokOAuth extends OAuthManager {
31904
+ credentialFile = "grok-oauth.json";
31905
+ providerName = "GrokOAuth";
31906
+ loginHint = "claudish login grok";
31907
+ static instance = null;
31908
+ static getInstance() {
31909
+ if (!GrokOAuth.instance) {
31910
+ GrokOAuth.instance = new GrokOAuth;
31911
+ }
31912
+ return GrokOAuth.instance;
31913
+ }
31914
+ constructor() {
31915
+ super();
31916
+ this.credentials = this.loadCredentials();
31917
+ }
31918
+ validateCredentials(data) {
31919
+ if (!data || typeof data !== "object")
31920
+ return false;
31921
+ const d = data;
31922
+ return typeof d.access_token === "string" && typeof d.refresh_token === "string" && typeof d.expires_at === "number";
31923
+ }
31924
+ async getToken() {
31925
+ return this.getAccessToken();
31926
+ }
31927
+ async doRefreshToken() {
31928
+ const current = this.credentials;
31929
+ if (!current) {
31930
+ throw new Error(`No Grok credentials found. Please run \`${this.loginHint}\` first.`);
31931
+ }
31932
+ const body = new URLSearchParams({
31933
+ grant_type: "refresh_token",
31934
+ refresh_token: current.refresh_token,
31935
+ client_id: current.client_id || GROK_PUBLIC_CLIENT_ID
31936
+ });
31937
+ const response = await fetch(TOKEN_ENDPOINT, {
31938
+ method: "POST",
31939
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
31940
+ body
31941
+ });
31942
+ const parsed = await response.json().catch(() => ({}));
31943
+ if (!response.ok || !parsed.access_token) {
31944
+ const detail = parsed.error_description ?? parsed.error ?? `HTTP ${response.status}`;
31945
+ throw new Error(`Grok token refresh failed: ${detail}. Run \`${this.loginHint}\` to sign in.`);
31946
+ }
31947
+ const next = {
31948
+ access_token: parsed.access_token,
31949
+ refresh_token: parsed.refresh_token ?? current.refresh_token,
31950
+ expires_at: Date.now() + (parsed.expires_in ?? 6 * 60 * 60) * 1000,
31951
+ client_id: current.client_id || GROK_PUBLIC_CLIENT_ID,
31952
+ scope: parsed.scope ?? current.scope
31953
+ };
31954
+ this.credentials = next;
31955
+ this.saveCredentials(next);
31956
+ return next.access_token;
31957
+ }
31958
+ async login(clientId = GROK_PUBLIC_CLIENT_ID) {
31959
+ const auth = await this.requestDeviceCode(clientId);
31960
+ const url2 = auth.verification_uri_complete ?? auth.verification_uri;
31961
+ console.log(`
31962
+ Sign in to Grok (SuperGrok or X Premium+ subscription required).`);
31963
+ console.log(`
31964
+ Code: ${auth.user_code}`);
31965
+ const disposeUrlPrompt = this.presentAuthUrl(url2);
31966
+ await this.openBrowser(url2, "Opening your browser\u2026 (approve the request there)");
31967
+ try {
31968
+ const credentials2 = await this.pollForToken(auth, clientId);
31969
+ this.credentials = credentials2;
31970
+ this.saveCredentials(credentials2);
31971
+ } finally {
31972
+ disposeUrlPrompt();
31973
+ }
31974
+ console.log(`
31975
+ Signed in to Grok. Try it with: claudish --model gk@grok-4.6 "hello"
31976
+ `);
31977
+ }
31978
+ async requestDeviceCode(clientId) {
31979
+ const response = await fetch(DEVICE_CODE_ENDPOINT, {
31980
+ method: "POST",
31981
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
31982
+ body: new URLSearchParams({ client_id: clientId, scope: GROK_SCOPES })
31983
+ });
31984
+ const parsed = await response.json().catch(() => ({}));
31985
+ if (!response.ok || !parsed.device_code || !parsed.user_code) {
31986
+ const detail = parsed.error_description ?? parsed.error ?? `HTTP ${response.status}`;
31987
+ throw new Error(`Could not start Grok device authorization: ${detail}`);
31988
+ }
31989
+ return parsed;
31990
+ }
31991
+ async pollForToken(auth, clientId) {
31992
+ let intervalMs = (auth.interval ?? DEFAULT_POLL_INTERVAL_S) * 1000;
31993
+ const deadline = Date.now() + auth.expires_in * 1000;
31994
+ while (Date.now() < deadline) {
31995
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
31996
+ let parsed;
31997
+ try {
31998
+ const response = await fetch(TOKEN_ENDPOINT, {
31999
+ method: "POST",
32000
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
32001
+ body: new URLSearchParams({
32002
+ grant_type: DEVICE_CODE_GRANT,
32003
+ device_code: auth.device_code,
32004
+ client_id: clientId
32005
+ })
32006
+ });
32007
+ parsed = await response.json().catch(() => ({}));
32008
+ } catch (error46) {
32009
+ log(`[${this.providerName}] Poll failed, retrying: ${error46.message}`);
32010
+ continue;
32011
+ }
32012
+ if (parsed.access_token) {
32013
+ return {
32014
+ access_token: parsed.access_token,
32015
+ refresh_token: parsed.refresh_token ?? "",
32016
+ expires_at: Date.now() + (parsed.expires_in ?? 6 * 60 * 60) * 1000,
32017
+ client_id: clientId,
32018
+ scope: parsed.scope
32019
+ };
32020
+ }
32021
+ if (parsed.error === "authorization_pending")
32022
+ continue;
32023
+ if (parsed.error === "slow_down") {
32024
+ intervalMs += 5000;
32025
+ continue;
32026
+ }
32027
+ throw new Error(`Grok sign-in failed: ${parsed.error_description ?? parsed.error ?? "unknown error"}`);
32028
+ }
32029
+ throw new Error("Grok sign-in timed out \u2014 the device code expired. Please try again.");
32030
+ }
32031
+ async logout() {
32032
+ const current = this.credentials;
32033
+ if (current?.refresh_token) {
32034
+ try {
32035
+ await fetch(REVOKE_ENDPOINT, {
32036
+ method: "POST",
32037
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
32038
+ body: new URLSearchParams({
32039
+ token: current.refresh_token,
32040
+ token_type_hint: "refresh_token",
32041
+ client_id: current.client_id || GROK_PUBLIC_CLIENT_ID
32042
+ })
32043
+ });
32044
+ } catch (error46) {
32045
+ log(`[${this.providerName}] Revocation failed (deleting locally anyway): ${error46}`);
32046
+ }
32047
+ }
32048
+ await super.logout();
32049
+ }
32050
+ };
32051
+ });
32052
+
32053
+ // src/providers/grok/grok-credentials.ts
32054
+ import { existsSync as existsSync11, readFileSync as readFileSync10, renameSync, writeFileSync as writeFileSync7 } from "fs";
32055
+ import { homedir as homedir14 } from "os";
32056
+ import { join as join14 } from "path";
32057
+ function grokHome() {
32058
+ return grokHomeOverride ?? join14(homedir14(), ".grok");
32059
+ }
32060
+ function grokAuthPath() {
32061
+ return join14(grokHome(), "auth.json");
32062
+ }
32063
+ function str(value) {
32064
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
32065
+ }
32066
+ function readGrokCredential() {
32067
+ let parsed;
32068
+ try {
32069
+ parsed = JSON.parse(readFileSync10(grokAuthPath(), "utf8"));
32070
+ } catch {
32071
+ return;
32072
+ }
32073
+ if (!parsed || typeof parsed !== "object")
32074
+ return;
32075
+ const entries = Object.entries(parsed).filter(([, v]) => v && typeof v === "object" && str(v.key));
32076
+ if (entries.length === 0)
32077
+ return;
32078
+ const chosen = entries.find(([, v]) => str(v.auth_mode)?.toLowerCase() === "oidc") ?? entries.find(([scope2]) => scope2 === LEGACY_SCOPE) ?? entries[0];
32079
+ const [scope, raw] = chosen;
32080
+ const key = str(raw.key);
32081
+ if (!key)
32082
+ return;
32083
+ return {
32084
+ scope,
32085
+ key,
32086
+ refreshToken: str(raw.refresh_token),
32087
+ expiresAt: str(raw.expires_at),
32088
+ clientId: str(raw.oidc_client_id),
32089
+ issuer: str(raw.oidc_issuer),
32090
+ authMode: str(raw.auth_mode)
32091
+ };
32092
+ }
32093
+ function claudishGrokOAuthPath() {
32094
+ return claudishOAuthPathOverride ?? join14(homedir14(), ".claudish", "grok-oauth.json");
32095
+ }
32096
+ function hasClaudishGrokOAuth() {
32097
+ return existsSync11(claudishGrokOAuthPath());
32098
+ }
32099
+ function hasGrokCredentials() {
32100
+ return hasClaudishGrokOAuth() || readGrokCredential() !== undefined;
32101
+ }
32102
+ function isGrokCredentialExpired(cred, now = Date.now()) {
32103
+ if (!cred.expiresAt)
32104
+ return false;
32105
+ const expiry = Date.parse(cred.expiresAt);
32106
+ if (Number.isNaN(expiry))
32107
+ return false;
32108
+ return expiry - EXPIRY_SKEW_MS2 <= now;
32109
+ }
32110
+ function readGrokClientVersion() {
32111
+ return readLocalGrokVersion() ?? FALLBACK_GROK_CLIENT_VERSION;
32112
+ }
32113
+ function readLocalGrokVersion() {
32114
+ for (const [file2, field] of [
32115
+ ["version.json", "version"],
32116
+ ["models_cache.json", "grok_version"]
32117
+ ]) {
32118
+ try {
32119
+ const parsed = JSON.parse(readFileSync10(join14(grokHome(), file2), "utf8"));
32120
+ const version2 = str(parsed[field]);
32121
+ if (version2)
32122
+ return version2;
32123
+ } catch {}
32124
+ }
32125
+ return;
32126
+ }
32127
+ async function resolveGrokClientVersion() {
32128
+ const local = readLocalGrokVersion();
32129
+ if (local)
32130
+ return local;
32131
+ if (liveClientVersion)
32132
+ return liveClientVersion;
32133
+ try {
32134
+ const response = await fetch(GROK_CHANNEL_URL, { signal: AbortSignal.timeout(5000) });
32135
+ if (response.ok) {
32136
+ const version2 = (await response.text()).trim().split(/\s+/)[0];
32137
+ if (/^\d+\.\d+\.\d+(-[A-Za-z0-9._]+)?$/.test(version2)) {
32138
+ liveClientVersion = version2;
32139
+ return version2;
32140
+ }
32141
+ }
32142
+ } catch {}
32143
+ return FALLBACK_GROK_CLIENT_VERSION;
32144
+ }
32145
+ function grokAuthHeaders(token, version2 = readGrokClientVersion()) {
32146
+ return {
32147
+ Authorization: `Bearer ${token}`,
32148
+ "x-grok-client-version": version2,
32149
+ "x-grok-client-identifier": GROK_CLIENT_IDENTIFIER
32150
+ };
32151
+ }
32152
+ function terminal(message) {
32153
+ const err = new Error(message);
32154
+ err.terminal = true;
32155
+ return err;
32156
+ }
32157
+ function persistRefreshedToken(scope, next) {
32158
+ const path = grokAuthPath();
32159
+ let parsed;
32160
+ try {
32161
+ parsed = JSON.parse(readFileSync10(path, "utf8"));
32162
+ } catch {
32163
+ return;
32164
+ }
32165
+ const entry = parsed[scope];
32166
+ if (!entry || typeof entry !== "object")
32167
+ return;
32168
+ entry.key = next.key;
32169
+ if (next.refreshToken)
32170
+ entry.refresh_token = next.refreshToken;
32171
+ if (next.expiresAt)
32172
+ entry.expires_at = next.expiresAt;
32173
+ const tmp = `${path}.claudish.tmp`;
32174
+ writeFileSync7(tmp, `${JSON.stringify(parsed, null, 2)}
32175
+ `, { mode: 384 });
32176
+ renameSync(tmp, path);
32177
+ }
32178
+ async function performRefresh(cred) {
32179
+ if (!cred.refreshToken || !cred.clientId) {
32180
+ throw terminal(`Grok credential is expired and cannot be refreshed. ${SIGN_IN_HINT}`);
32181
+ }
32182
+ const tokenEndpoint = `${(cred.issuer ?? "https://auth.x.ai").replace(/\/+$/, "")}/oauth2/token`;
32183
+ const body = new URLSearchParams({
32184
+ grant_type: "refresh_token",
32185
+ refresh_token: cred.refreshToken,
32186
+ client_id: cred.clientId
32187
+ });
32188
+ let response;
32189
+ try {
32190
+ response = await fetch(tokenEndpoint, {
32191
+ method: "POST",
32192
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
32193
+ body
32194
+ });
32195
+ } catch (error46) {
32196
+ throw new Error(`Could not reach ${tokenEndpoint} to refresh the Grok token: ${error46.message}`);
32197
+ }
32198
+ const text = await response.text();
32199
+ if (!response.ok) {
32200
+ let detail = text.slice(0, 300);
32201
+ try {
32202
+ const parsed2 = JSON.parse(text);
32203
+ detail = parsed2.error_description ?? parsed2.error ?? detail;
32204
+ } catch {}
32205
+ throw terminal(`Grok token refresh failed (${response.status}): ${detail}. ${SIGN_IN_HINT}`);
32206
+ }
32207
+ const parsed = JSON.parse(text);
32208
+ const accessToken = str(parsed.access_token);
32209
+ if (!accessToken) {
32210
+ throw terminal(`Grok token refresh returned no access_token. ${SIGN_IN_HINT}`);
32211
+ }
32212
+ const expiresAt = typeof parsed.expires_in === "number" ? new Date(Date.now() + parsed.expires_in * 1000).toISOString() : undefined;
32213
+ try {
32214
+ persistRefreshedToken(cred.scope, {
32215
+ key: accessToken,
32216
+ refreshToken: str(parsed.refresh_token),
32217
+ expiresAt
32218
+ });
32219
+ } catch {}
32220
+ return accessToken;
32221
+ }
32222
+ async function resolveGrokAccessToken() {
32223
+ if (hasClaudishGrokOAuth()) {
32224
+ try {
32225
+ return await GrokOAuth.getInstance().getToken();
32226
+ } catch (error46) {
32227
+ if (!readGrokCredential())
32228
+ throw terminal(`${error46.message}`);
32229
+ }
32230
+ }
32231
+ const cred = readGrokCredential();
32232
+ if (!cred)
32233
+ throw terminal(`No Grok subscription credential. ${SIGN_IN_HINT}`);
32234
+ if (!isGrokCredentialExpired(cred))
32235
+ return cred.key;
32236
+ return refreshShared(cred);
32237
+ }
32238
+ async function forceRefreshGrokAccessToken() {
32239
+ if (hasClaudishGrokOAuth()) {
32240
+ const oauth = GrokOAuth.getInstance();
32241
+ await oauth.refreshToken();
32242
+ return oauth.getToken();
32243
+ }
32244
+ const cred = readGrokCredential();
32245
+ if (!cred)
32246
+ throw terminal(`No Grok subscription credential. ${SIGN_IN_HINT}`);
32247
+ return refreshShared(cred);
32248
+ }
32249
+ function refreshShared(cred) {
32250
+ if (!refreshInFlight) {
32251
+ refreshInFlight = performRefresh(cred).finally(() => {
32252
+ refreshInFlight = null;
32253
+ });
32254
+ }
32255
+ return refreshInFlight;
32256
+ }
32257
+ var GROK_CLIENT_IDENTIFIER = "grok-shell", FALLBACK_GROK_CLIENT_VERSION = "1.0.4", LEGACY_SCOPE = "https://accounts.x.ai/sign-in", EXPIRY_SKEW_MS2, grokHomeOverride = null, claudishOAuthPathOverride = null, GROK_CHANNEL_URL = "https://x.ai/cli/stable", liveClientVersion = null, SIGN_IN_HINT, refreshInFlight = null;
32258
+ var init_grok_credentials = __esm(() => {
32259
+ init_grok_oauth();
32260
+ EXPIRY_SKEW_MS2 = 5 * 60 * 1000;
32261
+ SIGN_IN_HINT = "Run `claudish login grok` (no Grok CLI required \u2014 SuperGrok or X Premium+ subscription). " + "An existing `grok login` (~/.grok/auth.json) is also picked up automatically.";
32262
+ });
32263
+
32264
+ // src/auth/credentials/grok-credential.ts
32265
+ class GrokSubscriptionCredentialProvider {
32266
+ catalogName = "grok-subscription";
32267
+ async isAvailable() {
32268
+ try {
32269
+ return hasGrokCredentials();
32270
+ } catch {
32271
+ return false;
32272
+ }
32273
+ }
32274
+ async getRequestAuth() {
32275
+ const [token, version2] = await Promise.all([
32276
+ resolveGrokAccessToken(),
32277
+ resolveGrokClientVersion()
32278
+ ]);
32279
+ return { headers: grokAuthHeaders(token, version2) };
32280
+ }
32281
+ }
32282
+ var init_grok_credential = __esm(() => {
32283
+ init_grok_credentials();
32284
+ });
32285
+
32286
+ // src/auth/kimi-oauth.ts
32287
+ import { exec as exec3 } from "child_process";
32288
+ import { randomBytes as randomBytes3 } from "crypto";
32289
+ import { closeSync as closeSync4, existsSync as existsSync12, openSync as openSync4, readFileSync as readFileSync11, unlinkSync as unlinkSync4, writeSync as writeSync4 } from "fs";
32290
+ import { homedir as homedir15, hostname as hostname3, platform, release as release2 } from "os";
32291
+ import { join as join15 } from "path";
32292
+ import { promisify as promisify3 } from "util";
32293
+
31568
32294
  class KimiOAuth {
31569
32295
  static instance = null;
31570
32296
  credentials = null;
@@ -31590,23 +32316,23 @@ class KimiOAuth {
31590
32316
  return this.credentials !== null && !!this.credentials.refresh_token;
31591
32317
  }
31592
32318
  getCredentialsPath() {
31593
- const claudishDir = join13(homedir13(), ".claudish");
31594
- return join13(claudishDir, "kimi-oauth.json");
32319
+ const claudishDir = join15(homedir15(), ".claudish");
32320
+ return join15(claudishDir, "kimi-oauth.json");
31595
32321
  }
31596
32322
  getDeviceIdPath() {
31597
- const claudishDir = join13(homedir13(), ".claudish");
31598
- return join13(claudishDir, "kimi-device-id");
32323
+ const claudishDir = join15(homedir15(), ".claudish");
32324
+ return join15(claudishDir, "kimi-device-id");
31599
32325
  }
31600
32326
  loadOrCreateDeviceId() {
31601
32327
  const deviceIdPath = this.getDeviceIdPath();
31602
- const claudishDir = join13(homedir13(), ".claudish");
31603
- if (!existsSync10(claudishDir)) {
31604
- const { mkdirSync: mkdirSync7 } = __require("fs");
31605
- mkdirSync7(claudishDir, { recursive: true });
32328
+ const claudishDir = join15(homedir15(), ".claudish");
32329
+ if (!existsSync12(claudishDir)) {
32330
+ const { mkdirSync: mkdirSync8 } = __require("fs");
32331
+ mkdirSync8(claudishDir, { recursive: true });
31606
32332
  }
31607
- if (existsSync10(deviceIdPath)) {
32333
+ if (existsSync12(deviceIdPath)) {
31608
32334
  try {
31609
- const deviceId2 = readFileSync9(deviceIdPath, "utf-8").trim();
32335
+ const deviceId2 = readFileSync11(deviceIdPath, "utf-8").trim();
31610
32336
  if (deviceId2) {
31611
32337
  return deviceId2;
31612
32338
  }
@@ -31614,13 +32340,13 @@ class KimiOAuth {
31614
32340
  log(`[KimiOAuth] Failed to load device ID: ${e.message}`);
31615
32341
  }
31616
32342
  }
31617
- const deviceId = randomBytes2(16).toString("hex").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
32343
+ const deviceId = randomBytes3(16).toString("hex").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
31618
32344
  try {
31619
- const fd = openSync3(deviceIdPath, "w", 384);
32345
+ const fd = openSync4(deviceIdPath, "w", 384);
31620
32346
  try {
31621
- writeSync3(fd, deviceId, 0, "utf-8");
32347
+ writeSync4(fd, deviceId, 0, "utf-8");
31622
32348
  } finally {
31623
- closeSync3(fd);
32349
+ closeSync4(fd);
31624
32350
  }
31625
32351
  log(`[KimiOAuth] New device ID created: ${deviceId}`);
31626
32352
  } catch (e) {
@@ -31765,11 +32491,11 @@ Waiting for authorization...`);
31765
32491
  const currentPlatform = platform();
31766
32492
  try {
31767
32493
  if (currentPlatform === "darwin") {
31768
- await execAsync2(`open "${url2}"`);
32494
+ await execAsync3(`open "${url2}"`);
31769
32495
  } else if (currentPlatform === "win32") {
31770
- await execAsync2(`start "${url2}"`);
32496
+ await execAsync3(`start "${url2}"`);
31771
32497
  } else {
31772
- await execAsync2(`xdg-open "${url2}"`);
32498
+ await execAsync3(`xdg-open "${url2}"`);
31773
32499
  }
31774
32500
  } catch (e) {
31775
32501
  log(`[KimiOAuth] Failed to open browser: ${e.message}`);
@@ -31777,8 +32503,8 @@ Waiting for authorization...`);
31777
32503
  }
31778
32504
  async logout() {
31779
32505
  const credPath = this.getCredentialsPath();
31780
- if (existsSync10(credPath)) {
31781
- unlinkSync3(credPath);
32506
+ if (existsSync12(credPath)) {
32507
+ unlinkSync4(credPath);
31782
32508
  log("[KimiOAuth] Credentials deleted");
31783
32509
  }
31784
32510
  this.credentials = null;
@@ -31844,8 +32570,8 @@ Waiting for authorization...`);
31844
32570
  } catch (e) {
31845
32571
  log(`[KimiOAuth] Refresh failed: ${e.message}`);
31846
32572
  const credPath = this.getCredentialsPath();
31847
- if (existsSync10(credPath)) {
31848
- unlinkSync3(credPath);
32573
+ if (existsSync12(credPath)) {
32574
+ unlinkSync4(credPath);
31849
32575
  }
31850
32576
  this.credentials = null;
31851
32577
  if (process.env.MOONSHOT_API_KEY || process.env.KIMI_API_KEY) {
@@ -31861,11 +32587,11 @@ Details: ${e.message}`);
31861
32587
  }
31862
32588
  loadCredentials() {
31863
32589
  const credPath = this.getCredentialsPath();
31864
- if (!existsSync10(credPath)) {
32590
+ if (!existsSync12(credPath)) {
31865
32591
  return null;
31866
32592
  }
31867
32593
  try {
31868
- const data = readFileSync9(credPath, "utf-8");
32594
+ const data = readFileSync11(credPath, "utf-8");
31869
32595
  const credentials2 = JSON.parse(data);
31870
32596
  if (!credentials2.access_token || !credentials2.refresh_token || !credentials2.expires_at || !credentials2.scope || !credentials2.token_type) {
31871
32597
  log("[KimiOAuth] Invalid credentials file structure");
@@ -31880,17 +32606,17 @@ Details: ${e.message}`);
31880
32606
  }
31881
32607
  saveCredentials(credentials2) {
31882
32608
  const credPath = this.getCredentialsPath();
31883
- const claudishDir = join13(homedir13(), ".claudish");
31884
- if (!existsSync10(claudishDir)) {
31885
- const { mkdirSync: mkdirSync7 } = __require("fs");
31886
- mkdirSync7(claudishDir, { recursive: true });
32609
+ const claudishDir = join15(homedir15(), ".claudish");
32610
+ if (!existsSync12(claudishDir)) {
32611
+ const { mkdirSync: mkdirSync8 } = __require("fs");
32612
+ mkdirSync8(claudishDir, { recursive: true });
31887
32613
  }
31888
- const fd = openSync3(credPath, "w", 384);
32614
+ const fd = openSync4(credPath, "w", 384);
31889
32615
  try {
31890
32616
  const data = JSON.stringify(credentials2, null, 2);
31891
- writeSync3(fd, data, 0, "utf-8");
32617
+ writeSync4(fd, data, 0, "utf-8");
31892
32618
  } finally {
31893
- closeSync3(fd);
32619
+ closeSync4(fd);
31894
32620
  }
31895
32621
  log(`[KimiOAuth] Credentials saved to ${credPath}`);
31896
32622
  }
@@ -31898,10 +32624,10 @@ Details: ${e.message}`);
31898
32624
  function getKimiOAuth() {
31899
32625
  return KimiOAuth.getInstance();
31900
32626
  }
31901
- var execAsync2, OAUTH_CONFIG2;
32627
+ var execAsync3, OAUTH_CONFIG2;
31902
32628
  var init_kimi_oauth = __esm(() => {
31903
32629
  init_logger();
31904
- execAsync2 = promisify2(exec2);
32630
+ execAsync3 = promisify3(exec3);
31905
32631
  OAUTH_CONFIG2 = {
31906
32632
  clientId: "17e5f671-d194-4dfb-9706-5516cb48c098",
31907
32633
  authHost: "https://auth.kimi.com",
@@ -31911,18 +32637,18 @@ var init_kimi_oauth = __esm(() => {
31911
32637
  });
31912
32638
 
31913
32639
  // src/auth/oauth-registry.ts
31914
- import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
31915
- import { homedir as homedir14 } from "os";
31916
- import { join as join14 } from "path";
32640
+ import { existsSync as existsSync13, readFileSync as readFileSync12 } from "fs";
32641
+ import { homedir as homedir16 } from "os";
32642
+ import { join as join16 } from "path";
31917
32643
  function hasValidOAuthCredentials(descriptor) {
31918
- const credPath = join14(homedir14(), ".claudish", descriptor.credentialFile);
31919
- if (!existsSync11(credPath))
32644
+ const credPath = join16(homedir16(), ".claudish", descriptor.credentialFile);
32645
+ if (!existsSync13(credPath))
31920
32646
  return false;
31921
32647
  if (descriptor.validationMode === "file-exists") {
31922
32648
  return true;
31923
32649
  }
31924
32650
  try {
31925
- const data = JSON.parse(readFileSync10(credPath, "utf-8"));
32651
+ const data = JSON.parse(readFileSync12(credPath, "utf-8"));
31926
32652
  if (!data.access_token)
31927
32653
  return false;
31928
32654
  if (data.refresh_token)
@@ -31962,6 +32688,12 @@ var init_oauth_registry = __esm(() => {
31962
32688
  validationMode: "check-expiry",
31963
32689
  expiresAtField: "expires_at",
31964
32690
  expiryBufferMs: 5 * 60 * 1000
32691
+ },
32692
+ "grok-subscription": {
32693
+ credentialFile: "grok-oauth.json",
32694
+ validationMode: "check-expiry",
32695
+ expiresAtField: "expires_at",
32696
+ expiryBufferMs: 5 * 60 * 1000
31965
32697
  }
31966
32698
  };
31967
32699
  });
@@ -32110,11 +32842,11 @@ var init_native_anthropic_credential = __esm(() => {
32110
32842
  });
32111
32843
 
32112
32844
  // src/auth/vertex-auth.ts
32113
- import { exec as exec3 } from "child_process";
32114
- import { existsSync as existsSync12 } from "fs";
32115
- import { homedir as homedir15 } from "os";
32116
- import { join as join15 } from "path";
32117
- import { promisify as promisify3 } from "util";
32845
+ import { exec as exec4 } from "child_process";
32846
+ import { existsSync as existsSync14 } from "fs";
32847
+ import { homedir as homedir17 } from "os";
32848
+ import { join as join17 } from "path";
32849
+ import { promisify as promisify4 } from "util";
32118
32850
 
32119
32851
  class VertexAuthManager {
32120
32852
  cachedToken = null;
@@ -32168,12 +32900,12 @@ class VertexAuthManager {
32168
32900
  }
32169
32901
  async tryADC() {
32170
32902
  try {
32171
- const adcPath = join15(homedir15(), ".config/gcloud/application_default_credentials.json");
32172
- if (!existsSync12(adcPath)) {
32903
+ const adcPath = join17(homedir17(), ".config/gcloud/application_default_credentials.json");
32904
+ if (!existsSync14(adcPath)) {
32173
32905
  log("[VertexAuth] ADC credentials file not found");
32174
32906
  return null;
32175
32907
  }
32176
- const { stdout } = await execAsync3("gcloud auth application-default print-access-token", {
32908
+ const { stdout } = await execAsync4("gcloud auth application-default print-access-token", {
32177
32909
  timeout: 1e4
32178
32910
  });
32179
32911
  const token = stdout.trim();
@@ -32193,13 +32925,13 @@ class VertexAuthManager {
32193
32925
  if (!credPath) {
32194
32926
  return null;
32195
32927
  }
32196
- if (!existsSync12(credPath)) {
32928
+ if (!existsSync14(credPath)) {
32197
32929
  throw new Error(`Service account file not found: ${credPath}
32198
32930
 
32199
32931
  Check GOOGLE_APPLICATION_CREDENTIALS path.`);
32200
32932
  }
32201
32933
  try {
32202
- const { stdout } = await execAsync3(`gcloud auth print-access-token --credential-file-override="${credPath}"`, { timeout: 1e4 });
32934
+ const { stdout } = await execAsync4(`gcloud auth print-access-token --credential-file-override="${credPath}"`, { timeout: 1e4 });
32203
32935
  const token = stdout.trim();
32204
32936
  if (!token) {
32205
32937
  log("[VertexAuth] Service account returned empty token");
@@ -32232,8 +32964,8 @@ function validateVertexOAuthConfig() {
32232
32964
  ` + ` export VERTEX_PROJECT='your-gcp-project-id'
32233
32965
  ` + " export VERTEX_LOCATION='us-central1' # optional";
32234
32966
  }
32235
- const adcPath = join15(homedir15(), ".config/gcloud/application_default_credentials.json");
32236
- const hasADC = existsSync12(adcPath);
32967
+ const adcPath = join17(homedir17(), ".config/gcloud/application_default_credentials.json");
32968
+ const hasADC = existsSync14(adcPath);
32237
32969
  const hasServiceAccount = !!process.env.GOOGLE_APPLICATION_CREDENTIALS;
32238
32970
  if (!hasADC && !hasServiceAccount) {
32239
32971
  return `No Vertex AI credentials found.
@@ -32262,10 +32994,10 @@ function getVertexAuthManager() {
32262
32994
  }
32263
32995
  return authManagerInstance;
32264
32996
  }
32265
- var execAsync3, authManagerInstance = null;
32997
+ var execAsync4, authManagerInstance = null;
32266
32998
  var init_vertex_auth = __esm(() => {
32267
32999
  init_logger();
32268
- execAsync3 = promisify3(exec3);
33000
+ execAsync4 = promisify4(exec4);
32269
33001
  });
32270
33002
 
32271
33003
  // src/auth/credentials/vertex-credential.ts
@@ -32353,6 +33085,7 @@ class CredentialAuthority {
32353
33085
  authority.register(makeCodexCredential(), ["openai-codex"]);
32354
33086
  authority.register(new AntigravityCredentialProvider, ["antigravity"]);
32355
33087
  authority.register(new DevinCredentialProvider, ["devin"]);
33088
+ authority.register(new GrokSubscriptionCredentialProvider, ["grok-subscription"]);
32356
33089
  authority.register(makeKimiCredential(), ["kimi"]);
32357
33090
  authority.register(makeKimiCodingCredential(), ["kimi-coding"]);
32358
33091
  authority.register(new VertexCredentialProvider, ["vertex"]);
@@ -32396,6 +33129,7 @@ var init_authority = __esm(() => {
32396
33129
  init_api_key_credential();
32397
33130
  init_codex_credential();
32398
33131
  init_devin_credential();
33132
+ init_grok_credential();
32399
33133
  init_kimi_credential();
32400
33134
  init_local_credential();
32401
33135
  init_native_anthropic_credential();
@@ -34713,9 +35447,9 @@ var init_antigravity2 = __esm(() => {
34713
35447
  });
34714
35448
 
34715
35449
  // src/auth/quota/sources/codex.ts
34716
- import { existsSync as existsSync13, readFileSync as readFileSync11 } from "fs";
34717
- import { homedir as homedir16 } from "os";
34718
- import { join as join16 } from "path";
35450
+ import { existsSync as existsSync15, readFileSync as readFileSync13 } from "fs";
35451
+ import { homedir as homedir18 } from "os";
35452
+ import { join as join18 } from "path";
34719
35453
  function formatWindowMinutes(minutes) {
34720
35454
  if (!Number.isFinite(minutes) || minutes <= 0)
34721
35455
  return "";
@@ -34729,7 +35463,7 @@ function formatWindowMinutes(minutes) {
34729
35463
  return `${hours}h${minutes % 60}m`;
34730
35464
  }
34731
35465
  function credentialsPath() {
34732
- return join16(homedir16(), ".claudish", "codex-oauth.json");
35466
+ return join18(homedir18(), ".claudish", "codex-oauth.json");
34733
35467
  }
34734
35468
  function planLabel(planType) {
34735
35469
  if (!planType)
@@ -34781,10 +35515,10 @@ function scrapeCodexHeaders(headers) {
34781
35515
  }
34782
35516
  function resolveProbeModel() {
34783
35517
  try {
34784
- const cachePath = join16(homedir16(), ".codex", "models_cache.json");
34785
- if (!existsSync13(cachePath))
35518
+ const cachePath = join18(homedir18(), ".codex", "models_cache.json");
35519
+ if (!existsSync15(cachePath))
34786
35520
  return;
34787
- const cache2 = JSON.parse(readFileSync11(cachePath, "utf-8"));
35521
+ const cache2 = JSON.parse(readFileSync13(cachePath, "utf-8"));
34788
35522
  for (const m of cache2.models ?? []) {
34789
35523
  const slug = m?.slug ?? m?.id;
34790
35524
  if (typeof slug === "string" && slug.length > 0)
@@ -34796,9 +35530,9 @@ function resolveProbeModel() {
34796
35530
  function readCodexCredentials() {
34797
35531
  try {
34798
35532
  const path = credentialsPath();
34799
- if (!existsSync13(path))
35533
+ if (!existsSync15(path))
34800
35534
  return;
34801
- return JSON.parse(readFileSync11(path, "utf-8"));
35535
+ return JSON.parse(readFileSync13(path, "utf-8"));
34802
35536
  } catch {
34803
35537
  return;
34804
35538
  }
@@ -34829,7 +35563,7 @@ var init_codex = __esm(() => {
34829
35563
  },
34830
35564
  isAvailable() {
34831
35565
  try {
34832
- return existsSync13(credentialsPath());
35566
+ return existsSync15(credentialsPath());
34833
35567
  } catch {
34834
35568
  return false;
34835
35569
  }
@@ -35210,8 +35944,8 @@ var init_harness = __esm(() => {
35210
35944
 
35211
35945
  // src/behavior/journal.ts
35212
35946
  import { appendFile as appendFile2, mkdir, readFile, rename, stat, writeFile } from "fs/promises";
35213
- import { homedir as homedir17 } from "os";
35214
- import { dirname as dirname6, join as join17 } from "path";
35947
+ import { homedir as homedir19 } from "os";
35948
+ import { dirname as dirname6, join as join19 } from "path";
35215
35949
  function classifyPath(observed, expected) {
35216
35950
  if (!observed)
35217
35951
  return "not_applicable";
@@ -35223,7 +35957,7 @@ function classifyPath(observed, expected) {
35223
35957
  return dirOf(observed) === dirOf(expected) ? "same_dir_wrong_name" : "outside_expected_dir";
35224
35958
  }
35225
35959
  function journalPath() {
35226
- return join17(homedir17(), ".claudish", "behavior-journal.jsonl");
35960
+ return join19(homedir19(), ".claudish", "behavior-journal.jsonl");
35227
35961
  }
35228
35962
  async function prune(path) {
35229
35963
  const content = await readFile(path, "utf8");
@@ -35282,10 +36016,10 @@ __export(exports_aggregate, {
35282
36016
  contextBucket: () => contextBucket,
35283
36017
  TELEMETRY_SCHEMA_VERSION: () => TELEMETRY_SCHEMA_VERSION
35284
36018
  });
35285
- import { createHash as createHash3, randomBytes as randomBytes3 } from "crypto";
35286
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync7 } from "fs";
35287
- import { homedir as homedir18 } from "os";
35288
- import { dirname as dirname7, join as join18 } from "path";
36019
+ import { createHash as createHash4, randomBytes as randomBytes4 } from "crypto";
36020
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync8 } from "fs";
36021
+ import { homedir as homedir20 } from "os";
36022
+ import { dirname as dirname7, join as join20 } from "path";
35289
36023
  function contextBucket(inputTokens) {
35290
36024
  if (inputTokens < 50000)
35291
36025
  return "0-50k";
@@ -35306,7 +36040,7 @@ function contextFillPct(peakTokens, window2 = enforcedContextWindow) {
35306
36040
  return Math.min(100, Math.max(0, Math.round(peakTokens / window2 * 100)));
35307
36041
  }
35308
36042
  function hashSessionId(rawSessionId, model) {
35309
- return createHash3("sha256").update(`${SESSION_SALT}:${rawSessionId}:${model}`).digest("hex");
36043
+ return createHash4("sha256").update(`${SESSION_SALT}:${rawSessionId}:${model}`).digest("hex");
35310
36044
  }
35311
36045
  function setTelemetryConsent(value) {
35312
36046
  consent = value;
@@ -35403,7 +36137,7 @@ function pendingReports() {
35403
36137
  return [...sessions.values()].map(toReport);
35404
36138
  }
35405
36139
  function outboxPath() {
35406
- return join18(homedir18(), ".claudish", "behavior-outbox.jsonl");
36140
+ return join20(homedir20(), ".claudish", "behavior-outbox.jsonl");
35407
36141
  }
35408
36142
  function spoolPendingSync(path = outboxPath()) {
35409
36143
  if (sessions.size === 0)
@@ -35413,7 +36147,7 @@ function spoolPendingSync(path = outboxPath()) {
35413
36147
  if (reports.length === 0)
35414
36148
  return 0;
35415
36149
  try {
35416
- mkdirSync7(dirname7(path), { recursive: true });
36150
+ mkdirSync8(dirname7(path), { recursive: true });
35417
36151
  appendFileSync2(path, `${reports.map((r) => JSON.stringify(r)).join(`
35418
36152
  `)}
35419
36153
  `);
@@ -35426,7 +36160,7 @@ function spoolPendingSync(path = outboxPath()) {
35426
36160
  var TELEMETRY_SCHEMA_VERSION = 1, enforcedContextWindow = 0, SESSION_SALT, MAX_TRACKED_SESSIONS = 32, MAX_DECISION_KEYS = 200, sessions, consent = false;
35427
36161
  var init_aggregate = __esm(() => {
35428
36162
  init_logger();
35429
- SESSION_SALT = randomBytes3(32).toString("hex");
36163
+ SESSION_SALT = randomBytes4(32).toString("hex");
35430
36164
  sessions = new Map;
35431
36165
  process.on("exit", () => {
35432
36166
  try {
@@ -35631,10 +36365,10 @@ __export(exports_live_log, {
35631
36365
  recordLiveDivergence: () => recordLiveDivergence
35632
36366
  });
35633
36367
  import { appendFile as appendFile3 } from "fs/promises";
35634
- import { homedir as homedir19 } from "os";
35635
- import { join as join19 } from "path";
36368
+ import { homedir as homedir21 } from "os";
36369
+ import { join as join21 } from "path";
35636
36370
  function defaultPath() {
35637
- return join19(homedir19(), ".claudish", "behavior-divergences.jsonl");
36371
+ return join21(homedir21(), ".claudish", "behavior-divergences.jsonl");
35638
36372
  }
35639
36373
  async function recordLiveDivergence(entry, path = defaultPath()) {
35640
36374
  try {
@@ -36330,9 +37064,9 @@ var init_hooks = __esm(() => {
36330
37064
  });
36331
37065
 
36332
37066
  // src/behavior/observer/corpus.ts
36333
- import { appendFileSync as appendFileSync3, readFileSync as readFileSync12, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
36334
- import { homedir as homedir20 } from "os";
36335
- import { join as join20 } from "path";
37067
+ import { appendFileSync as appendFileSync3, readFileSync as readFileSync14, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
37068
+ import { homedir as homedir22 } from "os";
37069
+ import { join as join22 } from "path";
36336
37070
  function directoryOf2(filePath) {
36337
37071
  const slash = filePath.lastIndexOf("/");
36338
37072
  return slash > 0 ? filePath.slice(0, slash) : undefined;
@@ -36354,7 +37088,7 @@ function writeTargetsOf(row) {
36354
37088
  function replayTranscript(file2) {
36355
37089
  let text;
36356
37090
  try {
36357
- text = readFileSync12(file2, "utf8");
37091
+ text = readFileSync14(file2, "utf8");
36358
37092
  } catch {
36359
37093
  return [];
36360
37094
  }
@@ -36411,26 +37145,26 @@ function listTranscripts(root) {
36411
37145
  return files;
36412
37146
  }
36413
37147
  for (const project of projects) {
36414
- const dir = join20(root, project);
37148
+ const dir = join22(root, project);
36415
37149
  try {
36416
37150
  if (!statSync2(dir).isDirectory())
36417
37151
  continue;
36418
37152
  for (const f of readdirSync2(dir)) {
36419
37153
  if (f.endsWith(".jsonl"))
36420
- files.push(join20(dir, f));
37154
+ files.push(join22(dir, f));
36421
37155
  }
36422
37156
  } catch {}
36423
37157
  }
36424
37158
  return files;
36425
37159
  }
36426
37160
  function buildCorpus(options = {}) {
36427
- const root = options.projectsRoot ?? join20(homedir20(), ".claude", "projects");
37161
+ const root = options.projectsRoot ?? join22(homedir22(), ".claude", "projects");
36428
37162
  const files = listTranscripts(root);
36429
37163
  const records = [];
36430
37164
  for (const f of files)
36431
37165
  records.push(...replayTranscript(f));
36432
37166
  if (options.write && records.length > 0) {
36433
- const outputPath = options.outputPath ?? join20(homedir20(), ".claudish", "behavior-divergences.jsonl");
37167
+ const outputPath = options.outputPath ?? join22(homedir22(), ".claudish", "behavior-divergences.jsonl");
36434
37168
  try {
36435
37169
  appendFileSync3(outputPath, `${records.map((r) => JSON.stringify(r)).join(`
36436
37170
  `)}
@@ -37205,25 +37939,25 @@ var init_model_parser = __esm(() => {
37205
37939
 
37206
37940
  // src/stats-buffer.ts
37207
37941
  import {
37208
- existsSync as existsSync14,
37209
- mkdirSync as mkdirSync8,
37210
- readFileSync as readFileSync13,
37211
- renameSync,
37212
- unlinkSync as unlinkSync4,
37213
- writeFileSync as writeFileSync7
37942
+ existsSync as existsSync16,
37943
+ mkdirSync as mkdirSync9,
37944
+ readFileSync as readFileSync15,
37945
+ renameSync as renameSync2,
37946
+ unlinkSync as unlinkSync5,
37947
+ writeFileSync as writeFileSync8
37214
37948
  } from "fs";
37215
- import { homedir as homedir21 } from "os";
37216
- import { join as join21 } from "path";
37949
+ import { homedir as homedir23 } from "os";
37950
+ import { join as join23 } from "path";
37217
37951
  function ensureDir() {
37218
- if (!existsSync14(CLAUDISH_DIR)) {
37219
- mkdirSync8(CLAUDISH_DIR, { recursive: true });
37952
+ if (!existsSync16(CLAUDISH_DIR)) {
37953
+ mkdirSync9(CLAUDISH_DIR, { recursive: true });
37220
37954
  }
37221
37955
  }
37222
37956
  function readFromDisk() {
37223
37957
  try {
37224
- if (!existsSync14(BUFFER_FILE))
37958
+ if (!existsSync16(BUFFER_FILE))
37225
37959
  return [];
37226
- const raw = readFileSync13(BUFFER_FILE, "utf-8");
37960
+ const raw = readFileSync15(BUFFER_FILE, "utf-8");
37227
37961
  const parsed = JSON.parse(raw);
37228
37962
  if (!Array.isArray(parsed.events))
37229
37963
  return [];
@@ -37248,9 +37982,9 @@ function writeToDisk(events) {
37248
37982
  ensureDir();
37249
37983
  const trimmed2 = enforceSizeCap([...events]);
37250
37984
  const payload = { version: 1, events: trimmed2 };
37251
- const tmpFile = join21(CLAUDISH_DIR, `stats-buffer.tmp.${process.pid}.json`);
37252
- writeFileSync7(tmpFile, JSON.stringify(payload, null, 2), "utf-8");
37253
- renameSync(tmpFile, BUFFER_FILE);
37985
+ const tmpFile = join23(CLAUDISH_DIR, `stats-buffer.tmp.${process.pid}.json`);
37986
+ writeFileSync8(tmpFile, JSON.stringify(payload, null, 2), "utf-8");
37987
+ renameSync2(tmpFile, BUFFER_FILE);
37254
37988
  memoryCache = trimmed2;
37255
37989
  } catch {}
37256
37990
  }
@@ -37292,8 +38026,8 @@ function clearBuffer() {
37292
38026
  try {
37293
38027
  memoryCache = [];
37294
38028
  eventsSinceLastFlush = 0;
37295
- if (existsSync14(BUFFER_FILE)) {
37296
- unlinkSync4(BUFFER_FILE);
38029
+ if (existsSync16(BUFFER_FILE)) {
38030
+ unlinkSync5(BUFFER_FILE);
37297
38031
  }
37298
38032
  } catch {}
37299
38033
  }
@@ -37321,8 +38055,8 @@ function syncFlushOnExit() {
37321
38055
  var BUFFER_MAX_BYTES, CLAUDISH_DIR, BUFFER_FILE, memoryCache = null, eventsSinceLastFlush = 0, flushScheduled = false;
37322
38056
  var init_stats_buffer = __esm(() => {
37323
38057
  BUFFER_MAX_BYTES = 64 * 1024;
37324
- CLAUDISH_DIR = join21(homedir21(), ".claudish");
37325
- BUFFER_FILE = join21(CLAUDISH_DIR, "stats-buffer.json");
38058
+ CLAUDISH_DIR = join23(homedir23(), ".claudish");
38059
+ BUFFER_FILE = join23(CLAUDISH_DIR, "stats-buffer.json");
37326
38060
  process.on("exit", syncFlushOnExit);
37327
38061
  process.on("SIGTERM", () => {
37328
38062
  try {
@@ -37459,7 +38193,7 @@ __export(exports_telemetry, {
37459
38193
  classifyError: () => classifyError,
37460
38194
  buildReport: () => buildReport
37461
38195
  });
37462
- import { randomBytes as randomBytes4 } from "crypto";
38196
+ import { randomBytes as randomBytes5 } from "crypto";
37463
38197
  function getVersion() {
37464
38198
  return VERSION;
37465
38199
  }
@@ -37727,7 +38461,7 @@ function initTelemetry(_config) {
37727
38461
  } catch {
37728
38462
  consentEnabled = false;
37729
38463
  }
37730
- sessionId = randomBytes4(8).toString("hex");
38464
+ sessionId = randomBytes5(8).toString("hex");
37731
38465
  claudishVersion = getVersion();
37732
38466
  installMethod = detectInstallMethod();
37733
38467
  }
@@ -38250,6 +38984,8 @@ function extractProviderMessage(body) {
38250
38984
  function isTerminalError(status, bodyText, terminal429) {
38251
38985
  if (status === 401 || status === 403)
38252
38986
  return true;
38987
+ if (status === 426)
38988
+ return true;
38253
38989
  if (status === 429 && terminal429)
38254
38990
  return true;
38255
38991
  const lower = (bodyText || "").toLowerCase();
@@ -40533,9 +41269,9 @@ var init_openai_responses_sse = __esm(() => {
40533
41269
  });
40534
41270
 
40535
41271
  // src/handlers/shared/token-tracker.ts
40536
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync8 } from "fs";
40537
- import { homedir as homedir22 } from "os";
40538
- import { dirname as dirname8, join as join22 } from "path";
41272
+ import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync9 } from "fs";
41273
+ import { homedir as homedir24 } from "os";
41274
+ import { dirname as dirname8, join as join24 } from "path";
40539
41275
  function stripProviderPrefix(name) {
40540
41276
  const at = name.indexOf("@");
40541
41277
  return at === -1 ? name : name.slice(at + 1);
@@ -40723,9 +41459,9 @@ class TokenTracker {
40723
41459
  };
40724
41460
  }
40725
41461
  const override = process.env.CLAUDISH_TOKEN_FILE;
40726
- const outPath = override || join22(homedir22(), ".claudish", `tokens-${this.port}.json`);
40727
- mkdirSync9(dirname8(outPath), { recursive: true });
40728
- writeFileSync8(outPath, JSON.stringify(data), "utf-8");
41462
+ const outPath = override || join24(homedir24(), ".claudish", `tokens-${this.port}.json`);
41463
+ mkdirSync10(dirname8(outPath), { recursive: true });
41464
+ writeFileSync9(outPath, JSON.stringify(data), "utf-8");
40729
41465
  } catch (e) {
40730
41466
  log(`[TokenTracker] Error writing token file: ${e}`);
40731
41467
  }
@@ -41136,7 +41872,8 @@ class ComposedHandler {
41136
41872
  } else {
41137
41873
  const errorText = await response.text();
41138
41874
  log(`[${this.provider.displayName}] Error: ${errorText}`);
41139
- const hint = getRecoveryHint(response.status, errorText, this.provider.displayName);
41875
+ const transportTerminal = this.provider.classifyTerminalError?.(response.status, errorText);
41876
+ const hint = getRecoveryHint(response.status, errorText, this.provider.displayName, transportTerminal);
41140
41877
  let parsedErrorBody;
41141
41878
  try {
41142
41879
  parsedErrorBody = JSON.parse(errorText);
@@ -41189,7 +41926,7 @@ class ComposedHandler {
41189
41926
  const errorBody = parsedErrorBody ?? {
41190
41927
  error: { type: "api_error", message: errorText }
41191
41928
  };
41192
- if (isTerminalError(response.status, errorText, isTerminal429(errorText))) {
41929
+ if (isTerminalError(response.status, errorText, transportTerminal ?? isTerminal429(errorText))) {
41193
41930
  const surfaced = buildSurfacedErrorMessage({
41194
41931
  providerDisplayName: this.provider.displayName,
41195
41932
  status: response.status,
@@ -41565,14 +42302,17 @@ class ComposedHandler {
41565
42302
  }
41566
42303
  }
41567
42304
  }
41568
- function getRecoveryHint(status, errorText, providerName) {
42305
+ function getRecoveryHint(status, errorText, providerName, transportTerminal429) {
41569
42306
  const lower = errorText.toLowerCase();
41570
42307
  if (status === 503 || lower.includes("overloaded")) {
41571
42308
  return "Provider overloaded. Retry or use a different model.";
41572
42309
  }
41573
- if (status === 429 && isTerminal429(errorText)) {
42310
+ if (status === 429 && (transportTerminal429 ?? isTerminal429(errorText))) {
41574
42311
  return "Out of quota \u2014 check your plan & billing details. This won't recover on retry.";
41575
42312
  }
42313
+ if (status === 429 && transportTerminal429 === false) {
42314
+ return "Rate limited. Wait, reduce concurrency, or check plan limits.";
42315
+ }
41576
42316
  if (isQuotaExhaustionError(status, errorText)) {
41577
42317
  return "Subscription allowance spent \u2014 this refills on the provider's own schedule (see the message below). Reducing concurrency won't help; switch model/provider or wait.";
41578
42318
  }
@@ -43979,7 +44719,7 @@ var init_default_routing_rules = __esm(() => {
43979
44719
  "o1-*": ["openai-codex", "openai", "openrouter"],
43980
44720
  "o3-*": ["openai-codex", "openai", "openrouter"],
43981
44721
  "gemini-*": ["antigravity", "google", "openrouter"],
43982
- "grok-*": ["x-ai", "openrouter"],
44722
+ "grok-*": ["grok-subscription", "x-ai", "openrouter"],
43983
44723
  "kimi-*": ["kimi-coding", "opencode-zen-go", "kimi", "openrouter"],
43984
44724
  "k3*": ["kimi-coding", "opencode-zen-go", "kimi", "openrouter"],
43985
44725
  "minimax-*": ["minimax-coding", "opencode-zen-go", "minimax", "openrouter"],
@@ -44902,9 +45642,9 @@ var CLAUDISH_BIN_ENV = "CLAUDISH_BIN";
44902
45642
  // src/channel/session-manager.ts
44903
45643
  import { spawn } from "child_process";
44904
45644
  import { randomUUID as randomUUID4 } from "crypto";
44905
- import { createWriteStream, mkdirSync as mkdirSync10, writeFileSync as writeFileSync9 } from "fs";
44906
- import { homedir as homedir23 } from "os";
44907
- import { join as join23 } from "path";
45645
+ import { createWriteStream, mkdirSync as mkdirSync11, writeFileSync as writeFileSync10 } from "fs";
45646
+ import { homedir as homedir25 } from "os";
45647
+ import { join as join25 } from "path";
44908
45648
 
44909
45649
  class SessionManager {
44910
45650
  sessions = new Map;
@@ -44916,7 +45656,7 @@ class SessionManager {
44916
45656
  constructor(options) {
44917
45657
  this.maxSessions = options?.maxSessions ?? DEFAULT_MAX_SESSIONS;
44918
45658
  this.scrollbackCapacity = options?.scrollbackCapacity ?? DEFAULT_SCROLLBACK;
44919
- this.sessionsDir = options?.sessionsDir ?? process.env.CLAUDISH_SESSIONS_DIR ?? join23(homedir23(), ".claudish", "sessions");
45659
+ this.sessionsDir = options?.sessionsDir ?? process.env.CLAUDISH_SESSIONS_DIR ?? join25(homedir25(), ".claudish", "sessions");
44920
45660
  this.onStateChange = options?.onStateChange;
44921
45661
  }
44922
45662
  createSession(opts) {
@@ -44926,10 +45666,10 @@ class SessionManager {
44926
45666
  const sessionId2 = randomUUID4().slice(0, 8);
44927
45667
  const timeout = Math.min(opts.timeoutSeconds ?? DEFAULT_TIMEOUT, MAX_TIMEOUT);
44928
45668
  const startedAt = new Date().toISOString();
44929
- const sessionDir = join23(this.sessionsDir, sessionId2);
44930
- mkdirSync10(sessionDir, { recursive: true });
45669
+ const sessionDir = join25(this.sessionsDir, sessionId2);
45670
+ mkdirSync11(sessionDir, { recursive: true });
44931
45671
  if (opts.prompt) {
44932
- writeFileSync9(join23(sessionDir, "prompt.md"), opts.prompt, "utf-8");
45672
+ writeFileSync10(join25(sessionDir, "prompt.md"), opts.prompt, "utf-8");
44933
45673
  }
44934
45674
  const args = [
44935
45675
  "--model",
@@ -44965,7 +45705,7 @@ class SessionManager {
44965
45705
  });
44966
45706
  }
44967
45707
  });
44968
- const outputLogStream = createWriteStream(join23(sessionDir, "output.log"));
45708
+ const outputLogStream = createWriteStream(join25(sessionDir, "output.log"));
44969
45709
  const entry = {
44970
45710
  info: {
44971
45711
  sessionId: sessionId2,
@@ -45012,9 +45752,9 @@ class SessionManager {
45012
45752
  watcher.processExited(code);
45013
45753
  outputLogStream.end();
45014
45754
  if (entry.stderr) {
45015
- writeFileSync9(join23(sessionDir, "stderr.log"), entry.stderr, "utf-8");
45755
+ writeFileSync10(join25(sessionDir, "stderr.log"), entry.stderr, "utf-8");
45016
45756
  }
45017
- writeFileSync9(join23(sessionDir, "meta.json"), JSON.stringify(entry.info, null, 2), "utf-8");
45757
+ writeFileSync10(join25(sessionDir, "meta.json"), JSON.stringify(entry.info, null, 2), "utf-8");
45018
45758
  this.cleanupSigint();
45019
45759
  });
45020
45760
  proc.on("error", (err) => {
@@ -45324,9 +46064,9 @@ function compareByReleaseDateDesc(a, b) {
45324
46064
  }
45325
46065
 
45326
46066
  // src/model-loader.ts
45327
- import { existsSync as existsSync15, mkdirSync as mkdirSync11, readFileSync as readFileSync14, writeFileSync as writeFileSync10 } from "fs";
45328
- import { homedir as homedir24 } from "os";
45329
- import { join as join24 } from "path";
46067
+ import { existsSync as existsSync17, mkdirSync as mkdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync11 } from "fs";
46068
+ import { homedir as homedir26 } from "os";
46069
+ import { join as join26 } from "path";
45330
46070
  function groupRecommendedModels(entries) {
45331
46071
  const byId = new Map;
45332
46072
  const categoryOrder = new Map;
@@ -45436,9 +46176,9 @@ async function getRecommendedModels(opts = {}) {
45436
46176
  if (!forceRefresh && _cachedRecommendedModels) {
45437
46177
  return _cachedRecommendedModels;
45438
46178
  }
45439
- if (!forceRefresh && existsSync15(RECOMMENDED_MODELS_CACHE_PATH)) {
46179
+ if (!forceRefresh && existsSync17(RECOMMENDED_MODELS_CACHE_PATH)) {
45440
46180
  try {
45441
- const cacheData = JSON.parse(readFileSync14(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
46181
+ const cacheData = JSON.parse(readFileSync16(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
45442
46182
  if (cacheData.models && cacheData.models.length > 0 && isFreshEnough(cacheData)) {
45443
46183
  _cachedRecommendedModels = cacheData;
45444
46184
  return cacheData;
@@ -45454,9 +46194,9 @@ async function getRecommendedModels(opts = {}) {
45454
46194
  if (data.models && data.models.length > 0) {
45455
46195
  _cachedRecommendedModels = data;
45456
46196
  try {
45457
- const cacheDir = join24(homedir24(), ".claudish");
45458
- mkdirSync11(cacheDir, { recursive: true });
45459
- writeFileSync10(RECOMMENDED_MODELS_CACHE_PATH, JSON.stringify(data), "utf-8");
46197
+ const cacheDir = join26(homedir26(), ".claudish");
46198
+ mkdirSync12(cacheDir, { recursive: true });
46199
+ writeFileSync11(RECOMMENDED_MODELS_CACHE_PATH, JSON.stringify(data), "utf-8");
45460
46200
  } catch {}
45461
46201
  return data;
45462
46202
  }
@@ -45467,9 +46207,9 @@ async function getRecommendedModels(opts = {}) {
45467
46207
  function getRecommendedModelsSync() {
45468
46208
  if (_cachedRecommendedModels)
45469
46209
  return _cachedRecommendedModels;
45470
- if (existsSync15(RECOMMENDED_MODELS_CACHE_PATH)) {
46210
+ if (existsSync17(RECOMMENDED_MODELS_CACHE_PATH)) {
45471
46211
  try {
45472
- const cacheData = JSON.parse(readFileSync14(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
46212
+ const cacheData = JSON.parse(readFileSync16(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
45473
46213
  if (cacheData.models && cacheData.models.length > 0 && isFreshEnough(cacheData)) {
45474
46214
  _cachedRecommendedModels = cacheData;
45475
46215
  return cacheData;
@@ -45593,7 +46333,7 @@ var _cachedModelInfo = null, _cachedModelIds = null, _cachedRecommendedModels =
45593
46333
  var init_model_loader = __esm(() => {
45594
46334
  init_cache_ttl();
45595
46335
  FIREBASE_RECOMMENDED_URL = `${FIREBASE_BASE_URL}?catalog=recommended`;
45596
- RECOMMENDED_MODELS_CACHE_PATH = join24(homedir24(), ".claudish", "recommended-models-cache.json");
46336
+ RECOMMENDED_MODELS_CACHE_PATH = join26(homedir26(), ".claudish", "recommended-models-cache.json");
45597
46337
  FIREBASE_SLUG_TO_PROVIDER_NAME = {
45598
46338
  openai: "openai",
45599
46339
  google: "google",
@@ -45812,11 +46552,11 @@ var splitPath = (path) => {
45812
46552
  return patternCache[cacheKey];
45813
46553
  }
45814
46554
  return null;
45815
- }, tryDecode = (str, decoder) => {
46555
+ }, tryDecode = (str2, decoder) => {
45816
46556
  try {
45817
- return decoder(str);
46557
+ return decoder(str2);
45818
46558
  } catch {
45819
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
46559
+ return str2.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
45820
46560
  try {
45821
46561
  return decoder(match);
45822
46562
  } catch {
@@ -45824,7 +46564,7 @@ var splitPath = (path) => {
45824
46564
  }
45825
46565
  });
45826
46566
  }
45827
- }, tryDecodeURI = (str) => tryDecode(str, decodeURI), getPath = (request) => {
46567
+ }, tryDecodeURI = (str2) => tryDecode(str2, decodeURI), getPath = (request) => {
45828
46568
  const url2 = request.url;
45829
46569
  const start = url2.indexOf("/", url2.indexOf(":") + 4);
45830
46570
  let i = start;
@@ -45953,7 +46693,7 @@ var init_url = __esm(() => {
45953
46693
  });
45954
46694
 
45955
46695
  // ../../node_modules/.bun/hono@4.10.6/node_modules/hono/dist/request.js
45956
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_), HonoRequest;
46696
+ var tryDecodeURIComponent = (str2) => tryDecode(str2, decodeURIComponent_), HonoRequest;
45957
46697
  var init_request = __esm(() => {
45958
46698
  init_http_exception();
45959
46699
  init_constants();
@@ -46075,25 +46815,25 @@ var HtmlEscapedCallbackPhase, raw = (value, callbacks) => {
46075
46815
  escapedString.isEscaped = true;
46076
46816
  escapedString.callbacks = callbacks;
46077
46817
  return escapedString;
46078
- }, resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
46079
- if (typeof str === "object" && !(str instanceof String)) {
46080
- if (!(str instanceof Promise)) {
46081
- str = str.toString();
46818
+ }, resolveCallback = async (str2, phase, preserveCallbacks, context, buffer) => {
46819
+ if (typeof str2 === "object" && !(str2 instanceof String)) {
46820
+ if (!(str2 instanceof Promise)) {
46821
+ str2 = str2.toString();
46082
46822
  }
46083
- if (str instanceof Promise) {
46084
- str = await str;
46823
+ if (str2 instanceof Promise) {
46824
+ str2 = await str2;
46085
46825
  }
46086
46826
  }
46087
- const callbacks = str.callbacks;
46827
+ const callbacks = str2.callbacks;
46088
46828
  if (!callbacks?.length) {
46089
- return Promise.resolve(str);
46829
+ return Promise.resolve(str2);
46090
46830
  }
46091
46831
  if (buffer) {
46092
- buffer[0] += str;
46832
+ buffer[0] += str2;
46093
46833
  } else {
46094
- buffer = [str];
46834
+ buffer = [str2];
46095
46835
  }
46096
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
46836
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str22) => resolveCallback(str22, phase, false, context, buffer))).then(() => buffer[0]));
46097
46837
  if (preserveCallbacks) {
46098
46838
  return raw(await resStr, callbacks);
46099
46839
  } else {
@@ -48758,11 +49498,11 @@ var init_ollama_api_format = __esm(() => {
48758
49498
  });
48759
49499
 
48760
49500
  // src/providers/api-key-provenance.ts
48761
- import { existsSync as existsSync16, readFileSync as readFileSync15 } from "fs";
48762
- import { homedir as homedir25 } from "os";
48763
- import { join as join25, resolve as resolve2 } from "path";
49501
+ import { existsSync as existsSync18, readFileSync as readFileSync17 } from "fs";
49502
+ import { homedir as homedir27 } from "os";
49503
+ import { join as join27, resolve as resolve2 } from "path";
48764
49504
  function activeConfigPath() {
48765
- return activeGlobalConfigFile(join25(homedir25(), ".claudish", "config.json"));
49505
+ return activeGlobalConfigFile(join27(homedir27(), ".claudish", "config.json"));
48766
49506
  }
48767
49507
  function configLayerLabel() {
48768
49508
  return getConfigFileOverride() ? activeConfigPath() : "~/.claudish/config.json";
@@ -48839,9 +49579,9 @@ function formatProvenanceLog(p) {
48839
49579
  function readDotenvKey(envVars) {
48840
49580
  try {
48841
49581
  const dotenvPath = resolve2(".env");
48842
- if (!existsSync16(dotenvPath))
49582
+ if (!existsSync18(dotenvPath))
48843
49583
  return null;
48844
- const parsed = import_dotenv.parse(readFileSync15(dotenvPath, "utf-8"));
49584
+ const parsed = import_dotenv.parse(readFileSync17(dotenvPath, "utf-8"));
48845
49585
  for (const v of envVars) {
48846
49586
  if (parsed[v])
48847
49587
  return parsed[v];
@@ -48854,9 +49594,9 @@ function readDotenvKey(envVars) {
48854
49594
  function readConfigKey(envVar) {
48855
49595
  try {
48856
49596
  const configPath = activeConfigPath();
48857
- if (!existsSync16(configPath))
49597
+ if (!existsSync18(configPath))
48858
49598
  return null;
48859
- const cfg = JSON.parse(readFileSync15(configPath, "utf-8"));
49599
+ const cfg = JSON.parse(readFileSync17(configPath, "utf-8"));
48860
49600
  return cfg.apiKeys?.[envVar] || null;
48861
49601
  } catch {
48862
49602
  return null;
@@ -49042,6 +49782,29 @@ var init_gemini_apikey = __esm(() => {
49042
49782
  init_gemini_queue();
49043
49783
  });
49044
49784
 
49785
+ // src/providers/transport/grok-subscription.ts
49786
+ var GrokSubscriptionProviderTransport;
49787
+ var init_grok_subscription = __esm(() => {
49788
+ init_authority();
49789
+ init_grok_credentials();
49790
+ init_openai();
49791
+ GrokSubscriptionProviderTransport = class GrokSubscriptionProviderTransport extends OpenAIProviderTransport {
49792
+ async getHeaders() {
49793
+ const auth = await credentials.getRequestAuth("grok-subscription", {
49794
+ model: this.modelName
49795
+ });
49796
+ const headers = { ...auth.headers };
49797
+ if (this.provider.headers) {
49798
+ Object.assign(headers, this.provider.headers);
49799
+ }
49800
+ return headers;
49801
+ }
49802
+ async forceRefreshAuth() {
49803
+ await forceRefreshGrokAccessToken();
49804
+ }
49805
+ };
49806
+ });
49807
+
49045
49808
  // src/providers/transport/ollamacloud.ts
49046
49809
  class OllamaProviderTransport {
49047
49810
  name = "ollamacloud";
@@ -49202,7 +49965,7 @@ function createHandlerForProvider(ctx) {
49202
49965
  log(`[Proxy] Handler: provider=${ctx.provider.name}, model=${ctx.modelName}`);
49203
49966
  return profile.createHandler(ctx);
49204
49967
  }
49205
- var geminiProfile, antigravityProfile, devinProfile, openaiProfile, openaiCodexProfile, anthropicCompatProfile, glmProfile, openCodeZenProfile, ollamaCloudProfile, litellmProfile, vertexProfile, PROVIDER_PROFILES;
49968
+ var geminiProfile, antigravityProfile, devinProfile, grokSubscriptionProfile, openaiProfile, openaiCodexProfile, anthropicCompatProfile, glmProfile, openCodeZenProfile, ollamaCloudProfile, litellmProfile, vertexProfile, PROVIDER_PROFILES;
49206
49969
  var init_provider_profiles = __esm(() => {
49207
49970
  init_anthropic_api_format();
49208
49971
  init_base_api_format();
@@ -49222,6 +49985,7 @@ var init_provider_profiles = __esm(() => {
49222
49985
  init_antigravity();
49223
49986
  init_devin2();
49224
49987
  init_gemini_apikey();
49988
+ init_grok_subscription();
49225
49989
  init_litellm();
49226
49990
  init_ollamacloud();
49227
49991
  init_openai_codex();
@@ -49265,6 +50029,19 @@ var init_provider_profiles = __esm(() => {
49265
50029
  return handler;
49266
50030
  }
49267
50031
  };
50032
+ grokSubscriptionProfile = {
50033
+ createHandler(ctx) {
50034
+ const transport = new GrokSubscriptionProviderTransport(ctx.provider, ctx.modelName, "");
50035
+ const adapter = new OpenAIAPIFormat(ctx.modelName);
50036
+ const handler = new ComposedHandler(transport, ctx.targetModel, ctx.modelName, ctx.port, {
50037
+ adapter,
50038
+ tokenStrategy: "delta-aware",
50039
+ ...ctx.sharedOpts
50040
+ });
50041
+ log(`[Proxy] Created Grok subscription handler (composed): ${ctx.modelName}`);
50042
+ return handler;
50043
+ }
50044
+ };
49268
50045
  openaiProfile = {
49269
50046
  createHandler(ctx) {
49270
50047
  if (requiresResponsesApi(ctx.modelName)) {
@@ -49437,6 +50214,7 @@ var init_provider_profiles = __esm(() => {
49437
50214
  openai: openaiProfile,
49438
50215
  "openai-codex": openaiCodexProfile,
49439
50216
  "x-ai": openaiProfile,
50217
+ "grok-subscription": grokSubscriptionProfile,
49440
50218
  qwen: openaiProfile,
49441
50219
  minimax: anthropicCompatProfile,
49442
50220
  "minimax-coding": anthropicCompatProfile,
@@ -50174,9 +50952,9 @@ var init_poe = __esm(() => {
50174
50952
  });
50175
50953
 
50176
50954
  // src/services/pricing-cache.ts
50177
- import { existsSync as existsSync17, readFileSync as readFileSync16, statSync as statSync4 } from "fs";
50178
- import { homedir as homedir26 } from "os";
50179
- import { join as join26 } from "path";
50955
+ import { existsSync as existsSync19, readFileSync as readFileSync18, statSync as statSync4 } from "fs";
50956
+ import { homedir as homedir28 } from "os";
50957
+ import { join as join28 } from "path";
50180
50958
  function prefixMatch(modelName) {
50181
50959
  for (const [key, pricing] of pricingMap) {
50182
50960
  if (modelName.startsWith(key))
@@ -50214,12 +50992,12 @@ async function warmPricingCache() {
50214
50992
  }
50215
50993
  function loadDiskCache() {
50216
50994
  try {
50217
- if (!existsSync17(CACHE_FILE))
50995
+ if (!existsSync19(CACHE_FILE))
50218
50996
  return false;
50219
50997
  const stat2 = statSync4(CACHE_FILE);
50220
50998
  const age = Date.now() - stat2.mtimeMs;
50221
50999
  const isFresh = age < CACHE_TTL_MS3;
50222
- const raw2 = readFileSync16(CACHE_FILE, "utf-8");
51000
+ const raw2 = readFileSync18(CACHE_FILE, "utf-8");
50223
51001
  const data = JSON.parse(raw2);
50224
51002
  for (const [key, pricing] of Object.entries(data)) {
50225
51003
  pricingMap.set(key, pricing);
@@ -50235,8 +51013,8 @@ var init_pricing_cache = __esm(() => {
50235
51013
  init_logger();
50236
51014
  init_catalog_query();
50237
51015
  pricingMap = new Map;
50238
- CACHE_DIR = join26(homedir26(), ".claudish");
50239
- CACHE_FILE = join26(CACHE_DIR, "pricing-cache.json");
51016
+ CACHE_DIR = join28(homedir28(), ".claudish");
51017
+ CACHE_FILE = join28(CACHE_DIR, "pricing-cache.json");
50240
51018
  CACHE_TTL_MS3 = 24 * 60 * 60 * 1000;
50241
51019
  });
50242
51020
 
@@ -50761,20 +51539,20 @@ var init_redact = __esm(() => {
50761
51539
  });
50762
51540
 
50763
51541
  // src/team-stats.ts
50764
- import { existsSync as existsSync18, readFileSync as readFileSync17, writeFileSync as writeFileSync11 } from "fs";
50765
- import { join as join27 } from "path";
51542
+ import { existsSync as existsSync20, readFileSync as readFileSync19, writeFileSync as writeFileSync12 } from "fs";
51543
+ import { join as join29 } from "path";
50766
51544
  function statsDir(sessionPath) {
50767
- return join27(sessionPath, "stats");
51545
+ return join29(sessionPath, "stats");
50768
51546
  }
50769
51547
  function tokenFileFor(sessionPath, anonId) {
50770
- return join27(statsDir(sessionPath), `${anonId}.json`);
51548
+ return join29(statsDir(sessionPath), `${anonId}.json`);
50771
51549
  }
50772
51550
  function readTokenStats(sessionPath, anonId) {
50773
51551
  const path = tokenFileFor(sessionPath, anonId);
50774
- if (!existsSync18(path))
51552
+ if (!existsSync20(path))
50775
51553
  return null;
50776
51554
  try {
50777
- return JSON.parse(readFileSync17(path, "utf-8"));
51555
+ return JSON.parse(readFileSync19(path, "utf-8"));
50778
51556
  } catch {
50779
51557
  return null;
50780
51558
  }
@@ -50922,7 +51700,7 @@ ${segs.join(" \xB7 ")}`;
50922
51700
  }
50923
51701
  function writeStatusFile(sessionPath, manifest, status, opts) {
50924
51702
  try {
50925
- writeFileSync11(join27(sessionPath, "status.txt"), `${renderTeamStats(sessionPath, manifest, status, opts)}
51703
+ writeFileSync12(join29(sessionPath, "status.txt"), `${renderTeamStats(sessionPath, manifest, status, opts)}
50926
51704
  `, "utf-8");
50927
51705
  } catch {}
50928
51706
  }
@@ -51073,13 +51851,13 @@ __export(exports_team_orchestrator, {
51073
51851
  import { spawn as spawn2 } from "child_process";
51074
51852
  import {
51075
51853
  createWriteStream as createWriteStream2,
51076
- existsSync as existsSync19,
51077
- mkdirSync as mkdirSync12,
51078
- readFileSync as readFileSync18,
51854
+ existsSync as existsSync21,
51855
+ mkdirSync as mkdirSync13,
51856
+ readFileSync as readFileSync20,
51079
51857
  readdirSync as readdirSync3,
51080
- writeFileSync as writeFileSync12
51858
+ writeFileSync as writeFileSync13
51081
51859
  } from "fs";
51082
- import { join as join28, resolve as resolve3 } from "path";
51860
+ import { join as join30, resolve as resolve3 } from "path";
51083
51861
  function resolveCaptureMode(explicit, env = process.env) {
51084
51862
  if (explicit)
51085
51863
  return explicit;
@@ -51152,7 +51930,7 @@ function persistErrorLog(errorLogPath, header, stderr, stdoutTail) {
51152
51930
  parts.push("--- stderr ---", stderr.trim() ? redactSecrets(stderr) : "(empty)", "");
51153
51931
  parts.push("--- stdout (tail) ---", stdoutTail.trim() ? redactSecrets(stdoutTail) : "(empty)", "");
51154
51932
  try {
51155
- writeFileSync12(errorLogPath, parts.join(`
51933
+ writeFileSync13(errorLogPath, parts.join(`
51156
51934
  `), "utf-8");
51157
51935
  } catch {}
51158
51936
  }
@@ -51176,18 +51954,18 @@ function setupSession(sessionPath, models, input) {
51176
51954
  if (models.length === 0) {
51177
51955
  throw new Error("At least one model is required");
51178
51956
  }
51179
- if (existsSync19(join28(sessionPath, "manifest.json"))) {
51957
+ if (existsSync21(join30(sessionPath, "manifest.json"))) {
51180
51958
  throw new Error(`Session already exists at ${sessionPath}. Use a new directory path or delete the existing session first.`);
51181
51959
  }
51182
51960
  const sentinels = models.filter(isSentinelModel);
51183
51961
  if (sentinels.length > 0) {
51184
51962
  throw new Error(`Invalid model(s) for team run: ${sentinels.join(", ")}. These are Claude Code agent selectors, not external model IDs. Use real external models (e.g., "gemini-2.0-flash", "gpt-4o", "or@deepseek/deepseek-r1"). For Claude models, use a Task agent instead of the team tool.`);
51185
51963
  }
51186
- mkdirSync12(join28(sessionPath, "work"), { recursive: true });
51187
- mkdirSync12(join28(sessionPath, "errors"), { recursive: true });
51964
+ mkdirSync13(join30(sessionPath, "work"), { recursive: true });
51965
+ mkdirSync13(join30(sessionPath, "errors"), { recursive: true });
51188
51966
  if (input !== undefined) {
51189
- writeFileSync12(join28(sessionPath, "input.md"), input, "utf-8");
51190
- } else if (!existsSync19(join28(sessionPath, "input.md"))) {
51967
+ writeFileSync13(join30(sessionPath, "input.md"), input, "utf-8");
51968
+ } else if (!existsSync21(join30(sessionPath, "input.md"))) {
51191
51969
  throw new Error(`No input.md found at ${sessionPath} and no input provided`);
51192
51970
  }
51193
51971
  const ids = models.map((_, i) => String(i + 1).padStart(2, "0"));
@@ -51204,9 +51982,9 @@ function setupSession(sessionPath, models, input) {
51204
51982
  model: models[i],
51205
51983
  assignedAt: now
51206
51984
  };
51207
- mkdirSync12(join28(sessionPath, "work", anonId), { recursive: true });
51985
+ mkdirSync13(join30(sessionPath, "work", anonId), { recursive: true });
51208
51986
  }
51209
- writeFileSync12(join28(sessionPath, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
51987
+ writeFileSync13(join30(sessionPath, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
51210
51988
  const status = {
51211
51989
  startedAt: now,
51212
51990
  models: Object.fromEntries(Object.keys(manifest.models).map((id) => [
@@ -51220,7 +51998,7 @@ function setupSession(sessionPath, models, input) {
51220
51998
  }
51221
51999
  ]))
51222
52000
  };
51223
- writeFileSync12(join28(sessionPath, "status.json"), JSON.stringify(status, null, 2), "utf-8");
52001
+ writeFileSync13(join30(sessionPath, "status.json"), JSON.stringify(status, null, 2), "utf-8");
51224
52002
  return manifest;
51225
52003
  }
51226
52004
  function assertValidRequirePattern(pattern) {
@@ -51237,7 +52015,7 @@ function readFullOutputIfNeeded(opts) {
51237
52015
  if (crashed || !requirePattern || outputSize <= STDOUT_TAIL_LIMIT)
51238
52016
  return;
51239
52017
  try {
51240
- return readFileSync18(outputPath, "utf-8");
52018
+ return readFileSync20(outputPath, "utf-8");
51241
52019
  } catch {
51242
52020
  return;
51243
52021
  }
@@ -51245,15 +52023,15 @@ function readFullOutputIfNeeded(opts) {
51245
52023
  async function runModels(sessionPath, opts = {}) {
51246
52024
  const timeoutMs = (opts.timeout ?? 300) * 1000;
51247
52025
  assertValidRequirePattern(opts.requirePattern);
51248
- const manifest = JSON.parse(readFileSync18(join28(sessionPath, "manifest.json"), "utf-8"));
51249
- const statusPath = join28(sessionPath, "status.json");
51250
- const inputPath = join28(sessionPath, "input.md");
51251
- const inputContent = readFileSync18(inputPath, "utf-8");
52026
+ const manifest = JSON.parse(readFileSync20(join30(sessionPath, "manifest.json"), "utf-8"));
52027
+ const statusPath = join30(sessionPath, "status.json");
52028
+ const inputPath = join30(sessionPath, "input.md");
52029
+ const inputContent = readFileSync20(inputPath, "utf-8");
51252
52030
  const spawnPlan = await (opts.spawnPlanner ?? prehydrateCredentialsForSpawn)(Object.values(manifest.models).map((m) => m.model));
51253
- const statusCache = JSON.parse(readFileSync18(statusPath, "utf-8"));
52031
+ const statusCache = JSON.parse(readFileSync20(statusPath, "utf-8"));
51254
52032
  function updateModelStatus(id, update) {
51255
52033
  statusCache.models[id] = { ...statusCache.models[id], ...update };
51256
- writeFileSync12(statusPath, JSON.stringify(statusCache, null, 2), "utf-8");
52034
+ writeFileSync13(statusPath, JSON.stringify(statusCache, null, 2), "utf-8");
51257
52035
  }
51258
52036
  const minOutputBytes = opts.minOutputBytes ?? DEFAULT_MIN_OUTPUT_BYTES;
51259
52037
  const requirePattern = opts.requirePattern;
@@ -51286,7 +52064,7 @@ async function runModels(sessionPath, opts = {}) {
51286
52064
  persistErrorLog(rt.errorLogPath, `RECOVERED: ${note}`, stderr, stdoutTail);
51287
52065
  opts.onStatusChange?.(id, statusCache.models[id]);
51288
52066
  }
51289
- mkdirSync12(statsDir(sessionPath), { recursive: true });
52067
+ mkdirSync13(statsDir(sessionPath), { recursive: true });
51290
52068
  const processes = new Map;
51291
52069
  const runtimes = new Map;
51292
52070
  const sigintHandler = () => {
@@ -51298,8 +52076,8 @@ async function runModels(sessionPath, opts = {}) {
51298
52076
  process.on("SIGINT", sigintHandler);
51299
52077
  const completionPromises = [];
51300
52078
  for (const [anonId, entry] of Object.entries(manifest.models)) {
51301
- const outputPath = join28(sessionPath, `response-${anonId}.md`);
51302
- const errorLogPath = join28(sessionPath, "errors", `${anonId}.log`);
52079
+ const outputPath = join30(sessionPath, `response-${anonId}.md`);
52080
+ const errorLogPath = join30(sessionPath, "errors", `${anonId}.log`);
51303
52081
  const spawnModel = spawnPlan.pinned.get(entry.model) ?? entry.model;
51304
52082
  const args = [
51305
52083
  "--model",
@@ -51438,7 +52216,7 @@ async function runModels(sessionPath, opts = {}) {
51438
52216
  proc.on("exit", (code) => {
51439
52217
  const timedOut = statusCache.models[anonId]?.state === "TIMEOUT";
51440
52218
  if (!timedOut && meaningfulStderr(stderr)) {
51441
- writeFileSync12(errorLogPath, redactSecrets(stderr), "utf-8");
52219
+ writeFileSync13(errorLogPath, redactSecrets(stderr), "utf-8");
51442
52220
  }
51443
52221
  exitCode = code;
51444
52222
  if (outputStream.destroyed) {
@@ -51525,7 +52303,7 @@ async function runModels(sessionPath, opts = {}) {
51525
52303
  opts.onStatusChange?.(id, statusCache.models[id]);
51526
52304
  const stopped = await terminateChildTree(proc);
51527
52305
  if (!stopped) {
51528
- persistErrorLog(rt?.errorLogPath ?? join28(sessionPath, "errors", `${id}.log`), "TIMEOUT: child survived SIGKILL \u2014 it may still be running and billing", stderr, stdoutTail);
52306
+ persistErrorLog(rt?.errorLogPath ?? join30(sessionPath, "errors", `${id}.log`), "TIMEOUT: child survived SIGKILL \u2014 it may still be running and billing", stderr, stdoutTail);
51529
52307
  }
51530
52308
  };
51531
52309
  const allDone = Promise.all(completionPromises);
@@ -51584,23 +52362,23 @@ async function judgeResponses(sessionPath, opts = {}) {
51584
52362
  const responses = {};
51585
52363
  for (const file2 of responseFiles) {
51586
52364
  const id = file2.replace(/^response-/, "").replace(/\.md$/, "");
51587
- responses[id] = readFileSync18(join28(sessionPath, file2), "utf-8");
52365
+ responses[id] = readFileSync20(join30(sessionPath, file2), "utf-8");
51588
52366
  }
51589
- const input = readFileSync18(join28(sessionPath, "input.md"), "utf-8");
52367
+ const input = readFileSync20(join30(sessionPath, "input.md"), "utf-8");
51590
52368
  const judgePrompt = buildJudgePrompt(input, responses);
51591
- writeFileSync12(join28(sessionPath, "judge-prompt.md"), judgePrompt, "utf-8");
52369
+ writeFileSync13(join30(sessionPath, "judge-prompt.md"), judgePrompt, "utf-8");
51592
52370
  const judgeModels = opts.judges ?? getDefaultJudgeModels(sessionPath);
51593
- const judgePath = join28(sessionPath, "judging");
51594
- mkdirSync12(judgePath, { recursive: true });
52371
+ const judgePath = join30(sessionPath, "judging");
52372
+ mkdirSync13(judgePath, { recursive: true });
51595
52373
  setupSession(judgePath, judgeModels, judgePrompt);
51596
52374
  await runModels(judgePath, { claudeFlags: opts.claudeFlags });
51597
52375
  const votes = parseJudgeVotes(judgePath, Object.keys(responses));
51598
52376
  const verdict = aggregateVerdict(votes, Object.keys(responses));
51599
- writeFileSync12(join28(sessionPath, "verdict.md"), formatVerdict(verdict, sessionPath), "utf-8");
52377
+ writeFileSync13(join30(sessionPath, "verdict.md"), formatVerdict(verdict, sessionPath), "utf-8");
51600
52378
  return verdict;
51601
52379
  }
51602
52380
  function getStatus(sessionPath) {
51603
- return JSON.parse(readFileSync18(join28(sessionPath, "status.json"), "utf-8"));
52381
+ return JSON.parse(readFileSync20(join30(sessionPath, "status.json"), "utf-8"));
51604
52382
  }
51605
52383
  function fisherYatesShuffle(arr) {
51606
52384
  for (let i = arr.length - 1;i > 0; i--) {
@@ -51610,7 +52388,7 @@ function fisherYatesShuffle(arr) {
51610
52388
  return arr;
51611
52389
  }
51612
52390
  function getDefaultJudgeModels(sessionPath) {
51613
- const manifest = JSON.parse(readFileSync18(join28(sessionPath, "manifest.json"), "utf-8"));
52391
+ const manifest = JSON.parse(readFileSync20(join30(sessionPath, "manifest.json"), "utf-8"));
51614
52392
  return Object.values(manifest.models).map((e) => e.model);
51615
52393
  }
51616
52394
  function buildJudgePrompt(input, responses) {
@@ -51673,7 +52451,7 @@ function parseJudgeVotes(judgePath, responseIds) {
51673
52451
  const judgeId = file2.replace(/^response-/, "").replace(/\.md$/, "");
51674
52452
  let content;
51675
52453
  try {
51676
- content = readFileSync18(join28(judgePath, file2), "utf-8");
52454
+ content = readFileSync20(join30(judgePath, file2), "utf-8");
51677
52455
  } catch {
51678
52456
  continue;
51679
52457
  }
@@ -51725,7 +52503,7 @@ function aggregateVerdict(votes, responseIds) {
51725
52503
  function formatVerdict(verdict, sessionPath) {
51726
52504
  let manifest = null;
51727
52505
  try {
51728
- manifest = JSON.parse(readFileSync18(join28(sessionPath, "manifest.json"), "utf-8"));
52506
+ manifest = JSON.parse(readFileSync20(join30(sessionPath, "manifest.json"), "utf-8"));
51729
52507
  } catch {}
51730
52508
  let output = `# Team Verdict
51731
52509
 
@@ -51786,14 +52564,14 @@ __export(exports_mcp_server, {
51786
52564
  parseAnthropicSse: () => parseAnthropicSse,
51787
52565
  formatTeamResult: () => formatTeamResult
51788
52566
  });
51789
- import { existsSync as existsSync20, mkdirSync as mkdirSync13, readFileSync as readFileSync19, readdirSync as readdirSync4, writeFileSync as writeFileSync13 } from "fs";
51790
- import { homedir as homedir27 } from "os";
51791
- import { dirname as dirname9, join as join29, resolve as resolve4 } from "path";
52567
+ import { existsSync as existsSync22, mkdirSync as mkdirSync14, readFileSync as readFileSync21, readdirSync as readdirSync4, writeFileSync as writeFileSync14 } from "fs";
52568
+ import { homedir as homedir29 } from "os";
52569
+ import { dirname as dirname9, join as join31, resolve as resolve4 } from "path";
51792
52570
  import { fileURLToPath } from "url";
51793
52571
  async function loadAllModels(forceRefresh = false) {
51794
- if (!forceRefresh && existsSync20(ALL_MODELS_CACHE_PATH2)) {
52572
+ if (!forceRefresh && existsSync22(ALL_MODELS_CACHE_PATH2)) {
51795
52573
  try {
51796
- const cacheData = JSON.parse(readFileSync19(ALL_MODELS_CACHE_PATH2, "utf-8"));
52574
+ const cacheData = JSON.parse(readFileSync21(ALL_MODELS_CACHE_PATH2, "utf-8"));
51797
52575
  const lastUpdated = new Date(cacheData.lastUpdated);
51798
52576
  const ageInDays = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60 * 24);
51799
52577
  if (ageInDays <= CACHE_MAX_AGE_DAYS) {
@@ -51807,12 +52585,12 @@ async function loadAllModels(forceRefresh = false) {
51807
52585
  throw new Error(`API returned ${response.status}`);
51808
52586
  const data = await response.json();
51809
52587
  const models = data.data || [];
51810
- mkdirSync13(CLAUDISH_CACHE_DIR, { recursive: true });
51811
- writeFileSync13(ALL_MODELS_CACHE_PATH2, JSON.stringify({ lastUpdated: new Date().toISOString(), models }), "utf-8");
52588
+ mkdirSync14(CLAUDISH_CACHE_DIR, { recursive: true });
52589
+ writeFileSync14(ALL_MODELS_CACHE_PATH2, JSON.stringify({ lastUpdated: new Date().toISOString(), models }), "utf-8");
51812
52590
  return models;
51813
52591
  } catch {
51814
- if (existsSync20(ALL_MODELS_CACHE_PATH2)) {
51815
- const cacheData = JSON.parse(readFileSync19(ALL_MODELS_CACHE_PATH2, "utf-8"));
52592
+ if (existsSync22(ALL_MODELS_CACHE_PATH2)) {
52593
+ const cacheData = JSON.parse(readFileSync21(ALL_MODELS_CACHE_PATH2, "utf-8"));
51816
52594
  return cacheData.models || [];
51817
52595
  }
51818
52596
  return [];
@@ -52413,7 +53191,7 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
52413
53191
  let stderrFull = stderr_snippet || "";
52414
53192
  if (error_log_path) {
52415
53193
  try {
52416
- stderrFull = readFileSync19(error_log_path, "utf-8");
53194
+ stderrFull = readFileSync21(error_log_path, "utf-8");
52417
53195
  } catch {}
52418
53196
  }
52419
53197
  const sessionData = {};
@@ -52421,16 +53199,16 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
52421
53199
  const sp = session_path;
52422
53200
  for (const file2 of ["status.json", "manifest.json", "input.md"]) {
52423
53201
  try {
52424
- sessionData[file2] = readFileSync19(join29(sp, file2), "utf-8");
53202
+ sessionData[file2] = readFileSync21(join31(sp, file2), "utf-8");
52425
53203
  } catch {}
52426
53204
  }
52427
53205
  try {
52428
- const errorDir = join29(sp, "errors");
52429
- if (existsSync20(errorDir)) {
53206
+ const errorDir = join31(sp, "errors");
53207
+ if (existsSync22(errorDir)) {
52430
53208
  for (const f of readdirSync4(errorDir)) {
52431
53209
  if (f.endsWith(".log")) {
52432
53210
  try {
52433
- sessionData[`errors/${f}`] = readFileSync19(join29(errorDir, f), "utf-8");
53211
+ sessionData[`errors/${f}`] = readFileSync21(join31(errorDir, f), "utf-8");
52434
53212
  } catch {}
52435
53213
  }
52436
53214
  }
@@ -52440,7 +53218,7 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
52440
53218
  for (const f of readdirSync4(sp)) {
52441
53219
  if (f.startsWith("response-") && f.endsWith(".md")) {
52442
53220
  try {
52443
- const content = readFileSync19(join29(sp, f), "utf-8");
53221
+ const content = readFileSync21(join31(sp, f), "utf-8");
52444
53222
  sessionData[f] = content.slice(0, 200) + (content.length > 200 ? "... (truncated)" : "");
52445
53223
  } catch {}
52446
53224
  }
@@ -52449,9 +53227,9 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
52449
53227
  }
52450
53228
  let version2 = "unknown";
52451
53229
  try {
52452
- const pkgPath = join29(__dirname2, "../package.json");
52453
- if (existsSync20(pkgPath)) {
52454
- version2 = JSON.parse(readFileSync19(pkgPath, "utf-8")).version;
53230
+ const pkgPath = join31(__dirname2, "../package.json");
53231
+ if (existsSync22(pkgPath)) {
53232
+ version2 = JSON.parse(readFileSync21(pkgPath, "utf-8")).version;
52455
53233
  }
52456
53234
  } catch {}
52457
53235
  const report = {
@@ -52866,8 +53644,8 @@ var init_mcp_server = __esm(() => {
52866
53644
  import_dotenv2.config({ quiet: true });
52867
53645
  __filename2 = fileURLToPath(import.meta.url);
52868
53646
  __dirname2 = dirname9(__filename2);
52869
- CLAUDISH_CACHE_DIR = join29(homedir27(), ".claudish");
52870
- ALL_MODELS_CACHE_PATH2 = join29(CLAUDISH_CACHE_DIR, "all-models.json");
53647
+ CLAUDISH_CACHE_DIR = join31(homedir29(), ".claudish");
53648
+ ALL_MODELS_CACHE_PATH2 = join31(CLAUDISH_CACHE_DIR, "all-models.json");
52871
53649
  NEXT_STEP = {
52872
53650
  nonzero_exit: "read the evidence log, then retry or drop the model",
52873
53651
  timeout: "raise `timeout`, or pick a faster model",
@@ -52893,7 +53671,7 @@ var exports_serve_command = {};
52893
53671
  __export(exports_serve_command, {
52894
53672
  serveCommand: () => serveCommand
52895
53673
  });
52896
- import { existsSync as existsSync21, readFileSync as readFileSync20 } from "fs";
53674
+ import { existsSync as existsSync23, readFileSync as readFileSync22 } from "fs";
52897
53675
  function parseServeArgs(args) {
52898
53676
  const out = {};
52899
53677
  for (let i = 0;i < args.length; i++) {
@@ -52912,12 +53690,12 @@ function parseServeArgs(args) {
52912
53690
  return out;
52913
53691
  }
52914
53692
  function loadModelMap(path) {
52915
- if (!existsSync21(path)) {
53693
+ if (!existsSync23(path)) {
52916
53694
  throw new Error(`--models file not found: ${path}`);
52917
53695
  }
52918
53696
  let raw2;
52919
53697
  try {
52920
- raw2 = readFileSync20(path, "utf-8");
53698
+ raw2 = readFileSync22(path, "utf-8");
52921
53699
  } catch (e) {
52922
53700
  throw new Error(`failed to read --models file ${path}: ${e instanceof Error ? e.message : String(e)}`);
52923
53701
  }
@@ -52996,7 +53774,7 @@ var exports_behavior_command = {};
52996
53774
  __export(exports_behavior_command, {
52997
53775
  behaviorCommand: () => behaviorCommand
52998
53776
  });
52999
- import { existsSync as existsSync22, readFileSync as readFileSync21, writeFileSync as writeFileSync14 } from "fs";
53777
+ import { existsSync as existsSync24, readFileSync as readFileSync23, writeFileSync as writeFileSync15 } from "fs";
53000
53778
  function severityColor(sev) {
53001
53779
  if (sev === "fix")
53002
53780
  return green(sev);
@@ -53094,8 +53872,8 @@ function setTelemetryEnabled(value) {
53094
53872
  const path = getConfigPath();
53095
53873
  let cfg = {};
53096
53874
  try {
53097
- if (existsSync22(path)) {
53098
- const parsed = JSON.parse(readFileSync21(path, "utf-8"));
53875
+ if (existsSync24(path)) {
53876
+ const parsed = JSON.parse(readFileSync23(path, "utf-8"));
53099
53877
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
53100
53878
  cfg = parsed;
53101
53879
  }
@@ -53104,7 +53882,7 @@ function setTelemetryEnabled(value) {
53104
53882
  const behavior = cfg.behavior && typeof cfg.behavior === "object" && !Array.isArray(cfg.behavior) ? { ...cfg.behavior } : {};
53105
53883
  behavior.telemetry = { enabled: value };
53106
53884
  cfg.behavior = behavior;
53107
- writeFileSync14(path, `${JSON.stringify(cfg, null, 2)}
53885
+ writeFileSync15(path, `${JSON.stringify(cfg, null, 2)}
53108
53886
  `, "utf-8");
53109
53887
  }
53110
53888
  function showTelemetry(action, json2) {
@@ -53116,8 +53894,8 @@ function showTelemetry(action, json2) {
53116
53894
  let pending = 0;
53117
53895
  try {
53118
53896
  const path = outboxPath();
53119
- if (existsSync22(path)) {
53120
- pending = readFileSync21(path, "utf8").split(`
53897
+ if (existsSync24(path)) {
53898
+ pending = readFileSync23(path, "utf8").split(`
53121
53899
  `).filter(Boolean).length;
53122
53900
  }
53123
53901
  } catch {}
@@ -53189,9 +53967,9 @@ __export(exports_team_grid, {
53189
53967
  });
53190
53968
  import { spawn as spawn3 } from "child_process";
53191
53969
  import { execSync } from "child_process";
53192
- import { existsSync as existsSync23, readFileSync as readFileSync22, writeFileSync as writeFileSync15 } from "fs";
53970
+ import { existsSync as existsSync25, readFileSync as readFileSync24, writeFileSync as writeFileSync16 } from "fs";
53193
53971
  import { connect as netConnect } from "net";
53194
- import { dirname as dirname10, join as join30 } from "path";
53972
+ import { dirname as dirname10, join as join32 } from "path";
53195
53973
  import { setTimeout as wait } from "timers/promises";
53196
53974
  import { fileURLToPath as fileURLToPath2 } from "url";
53197
53975
  function resolveRouteInfo(modelId) {
@@ -53285,18 +54063,18 @@ function buildPaneHeader(model, prompt, bg) {
53285
54063
  function findMagmuxBinary() {
53286
54064
  const thisFile = fileURLToPath2(import.meta.url);
53287
54065
  const thisDir = dirname10(thisFile);
53288
- const pkgRoot = join30(thisDir, "..");
54066
+ const pkgRoot = join32(thisDir, "..");
53289
54067
  const platform2 = process.platform;
53290
54068
  const arch = process.arch;
53291
- const bundledMagmux = join30(pkgRoot, "native", `magmux-${platform2}-${arch}`);
53292
- if (existsSync23(bundledMagmux))
54069
+ const bundledMagmux = join32(pkgRoot, "native", `magmux-${platform2}-${arch}`);
54070
+ if (existsSync25(bundledMagmux))
53293
54071
  return bundledMagmux;
53294
54072
  try {
53295
54073
  const pkgName = `@claudish/magmux-${platform2}-${arch}`;
53296
54074
  let searchDir = pkgRoot;
53297
54075
  for (let i = 0;i < 5; i++) {
53298
- const candidate = join30(searchDir, "node_modules", pkgName, "bin", "magmux");
53299
- if (existsSync23(candidate))
54076
+ const candidate = join32(searchDir, "node_modules", pkgName, "bin", "magmux");
54077
+ if (existsSync25(candidate))
53300
54078
  return candidate;
53301
54079
  const parent = dirname10(searchDir);
53302
54080
  if (parent === searchDir)
@@ -53320,7 +54098,7 @@ function withoutControlPanes(evt) {
53320
54098
  async function subscribeToMagmux(sockPath, onEvent) {
53321
54099
  let client = null;
53322
54100
  for (let attempt = 0;attempt < 40; attempt++) {
53323
- if (existsSync23(sockPath)) {
54101
+ if (existsSync25(sockPath)) {
53324
54102
  try {
53325
54103
  client = await new Promise((resolve5, reject) => {
53326
54104
  const s = netConnect(sockPath);
@@ -53407,9 +54185,9 @@ async function runWithGrid(sessionPath, models, input, opts) {
53407
54185
  const keep = opts?.keep ?? false;
53408
54186
  const manifest = setupSession(sessionPath, models, input);
53409
54187
  const startedAt = new Date().toISOString();
53410
- const gridfilePath = join30(sessionPath, "gridfile.txt");
53411
- const prompt = readFileSync22(join30(sessionPath, "input.md"), "utf-8").replace(/'/g, "'\\''").replace(/\n/g, " ");
53412
- const rawPrompt = readFileSync22(join30(sessionPath, "input.md"), "utf-8");
54188
+ const gridfilePath = join32(sessionPath, "gridfile.txt");
54189
+ const prompt = readFileSync24(join32(sessionPath, "input.md"), "utf-8").replace(/'/g, "'\\''").replace(/\n/g, " ");
54190
+ const rawPrompt = readFileSync24(join32(sessionPath, "input.md"), "utf-8");
53413
54191
  const usedBannerColors = new Set;
53414
54192
  const gridLines = Object.entries(manifest.models).map(([anonId]) => {
53415
54193
  const model = manifest.models[anonId].model;
@@ -53420,7 +54198,7 @@ async function runWithGrid(sessionPath, models, input, opts) {
53420
54198
  const header = buildPaneHeader(model, rawPrompt, bg);
53421
54199
  return `${header} claudish --model ${model} -y --quiet '${prompt}'`;
53422
54200
  });
53423
- writeFileSync15(gridfilePath, `${gridLines.join(`
54201
+ writeFileSync16(gridfilePath, `${gridLines.join(`
53424
54202
  `)}
53425
54203
  `, "utf-8");
53426
54204
  const magmuxPath = findMagmuxBinary();
@@ -53440,8 +54218,8 @@ async function runWithGrid(sessionPath, models, input, opts) {
53440
54218
  });
53441
54219
  const [{ results }] = await Promise.all([subscription, procExit]);
53442
54220
  const status = buildTeamStatus(manifest, startedAt, results?.panes ?? null);
53443
- const statusPath = join30(sessionPath, "status.json");
53444
- writeFileSync15(statusPath, JSON.stringify(status, null, 2), "utf-8");
54221
+ const statusPath = join32(sessionPath, "status.json");
54222
+ writeFileSync16(statusPath, JSON.stringify(status, null, 2), "utf-8");
53445
54223
  return status;
53446
54224
  }
53447
54225
  var BANNER_BG_COLORS;
@@ -53465,8 +54243,8 @@ var exports_team_cli = {};
53465
54243
  __export(exports_team_cli, {
53466
54244
  teamCommand: () => teamCommand
53467
54245
  });
53468
- import { readFileSync as readFileSync23 } from "fs";
53469
- import { join as join31 } from "path";
54246
+ import { readFileSync as readFileSync25 } from "fs";
54247
+ import { join as join33 } from "path";
53470
54248
  function getFlag(args, flag) {
53471
54249
  const idx = args.indexOf(flag);
53472
54250
  if (idx === -1 || idx + 1 >= args.length)
@@ -53589,7 +54367,7 @@ async function teamCommand(args) {
53589
54367
  }
53590
54368
  case "judge": {
53591
54369
  await judgeResponses(sessionPath, { judges });
53592
- console.log(readFileSync23(join31(sessionPath, "verdict.md"), "utf-8"));
54370
+ console.log(readFileSync25(join33(sessionPath, "verdict.md"), "utf-8"));
53593
54371
  break;
53594
54372
  }
53595
54373
  case "run-and-judge": {
@@ -53607,7 +54385,7 @@ async function teamCommand(args) {
53607
54385
  });
53608
54386
  printStatus(status);
53609
54387
  await judgeResponses(sessionPath, { judges });
53610
- console.log(readFileSync23(join31(sessionPath, "verdict.md"), "utf-8"));
54388
+ console.log(readFileSync25(join33(sessionPath, "verdict.md"), "utf-8"));
53611
54389
  break;
53612
54390
  }
53613
54391
  case "status": {
@@ -54699,7 +55477,7 @@ function wrapAnsi(string5, columns, options) {
54699
55477
  return String(string5).normalize().replaceAll(`\r
54700
55478
  `, `
54701
55479
  `).split(`
54702
- `).map((line) => exec4(line, columns, options)).join(`
55480
+ `).map((line) => exec5(line, columns, options)).join(`
54703
55481
  `);
54704
55482
  }
54705
55483
  var ESCAPES, END_CODE = 39, ANSI_ESCAPE_BELL = "\x07", ANSI_CSI = "[", ANSI_OSC = "]", ANSI_SGR_TERMINATOR = "m", ANSI_ESCAPE_LINK, wrapAnsiCode = (code) => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`, wrapAnsiHyperlink = (url2) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${url2}${ANSI_ESCAPE_BELL}`, wordLengths = (string5) => string5.split(" ").map((character) => stringWidth(character)), wrapWord = (rows, word, columns) => {
@@ -54753,7 +55531,7 @@ var ESCAPES, END_CODE = 39, ANSI_ESCAPE_BELL = "\x07", ANSI_CSI = "[", ANSI_OSC
54753
55531
  return string5;
54754
55532
  }
54755
55533
  return words.slice(0, last).join(" ") + words.slice(last).join("");
54756
- }, exec4 = (string5, columns, options = {}) => {
55534
+ }, exec5 = (string5, columns, options = {}) => {
54757
55535
  if (options.trim !== false && string5.trim() === "") {
54758
55536
  return "";
54759
55537
  }
@@ -54855,7 +55633,7 @@ var init_wrap_ansi = __esm(() => {
54855
55633
  function breakLines(content, width) {
54856
55634
  return content.split(`
54857
55635
  `).flatMap((line) => wrapAnsi(line, width, { trim: false, hard: true }).split(`
54858
- `).map((str) => str.trimEnd())).join(`
55636
+ `).map((str2) => str2.trimEnd())).join(`
54859
55637
  `);
54860
55638
  }
54861
55639
  function readlineWidth() {
@@ -61401,12 +62179,12 @@ var require_bom_handling = __commonJS((exports) => {
61401
62179
  this.encoder = encoder;
61402
62180
  this.addBOM = true;
61403
62181
  }
61404
- PrependBOMWrapper.prototype.write = function(str) {
62182
+ PrependBOMWrapper.prototype.write = function(str2) {
61405
62183
  if (this.addBOM) {
61406
- str = BOMChar + str;
62184
+ str2 = BOMChar + str2;
61407
62185
  this.addBOM = false;
61408
62186
  }
61409
- return this.encoder.write(str);
62187
+ return this.encoder.write(str2);
61410
62188
  };
61411
62189
  PrependBOMWrapper.prototype.end = function() {
61412
62190
  return this.encoder.end();
@@ -61497,29 +62275,29 @@ var require_internal = __commonJS((exports, module) => {
61497
62275
  function InternalEncoder(options, codec2) {
61498
62276
  this.enc = codec2.enc;
61499
62277
  }
61500
- InternalEncoder.prototype.write = function(str) {
61501
- return Buffer2.from(str, this.enc);
62278
+ InternalEncoder.prototype.write = function(str2) {
62279
+ return Buffer2.from(str2, this.enc);
61502
62280
  };
61503
62281
  InternalEncoder.prototype.end = function() {};
61504
62282
  function InternalEncoderBase64(options, codec2) {
61505
62283
  this.prevStr = "";
61506
62284
  }
61507
- InternalEncoderBase64.prototype.write = function(str) {
61508
- str = this.prevStr + str;
61509
- var completeQuads = str.length - str.length % 4;
61510
- this.prevStr = str.slice(completeQuads);
61511
- str = str.slice(0, completeQuads);
61512
- return Buffer2.from(str, "base64");
62285
+ InternalEncoderBase64.prototype.write = function(str2) {
62286
+ str2 = this.prevStr + str2;
62287
+ var completeQuads = str2.length - str2.length % 4;
62288
+ this.prevStr = str2.slice(completeQuads);
62289
+ str2 = str2.slice(0, completeQuads);
62290
+ return Buffer2.from(str2, "base64");
61513
62291
  };
61514
62292
  InternalEncoderBase64.prototype.end = function() {
61515
62293
  return Buffer2.from(this.prevStr, "base64");
61516
62294
  };
61517
62295
  function InternalEncoderCesu8(options, codec2) {}
61518
- InternalEncoderCesu8.prototype.write = function(str) {
61519
- var buf = Buffer2.alloc(str.length * 3);
62296
+ InternalEncoderCesu8.prototype.write = function(str2) {
62297
+ var buf = Buffer2.alloc(str2.length * 3);
61520
62298
  var bufIdx = 0;
61521
- for (var i = 0;i < str.length; i++) {
61522
- var charCode = str.charCodeAt(i);
62299
+ for (var i = 0;i < str2.length; i++) {
62300
+ var charCode = str2.charCodeAt(i);
61523
62301
  if (charCode < 128) {
61524
62302
  buf[bufIdx++] = charCode;
61525
62303
  } else if (charCode < 2048) {
@@ -61599,25 +62377,25 @@ var require_internal = __commonJS((exports, module) => {
61599
62377
  function InternalEncoderUtf8(options, codec2) {
61600
62378
  this.highSurrogate = "";
61601
62379
  }
61602
- InternalEncoderUtf8.prototype.write = function(str) {
62380
+ InternalEncoderUtf8.prototype.write = function(str2) {
61603
62381
  if (this.highSurrogate) {
61604
- str = this.highSurrogate + str;
62382
+ str2 = this.highSurrogate + str2;
61605
62383
  this.highSurrogate = "";
61606
62384
  }
61607
- if (str.length > 0) {
61608
- var charCode = str.charCodeAt(str.length - 1);
62385
+ if (str2.length > 0) {
62386
+ var charCode = str2.charCodeAt(str2.length - 1);
61609
62387
  if (charCode >= 55296 && charCode < 56320) {
61610
- this.highSurrogate = str[str.length - 1];
61611
- str = str.slice(0, str.length - 1);
62388
+ this.highSurrogate = str2[str2.length - 1];
62389
+ str2 = str2.slice(0, str2.length - 1);
61612
62390
  }
61613
62391
  }
61614
- return Buffer2.from(str, this.enc);
62392
+ return Buffer2.from(str2, this.enc);
61615
62393
  };
61616
62394
  InternalEncoderUtf8.prototype.end = function() {
61617
62395
  if (this.highSurrogate) {
61618
- var str = this.highSurrogate;
62396
+ var str2 = this.highSurrogate;
61619
62397
  this.highSurrogate = "";
61620
- return Buffer2.from(str, this.enc);
62398
+ return Buffer2.from(str2, this.enc);
61621
62399
  }
61622
62400
  };
61623
62401
  });
@@ -61641,8 +62419,8 @@ var require_utf32 = __commonJS((exports) => {
61641
62419
  this.isLE = codec2.isLE;
61642
62420
  this.highSurrogate = 0;
61643
62421
  }
61644
- Utf32Encoder.prototype.write = function(str) {
61645
- var src = Buffer2.from(str, "ucs2");
62422
+ Utf32Encoder.prototype.write = function(str2) {
62423
+ var src = Buffer2.from(str2, "ucs2");
61646
62424
  var dst = Buffer2.alloc(src.length * 2);
61647
62425
  var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
61648
62426
  var offset = 0;
@@ -61763,8 +62541,8 @@ var require_utf32 = __commonJS((exports) => {
61763
62541
  }
61764
62542
  this.encoder = codec2.iconv.getEncoder(options.defaultEncoding || "utf-32le", options);
61765
62543
  }
61766
- Utf32AutoEncoder.prototype.write = function(str) {
61767
- return this.encoder.write(str);
62544
+ Utf32AutoEncoder.prototype.write = function(str2) {
62545
+ return this.encoder.write(str2);
61768
62546
  };
61769
62547
  Utf32AutoEncoder.prototype.end = function() {
61770
62548
  return this.encoder.end();
@@ -61865,8 +62643,8 @@ var require_utf16 = __commonJS((exports) => {
61865
62643
  Utf16BECodec.prototype.decoder = Utf16BEDecoder;
61866
62644
  Utf16BECodec.prototype.bomAware = true;
61867
62645
  function Utf16BEEncoder() {}
61868
- Utf16BEEncoder.prototype.write = function(str) {
61869
- var buf = Buffer2.from(str, "ucs2");
62646
+ Utf16BEEncoder.prototype.write = function(str2) {
62647
+ var buf = Buffer2.from(str2, "ucs2");
61870
62648
  for (var i = 0;i < buf.length; i += 2) {
61871
62649
  var tmp = buf[i];
61872
62650
  buf[i] = buf[i + 1];
@@ -61914,8 +62692,8 @@ var require_utf16 = __commonJS((exports) => {
61914
62692
  }
61915
62693
  this.encoder = codec2.iconv.getEncoder("utf-16le", options);
61916
62694
  }
61917
- Utf16Encoder.prototype.write = function(str) {
61918
- return this.encoder.write(str);
62695
+ Utf16Encoder.prototype.write = function(str2) {
62696
+ return this.encoder.write(str2);
61919
62697
  };
61920
62698
  Utf16Encoder.prototype.end = function() {
61921
62699
  return this.encoder.end();
@@ -62014,8 +62792,8 @@ var require_utf7 = __commonJS((exports) => {
62014
62792
  function Utf7Encoder(options, codec2) {
62015
62793
  this.iconv = codec2.iconv;
62016
62794
  }
62017
- Utf7Encoder.prototype.write = function(str) {
62018
- return Buffer2.from(str.replace(nonDirectChars, function(chunk) {
62795
+ Utf7Encoder.prototype.write = function(str2) {
62796
+ return Buffer2.from(str2.replace(nonDirectChars, function(chunk) {
62019
62797
  return "+" + (chunk === "+" ? "" : this.iconv.encode(chunk, "utf16-be").toString("base64").replace(/=+$/, "")) + "-";
62020
62798
  }.bind(this)));
62021
62799
  };
@@ -62098,14 +62876,14 @@ var require_utf7 = __commonJS((exports) => {
62098
62876
  this.base64Accum = Buffer2.alloc(6);
62099
62877
  this.base64AccumIdx = 0;
62100
62878
  }
62101
- Utf7IMAPEncoder.prototype.write = function(str) {
62879
+ Utf7IMAPEncoder.prototype.write = function(str2) {
62102
62880
  var inBase64 = this.inBase64;
62103
62881
  var base64Accum = this.base64Accum;
62104
62882
  var base64AccumIdx = this.base64AccumIdx;
62105
- var buf = Buffer2.alloc(str.length * 5 + 10);
62883
+ var buf = Buffer2.alloc(str2.length * 5 + 10);
62106
62884
  var bufIdx = 0;
62107
- for (var i2 = 0;i2 < str.length; i2++) {
62108
- var uChar = str.charCodeAt(i2);
62885
+ for (var i2 = 0;i2 < str2.length; i2++) {
62886
+ var uChar = str2.charCodeAt(i2);
62109
62887
  if (uChar >= 32 && uChar <= 126) {
62110
62888
  if (inBase64) {
62111
62889
  if (base64AccumIdx > 0) {
@@ -62243,10 +63021,10 @@ var require_sbcs_codec = __commonJS((exports) => {
62243
63021
  function SBCSEncoder(options, codec2) {
62244
63022
  this.encodeBuf = codec2.encodeBuf;
62245
63023
  }
62246
- SBCSEncoder.prototype.write = function(str) {
62247
- var buf = Buffer2.alloc(str.length);
62248
- for (var i = 0;i < str.length; i++) {
62249
- buf[i] = this.encodeBuf[str.charCodeAt(i)];
63024
+ SBCSEncoder.prototype.write = function(str2) {
63025
+ var buf = Buffer2.alloc(str2.length);
63026
+ for (var i = 0;i < str2.length; i++) {
63027
+ buf[i] = this.encodeBuf[str2.charCodeAt(i)];
62250
63028
  }
62251
63029
  return buf;
62252
63030
  };
@@ -63115,8 +63893,8 @@ var require_dbcs_codec = __commonJS((exports) => {
63115
63893
  this.defaultCharSingleByte = codec2.defCharSB;
63116
63894
  this.gb18030 = codec2.gb18030;
63117
63895
  }
63118
- DBCSEncoder.prototype.write = function(str) {
63119
- var newBuf = Buffer2.alloc(str.length * (this.gb18030 ? 4 : 3));
63896
+ DBCSEncoder.prototype.write = function(str2) {
63897
+ var newBuf = Buffer2.alloc(str2.length * (this.gb18030 ? 4 : 3));
63120
63898
  var leadSurrogate = this.leadSurrogate;
63121
63899
  var seqObj = this.seqObj;
63122
63900
  var nextChar = -1;
@@ -63124,9 +63902,9 @@ var require_dbcs_codec = __commonJS((exports) => {
63124
63902
  var j = 0;
63125
63903
  while (true) {
63126
63904
  if (nextChar === -1) {
63127
- if (i2 == str.length)
63905
+ if (i2 == str2.length)
63128
63906
  break;
63129
- var uCode = str.charCodeAt(i2++);
63907
+ var uCode = str2.charCodeAt(i2++);
63130
63908
  } else {
63131
63909
  var uCode = nextChar;
63132
63910
  nextChar = -1;
@@ -64865,10 +65643,10 @@ var require_lib3 = __commonJS((exports, module) => {
64865
65643
  iconv.encodings = null;
64866
65644
  iconv.defaultCharUnicode = "\uFFFD";
64867
65645
  iconv.defaultCharSingleByte = "?";
64868
- iconv.encode = function encode3(str, encoding, options) {
64869
- str = "" + (str || "");
65646
+ iconv.encode = function encode3(str2, encoding, options) {
65647
+ str2 = "" + (str2 || "");
64870
65648
  var encoder = iconv.getEncoder(encoding, options);
64871
- var res = encoder.write(str);
65649
+ var res = encoder.write(str2);
64872
65650
  var trail = encoder.end();
64873
65651
  return trail && trail.length > 0 ? Buffer2.concat([res, trail]) : res;
64874
65652
  };
@@ -65033,7 +65811,7 @@ var init_RemoveFileError = __esm(() => {
65033
65811
 
65034
65812
  // ../../node_modules/.bun/@inquirer+external-editor@2.0.1+04f2146be16c61ef/node_modules/@inquirer/external-editor/dist/index.js
65035
65813
  import { spawn as spawn4, spawnSync as spawnSync2 } from "child_process";
65036
- import { readFileSync as readFileSync24, unlinkSync as unlinkSync5, writeFileSync as writeFileSync16 } from "fs";
65814
+ import { readFileSync as readFileSync26, unlinkSync as unlinkSync6, writeFileSync as writeFileSync17 } from "fs";
65037
65815
  import path from "path";
65038
65816
  import os from "os";
65039
65817
  import { randomUUID as randomUUID5 } from "crypto";
@@ -65057,12 +65835,12 @@ function sanitizeAffix(affix) {
65057
65835
  return "";
65058
65836
  return affix.replace(/[^a-zA-Z0-9_.-]/g, "_");
65059
65837
  }
65060
- function splitStringBySpace(str) {
65838
+ function splitStringBySpace(str2) {
65061
65839
  const pieces = [];
65062
65840
  let currentString = "";
65063
- for (let strIndex = 0;strIndex < str.length; strIndex++) {
65064
- const currentLetter = str.charAt(strIndex);
65065
- if (strIndex > 0 && currentLetter === " " && str[strIndex - 1] !== "\\" && currentString.length > 0) {
65841
+ for (let strIndex = 0;strIndex < str2.length; strIndex++) {
65842
+ const currentLetter = str2.charAt(strIndex);
65843
+ if (strIndex > 0 && currentLetter === " " && str2[strIndex - 1] !== "\\" && currentString.length > 0) {
65066
65844
  pieces.push(currentString);
65067
65845
  currentString = "";
65068
65846
  } else {
@@ -65142,14 +65920,14 @@ class ExternalEditor {
65142
65920
  if (Object.prototype.hasOwnProperty.call(this.fileOptions, "mode")) {
65143
65921
  opt.mode = this.fileOptions.mode;
65144
65922
  }
65145
- writeFileSync16(this.tempFile, this.text, opt);
65923
+ writeFileSync17(this.tempFile, this.text, opt);
65146
65924
  } catch (createFileError) {
65147
65925
  throw new CreateFileError(createFileError);
65148
65926
  }
65149
65927
  }
65150
65928
  readTemporaryFile() {
65151
65929
  try {
65152
- const tempFileBuffer = readFileSync24(this.tempFile);
65930
+ const tempFileBuffer = readFileSync26(this.tempFile);
65153
65931
  if (tempFileBuffer.length === 0) {
65154
65932
  this.text = "";
65155
65933
  } else {
@@ -65165,7 +65943,7 @@ class ExternalEditor {
65165
65943
  }
65166
65944
  removeTemporaryFile() {
65167
65945
  try {
65168
- unlinkSync5(this.tempFile);
65946
+ unlinkSync6(this.tempFile);
65169
65947
  } catch (removeFileError) {
65170
65948
  throw new RemoveFileError(removeFileError);
65171
65949
  }
@@ -66130,9 +66908,9 @@ var init_dist16 = __esm(() => {
66130
66908
 
66131
66909
  // src/auth/antigravity-oauth.ts
66132
66910
  import { spawnSync as spawnSync3 } from "child_process";
66133
- import { existsSync as existsSync24, unlinkSync as unlinkSync6 } from "fs";
66134
- import { homedir as homedir28 } from "os";
66135
- import { join as join32 } from "path";
66911
+ import { existsSync as existsSync26, unlinkSync as unlinkSync7 } from "fs";
66912
+ import { homedir as homedir30 } from "os";
66913
+ import { join as join34 } from "path";
66136
66914
  async function defaultSuggestModel() {
66137
66915
  try {
66138
66916
  const tok = readSharedAntigravityToken();
@@ -66253,9 +67031,9 @@ No session detected yet. Starting the Antigravity CLI interactively \u2014
66253
67031
  async logout(deps) {
66254
67032
  deleteSharedAntigravityToken(deps);
66255
67033
  try {
66256
- const tokenFile = join32(homedir28(), ".gemini", "antigravity-cli", "antigravity-oauth-token");
66257
- if (existsSync24(tokenFile))
66258
- unlinkSync6(tokenFile);
67034
+ const tokenFile = join34(homedir30(), ".gemini", "antigravity-cli", "antigravity-oauth-token");
67035
+ if (existsSync26(tokenFile))
67036
+ unlinkSync7(tokenFile);
66259
67037
  } catch {}
66260
67038
  log("[AntigravityOAuth] Antigravity session cleared (keychain + agy token file)");
66261
67039
  }
@@ -66353,6 +67131,7 @@ var init_auth_commands = __esm(() => {
66353
67131
  init_antigravity_oauth();
66354
67132
  init_antigravity_token();
66355
67133
  init_codex_oauth();
67134
+ init_grok_oauth();
66356
67135
  init_kimi_oauth();
66357
67136
  init_oauth_registry();
66358
67137
  AUTH_PROVIDERS = [
@@ -66376,6 +67155,13 @@ var init_auth_commands = __esm(() => {
66376
67155
  prefix: "cx@",
66377
67156
  getInstance: () => CodexOAuth.getInstance(),
66378
67157
  registryKeys: ["openai-codex"]
67158
+ },
67159
+ {
67160
+ name: "grok",
67161
+ displayName: "Grok Build (SuperGrok / X Premium+)",
67162
+ prefix: "gk@",
67163
+ getInstance: () => GrokOAuth.getInstance(),
67164
+ registryKeys: ["grok-subscription"]
66379
67165
  }
66380
67166
  ];
66381
67167
  });
@@ -68120,9 +68906,9 @@ function timelineBarCells(totalMs, maxTotalMs, barWidth) {
68120
68906
  function splitStageCells(ttfbMs, ttftMs, totalMs, barCells) {
68121
68907
  const net = Math.max(0, ttfbMs);
68122
68908
  const srv = Math.max(0, ttftMs - ttfbMs);
68123
- const str = Math.max(0, totalMs - ttftMs);
68124
- const durations = [net, srv, str];
68125
- const sum = net + srv + str;
68909
+ const str2 = Math.max(0, totalMs - ttftMs);
68910
+ const durations = [net, srv, str2];
68911
+ const sum = net + srv + str2;
68126
68912
  if (barCells <= 0)
68127
68913
  return { network: 0, server: 0, streaming: 0 };
68128
68914
  if (sum <= 0) {
@@ -68731,11 +69517,11 @@ function renderCard(result, isLiveProbe, w, width, scales, directKeyVar) {
68731
69517
  function renderLegend(w) {
68732
69518
  const net = STAGE_BG_ANSI.network;
68733
69519
  const srv = STAGE_BG_ANSI.server;
68734
- const str = STAGE_BG_ANSI.streaming;
69520
+ const str2 = STAGE_BG_ANSI.streaming;
68735
69521
  const netFg = hexToAnsiFg(STAGE_FG.network);
68736
69522
  const srvFg = hexToAnsiFg(STAGE_FG.server);
68737
69523
  const strFg = hexToAnsiFg(STAGE_FG.streaming);
68738
- w(` ${pc.dim}Stages:${pc.reset} ` + `${net} ${ANSI_RESET}${netFg} network${pc.reset} ` + `${srv} ${ANSI_RESET}${srvFg} server${pc.reset} ` + `${str} ${ANSI_RESET}${strFg} streaming${pc.reset} ` + `${pc.dim}\xB7\xB7 idle${pc.reset}
69524
+ w(` ${pc.dim}Stages:${pc.reset} ` + `${net} ${ANSI_RESET}${netFg} network${pc.reset} ` + `${srv} ${ANSI_RESET}${srvFg} server${pc.reset} ` + `${str2} ${ANSI_RESET}${strFg} streaming${pc.reset} ` + `${pc.dim}\xB7\xB7 idle${pc.reset}
68739
69525
  `);
68740
69526
  w(` ${pc.dim}bar length = total time, shared scale (slowest = full bar) \xB7 ` + `tok/s scaled to fastest${pc.reset}
68741
69527
  `);
@@ -70371,22 +71157,22 @@ __export(exports_cli, {
70371
71157
  });
70372
71158
  import {
70373
71159
  copyFileSync as copyFileSync2,
70374
- existsSync as existsSync25,
70375
- mkdirSync as mkdirSync14,
70376
- readFileSync as readFileSync25,
71160
+ existsSync as existsSync27,
71161
+ mkdirSync as mkdirSync15,
71162
+ readFileSync as readFileSync27,
70377
71163
  readdirSync as readdirSync5,
70378
- unlinkSync as unlinkSync7,
70379
- writeFileSync as writeFileSync17
71164
+ unlinkSync as unlinkSync8,
71165
+ writeFileSync as writeFileSync18
70380
71166
  } from "fs";
70381
- import { homedir as homedir29 } from "os";
70382
- import { dirname as dirname11, join as join33 } from "path";
71167
+ import { homedir as homedir31 } from "os";
71168
+ import { dirname as dirname11, join as join35 } from "path";
70383
71169
  import { fileURLToPath as fileURLToPath3 } from "url";
70384
71170
  function getVersion3() {
70385
71171
  return VERSION;
70386
71172
  }
70387
71173
  function clearAllModelCaches() {
70388
- const cacheDir = join33(homedir29(), ".claudish");
70389
- if (!existsSync25(cacheDir))
71174
+ const cacheDir = join35(homedir31(), ".claudish");
71175
+ if (!existsSync27(cacheDir))
70390
71176
  return;
70391
71177
  const cachePatterns = ["pricing-cache.json", "recommended-models-cache.json"];
70392
71178
  let cleared = 0;
@@ -70394,7 +71180,7 @@ function clearAllModelCaches() {
70394
71180
  const files = readdirSync5(cacheDir);
70395
71181
  for (const file2 of files) {
70396
71182
  if (cachePatterns.includes(file2)) {
70397
- unlinkSync7(join33(cacheDir, file2));
71183
+ unlinkSync8(join35(cacheDir, file2));
70398
71184
  cleared++;
70399
71185
  }
70400
71186
  }
@@ -70810,15 +71596,15 @@ Usage: claudish --models --provider <slug>`);
70810
71596
  });
70811
71597
  config3.resolvedDefaultProvider = resolved;
70812
71598
  if (resolved.legacyAutoPromoted && !config3.quiet) {
70813
- const markerFile = join33(homedir29(), ".claudish", ".legacy-litellm-hint-shown");
70814
- if (!existsSync25(markerFile)) {
71599
+ const markerFile = join35(homedir31(), ".claudish", ".legacy-litellm-hint-shown");
71600
+ if (!existsSync27(markerFile)) {
70815
71601
  const hint = buildLegacyHint(resolved);
70816
71602
  if (hint) {
70817
71603
  console.error(hint);
70818
71604
  }
70819
71605
  try {
70820
- mkdirSync14(dirname11(markerFile), { recursive: true });
70821
- writeFileSync17(markerFile, new Date().toISOString(), "utf-8");
71606
+ mkdirSync15(dirname11(markerFile), { recursive: true });
71607
+ writeFileSync18(markerFile, new Date().toISOString(), "utf-8");
70822
71608
  } catch {}
70823
71609
  }
70824
71610
  }
@@ -71888,8 +72674,8 @@ ${h("MORE INFO")}
71888
72674
  }
71889
72675
  function printAIAgentGuide() {
71890
72676
  try {
71891
- const guidePath = join33(__dirname3, "../AI_AGENT_GUIDE.md");
71892
- const guideContent = readFileSync25(guidePath, "utf-8");
72677
+ const guidePath = join35(__dirname3, "../AI_AGENT_GUIDE.md");
72678
+ const guideContent = readFileSync27(guidePath, "utf-8");
71893
72679
  console.log(guideContent);
71894
72680
  } catch (error46) {
71895
72681
  console.error("Error reading AI Agent Guide:");
@@ -71905,19 +72691,19 @@ async function initializeClaudishSkill() {
71905
72691
  console.log(`\uD83D\uDD27 Initializing Claudish skill in current project...
71906
72692
  `);
71907
72693
  const cwd = process.cwd();
71908
- const claudeDir = join33(cwd, ".claude");
71909
- const skillsDir = join33(claudeDir, "skills");
71910
- const claudishSkillDir = join33(skillsDir, "claudish-usage");
71911
- const skillFile = join33(claudishSkillDir, "SKILL.md");
71912
- if (existsSync25(skillFile)) {
72694
+ const claudeDir = join35(cwd, ".claude");
72695
+ const skillsDir = join35(claudeDir, "skills");
72696
+ const claudishSkillDir = join35(skillsDir, "claudish-usage");
72697
+ const skillFile = join35(claudishSkillDir, "SKILL.md");
72698
+ if (existsSync27(skillFile)) {
71913
72699
  console.log("\u2705 Claudish skill already installed at:");
71914
72700
  console.log(` ${skillFile}
71915
72701
  `);
71916
72702
  console.log("\uD83D\uDCA1 To reinstall, delete the file and run 'claudish --init' again.");
71917
72703
  return;
71918
72704
  }
71919
- const sourceSkillPath = join33(__dirname3, "../skills/claudish-usage/SKILL.md");
71920
- if (!existsSync25(sourceSkillPath)) {
72705
+ const sourceSkillPath = join35(__dirname3, "../skills/claudish-usage/SKILL.md");
72706
+ if (!existsSync27(sourceSkillPath)) {
71921
72707
  console.error("\u274C Error: Claudish skill file not found in installation.");
71922
72708
  console.error(` Expected at: ${sourceSkillPath}`);
71923
72709
  console.error(`
@@ -71926,16 +72712,16 @@ async function initializeClaudishSkill() {
71926
72712
  process.exit(1);
71927
72713
  }
71928
72714
  try {
71929
- if (!existsSync25(claudeDir)) {
71930
- mkdirSync14(claudeDir, { recursive: true });
72715
+ if (!existsSync27(claudeDir)) {
72716
+ mkdirSync15(claudeDir, { recursive: true });
71931
72717
  console.log("\uD83D\uDCC1 Created .claude/ directory");
71932
72718
  }
71933
- if (!existsSync25(skillsDir)) {
71934
- mkdirSync14(skillsDir, { recursive: true });
72719
+ if (!existsSync27(skillsDir)) {
72720
+ mkdirSync15(skillsDir, { recursive: true });
71935
72721
  console.log("\uD83D\uDCC1 Created .claude/skills/ directory");
71936
72722
  }
71937
- if (!existsSync25(claudishSkillDir)) {
71938
- mkdirSync14(claudishSkillDir, { recursive: true });
72723
+ if (!existsSync27(claudishSkillDir)) {
72724
+ mkdirSync15(claudishSkillDir, { recursive: true });
71939
72725
  console.log("\uD83D\uDCC1 Created .claude/skills/claudish-usage/ directory");
71940
72726
  }
71941
72727
  copyFileSync2(sourceSkillPath, skillFile);
@@ -72020,33 +72806,33 @@ __export(exports_update_checker, {
72020
72806
  clearCache: () => clearCache,
72021
72807
  checkForUpdates: () => checkForUpdates
72022
72808
  });
72023
- import { existsSync as existsSync26, mkdirSync as mkdirSync15, readFileSync as readFileSync26, unlinkSync as unlinkSync8, writeFileSync as writeFileSync18 } from "fs";
72024
- import { homedir as homedir30, platform as platform2, tmpdir } from "os";
72025
- import { join as join34 } from "path";
72809
+ import { existsSync as existsSync28, mkdirSync as mkdirSync16, readFileSync as readFileSync28, unlinkSync as unlinkSync9, writeFileSync as writeFileSync19 } from "fs";
72810
+ import { homedir as homedir32, platform as platform2, tmpdir } from "os";
72811
+ import { join as join36 } from "path";
72026
72812
  function getCacheFilePath() {
72027
72813
  let cacheDir;
72028
72814
  if (isWindows) {
72029
- const localAppData = process.env.LOCALAPPDATA || join34(homedir30(), "AppData", "Local");
72030
- cacheDir = join34(localAppData, "claudish");
72815
+ const localAppData = process.env.LOCALAPPDATA || join36(homedir32(), "AppData", "Local");
72816
+ cacheDir = join36(localAppData, "claudish");
72031
72817
  } else {
72032
- cacheDir = join34(homedir30(), ".cache", "claudish");
72818
+ cacheDir = join36(homedir32(), ".cache", "claudish");
72033
72819
  }
72034
72820
  try {
72035
- if (!existsSync26(cacheDir)) {
72036
- mkdirSync15(cacheDir, { recursive: true });
72821
+ if (!existsSync28(cacheDir)) {
72822
+ mkdirSync16(cacheDir, { recursive: true });
72037
72823
  }
72038
- return join34(cacheDir, "update-check.json");
72824
+ return join36(cacheDir, "update-check.json");
72039
72825
  } catch {
72040
- return join34(tmpdir(), "claudish-update-check.json");
72826
+ return join36(tmpdir(), "claudish-update-check.json");
72041
72827
  }
72042
72828
  }
72043
72829
  function readCache() {
72044
72830
  try {
72045
72831
  const cachePath = getCacheFilePath();
72046
- if (!existsSync26(cachePath)) {
72832
+ if (!existsSync28(cachePath)) {
72047
72833
  return null;
72048
72834
  }
72049
- const data = JSON.parse(readFileSync26(cachePath, "utf-8"));
72835
+ const data = JSON.parse(readFileSync28(cachePath, "utf-8"));
72050
72836
  return data;
72051
72837
  } catch {
72052
72838
  return null;
@@ -72059,7 +72845,7 @@ function writeCache(latestVersion) {
72059
72845
  lastCheck: Date.now(),
72060
72846
  latestVersion
72061
72847
  };
72062
- writeFileSync18(cachePath, JSON.stringify(data), "utf-8");
72848
+ writeFileSync19(cachePath, JSON.stringify(data), "utf-8");
72063
72849
  } catch {}
72064
72850
  }
72065
72851
  function isCacheValid(cache2) {
@@ -72069,8 +72855,8 @@ function isCacheValid(cache2) {
72069
72855
  function clearCache() {
72070
72856
  try {
72071
72857
  const cachePath = getCacheFilePath();
72072
- if (existsSync26(cachePath)) {
72073
- unlinkSync8(cachePath);
72858
+ if (existsSync28(cachePath)) {
72859
+ unlinkSync9(cachePath);
72074
72860
  }
72075
72861
  } catch {}
72076
72862
  }
@@ -72954,15 +73740,15 @@ var init_local_liveness = __esm(() => {
72954
73740
  });
72955
73741
 
72956
73742
  // src/providers/probe-catalog.ts
72957
- import { existsSync as existsSync27, mkdirSync as mkdirSync16, readFileSync as readFileSync27, writeFileSync as writeFileSync19 } from "fs";
72958
- import { homedir as homedir31 } from "os";
72959
- import { dirname as dirname12, join as join35 } from "path";
73743
+ import { existsSync as existsSync29, mkdirSync as mkdirSync17, readFileSync as readFileSync29, writeFileSync as writeFileSync20 } from "fs";
73744
+ import { homedir as homedir33 } from "os";
73745
+ import { dirname as dirname12, join as join37 } from "path";
72960
73746
  function readProbeModelsCache(path2 = PROBE_MODELS_CACHE_PATH) {
72961
- if (!existsSync27(path2))
73747
+ if (!existsSync29(path2))
72962
73748
  return null;
72963
73749
  let raw2;
72964
73750
  try {
72965
- raw2 = JSON.parse(readFileSync27(path2, "utf-8"));
73751
+ raw2 = JSON.parse(readFileSync29(path2, "utf-8"));
72966
73752
  } catch {
72967
73753
  return null;
72968
73754
  }
@@ -72971,8 +73757,8 @@ function readProbeModelsCache(path2 = PROBE_MODELS_CACHE_PATH) {
72971
73757
  return raw2;
72972
73758
  }
72973
73759
  function writeProbeModelsCache(data, path2 = PROBE_MODELS_CACHE_PATH) {
72974
- mkdirSync16(dirname12(path2), { recursive: true });
72975
- writeFileSync19(path2, JSON.stringify(data), "utf-8");
73760
+ mkdirSync17(dirname12(path2), { recursive: true });
73761
+ writeFileSync20(path2, JSON.stringify(data), "utf-8");
72976
73762
  }
72977
73763
  function isCacheFresh(data, ttlMs = CACHE_TTL_MS4) {
72978
73764
  if (!data?.generatedAt)
@@ -73091,7 +73877,7 @@ function isValidResponse(raw2) {
73091
73877
  var PROBE_MODELS_URL = "https://us-central1-claudish-6da10.cloudfunctions.net/probeModels", CACHE_TTL_MS4, FETCH_TIMEOUT_MS3 = 15000, PROBE_MODELS_CACHE_PATH, _inFlight = null;
73092
73878
  var init_probe_catalog = __esm(() => {
73093
73879
  CACHE_TTL_MS4 = 60 * 60 * 1000;
73094
- PROBE_MODELS_CACHE_PATH = join35(homedir31(), ".claudish", "probe-models.json");
73880
+ PROBE_MODELS_CACHE_PATH = join37(homedir33(), ".claudish", "probe-models.json");
73095
73881
  });
73096
73882
 
73097
73883
  // src/tui/constants.ts
@@ -79444,18 +80230,18 @@ __export(exports_claude_runner, {
79444
80230
  });
79445
80231
  import { spawn as spawn5 } from "child_process";
79446
80232
  import {
79447
- closeSync as closeSync4,
79448
- existsSync as existsSync28,
79449
- mkdirSync as mkdirSync17,
79450
- openSync as openSync4,
79451
- readFileSync as readFileSync28,
80233
+ closeSync as closeSync5,
80234
+ existsSync as existsSync30,
80235
+ mkdirSync as mkdirSync18,
80236
+ openSync as openSync5,
80237
+ readFileSync as readFileSync30,
79452
80238
  readdirSync as readdirSync6,
79453
80239
  statSync as statSync5,
79454
- unlinkSync as unlinkSync9,
79455
- writeFileSync as writeFileSync20
80240
+ unlinkSync as unlinkSync10,
80241
+ writeFileSync as writeFileSync21
79456
80242
  } from "fs";
79457
- import { homedir as homedir32, tmpdir as tmpdir2 } from "os";
79458
- import { dirname as dirname13, join as join36 } from "path";
80243
+ import { homedir as homedir34, tmpdir as tmpdir2 } from "os";
80244
+ import { dirname as dirname13, join as join38 } from "path";
79459
80245
  import { isatty } from "tty";
79460
80246
  function releaseTerminalIsolation() {
79461
80247
  if (!restoreTerminal)
@@ -79490,14 +80276,14 @@ function isProxyAuthMode(config3) {
79490
80276
  }
79491
80277
  function managedSettingsPath() {
79492
80278
  if (isWindows2()) {
79493
- return join36(process.env.PROGRAMDATA || "C:\\ProgramData", "ClaudeCode", "managed-settings.json");
80279
+ return join38(process.env.PROGRAMDATA || "C:\\ProgramData", "ClaudeCode", "managed-settings.json");
79494
80280
  }
79495
80281
  if (process.platform === "darwin") {
79496
80282
  return "/Library/Application Support/ClaudeCode/managed-settings.json";
79497
80283
  }
79498
80284
  return "/etc/claude-code/managed-settings.json";
79499
80285
  }
79500
- function managedSettingsForcesClaudeAi(readFile3 = readFileSync28) {
80286
+ function managedSettingsForcesClaudeAi(readFile3 = readFileSync30) {
79501
80287
  try {
79502
80288
  const raw2 = readFile3(managedSettingsPath(), "utf-8");
79503
80289
  const parsed = JSON.parse(raw2);
@@ -79511,9 +80297,9 @@ function isWindows2() {
79511
80297
  }
79512
80298
  function createStatusLineScript(tokenFilePath) {
79513
80299
  const homeDir = process.env.HOME || process.env.USERPROFILE || tmpdir2();
79514
- const claudishDir = join36(homeDir, ".claudish");
80300
+ const claudishDir = join38(homeDir, ".claudish");
79515
80301
  const timestamp = Date.now();
79516
- const scriptPath = join36(claudishDir, `status-${timestamp}.js`);
80302
+ const scriptPath = join38(claudishDir, `status-${timestamp}.js`);
79517
80303
  const escapedTokenPath = tokenFilePath.replace(/\\/g, "\\\\");
79518
80304
  const script = `
79519
80305
  const fs = require('fs');
@@ -79640,13 +80426,13 @@ process.stdin.on('end', () => {
79640
80426
  }
79641
80427
  });
79642
80428
  `;
79643
- writeFileSync20(scriptPath, script, "utf-8");
80429
+ writeFileSync21(scriptPath, script, "utf-8");
79644
80430
  return scriptPath;
79645
80431
  }
79646
80432
  function initializeTokenFile(tokenFilePath) {
79647
80433
  try {
79648
- mkdirSync17(dirname13(tokenFilePath), { recursive: true });
79649
- writeFileSync20(tokenFilePath, JSON.stringify({
80434
+ mkdirSync18(dirname13(tokenFilePath), { recursive: true });
80435
+ writeFileSync21(tokenFilePath, JSON.stringify({
79650
80436
  input_tokens: 0,
79651
80437
  output_tokens: 0,
79652
80438
  total_tokens: 0,
@@ -79677,11 +80463,11 @@ function cleanupStaleTokenFiles(dir, now = Date.now(), maxAgeMs = STALE_TOKEN_FI
79677
80463
  if (!name.startsWith("tokens-") || !name.endsWith(".json"))
79678
80464
  continue;
79679
80465
  scanned++;
79680
- const full = join36(dir, name);
80466
+ const full = join38(dir, name);
79681
80467
  try {
79682
80468
  if (statSync5(full).mtimeMs >= cutoff)
79683
80469
  continue;
79684
- unlinkSync9(full);
80470
+ unlinkSync10(full);
79685
80471
  removed++;
79686
80472
  } catch {}
79687
80473
  }
@@ -79694,7 +80480,7 @@ function parseSettingsArg(value) {
79694
80480
  if (value.trimStart().startsWith("{")) {
79695
80481
  return JSON.parse(value);
79696
80482
  }
79697
- return JSON.parse(readFileSync28(value, "utf-8"));
80483
+ return JSON.parse(readFileSync30(value, "utf-8"));
79698
80484
  }
79699
80485
  function parseSettingsArgSafe(value) {
79700
80486
  try {
@@ -79706,13 +80492,13 @@ function parseSettingsArgSafe(value) {
79706
80492
  }
79707
80493
  function userSettingsFileCandidates(cwd) {
79708
80494
  return [
79709
- join36(homedir32(), ".claude", "settings.json"),
79710
- join36(cwd, ".claude", "settings.json"),
79711
- join36(cwd, ".claude", "settings.local.json")
80495
+ join38(homedir34(), ".claude", "settings.json"),
80496
+ join38(cwd, ".claude", "settings.json"),
80497
+ join38(cwd, ".claude", "settings.local.json")
79712
80498
  ];
79713
80499
  }
79714
80500
  function discoverUserStatusLineCommand(claudeArgs = [], cwd = process.cwd()) {
79715
- const sources = userSettingsFileCandidates(cwd).filter((file2) => existsSync28(file2));
80501
+ const sources = userSettingsFileCandidates(cwd).filter((file2) => existsSync30(file2));
79716
80502
  const idx = claudeArgs.indexOf("--settings");
79717
80503
  const settingsArg = idx === -1 ? undefined : claudeArgs[idx + 1];
79718
80504
  if (settingsArg)
@@ -79749,13 +80535,13 @@ function buildChainedStatusCommand(userCommand, claudishBody, claudishSegment) {
79749
80535
  }
79750
80536
  function createTempSettingsFile(_modelDisplay, port, proxyAuthMode, userStatusLineCommand) {
79751
80537
  const homeDir = process.env.HOME || process.env.USERPROFILE || tmpdir2();
79752
- const claudishDir = join36(homeDir, ".claudish");
80538
+ const claudishDir = join38(homeDir, ".claudish");
79753
80539
  try {
79754
- mkdirSync17(claudishDir, { recursive: true });
80540
+ mkdirSync18(claudishDir, { recursive: true });
79755
80541
  } catch {}
79756
80542
  const timestamp = Date.now();
79757
- const tempPath = join36(claudishDir, `settings-${timestamp}.json`);
79758
- const tokenFilePath = join36(claudishDir, `tokens-${port}.json`);
80543
+ const tempPath = join38(claudishDir, `settings-${timestamp}.json`);
80544
+ const tokenFilePath = join38(claudishDir, `tokens-${port}.json`);
79759
80545
  cleanupStaleTokenFiles(claudishDir);
79760
80546
  initializeTokenFile(tokenFilePath);
79761
80547
  let statusCommand;
@@ -79788,7 +80574,7 @@ function createTempSettingsFile(_modelDisplay, port, proxyAuthMode, userStatusLi
79788
80574
  padding: 0
79789
80575
  };
79790
80576
  const settings = buildClaudishSettingsOverlay(statusLine, proxyAuthMode);
79791
- writeFileSync20(tempPath, JSON.stringify(settings, null, 2), "utf-8");
80577
+ writeFileSync21(tempPath, JSON.stringify(settings, null, 2), "utf-8");
79792
80578
  return { path: tempPath, statusLine, tokenFilePath };
79793
80579
  }
79794
80580
  function buildClaudishSettingsOverlay(statusLine, proxyAuthMode) {
@@ -79813,7 +80599,7 @@ function mergeUserSettingsIfPresent(config3, tempSettingsPath, statusLine, proxy
79813
80599
  if (proxyAuthMode && !("forceLoginMethod" in userSettings)) {
79814
80600
  userSettings.forceLoginMethod = "console";
79815
80601
  }
79816
- writeFileSync20(tempSettingsPath, JSON.stringify(userSettings, null, 2), "utf-8");
80602
+ writeFileSync21(tempSettingsPath, JSON.stringify(userSettings, null, 2), "utf-8");
79817
80603
  } catch {
79818
80604
  if (!config3.quiet) {
79819
80605
  console.warn(`[claudish] Warning: could not merge user settings: ${userSettingsValue}`);
@@ -80005,8 +80791,8 @@ async function runClaudeWithProxy(config3, proxyUrl, onCleanup) {
80005
80791
  console.error("Install it from: https://claude.com/claude-code");
80006
80792
  console.error(`
80007
80793
  Or set CLAUDE_PATH to your custom installation:`);
80008
- const home = homedir32();
80009
- const localPath = isWindows2() ? join36(home, ".claude", "local", "claude.exe") : join36(home, ".claude", "local", "claude");
80794
+ const home = homedir34();
80795
+ const localPath = isWindows2() ? join38(home, ".claude", "local", "claude.exe") : join38(home, ".claude", "local", "claude");
80010
80796
  console.error(` export CLAUDE_PATH=${localPath}`);
80011
80797
  process.exit(1);
80012
80798
  }
@@ -80017,11 +80803,11 @@ Or set CLAUDE_PATH to your custom installation:`);
80017
80803
  const childWantsTty = config3.interactive && !process.stdout.isTTY && Boolean(process.stdin.isTTY);
80018
80804
  if (childWantsTty) {
80019
80805
  try {
80020
- const fd = openSync4("/dev/fd/0", "r+");
80806
+ const fd = openSync5("/dev/fd/0", "r+");
80021
80807
  if (isatty(fd)) {
80022
80808
  ttyFd = fd;
80023
80809
  } else {
80024
- closeSync4(fd);
80810
+ closeSync5(fd);
80025
80811
  }
80026
80812
  } catch {
80027
80813
  ttyFd = undefined;
@@ -80044,7 +80830,7 @@ Or set CLAUDE_PATH to your custom installation:`);
80044
80830
  const fdToClose = ttyFd;
80045
80831
  proc.on("spawn", () => {
80046
80832
  try {
80047
- closeSync4(fdToClose);
80833
+ closeSync5(fdToClose);
80048
80834
  } catch {}
80049
80835
  });
80050
80836
  }
@@ -80057,7 +80843,7 @@ Or set CLAUDE_PATH to your custom installation:`);
80057
80843
  });
80058
80844
  releaseTerminalIsolation();
80059
80845
  try {
80060
- unlinkSync9(tempSettingsPath);
80846
+ unlinkSync10(tempSettingsPath);
80061
80847
  } catch {}
80062
80848
  return exitCode;
80063
80849
  }
@@ -80077,7 +80863,7 @@ function setupSignalHandlers(proc, tempSettingsPath, quiet, onCleanup) {
80077
80863
  } catch {}
80078
80864
  }
80079
80865
  try {
80080
- unlinkSync9(tempSettingsPath);
80866
+ unlinkSync10(tempSettingsPath);
80081
80867
  } catch {}
80082
80868
  process.exit(0);
80083
80869
  });
@@ -80086,23 +80872,23 @@ function setupSignalHandlers(proc, tempSettingsPath, quiet, onCleanup) {
80086
80872
  async function findClaudeBinary() {
80087
80873
  const isWindows3 = process.platform === "win32";
80088
80874
  if (process.env.CLAUDE_PATH) {
80089
- if (existsSync28(process.env.CLAUDE_PATH)) {
80875
+ if (existsSync30(process.env.CLAUDE_PATH)) {
80090
80876
  return process.env.CLAUDE_PATH;
80091
80877
  }
80092
80878
  }
80093
- const home = homedir32();
80094
- const localPath = isWindows3 ? join36(home, ".claude", "local", "claude.exe") : join36(home, ".claude", "local", "claude");
80095
- if (existsSync28(localPath)) {
80879
+ const home = homedir34();
80880
+ const localPath = isWindows3 ? join38(home, ".claude", "local", "claude.exe") : join38(home, ".claude", "local", "claude");
80881
+ if (existsSync30(localPath)) {
80096
80882
  return localPath;
80097
80883
  }
80098
80884
  if (isWindows3) {
80099
80885
  const windowsPaths = [
80100
- join36(home, "AppData", "Roaming", "npm", "claude.cmd"),
80101
- join36(home, ".npm-global", "claude.cmd"),
80102
- join36(home, "node_modules", ".bin", "claude.cmd")
80886
+ join38(home, "AppData", "Roaming", "npm", "claude.cmd"),
80887
+ join38(home, ".npm-global", "claude.cmd"),
80888
+ join38(home, "node_modules", ".bin", "claude.cmd")
80103
80889
  ];
80104
80890
  for (const path2 of windowsPaths) {
80105
- if (existsSync28(path2)) {
80891
+ if (existsSync30(path2)) {
80106
80892
  return path2;
80107
80893
  }
80108
80894
  }
@@ -80110,14 +80896,14 @@ async function findClaudeBinary() {
80110
80896
  const commonPaths = [
80111
80897
  "/usr/local/bin/claude",
80112
80898
  "/opt/homebrew/bin/claude",
80113
- join36(home, ".npm-global/bin/claude"),
80114
- join36(home, ".local/bin/claude"),
80115
- join36(home, "node_modules/.bin/claude"),
80899
+ join38(home, ".npm-global/bin/claude"),
80900
+ join38(home, ".local/bin/claude"),
80901
+ join38(home, "node_modules/.bin/claude"),
80116
80902
  "/data/data/com.termux/files/usr/bin/claude",
80117
- join36(home, "../usr/bin/claude")
80903
+ join38(home, "../usr/bin/claude")
80118
80904
  ];
80119
80905
  for (const path2 of commonPaths) {
80120
- if (existsSync28(path2)) {
80906
+ if (existsSync30(path2)) {
80121
80907
  return path2;
80122
80908
  }
80123
80909
  }
@@ -80176,18 +80962,18 @@ __export(exports_diag_output, {
80176
80962
  NullDiagOutput: () => NullDiagOutput,
80177
80963
  LogFileDiagOutput: () => LogFileDiagOutput
80178
80964
  });
80179
- import { createWriteStream as createWriteStream3, mkdirSync as mkdirSync18, unlinkSync as unlinkSync10, writeFileSync as writeFileSync21 } from "fs";
80180
- import { homedir as homedir33 } from "os";
80181
- import { join as join37 } from "path";
80965
+ import { createWriteStream as createWriteStream3, mkdirSync as mkdirSync19, unlinkSync as unlinkSync11, writeFileSync as writeFileSync22 } from "fs";
80966
+ import { homedir as homedir35 } from "os";
80967
+ import { join as join39 } from "path";
80182
80968
  function getClaudishDir() {
80183
- const dir = join37(homedir33(), ".claudish");
80969
+ const dir = join39(homedir35(), ".claudish");
80184
80970
  try {
80185
- mkdirSync18(dir, { recursive: true });
80971
+ mkdirSync19(dir, { recursive: true });
80186
80972
  } catch {}
80187
80973
  return dir;
80188
80974
  }
80189
80975
  function getDiagLogPath() {
80190
- return join37(getClaudishDir(), `diag-${process.pid}.log`);
80976
+ return join39(getClaudishDir(), `diag-${process.pid}.log`);
80191
80977
  }
80192
80978
 
80193
80979
  class LogFileDiagOutput {
@@ -80196,7 +80982,7 @@ class LogFileDiagOutput {
80196
80982
  constructor() {
80197
80983
  this.logPath = getDiagLogPath();
80198
80984
  try {
80199
- writeFileSync21(this.logPath, `--- claudish diag session ${new Date().toISOString()} ---
80985
+ writeFileSync22(this.logPath, `--- claudish diag session ${new Date().toISOString()} ---
80200
80986
  `);
80201
80987
  } catch {}
80202
80988
  this.stream = createWriteStream3(this.logPath, { flags: "a" });
@@ -80215,7 +81001,7 @@ class LogFileDiagOutput {
80215
81001
  this.stream.end();
80216
81002
  } catch {}
80217
81003
  try {
80218
- unlinkSync10(this.logPath);
81004
+ unlinkSync11(this.logPath);
80219
81005
  } catch {}
80220
81006
  }
80221
81007
  getLogPath() {
@@ -80783,9 +81569,9 @@ __export(exports_session_discovery, {
80783
81569
  ACTIVE_WINDOW_MS: () => ACTIVE_WINDOW_MS
80784
81570
  });
80785
81571
  import { execFile, execFileSync as execFileSync2 } from "child_process";
80786
- import { closeSync as closeSync5, openSync as openSync5, readSync, readdirSync as readdirSync7, statSync as statSync6 } from "fs";
80787
- import { homedir as homedir34 } from "os";
80788
- import { basename, join as join38 } from "path";
81572
+ import { closeSync as closeSync6, openSync as openSync6, readSync, readdirSync as readdirSync7, statSync as statSync6 } from "fs";
81573
+ import { homedir as homedir36 } from "os";
81574
+ import { basename, join as join40 } from "path";
80789
81575
  function slugForPath(absPath) {
80790
81576
  return absPath.replace(/[/.]/g, "-");
80791
81577
  }
@@ -80834,7 +81620,7 @@ function projectDirs() {
80834
81620
  }
80835
81621
  }
80836
81622
  function sessionsIn(dirName) {
80837
- const dir = join38(PROJECTS_DIR, dirName);
81623
+ const dir = join40(PROJECTS_DIR, dirName);
80838
81624
  let names;
80839
81625
  try {
80840
81626
  names = readdirSync7(dir).filter((n) => n.endsWith(".jsonl"));
@@ -80843,7 +81629,7 @@ function sessionsIn(dirName) {
80843
81629
  }
80844
81630
  const rows = [];
80845
81631
  for (const n of names) {
80846
- const file2 = join38(dir, n);
81632
+ const file2 = join40(dir, n);
80847
81633
  try {
80848
81634
  const st = statSync6(file2);
80849
81635
  if (st.size === 0)
@@ -81023,7 +81809,7 @@ function readChunk(file2, pos, len) {
81023
81809
  return "";
81024
81810
  let fd = null;
81025
81811
  try {
81026
- fd = openSync5(file2, "r");
81812
+ fd = openSync6(file2, "r");
81027
81813
  const buf = Buffer.allocUnsafe(len);
81028
81814
  const n = readSync(fd, buf, 0, len, pos);
81029
81815
  return buf.subarray(0, n).toString("utf-8");
@@ -81032,7 +81818,7 @@ function readChunk(file2, pos, len) {
81032
81818
  } finally {
81033
81819
  if (fd !== null) {
81034
81820
  try {
81035
- closeSync5(fd);
81821
+ closeSync6(fd);
81036
81822
  } catch {}
81037
81823
  }
81038
81824
  }
@@ -81202,7 +81988,7 @@ function findLatestSessionId(cwd = process.cwd(), sinceMs = 0) {
81202
81988
  }
81203
81989
  var ENTRYPOINT_BYTES = 8192, PROJECTS_DIR, ACTIVE_WINDOW_MS = 120000, HEAD_BYTES, TAIL_BYTES, HARNESS_ENVELOPES, DEEP_TAIL_BYTES, RECENT_AI_TURNS = 5, RECENT_USER_TURNS = 1;
81204
81990
  var init_session_discovery = __esm(() => {
81205
- PROJECTS_DIR = join38(homedir34(), ".claude", "projects");
81991
+ PROJECTS_DIR = join40(homedir36(), ".claude", "projects");
81206
81992
  HEAD_BYTES = 64 * 1024;
81207
81993
  TAIL_BYTES = 128 * 1024;
81208
81994
  HARNESS_ENVELOPES = [
@@ -81215,7 +82001,7 @@ var init_session_discovery = __esm(() => {
81215
82001
  });
81216
82002
 
81217
82003
  // src/session/conversation.ts
81218
- import { closeSync as closeSync6, openSync as openSync6, readSync as readSync2, statSync as statSync7 } from "fs";
82004
+ import { closeSync as closeSync7, openSync as openSync7, readSync as readSync2, statSync as statSync7 } from "fs";
81219
82005
  import { StringDecoder } from "string_decoder";
81220
82006
  function looksLikeTurn(line) {
81221
82007
  const assistant = line.includes('"type":"assistant"');
@@ -81271,7 +82057,7 @@ function readConversation(file2, opts = {}) {
81271
82057
  let fd = null;
81272
82058
  try {
81273
82059
  const size = statSync7(file2).size;
81274
- fd = openSync6(file2, "r");
82060
+ fd = openSync7(file2, "r");
81275
82061
  const buf = Buffer.allocUnsafe(chunkBytes);
81276
82062
  const decoder = new StringDecoder("utf-8");
81277
82063
  let pending = "";
@@ -81327,7 +82113,7 @@ function readConversation(file2, opts = {}) {
81327
82113
  } catch {} finally {
81328
82114
  if (fd !== null) {
81329
82115
  try {
81330
- closeSync6(fd);
82116
+ closeSync7(fd);
81331
82117
  } catch {}
81332
82118
  }
81333
82119
  }
@@ -82894,16 +83680,16 @@ __export(exports_session_stats, {
82894
83680
  readSessionStats: () => readSessionStats,
82895
83681
  computeSavings: () => computeSavings
82896
83682
  });
82897
- import { readFileSync as readFileSync29 } from "fs";
82898
- import { homedir as homedir35 } from "os";
82899
- import { join as join39 } from "path";
83683
+ import { readFileSync as readFileSync31 } from "fs";
83684
+ import { homedir as homedir37 } from "os";
83685
+ import { join as join41 } from "path";
82900
83686
  function tokenFilePath(port) {
82901
- return process.env.CLAUDISH_TOKEN_FILE || join39(homedir35(), ".claudish", `tokens-${port}.json`);
83687
+ return process.env.CLAUDISH_TOKEN_FILE || join41(homedir37(), ".claudish", `tokens-${port}.json`);
82902
83688
  }
82903
83689
  function readSessionStats(port, opts) {
82904
83690
  let raw2;
82905
83691
  try {
82906
- raw2 = JSON.parse(readFileSync29(tokenFilePath(port), "utf-8"));
83692
+ raw2 = JSON.parse(readFileSync31(tokenFilePath(port), "utf-8"));
82907
83693
  } catch {
82908
83694
  return null;
82909
83695
  }
@@ -83243,8 +84029,8 @@ var init_session_summary = __esm(() => {
83243
84029
  init_op_source();
83244
84030
  init_startup_trace();
83245
84031
  var import_dotenv3 = __toESM(require_main(), 1);
83246
- import { existsSync as existsSync29, readFileSync as readFileSync30 } from "fs";
83247
- import { join as join40, resolve as resolve5 } from "path";
84032
+ import { existsSync as existsSync31, readFileSync as readFileSync32 } from "fs";
84033
+ import { join as join42, resolve as resolve5 } from "path";
83248
84034
  import_dotenv3.config({ quiet: true });
83249
84035
  function classifyStartupKind() {
83250
84036
  const argv = process.argv.slice(2);
@@ -83343,7 +84129,7 @@ async function applyConfigOverride() {
83343
84129
  const { planConfigOverride: planConfigOverride2, setConfigFileOverride: setConfigFileOverride2 } = await Promise.resolve().then(() => exports_config_override);
83344
84130
  const plan = planConfigOverride2(process.argv.slice(2), process.env, {
83345
84131
  resolve: resolve5,
83346
- exists: existsSync29
84132
+ exists: existsSync31
83347
84133
  });
83348
84134
  if (plan.kind === "none")
83349
84135
  return;
@@ -83498,14 +84284,14 @@ async function runCli() {
83498
84284
  if (cliConfig.team && cliConfig.team.length > 0) {
83499
84285
  let prompt = cliConfig.claudeArgs.join(" ");
83500
84286
  if (cliConfig.inputFile) {
83501
- prompt = readFileSync30(cliConfig.inputFile, "utf-8");
84287
+ prompt = readFileSync32(cliConfig.inputFile, "utf-8");
83502
84288
  }
83503
84289
  if (!prompt.trim()) {
83504
84290
  console.error("Error: --team requires a prompt (positional args or -f <file>)");
83505
84291
  process.exit(1);
83506
84292
  }
83507
84293
  const mode = cliConfig.teamMode ?? "default";
83508
- const sessionPath = join40(process.cwd(), `.claudish-team-${Date.now()}`);
84294
+ const sessionPath = join42(process.cwd(), `.claudish-team-${Date.now()}`);
83509
84295
  if (mode === "json") {
83510
84296
  const { setupSession: setupSession2, runModels: runModels2 } = await Promise.resolve().then(() => (init_team_orchestrator(), exports_team_orchestrator));
83511
84297
  setupSession2(sessionPath, cliConfig.team, prompt);
@@ -83515,9 +84301,9 @@ async function runCli() {
83515
84301
  });
83516
84302
  const result = { ...status2, responses: {} };
83517
84303
  for (const anonId of Object.keys(status2.models)) {
83518
- const responsePath = join40(sessionPath, `response-${anonId}.md`);
84304
+ const responsePath = join42(sessionPath, `response-${anonId}.md`);
83519
84305
  try {
83520
- const raw2 = readFileSync30(responsePath, "utf-8").trim();
84306
+ const raw2 = readFileSync32(responsePath, "utf-8").trim();
83521
84307
  try {
83522
84308
  result.responses[anonId] = JSON.parse(raw2);
83523
84309
  } catch {