claudish 7.11.0 → 7.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1250 -715
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -581,7 +581,527 @@ var init_onepassword_config = __esm(() => {
581
581
  });
582
582
 
583
583
  // src/version.ts
584
- var VERSION = "7.11.0";
584
+ var VERSION = "7.12.1";
585
+
586
+ // src/logger.ts
587
+ var exports_logger = {};
588
+ __export(exports_logger, {
589
+ truncateContent: () => truncateContent,
590
+ structuralRedact: () => structuralRedact,
591
+ setStderrQuiet: () => setStderrQuiet,
592
+ setLogLevel: () => setLogLevel,
593
+ setDiagOutput: () => setDiagOutput,
594
+ maskCredential: () => maskCredential,
595
+ logStructured: () => logStructured,
596
+ logStderr: () => logStderr,
597
+ log: () => log,
598
+ isLoggingEnabled: () => isLoggingEnabled,
599
+ initLogger: () => initLogger,
600
+ getLogLevel: () => getLogLevel,
601
+ getLogFilePath: () => getLogFilePath,
602
+ getAlwaysOnLogPath: () => getAlwaysOnLogPath
603
+ });
604
+ import { appendFile, existsSync as existsSync2, mkdirSync, readdirSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
605
+ import { homedir as homedir2 } from "os";
606
+ import { join as join2 } from "path";
607
+ function flushLogBuffer() {
608
+ if (!logFilePath || logBuffer.length === 0)
609
+ return;
610
+ const toWrite = logBuffer.join("");
611
+ logBuffer = [];
612
+ appendFile(logFilePath, toWrite, (err) => {
613
+ if (err) {
614
+ console.error(`[claudish] Warning: Failed to write to log file: ${err.message}`);
615
+ }
616
+ });
617
+ }
618
+ function flushAlwaysOnBuffer() {
619
+ if (!alwaysOnLogPath || alwaysOnBuffer.length === 0)
620
+ return;
621
+ const toWrite = alwaysOnBuffer.join("");
622
+ alwaysOnBuffer = [];
623
+ appendFile(alwaysOnLogPath, toWrite, () => {});
624
+ }
625
+ function scheduleFlush() {
626
+ if (flushTimer)
627
+ return;
628
+ flushTimer = setInterval(() => {
629
+ flushLogBuffer();
630
+ flushAlwaysOnBuffer();
631
+ }, FLUSH_INTERVAL_MS);
632
+ process.on("exit", () => {
633
+ if (flushTimer) {
634
+ clearInterval(flushTimer);
635
+ flushTimer = null;
636
+ }
637
+ if (logFilePath && logBuffer.length > 0) {
638
+ writeFileSync2(logFilePath, logBuffer.join(""), { flag: "a" });
639
+ logBuffer = [];
640
+ }
641
+ if (alwaysOnLogPath && alwaysOnBuffer.length > 0) {
642
+ writeFileSync2(alwaysOnLogPath, alwaysOnBuffer.join(""), { flag: "a" });
643
+ alwaysOnBuffer = [];
644
+ }
645
+ });
646
+ }
647
+ function rotateOldLogs(dir, keep) {
648
+ try {
649
+ const files = readdirSync(dir).filter((f) => f.startsWith("claudish_") && f.endsWith(".log")).sort().reverse();
650
+ for (const file of files.slice(keep)) {
651
+ try {
652
+ unlinkSync(join2(dir, file));
653
+ } catch {}
654
+ }
655
+ } catch {}
656
+ }
657
+ function structuralRedact(jsonStr) {
658
+ try {
659
+ const obj = JSON.parse(jsonStr);
660
+ return JSON.stringify(redactDeep(obj));
661
+ } catch {
662
+ return jsonStr.replace(/"[^"]{20,}"/g, (m) => `"<${m.length - 2} chars>"`);
663
+ }
664
+ }
665
+ function redactDeep(val, key) {
666
+ if (val === null || val === undefined)
667
+ return val;
668
+ if (typeof val === "boolean" || typeof val === "number")
669
+ return val;
670
+ if (typeof val === "string") {
671
+ if (key && CONTENT_KEYS.has(key)) {
672
+ return `<${val.length} chars>`;
673
+ }
674
+ return val.length <= 20 ? val : `<${val.length} chars>`;
675
+ }
676
+ if (Array.isArray(val))
677
+ return val.map((v) => redactDeep(v));
678
+ if (typeof val === "object") {
679
+ const result = {};
680
+ for (const [k, v] of Object.entries(val)) {
681
+ result[k] = redactDeep(v, k);
682
+ }
683
+ return result;
684
+ }
685
+ return val;
686
+ }
687
+ function isStructuralLogWorthy(msg) {
688
+ return msg.startsWith("[SSE:") || msg.startsWith("[Proxy]") || msg.startsWith("[Fallback]") || msg.startsWith("[Streaming] ===") || msg.startsWith("[Streaming] Chunk:") || msg.startsWith("[Streaming] Received") || msg.startsWith("[Streaming] Text-based tool calls") || msg.startsWith("[Streaming] Final usage") || msg.startsWith("[Streaming] Sending") || msg.startsWith("[AnthropicSSE] Stream complete") || msg.startsWith("[AnthropicSSE] Tool use:") || msg.includes("Response status:") || msg.includes("Error") || msg.includes("error") || msg.includes("[Auto-route]");
689
+ }
690
+ function redactLogLine(message, timestamp) {
691
+ if (message.startsWith("[SSE:")) {
692
+ const prefixEnd = message.indexOf("] ") + 2;
693
+ const prefix = message.substring(0, prefixEnd);
694
+ const payload = message.substring(prefixEnd);
695
+ return `[${timestamp}] ${prefix}${structuralRedact(payload)}
696
+ `;
697
+ }
698
+ return `[${timestamp}] ${message}
699
+ `;
700
+ }
701
+ function initLogger(debugMode, level = "info", noLogs = false) {
702
+ if (!noLogs) {
703
+ const logsDir = join2(homedir2(), ".claudish", "logs");
704
+ if (!existsSync2(logsDir)) {
705
+ mkdirSync(logsDir, { recursive: true });
706
+ }
707
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").split("T").join("_").slice(0, -5);
708
+ alwaysOnLogPath = join2(logsDir, `claudish_${timestamp}.log`);
709
+ writeFileSync2(alwaysOnLogPath, `Claudish Session Log - ${new Date().toISOString()}
710
+ Mode: structural (content redacted)
711
+ ${"=".repeat(60)}
712
+
713
+ `);
714
+ rotateOldLogs(logsDir, 20);
715
+ scheduleFlush();
716
+ }
717
+ if (debugMode) {
718
+ logLevel = level;
719
+ const logsDir = join2(process.cwd(), "logs");
720
+ if (!existsSync2(logsDir)) {
721
+ mkdirSync(logsDir, { recursive: true });
722
+ }
723
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").split("T").join("_").slice(0, -5);
724
+ logFilePath = join2(logsDir, `claudish_${timestamp}.log`);
725
+ writeFileSync2(logFilePath, `Claudish Debug Log - ${new Date().toISOString()}
726
+ Log Level: ${level}
727
+ ${"=".repeat(80)}
728
+
729
+ `);
730
+ scheduleFlush();
731
+ } else {
732
+ logFilePath = null;
733
+ if (noLogs && flushTimer) {
734
+ clearInterval(flushTimer);
735
+ flushTimer = null;
736
+ }
737
+ }
738
+ }
739
+ function log(message, forceConsole = false) {
740
+ const timestamp = new Date().toISOString();
741
+ const logLine = `[${timestamp}] ${message}
742
+ `;
743
+ if (logFilePath) {
744
+ logBuffer.push(logLine);
745
+ if (logBuffer.length >= MAX_BUFFER_SIZE) {
746
+ flushLogBuffer();
747
+ }
748
+ }
749
+ if (alwaysOnLogPath && isStructuralLogWorthy(message)) {
750
+ const redactedLine = redactLogLine(message, timestamp);
751
+ alwaysOnBuffer.push(redactedLine);
752
+ if (alwaysOnBuffer.length >= MAX_BUFFER_SIZE) {
753
+ flushAlwaysOnBuffer();
754
+ }
755
+ }
756
+ if (forceConsole) {
757
+ console.log(message);
758
+ }
759
+ }
760
+ function logStderr(message) {
761
+ if (diagOutput) {
762
+ diagOutput.write(message);
763
+ } else if (!stderrQuiet) {
764
+ process.stderr.write(`[claudish] ${message}
765
+ `);
766
+ }
767
+ log(message);
768
+ }
769
+ function setDiagOutput(output) {
770
+ diagOutput = output;
771
+ }
772
+ function setStderrQuiet(quiet) {
773
+ stderrQuiet = quiet;
774
+ }
775
+ function getLogFilePath() {
776
+ return logFilePath;
777
+ }
778
+ function getAlwaysOnLogPath() {
779
+ return alwaysOnLogPath;
780
+ }
781
+ function isLoggingEnabled() {
782
+ return logFilePath !== null || alwaysOnLogPath !== null;
783
+ }
784
+ function maskCredential(credential) {
785
+ if (!credential || credential.length <= 8) {
786
+ return "***";
787
+ }
788
+ return `${credential.substring(0, 4)}...${credential.substring(credential.length - 4)}`;
789
+ }
790
+ function setLogLevel(level) {
791
+ logLevel = level;
792
+ if (logFilePath) {
793
+ log(`[Logger] Log level changed to: ${level}`);
794
+ }
795
+ }
796
+ function getLogLevel() {
797
+ return logLevel;
798
+ }
799
+ function truncateContent(content, maxLength = 200) {
800
+ if (content === undefined || content === null)
801
+ return "[empty]";
802
+ const str = typeof content === "string" ? content : JSON.stringify(content) ?? "[empty]";
803
+ if (str.length <= maxLength) {
804
+ return str;
805
+ }
806
+ return `${str.substring(0, maxLength)}... [truncated ${str.length - maxLength} chars]`;
807
+ }
808
+ function logStructured(label, data) {
809
+ if (!logFilePath)
810
+ return;
811
+ if (logLevel === "minimal") {
812
+ log(`[${label}]`);
813
+ return;
814
+ }
815
+ if (logLevel === "info") {
816
+ const structured = {};
817
+ for (const [key, value] of Object.entries(data)) {
818
+ if (typeof value === "string" || typeof value === "object") {
819
+ structured[key] = truncateContent(value, 150);
820
+ } else {
821
+ structured[key] = value;
822
+ }
823
+ }
824
+ log(`[${label}] ${JSON.stringify(structured, null, 2)}`);
825
+ return;
826
+ }
827
+ log(`[${label}] ${JSON.stringify(data, null, 2)}`);
828
+ }
829
+ var logFilePath = null, logLevel = "info", stderrQuiet = false, diagOutput = null, logBuffer, flushTimer = null, FLUSH_INTERVAL_MS = 100, MAX_BUFFER_SIZE = 50, alwaysOnLogPath = null, alwaysOnBuffer, CONTENT_KEYS;
830
+ var init_logger = __esm(() => {
831
+ logBuffer = [];
832
+ alwaysOnBuffer = [];
833
+ CONTENT_KEYS = new Set([
834
+ "content",
835
+ "reasoning_content",
836
+ "text",
837
+ "thinking",
838
+ "partial_json",
839
+ "arguments",
840
+ "input"
841
+ ]);
842
+ });
843
+
844
+ // src/startup-trace.ts
845
+ import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
846
+ import { homedir as homedir3 } from "os";
847
+ import { dirname, join as join3 } from "path";
848
+ function defaultSeams() {
849
+ return {
850
+ now: () => performance.now(),
851
+ outPath: STARTUP_METRICS_FILE,
852
+ env: process.env,
853
+ stderr: (line) => {
854
+ process.stderr.write(`${line}
855
+ `);
856
+ },
857
+ maxLines: STARTUP_METRICS_MAX_LINES,
858
+ slowThresholdMs: SLOW_START_THRESHOLD_MS
859
+ };
860
+ }
861
+ function round1(n) {
862
+ return Math.round(n * 10) / 10;
863
+ }
864
+ function safeNow() {
865
+ try {
866
+ return seams.now();
867
+ } catch {
868
+ return 0;
869
+ }
870
+ }
871
+ function traceModeOn() {
872
+ try {
873
+ return seams.env.CLAUDISH_STARTUP_TRACE === "1";
874
+ } catch {
875
+ return false;
876
+ }
877
+ }
878
+ function errorMeta(err) {
879
+ let msg;
880
+ try {
881
+ msg = err instanceof Error ? err.message : String(err);
882
+ } catch {
883
+ msg = "unknown";
884
+ }
885
+ const firstLine = msg.split(`
886
+ `)[0] ?? "";
887
+ return { error: true, errorMsg: firstLine.slice(0, 120) };
888
+ }
889
+ function record(name, startMs, meta) {
890
+ try {
891
+ const span = {
892
+ name,
893
+ startMs: round1(startMs),
894
+ durMs: round1(safeNow() - startMs),
895
+ ...meta && Object.keys(meta).length > 0 ? { meta } : {}
896
+ };
897
+ if (terminalSuppressed) {
898
+ try {
899
+ suppressedLogSink?.(`[startup-trace] ${formatSpanLine(span)}`);
900
+ } catch {}
901
+ if (spans.length < MAX_BUFFERED_SPANS)
902
+ spans.push(span);
903
+ return;
904
+ }
905
+ if (finalized) {
906
+ if (traceModeOn())
907
+ seams.stderr(`[startup-trace] ${formatSpanLine(span)}`);
908
+ return;
909
+ }
910
+ if (spans.length >= MAX_BUFFERED_SPANS)
911
+ return;
912
+ spans.push(span);
913
+ } catch {}
914
+ }
915
+ function isThenable(v) {
916
+ return !!v && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
917
+ }
918
+ function traceSpan(name, fn, meta) {
919
+ const start = safeNow();
920
+ let result;
921
+ try {
922
+ result = fn();
923
+ } catch (err) {
924
+ record(name, start, { ...meta, ...errorMeta(err) });
925
+ throw err;
926
+ }
927
+ if (isThenable(result)) {
928
+ return result.then((value) => {
929
+ record(name, start, meta);
930
+ return value;
931
+ }, (err) => {
932
+ record(name, start, { ...meta, ...errorMeta(err) });
933
+ throw err;
934
+ });
935
+ }
936
+ record(name, start, meta);
937
+ return result;
938
+ }
939
+ function beginSpan(name, meta) {
940
+ const start = safeNow();
941
+ let ended = false;
942
+ return (extraMeta) => {
943
+ if (ended)
944
+ return;
945
+ ended = true;
946
+ record(name, start, { ...meta, ...extraMeta });
947
+ };
948
+ }
949
+ function beginQueuedSpan(name, meta) {
950
+ const enqueuedAt = safeNow();
951
+ let startedAt;
952
+ let ended = false;
953
+ return {
954
+ start() {
955
+ if (startedAt === undefined)
956
+ startedAt = safeNow();
957
+ },
958
+ end(extraMeta) {
959
+ if (ended)
960
+ return;
961
+ ended = true;
962
+ const endAt = safeNow();
963
+ const startAt = startedAt ?? endAt;
964
+ record(name, enqueuedAt, {
965
+ ...meta,
966
+ ...extraMeta,
967
+ waitMs: round1(startAt - enqueuedAt),
968
+ execMs: round1(endAt - startAt)
969
+ });
970
+ }
971
+ };
972
+ }
973
+ function addSpanMeta(name, meta) {
974
+ try {
975
+ if (finalized)
976
+ return;
977
+ for (let i = spans.length - 1;i >= 0; i--) {
978
+ if (spans[i].name === name) {
979
+ spans[i].meta = { ...spans[i].meta, ...meta };
980
+ return;
981
+ }
982
+ }
983
+ } catch {}
984
+ }
985
+ function suppressStartupTraceTerminalOutput(opts = {}) {
986
+ try {
987
+ terminalSuppressed = true;
988
+ if (opts.logSink) {
989
+ suppressedLogSink = opts.logSink;
990
+ return;
991
+ }
992
+ Promise.resolve().then(() => (init_logger(), exports_logger)).then((logger) => {
993
+ suppressedLogSink = (line) => {
994
+ if (logger.getLogFilePath())
995
+ logger.log(line);
996
+ };
997
+ }).catch(() => {});
998
+ } catch {}
999
+ }
1000
+ function setStartupAuthKind(kind) {
1001
+ try {
1002
+ if (!finalized)
1003
+ authKind = kind;
1004
+ } catch {}
1005
+ }
1006
+ function fmtDur(ms) {
1007
+ if (!Number.isFinite(ms))
1008
+ return "?";
1009
+ if (ms >= 1000)
1010
+ return `${(ms / 1000).toFixed(1)}s`;
1011
+ return `${Math.round(ms)}ms`;
1012
+ }
1013
+ function fmtWaitExec(meta) {
1014
+ if (typeof meta?.waitMs !== "number" || typeof meta?.execMs !== "number")
1015
+ return "";
1016
+ return ` (wait ${fmtDur(meta.waitMs)} + exec ${fmtDur(meta.execMs)})`;
1017
+ }
1018
+ function fmtExtraMeta(meta) {
1019
+ if (!meta)
1020
+ return "";
1021
+ const parts = Object.entries(meta).filter(([k]) => k !== "waitMs" && k !== "execMs").map(([k, v]) => `${k}=${v}`);
1022
+ return parts.length > 0 ? ` ${parts.join(" ")}` : "";
1023
+ }
1024
+ function formatSpanLine(span) {
1025
+ return `${span.name} ${fmtDur(span.durMs)}${fmtWaitExec(span.meta)}${fmtExtraMeta(span.meta)}`;
1026
+ }
1027
+ function displayPath(p) {
1028
+ try {
1029
+ const home = homedir3();
1030
+ return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
1031
+ } catch {
1032
+ return p;
1033
+ }
1034
+ }
1035
+ function writeJsonlCapped(payload) {
1036
+ const path = seams.outPath;
1037
+ const line = JSON.stringify(payload);
1038
+ try {
1039
+ mkdirSync2(dirname(path), { recursive: true });
1040
+ } catch {}
1041
+ let existing;
1042
+ try {
1043
+ existing = readFileSync2(path, "utf-8").split(`
1044
+ `).filter((l) => l.trim() !== "");
1045
+ } catch {
1046
+ existing = undefined;
1047
+ }
1048
+ if (existing && existing.length + 1 > seams.maxLines) {
1049
+ const kept = [...existing, line].slice(-seams.maxLines);
1050
+ writeFileSync3(path, `${kept.join(`
1051
+ `)}
1052
+ `);
1053
+ } else {
1054
+ appendFileSync(path, `${line}
1055
+ `);
1056
+ }
1057
+ }
1058
+ function printSlowLine(payload) {
1059
+ const top = [...payload.spans].sort((a, b) => b.durMs - a.durMs).slice(0, 3).map((s) => `${s.name} ${fmtDur(s.durMs)}${fmtWaitExec(s.meta)}`);
1060
+ const detail = top.length > 0 ? ` \u2014 ${top.join(", ")}` : "";
1061
+ seams.stderr(`[claudish] slow start ${fmtDur(payload.totalMs)}${detail} \u2026 full data: ` + `${displayPath(seams.outPath)} (CLAUDISH_STARTUP_TRACE=1 for live detail)`);
1062
+ }
1063
+ function printTable(payload) {
1064
+ seams.stderr(`[claudish] startup trace (${payload.argvKind}) \u2014 total ${fmtDur(payload.totalMs)}` + ` \xB7 auth ${payload.authKind} \xB7 v${payload.version}`);
1065
+ seams.stderr(" start dur span");
1066
+ for (const s of payload.spans) {
1067
+ const start = fmtDur(s.startMs).padStart(7);
1068
+ const dur = fmtDur(s.durMs).padStart(9);
1069
+ seams.stderr(` ${start} ${dur} ${s.name}${fmtWaitExec(s.meta)}${fmtExtraMeta(s.meta)}`);
1070
+ }
1071
+ seams.stderr(` metrics: ${displayPath(seams.outPath)}`);
1072
+ }
1073
+ function finalizeStartupTrace(context, opts = {}) {
1074
+ try {
1075
+ if (finalized)
1076
+ return;
1077
+ const totalMs = safeNow();
1078
+ const payload = {
1079
+ ts: new Date().toISOString(),
1080
+ version: VERSION,
1081
+ argvKind: context,
1082
+ totalMs: round1(totalMs),
1083
+ authKind,
1084
+ spans
1085
+ };
1086
+ finalized = true;
1087
+ try {
1088
+ writeJsonlCapped(payload);
1089
+ } catch {}
1090
+ try {
1091
+ if (terminalSuppressed) {} else if (traceModeOn()) {
1092
+ printTable(payload);
1093
+ } else if (totalMs > seams.slowThresholdMs && !opts.quiet) {
1094
+ printSlowLine(payload);
1095
+ }
1096
+ } catch {}
1097
+ } catch {}
1098
+ }
1099
+ var STARTUP_METRICS_FILE, STARTUP_METRICS_MAX_LINES = 500, SLOW_START_THRESHOLD_MS = 8000, MAX_BUFFERED_SPANS = 500, seams, spans, finalized = false, authKind = "none", terminalSuppressed = false, suppressedLogSink;
1100
+ var init_startup_trace = __esm(() => {
1101
+ STARTUP_METRICS_FILE = join3(homedir3(), ".claudish", "startup-metrics.jsonl");
1102
+ seams = defaultSeams();
1103
+ spans = [];
1104
+ });
585
1105
 
586
1106
  // src/providers/onepassword-wasm.ts
587
1107
  var exports_onepassword_wasm = {};
@@ -595,17 +1115,17 @@ __export(exports_onepassword_wasm, {
595
1115
  SDK_CORE_INTEGRITY: () => SDK_CORE_INTEGRITY
596
1116
  });
597
1117
  import { createHash } from "crypto";
598
- import { copyFileSync, existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2 } from "fs";
1118
+ import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
599
1119
  import { createRequire } from "module";
600
- import { homedir as homedir2 } from "os";
601
- import { dirname, join as join2 } from "path";
1120
+ import { homedir as homedir4 } from "os";
1121
+ import { dirname as dirname2, join as join4 } from "path";
602
1122
  import { gunzipSync } from "zlib";
603
1123
  function tarballUrl() {
604
1124
  return `https://registry.npmjs.org/@1password/sdk-core/-/sdk-core-${SDK_CORE_VERSION}.tgz`;
605
1125
  }
606
1126
  function cacheWasmPath() {
607
- const root = cacheRootOverride ?? join2(homedir2(), ".claudish");
608
- return join2(root, "cache", "1password", WASM_FILENAME);
1127
+ const root = cacheRootOverride ?? join4(homedir4(), ".claudish");
1128
+ return join4(root, "cache", "1password", WASM_FILENAME);
609
1129
  }
610
1130
  function verifyIntegrity(bytes) {
611
1131
  const [algo, expected] = SDK_CORE_INTEGRITY.split("-", 2);
@@ -641,12 +1161,12 @@ function installReadFileSyncIntercept() {
641
1161
  fs.readFileSync = (path, ...rest) => {
642
1162
  if (typeof path === "string" && path.endsWith(WASM_FILENAME)) {
643
1163
  const cached = cacheWasmPath();
644
- if (existsSync2(cached)) {
1164
+ if (existsSync3(cached)) {
645
1165
  return original(cached);
646
1166
  }
647
- if (existsSync2(path)) {
1167
+ if (existsSync3(path)) {
648
1168
  try {
649
- mkdirSync(dirname(cached), { recursive: true });
1169
+ mkdirSync3(dirname2(cached), { recursive: true });
650
1170
  copyFileSync(path, cached);
651
1171
  } catch {}
652
1172
  }
@@ -669,9 +1189,9 @@ async function downloadAndCacheWasm() {
669
1189
  if (!wasm) {
670
1190
  throw new Error(`1Password runtime archive did not contain ${WASM_TARBALL_ENTRY}`);
671
1191
  }
672
- mkdirSync(dirname(cached), { recursive: true });
1192
+ mkdirSync3(dirname2(cached), { recursive: true });
673
1193
  const tmp = `${cached}.tmp`;
674
- writeFileSync2(tmp, wasm);
1194
+ writeFileSync4(tmp, wasm);
675
1195
  createRequire(import.meta.url)("node:fs").renameSync(tmp, cached);
676
1196
  process.stderr.write(`[claudish] 1Password runtime cached.
677
1197
  `);
@@ -683,7 +1203,7 @@ function ensureOpWasmAvailable() {
683
1203
  return ensured;
684
1204
  ensured = (async () => {
685
1205
  installReadFileSyncIntercept();
686
- if (existsSync2(cacheWasmPath()))
1206
+ if (existsSync3(cacheWasmPath()))
687
1207
  return;
688
1208
  if (seedCacheFromNearbyWasm())
689
1209
  return;
@@ -702,8 +1222,8 @@ function resolveNearbyWasmPath() {
702
1222
  try {
703
1223
  const require2 = createRequire(import.meta.url);
704
1224
  const coreJs = require2.resolve("@1password/sdk-core/nodejs/core.js");
705
- const wasm = join2(dirname(coreJs), WASM_FILENAME);
706
- return existsSync2(wasm) ? wasm : null;
1225
+ const wasm = join4(dirname2(coreJs), WASM_FILENAME);
1226
+ return existsSync3(wasm) ? wasm : null;
707
1227
  } catch {
708
1228
  return null;
709
1229
  }
@@ -714,7 +1234,7 @@ function seedCacheFromNearbyWasm() {
714
1234
  return false;
715
1235
  try {
716
1236
  const cached = cacheWasmPath();
717
- mkdirSync(dirname(cached), { recursive: true });
1237
+ mkdirSync3(dirname2(cached), { recursive: true });
718
1238
  copyFileSync(real, cached);
719
1239
  return true;
720
1240
  } catch {
@@ -3065,9 +3585,11 @@ var exports_onepassword = {};
3065
3585
  __export(exports_onepassword, {
3066
3586
  withSdkRetry: () => withSdkRetry,
3067
3587
  valueTail: () => valueTail,
3588
+ resolveSecretsPartial: () => resolveSecretsPartial,
3068
3589
  resolveSecrets: () => resolveSecrets,
3069
3590
  resolveSdkAuth: () => resolveSdkAuth,
3070
3591
  resolveGlobImportForEnvVars: () => resolveGlobImportForEnvVars,
3592
+ resolveGlobImportAll: () => resolveGlobImportAll,
3071
3593
  resolveGlobImport: () => resolveGlobImport,
3072
3594
  resolveDesktopAccount: () => resolveDesktopAccount,
3073
3595
  resetSdkClientCache: () => resetSdkClientCache,
@@ -3160,7 +3682,7 @@ function globToRegExp(glob) {
3160
3682
  async function discoverItemFields(vault, item, opts = {}) {
3161
3683
  const warn = opts.warn ?? ((m) => console.error(m));
3162
3684
  const client = await acquireSdkClient(opts, `1Password item discovery for '${item}'`);
3163
- const vaults = await client.vaults.list();
3685
+ const vaults = await traceSpan("op:vaults.list", () => client.vaults.list());
3164
3686
  const vaultMatches = vaults.filter((v) => v.title === vault);
3165
3687
  if (vaultMatches.length === 0) {
3166
3688
  throw new Error(`1Password vault '${vault}' not found. ` + `Available vaults: ${vaults.map((v) => v.title).join(", ") || "(none)"}.`);
@@ -3169,7 +3691,7 @@ async function discoverItemFields(vault, item, opts = {}) {
3169
3691
  warn(`[claudish] multiple 1Password vaults titled '${vault}'; using the first ` + `(id ${vaultMatches[0].id}).`);
3170
3692
  }
3171
3693
  const vaultId = vaultMatches[0].id;
3172
- const items = await client.items.list(vaultId);
3694
+ const items = await traceSpan("op:items.list", () => client.items.list(vaultId), { vault });
3173
3695
  const itemMatches = items.filter((i) => i.title === item);
3174
3696
  if (itemMatches.length === 0) {
3175
3697
  throw new Error(`1Password item '${item}' not found in vault '${vault}'. ` + `Available items: ${items.map((i) => i.title).slice(0, 12).join(", ") || "(none)"}.`);
@@ -3178,7 +3700,10 @@ async function discoverItemFields(vault, item, opts = {}) {
3178
3700
  warn(`[claudish] multiple 1Password items titled '${item}' in vault '${vault}'; ` + `using the first (id ${itemMatches[0].id}).`);
3179
3701
  }
3180
3702
  const itemId = itemMatches[0].id;
3181
- const full = await client.items.get(vaultId, itemId);
3703
+ const full = await traceSpan("op:items.get", () => client.items.get(vaultId, itemId), {
3704
+ vault,
3705
+ item
3706
+ });
3182
3707
  const out = [];
3183
3708
  for (const field of full.fields) {
3184
3709
  if (typeof field.title !== "string")
@@ -3198,7 +3723,10 @@ async function discoverItemFields(vault, item, opts = {}) {
3198
3723
  }
3199
3724
  async function discoverItemFieldsById(vaultId, itemId, vaultTitle, itemTitle, opts = {}) {
3200
3725
  const client = await acquireSdkClient(opts, `1Password item discovery for '${itemTitle}'`);
3201
- const full = await client.items.get(vaultId, itemId);
3726
+ const full = await traceSpan("op:items.get", () => client.items.get(vaultId, itemId), {
3727
+ vault: vaultTitle,
3728
+ item: itemTitle
3729
+ });
3202
3730
  const out = [];
3203
3731
  for (const field of full.fields) {
3204
3732
  if (typeof field.title !== "string")
@@ -3218,11 +3746,11 @@ async function discoverItemFieldsById(vaultId, itemId, vaultTitle, itemTitle, op
3218
3746
  }
3219
3747
  async function listVaults(opts = {}) {
3220
3748
  const client = await acquireSdkClient(opts, "1Password vault listing");
3221
- return client.vaults.list();
3749
+ return traceSpan("op:vaults.list", () => client.vaults.list());
3222
3750
  }
3223
3751
  async function listItems(vaultId, opts = {}) {
3224
3752
  const client = await acquireSdkClient(opts, "1Password item listing");
3225
- return client.items.list(vaultId);
3753
+ return traceSpan("op:items.list", () => client.items.list(vaultId));
3226
3754
  }
3227
3755
  function sectionLabel(item, sectionId) {
3228
3756
  if (!sectionId)
@@ -3279,6 +3807,34 @@ async function resolveGlobImport(opPath, opts = {}) {
3279
3807
  env: opts.env
3280
3808
  });
3281
3809
  }
3810
+ async function resolveGlobImportAll(opPath, opts = {}) {
3811
+ const warn = opts.warn ?? ((m) => console.error(m));
3812
+ const glob = parseGlobImport(opPath);
3813
+ const fields = await discoverItemFields(glob.vault, glob.item, {
3814
+ sdkFactory: opts.sdkFactory,
3815
+ auth: opts.auth,
3816
+ env: opts.env,
3817
+ warn
3818
+ });
3819
+ const matches = filterGlobFields(fields, glob);
3820
+ const refMap = {};
3821
+ for (const m of matches) {
3822
+ if (!m.valid)
3823
+ continue;
3824
+ refMap[m.envName] = m.field.reference;
3825
+ }
3826
+ if (Object.keys(refMap).length === 0)
3827
+ return {};
3828
+ const { resolved, failures } = await resolveSecretsPartial(refMap, {
3829
+ sdkFactory: opts.sdkFactory,
3830
+ auth: opts.auth,
3831
+ env: opts.env
3832
+ });
3833
+ for (const f of failures) {
3834
+ warn(`[claudish] 1Password glob field could not be resolved (skipped): ${f}`);
3835
+ }
3836
+ return resolved;
3837
+ }
3282
3838
  async function resolveGlobImportForEnvVars(opPath, envNames, opts = {}) {
3283
3839
  const wanted = new Set(envNames);
3284
3840
  if (wanted.size === 0)
@@ -3399,8 +3955,15 @@ function isTransientSdkError(err) {
3399
3955
  const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
3400
3956
  return msg.includes("ipc operation failed") || msg.includes("ipc operation") || msg.includes("-4") || msg.includes("denied") || msg.includes("broken pipe") || msg.includes("connection") || msg.includes("invalid client id") || msg.includes("invalid client") || msg.includes("invalid session") || msg.includes("session expired") || msg.includes("session not found") || msg.includes("unauthorized") || msg.includes("token expired") || msg.includes("not authenticated");
3401
3957
  }
3402
- function runSdkExclusive(op) {
3403
- const run = sdkQueue.then(op, op);
3958
+ function runSdkExclusive(op, label = "op:sdk-op", meta) {
3959
+ const span = beginQueuedSpan(label, meta);
3960
+ const timedOp = () => {
3961
+ span.start();
3962
+ return op();
3963
+ };
3964
+ const run = sdkQueue.then(timedOp, timedOp);
3965
+ run.then(() => span.end(), (err) => span.end({ error: true, errorMsg: String(err).split(`
3966
+ `)[0].slice(0, 120) }));
3404
3967
  sdkQueue = run.then(() => {
3405
3968
  return;
3406
3969
  }, () => {
@@ -3411,16 +3974,22 @@ function runSdkExclusive(op) {
3411
3974
  function sdkSleep(ms) {
3412
3975
  return new Promise((resolve) => setTimeout(resolve, ms));
3413
3976
  }
3414
- async function withSdkRetry(op) {
3977
+ async function withSdkRetry(op, label = "op:sdk-op") {
3415
3978
  const MAX_ATTEMPTS = 3;
3416
3979
  let lastErr;
3417
3980
  for (let attempt = 1;attempt <= MAX_ATTEMPTS; attempt++) {
3418
3981
  try {
3419
- return await runSdkExclusive(op);
3982
+ const result = await runSdkExclusive(op, label, { attempt });
3983
+ if (attempt > 1)
3984
+ addSpanMeta(label, { attempts: attempt, retried: true, cacheReset: true });
3985
+ return result;
3420
3986
  } catch (err) {
3421
3987
  lastErr = err;
3422
- if (!isTransientSdkError(err) || attempt === MAX_ATTEMPTS)
3988
+ if (!isTransientSdkError(err) || attempt === MAX_ATTEMPTS) {
3989
+ if (attempt > 1)
3990
+ addSpanMeta(label, { attempts: attempt, retried: true, cacheReset: true });
3423
3991
  throw err;
3992
+ }
3424
3993
  resetSdkClientCache();
3425
3994
  await sdkSleep(150 * attempt);
3426
3995
  }
@@ -3446,7 +4015,7 @@ function resolveDesktopAccount(opts = {}) {
3446
4015
  return { accountName: configAccount };
3447
4016
  const lister = opts.opAccountLister ?? defaultOpAccountLister;
3448
4017
  const accounts = lister();
3449
- const remediation = "Set OP_ACCOUNT to your account URL (e.g. my-team.1password.com) or `onepasswordAccount` in ~/.claudish/config.json.";
4018
+ const remediation = "Set OP_ACCOUNT to your account URL (e.g. my-team.1password.com) or " + "`onepasswordAccount` in ~/.claudish/config.json.";
3450
4019
  if (!accounts || accounts.length === 0) {
3451
4020
  return {
3452
4021
  error: `Could not determine which 1Password account to use (no service-account token, and \`op account list\` is unavailable). ${remediation}`
@@ -3500,17 +4069,18 @@ async function acquireSdkClient(opts, context) {
3500
4069
  if (!auth) {
3501
4070
  throw buildAuthError(`1Password SDK auth is required for ${context}, but neither OP_SERVICE_ACCOUNT_TOKEN nor a 1Password account (OP_ACCOUNT / onepasswordAccount config) is available.`);
3502
4071
  }
4072
+ setStartupAuthKind(auth.kind);
3503
4073
  const sdkFactory = opts.sdkFactory ?? defaultSdkClientFactory;
3504
4074
  return sdkFactory(auth);
3505
4075
  }
3506
- function mapSdkResolveAll(refs, response) {
4076
+ function mapSdkResolveAllPartial(refs, response) {
3507
4077
  const responses = response.individualResponses ?? {};
3508
- const out = {};
4078
+ const resolved = {};
3509
4079
  const failures = [];
3510
4080
  for (const [envVar, ref] of Object.entries(refs)) {
3511
4081
  const entry = responses[ref];
3512
4082
  if (entry?.content && typeof entry.content.secret === "string") {
3513
- out[envVar] = entry.content.secret;
4083
+ resolved[envVar] = entry.content.secret;
3514
4084
  continue;
3515
4085
  }
3516
4086
  if (entry?.error !== undefined) {
@@ -3519,12 +4089,16 @@ function mapSdkResolveAll(refs, response) {
3519
4089
  }
3520
4090
  failures.push(`${envVar} (${ref}): no value returned`);
3521
4091
  }
4092
+ return { resolved, failures };
4093
+ }
4094
+ function mapSdkResolveAll(refs, response) {
4095
+ const { resolved, failures } = mapSdkResolveAllPartial(refs, response);
3522
4096
  if (failures.length > 0) {
3523
4097
  throw new Error(`1Password SDK could not resolve secret reference(s):
3524
4098
  ${failures.join(`
3525
4099
  `)}`);
3526
4100
  }
3527
- return out;
4101
+ return resolved;
3528
4102
  }
3529
4103
  function describeSdkError(error) {
3530
4104
  if (error && typeof error === "object") {
@@ -3545,9 +4119,17 @@ async function resolveSecrets(refs, opts = {}) {
3545
4119
  if (keys.length === 0)
3546
4120
  return {};
3547
4121
  const client = await acquireSdkClient(opts, "resolving 1Password secret reference(s)");
3548
- const response = await client.secrets.resolveAll(keys.map((k) => refs[k]));
4122
+ const response = await traceSpan("op:secrets.resolveAll", () => client.secrets.resolveAll(keys.map((k) => refs[k])), { refs: keys.length });
3549
4123
  return mapSdkResolveAll(refs, response);
3550
4124
  }
4125
+ async function resolveSecretsPartial(refs, opts = {}) {
4126
+ const keys = Object.keys(refs);
4127
+ if (keys.length === 0)
4128
+ return { resolved: {}, failures: [] };
4129
+ const client = await acquireSdkClient(opts, "resolving 1Password secret reference(s)");
4130
+ const response = await traceSpan("op:secrets.resolveAll", () => client.secrets.resolveAll(keys.map((k) => refs[k])), { refs: keys.length });
4131
+ return mapSdkResolveAllPartial(refs, response);
4132
+ }
3551
4133
  async function readEnvironment(environmentId, opts = {}) {
3552
4134
  const id = (environmentId ?? "").trim();
3553
4135
  if (id === "") {
@@ -3555,9 +4137,9 @@ async function readEnvironment(environmentId, opts = {}) {
3555
4137
  }
3556
4138
  const client = await acquireSdkClient(opts, `1Password Environment '${id}'`);
3557
4139
  if (!client.environments || typeof client.environments.getVariables !== "function") {
3558
- throw new Error("1Password Environments require @1password/sdk 0.4.1-beta.1 or later (the stable 0.4.0 has no environments API). Install: `bun add @1password/sdk@0.4.1-beta.1`.");
4140
+ throw new Error("1Password Environments require @1password/sdk 0.4.1-beta.1 or later (the " + "stable 0.4.0 has no environments API). Install: " + "`bun add @1password/sdk@0.4.1-beta.1`.");
3559
4141
  }
3560
- const { variables } = await client.environments.getVariables(id);
4142
+ const { variables } = await traceSpan("op:environments.getVariables", () => client.environments.getVariables(id));
3561
4143
  if (!Array.isArray(variables) || variables.length === 0) {
3562
4144
  throw new Error(`1Password Environment '${id}' resolved to no variables. Check that the Environment ID is correct and contains entries.`);
3563
4145
  }
@@ -3574,14 +4156,16 @@ var OP_REF_RE, opHydratedVars, ENV_VAR_NAME_RE, sdkClientCache, defaultSdkClient
3574
4156
  if (cached)
3575
4157
  return cached;
3576
4158
  const build = (async () => {
3577
- const { ensureOpWasmAvailable: ensureOpWasmAvailable2 } = await Promise.resolve().then(() => (init_onepassword_wasm(), exports_onepassword_wasm));
3578
- await ensureOpWasmAvailable2();
3579
- const { createClient, DesktopAuth } = await Promise.resolve().then(() => __toESM(require_sdk(), 1));
3580
- const client = await createClient({
4159
+ const { createClient, DesktopAuth } = await traceSpan("op:sdk-wasm-import", async () => {
4160
+ const { ensureOpWasmAvailable: ensureOpWasmAvailable2 } = await Promise.resolve().then(() => (init_onepassword_wasm(), exports_onepassword_wasm));
4161
+ await ensureOpWasmAvailable2();
4162
+ return Promise.resolve().then(() => __toESM(require_sdk(), 1));
4163
+ });
4164
+ const client = await traceSpan("op:client-handshake", () => createClient({
3581
4165
  auth: auth.kind === "token" ? auth.token : new DesktopAuth(auth.accountName),
3582
4166
  integrationName: "claudish",
3583
4167
  integrationVersion: VERSION || "1.0.0"
3584
- });
4168
+ }), { mayIncludeUserPrompt: true, authKind: auth.kind });
3585
4169
  return client;
3586
4170
  })();
3587
4171
  sdkClientCache.set(key, build);
@@ -3615,6 +4199,7 @@ var OP_REF_RE, opHydratedVars, ENV_VAR_NAME_RE, sdkClientCache, defaultSdkClient
3615
4199
  }
3616
4200
  };
3617
4201
  var init_onepassword = __esm(() => {
4202
+ init_startup_trace();
3618
4203
  OP_REF_RE = /^op:\/\/[^\s]+$/;
3619
4204
  opHydratedVars = new Set;
3620
4205
  ENV_VAR_NAME_RE = /^[A-Z_][A-Z0-9_]*$/;
@@ -3623,9 +4208,9 @@ var init_onepassword = __esm(() => {
3623
4208
  });
3624
4209
 
3625
4210
  // src/auth/credentials/op-source.ts
3626
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
3627
- import { homedir as homedir3 } from "os";
3628
- import { join as join3 } from "path";
4211
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
4212
+ import { homedir as homedir5 } from "os";
4213
+ import { join as join5 } from "path";
3629
4214
  function saveAccount(accountUrl, scope) {
3630
4215
  try {
3631
4216
  saveOnepasswordAccount(accountUrl, scope);
@@ -3680,7 +4265,7 @@ async function getSdkAuth(allowPrompt) {
3680
4265
  const { resolveSdkAuth: resolveSdkAuth2 } = await Promise.resolve().then(() => (init_onepassword(), exports_onepassword));
3681
4266
  const interactive = allowPrompt && Boolean(process.stdout.isTTY) && !process.argv.includes("--stdin");
3682
4267
  try {
3683
- const auth = await resolveSdkAuth2({
4268
+ const auth = await traceSpan("op:auth-resolve", () => resolveSdkAuth2({
3684
4269
  configAccount: readOnepasswordAccount(),
3685
4270
  interactive,
3686
4271
  onNeedsPicker: async (accounts) => {
@@ -3691,7 +4276,7 @@ async function getSdkAuth(allowPrompt) {
3691
4276
  }
3692
4277
  return chosen;
3693
4278
  }
3694
- });
4279
+ }), { mayIncludeUserPrompt: true, interactive });
3695
4280
  cachedSdkAuth = auth;
3696
4281
  sdkAuthResolved = true;
3697
4282
  return auth;
@@ -3708,11 +4293,13 @@ function resolveExplicitFlagAuth() {
3708
4293
  return getSdkAuth(true);
3709
4294
  }
3710
4295
  function readConfigRaw() {
4296
+ if (testSeams?.config)
4297
+ return testSeams.config;
3711
4298
  try {
3712
- const configPath = join3(homedir3(), ".claudish", "config.json");
3713
- if (!existsSync3(configPath))
4299
+ const configPath = join5(homedir5(), ".claudish", "config.json");
4300
+ if (!existsSync4(configPath))
3714
4301
  return {};
3715
- return JSON.parse(readFileSync2(configPath, "utf-8"));
4302
+ return JSON.parse(readFileSync3(configPath, "utf-8"));
3716
4303
  } catch {
3717
4304
  return {};
3718
4305
  }
@@ -3753,8 +4340,21 @@ function computeHasOpSources() {
3753
4340
  }
3754
4341
  return false;
3755
4342
  }
3756
- function runOpExclusive(op) {
3757
- const run = opQueue.then(op, op);
4343
+ function runOpExclusive(op, label = "op:resolve", meta) {
4344
+ const span = beginQueuedSpan(label, meta);
4345
+ let extraMeta = {};
4346
+ const ctx = {
4347
+ addMeta(m) {
4348
+ extraMeta = { ...extraMeta, ...m };
4349
+ }
4350
+ };
4351
+ const timedOp = () => {
4352
+ span.start();
4353
+ return op(ctx);
4354
+ };
4355
+ const run = opQueue.then(timedOp, timedOp);
4356
+ run.then(() => span.end(extraMeta), (err) => span.end({ ...extraMeta, error: true, errorMsg: String(err).split(`
4357
+ `)[0].slice(0, 120) }));
3758
4358
  opQueue = run.then(() => {
3759
4359
  return;
3760
4360
  }, () => {
@@ -3762,6 +4362,48 @@ function runOpExclusive(op) {
3762
4362
  });
3763
4363
  return run;
3764
4364
  }
4365
+ function maskGlobForTrace(globPath) {
4366
+ const body = globPath.startsWith("op://") ? globPath.slice("op://".length) : globPath;
4367
+ const segments = body.split("/");
4368
+ if (segments.length < 2)
4369
+ return globPath.slice(0, 48);
4370
+ const [vault, item, ...rest] = segments;
4371
+ const maskedItem = item.length > 20 ? `${item.slice(0, 12)}\u2026${item.slice(-4)}` : item;
4372
+ return `op://${vault}/${maskedItem}/${rest.join("/")}`;
4373
+ }
4374
+ async function resolveGlobShared(globPath, auth) {
4375
+ const existing = globResolutions.get(globPath);
4376
+ if (existing)
4377
+ return { resolved: await existing, cacheHit: true };
4378
+ const spanName = `op:glob-resolve(${maskGlobForTrace(globPath)})`;
4379
+ const promise = (async () => {
4380
+ const { resolveGlobImportAll: resolveGlobImportAll2, recordOpHydratedVars: recordOpHydratedVars2 } = await Promise.resolve().then(() => (init_onepassword(), exports_onepassword));
4381
+ const resolved = await traceSpan(spanName, () => resolveGlobImportAll2(globPath, {
4382
+ auth,
4383
+ sdkFactory: testSeams?.sdkFactory,
4384
+ warn: (m) => console.error(m)
4385
+ }));
4386
+ addSpanMeta(spanName, { vars: Object.keys(resolved).length });
4387
+ for (const [k, v] of Object.entries(resolved)) {
4388
+ resolvedCache.set(k, v);
4389
+ globResolvedVars.add(k);
4390
+ }
4391
+ recordOpHydratedVars2(Object.keys(resolved));
4392
+ return resolved;
4393
+ })();
4394
+ globResolutions.set(globPath, promise);
4395
+ promise.catch(() => {
4396
+ if (globResolutions.get(globPath) === promise)
4397
+ globResolutions.delete(globPath);
4398
+ });
4399
+ return { resolved: await promise, cacheHit: false };
4400
+ }
4401
+ function invalidateOpResolutionCache() {
4402
+ resolvedCache.clear();
4403
+ globResolutions.clear();
4404
+ globResolvedVars.clear();
4405
+ sniffed = undefined;
4406
+ }
3765
4407
  async function resolveOpKeyForEnvVars(wanted, opts = {}) {
3766
4408
  if (wanted.size === 0)
3767
4409
  return {};
@@ -3776,27 +4418,34 @@ async function resolveOpKeyForEnvVars(wanted, opts = {}) {
3776
4418
  }
3777
4419
  if (stillWanted.size === 0)
3778
4420
  return cached;
3779
- return runOpExclusive(async () => {
4421
+ const label = `op:resolve(${[...stillWanted].sort().join(",")})`;
4422
+ return runOpExclusive(async (span) => {
3780
4423
  const out = { ...cached };
3781
4424
  const wantNow = new Set;
4425
+ let servedFromGlob = false;
3782
4426
  for (const w of stillWanted) {
3783
4427
  const hit = resolvedCache.get(w);
3784
- if (hit !== undefined)
4428
+ if (hit !== undefined) {
3785
4429
  out[w] = hit;
3786
- else
4430
+ if (globResolvedVars.has(w))
4431
+ servedFromGlob = true;
4432
+ } else {
3787
4433
  wantNow.add(w);
4434
+ }
3788
4435
  }
4436
+ if (servedFromGlob)
4437
+ span.addMeta({ globCacheHit: true });
3789
4438
  if (wantNow.size === 0)
3790
4439
  return out;
3791
- const resolved = await resolveOpKeyForEnvVarsInner(wantNow, opts);
4440
+ const resolved = await resolveOpKeyForEnvVarsInner(wantNow, opts, span);
3792
4441
  for (const [k, v] of Object.entries(resolved)) {
3793
4442
  resolvedCache.set(k, v);
3794
4443
  out[k] = v;
3795
4444
  }
3796
4445
  return out;
3797
- });
4446
+ }, label);
3798
4447
  }
3799
- async function resolveOpKeyForEnvVarsInner(wanted, opts = {}) {
4448
+ async function resolveOpKeyForEnvVarsInner(wanted, opts = {}, span) {
3800
4449
  if (wanted.size === 0)
3801
4450
  return {};
3802
4451
  if (!hasOpSources())
@@ -3804,21 +4453,20 @@ async function resolveOpKeyForEnvVarsInner(wanted, opts = {}) {
3804
4453
  const onAuthFailure = opts.onAuthFailure ?? "skip";
3805
4454
  const allowPrompt = opts.allowPrompt ?? false;
3806
4455
  let auth;
3807
- try {
3808
- auth = await getSdkAuth(allowPrompt);
3809
- } catch (err) {
3810
- if (err instanceof OpAuthError && onAuthFailure === "skip") {
3811
- console.error(`[claudish] 1Password auth unavailable, skipping op:// keys: ${err.message}`);
3812
- return {};
4456
+ if (testSeams?.auth) {
4457
+ auth = testSeams.auth;
4458
+ } else {
4459
+ try {
4460
+ auth = await getSdkAuth(allowPrompt);
4461
+ } catch (err) {
4462
+ if (err instanceof OpAuthError && onAuthFailure === "skip") {
4463
+ console.error(`[claudish] 1Password auth unavailable, skipping op:// keys: ${err.message}`);
4464
+ return {};
4465
+ }
4466
+ throw err;
3813
4467
  }
3814
- throw err;
3815
4468
  }
3816
- const {
3817
- collectConfigImports: collectConfigImports2,
3818
- resolveSecrets: resolveSecrets2,
3819
- resolveGlobImportForEnvVars: resolveGlobImportForEnvVars2,
3820
- recordOpHydratedVars: recordOpHydratedVars2
3821
- } = await Promise.resolve().then(() => (init_onepassword(), exports_onepassword));
4469
+ const { collectConfigImports: collectConfigImports2, resolveSecrets: resolveSecrets2, recordOpHydratedVars: recordOpHydratedVars2 } = await Promise.resolve().then(() => (init_onepassword(), exports_onepassword));
3822
4470
  const cfg = readConfigRaw();
3823
4471
  const out = {};
3824
4472
  try {
@@ -3831,7 +4479,10 @@ async function resolveOpKeyForEnvVarsInner(wanted, opts = {}) {
3831
4479
  wantedRefs[envVar] = ref;
3832
4480
  }
3833
4481
  if (Object.keys(wantedRefs).length > 0) {
3834
- const resolved = await resolveSecrets2(wantedRefs, { auth });
4482
+ const resolved = await resolveSecrets2(wantedRefs, {
4483
+ auth,
4484
+ sdkFactory: testSeams?.sdkFactory
4485
+ });
3835
4486
  Object.assign(out, resolved);
3836
4487
  }
3837
4488
  const stillWanted = new Set([...wanted].filter((w) => !(w in out)));
@@ -3839,13 +4490,15 @@ async function resolveOpKeyForEnvVarsInner(wanted, opts = {}) {
3839
4490
  if (stillWanted.size === 0)
3840
4491
  break;
3841
4492
  try {
3842
- const resolved = await resolveGlobImportForEnvVars2(globPath, stillWanted, {
3843
- auth,
3844
- warn: () => {}
3845
- });
3846
- for (const [k, v] of Object.entries(resolved)) {
3847
- out[k] = v;
3848
- stillWanted.delete(k);
4493
+ const { resolved, cacheHit } = await resolveGlobShared(globPath, auth);
4494
+ if (cacheHit)
4495
+ span?.addMeta({ globCacheHit: true });
4496
+ for (const w of [...stillWanted]) {
4497
+ const v = resolved[w];
4498
+ if (v !== undefined) {
4499
+ out[w] = v;
4500
+ stillWanted.delete(w);
4501
+ }
3849
4502
  }
3850
4503
  } catch (globErr) {
3851
4504
  const m = globErr instanceof Error ? globErr.message : String(globErr);
@@ -3865,7 +4518,10 @@ async function resolveOpKeyForEnvVarsInner(wanted, opts = {}) {
3865
4518
  customRefs[envVar] = apiKey;
3866
4519
  }
3867
4520
  if (Object.keys(customRefs).length > 0) {
3868
- const resolved = await resolveSecrets2(customRefs, { auth });
4521
+ const resolved = await resolveSecrets2(customRefs, {
4522
+ auth,
4523
+ sdkFactory: testSeams?.sdkFactory
4524
+ });
3869
4525
  Object.assign(out, resolved);
3870
4526
  }
3871
4527
  }
@@ -3883,9 +4539,10 @@ async function resolveOpKeyForEnvVarsInner(wanted, opts = {}) {
3883
4539
  recordOpHydratedVars2(Object.keys(out));
3884
4540
  return out;
3885
4541
  }
3886
- var OpAuthError, cachedSdkAuth, sdkAuthResolved = false, authInFlight, sniffed, opQueue, resolvedCache;
4542
+ var OpAuthError, cachedSdkAuth, sdkAuthResolved = false, authInFlight, testSeams, sniffed, opQueue, resolvedCache, globResolutions, globResolvedVars;
3887
4543
  var init_op_source = __esm(() => {
3888
4544
  init_onepassword_config();
4545
+ init_startup_trace();
3889
4546
  OpAuthError = class OpAuthError extends Error {
3890
4547
  constructor(message) {
3891
4548
  super(message);
@@ -3894,6 +4551,8 @@ var init_op_source = __esm(() => {
3894
4551
  };
3895
4552
  opQueue = Promise.resolve();
3896
4553
  resolvedCache = new Map;
4554
+ globResolutions = new Map;
4555
+ globResolvedVars = new Set;
3897
4556
  });
3898
4557
 
3899
4558
  // src/onepassword-command.ts
@@ -15889,7 +16548,7 @@ function tuple(items, _paramsOrRest, _params) {
15889
16548
  ...exports_util.normalizeParams(params)
15890
16549
  });
15891
16550
  }
15892
- function record(keyType, valueType, params) {
16551
+ function record2(keyType, valueType, params) {
15893
16552
  return new ZodRecord({
15894
16553
  type: "record",
15895
16554
  keyType,
@@ -16088,7 +16747,7 @@ function _instanceof(cls, params = {
16088
16747
  }
16089
16748
  function json(params) {
16090
16749
  const jsonSchema = lazy(() => {
16091
- return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]);
16750
+ return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record2(string2(), jsonSchema)]);
16092
16751
  });
16093
16752
  return jsonSchema;
16094
16753
  }
@@ -16764,7 +17423,7 @@ __export(exports_external, {
16764
17423
  regexes: () => exports_regexes,
16765
17424
  regex: () => _regex,
16766
17425
  refine: () => refine,
16767
- record: () => record,
17426
+ record: () => record2,
16768
17427
  readonly: () => readonly,
16769
17428
  property: () => _property,
16770
17429
  promise: () => promise,
@@ -17091,7 +17750,7 @@ var init_types = __esm(() => {
17091
17750
  });
17092
17751
  FormElicitationCapabilitySchema = intersection(object2({
17093
17752
  applyDefaults: boolean2().optional()
17094
- }), record(string2(), unknown()));
17753
+ }), record2(string2(), unknown()));
17095
17754
  ElicitationCapabilitySchema = preprocess((value) => {
17096
17755
  if (value && typeof value === "object" && !Array.isArray(value)) {
17097
17756
  if (Object.keys(value).length === 0) {
@@ -17102,7 +17761,7 @@ var init_types = __esm(() => {
17102
17761
  }, intersection(object2({
17103
17762
  form: FormElicitationCapabilitySchema.optional(),
17104
17763
  url: AssertObjectSchema.optional()
17105
- }), record(string2(), unknown()).optional()));
17764
+ }), record2(string2(), unknown()).optional()));
17106
17765
  ClientTasksCapabilitySchema = looseObject({
17107
17766
  list: AssertObjectSchema.optional(),
17108
17767
  cancel: AssertObjectSchema.optional(),
@@ -17125,7 +17784,7 @@ var init_types = __esm(() => {
17125
17784
  }).optional()
17126
17785
  });
17127
17786
  ClientCapabilitiesSchema = object2({
17128
- experimental: record(string2(), AssertObjectSchema).optional(),
17787
+ experimental: record2(string2(), AssertObjectSchema).optional(),
17129
17788
  sampling: object2({
17130
17789
  context: AssertObjectSchema.optional(),
17131
17790
  tools: AssertObjectSchema.optional()
@@ -17146,7 +17805,7 @@ var init_types = __esm(() => {
17146
17805
  params: InitializeRequestParamsSchema
17147
17806
  });
17148
17807
  ServerCapabilitiesSchema = object2({
17149
- experimental: record(string2(), AssertObjectSchema).optional(),
17808
+ experimental: record2(string2(), AssertObjectSchema).optional(),
17150
17809
  logging: AssertObjectSchema.optional(),
17151
17810
  completions: AssertObjectSchema.optional(),
17152
17811
  prompts: object2({
@@ -17246,7 +17905,7 @@ var init_types = __esm(() => {
17246
17905
  ResourceContentsSchema = object2({
17247
17906
  uri: string2(),
17248
17907
  mimeType: optional(string2()),
17249
- _meta: record(string2(), unknown()).optional()
17908
+ _meta: record2(string2(), unknown()).optional()
17250
17909
  });
17251
17910
  TextResourceContentsSchema = ResourceContentsSchema.extend({
17252
17911
  text: string2()
@@ -17350,7 +18009,7 @@ var init_types = __esm(() => {
17350
18009
  });
17351
18010
  GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
17352
18011
  name: string2(),
17353
- arguments: record(string2(), string2()).optional()
18012
+ arguments: record2(string2(), string2()).optional()
17354
18013
  });
17355
18014
  GetPromptRequestSchema = RequestSchema.extend({
17356
18015
  method: literal("prompts/get"),
@@ -17360,34 +18019,34 @@ var init_types = __esm(() => {
17360
18019
  type: literal("text"),
17361
18020
  text: string2(),
17362
18021
  annotations: AnnotationsSchema.optional(),
17363
- _meta: record(string2(), unknown()).optional()
18022
+ _meta: record2(string2(), unknown()).optional()
17364
18023
  });
17365
18024
  ImageContentSchema = object2({
17366
18025
  type: literal("image"),
17367
18026
  data: Base64Schema,
17368
18027
  mimeType: string2(),
17369
18028
  annotations: AnnotationsSchema.optional(),
17370
- _meta: record(string2(), unknown()).optional()
18029
+ _meta: record2(string2(), unknown()).optional()
17371
18030
  });
17372
18031
  AudioContentSchema = object2({
17373
18032
  type: literal("audio"),
17374
18033
  data: Base64Schema,
17375
18034
  mimeType: string2(),
17376
18035
  annotations: AnnotationsSchema.optional(),
17377
- _meta: record(string2(), unknown()).optional()
18036
+ _meta: record2(string2(), unknown()).optional()
17378
18037
  });
17379
18038
  ToolUseContentSchema = object2({
17380
18039
  type: literal("tool_use"),
17381
18040
  name: string2(),
17382
18041
  id: string2(),
17383
- input: record(string2(), unknown()),
17384
- _meta: record(string2(), unknown()).optional()
18042
+ input: record2(string2(), unknown()),
18043
+ _meta: record2(string2(), unknown()).optional()
17385
18044
  });
17386
18045
  EmbeddedResourceSchema = object2({
17387
18046
  type: literal("resource"),
17388
18047
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
17389
18048
  annotations: AnnotationsSchema.optional(),
17390
- _meta: record(string2(), unknown()).optional()
18049
+ _meta: record2(string2(), unknown()).optional()
17391
18050
  });
17392
18051
  ResourceLinkSchema = ResourceSchema.extend({
17393
18052
  type: literal("resource_link")
@@ -17427,17 +18086,17 @@ var init_types = __esm(() => {
17427
18086
  description: string2().optional(),
17428
18087
  inputSchema: object2({
17429
18088
  type: literal("object"),
17430
- properties: record(string2(), AssertObjectSchema).optional(),
18089
+ properties: record2(string2(), AssertObjectSchema).optional(),
17431
18090
  required: array(string2()).optional()
17432
18091
  }).catchall(unknown()),
17433
18092
  outputSchema: object2({
17434
18093
  type: literal("object"),
17435
- properties: record(string2(), AssertObjectSchema).optional(),
18094
+ properties: record2(string2(), AssertObjectSchema).optional(),
17436
18095
  required: array(string2()).optional()
17437
18096
  }).catchall(unknown()).optional(),
17438
18097
  annotations: ToolAnnotationsSchema.optional(),
17439
18098
  execution: ToolExecutionSchema.optional(),
17440
- _meta: record(string2(), unknown()).optional()
18099
+ _meta: record2(string2(), unknown()).optional()
17441
18100
  });
17442
18101
  ListToolsRequestSchema = PaginatedRequestSchema.extend({
17443
18102
  method: literal("tools/list")
@@ -17447,7 +18106,7 @@ var init_types = __esm(() => {
17447
18106
  });
17448
18107
  CallToolResultSchema = ResultSchema.extend({
17449
18108
  content: array(ContentBlockSchema).default([]),
17450
- structuredContent: record(string2(), unknown()).optional(),
18109
+ structuredContent: record2(string2(), unknown()).optional(),
17451
18110
  isError: boolean2().optional()
17452
18111
  });
17453
18112
  CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
@@ -17455,7 +18114,7 @@ var init_types = __esm(() => {
17455
18114
  }));
17456
18115
  CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
17457
18116
  name: string2(),
17458
- arguments: record(string2(), unknown()).optional()
18117
+ arguments: record2(string2(), unknown()).optional()
17459
18118
  });
17460
18119
  CallToolRequestSchema = RequestSchema.extend({
17461
18120
  method: literal("tools/call"),
@@ -17504,7 +18163,7 @@ var init_types = __esm(() => {
17504
18163
  content: array(ContentBlockSchema).default([]),
17505
18164
  structuredContent: object2({}).loose().optional(),
17506
18165
  isError: boolean2().optional(),
17507
- _meta: record(string2(), unknown()).optional()
18166
+ _meta: record2(string2(), unknown()).optional()
17508
18167
  });
17509
18168
  SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
17510
18169
  SamplingMessageContentBlockSchema = discriminatedUnion("type", [
@@ -17517,7 +18176,7 @@ var init_types = __esm(() => {
17517
18176
  SamplingMessageSchema = object2({
17518
18177
  role: RoleSchema,
17519
18178
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
17520
- _meta: record(string2(), unknown()).optional()
18179
+ _meta: record2(string2(), unknown()).optional()
17521
18180
  });
17522
18181
  CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
17523
18182
  messages: array(SamplingMessageSchema),
@@ -17630,7 +18289,7 @@ var init_types = __esm(() => {
17630
18289
  message: string2(),
17631
18290
  requestedSchema: object2({
17632
18291
  type: literal("object"),
17633
- properties: record(string2(), PrimitiveSchemaDefinitionSchema),
18292
+ properties: record2(string2(), PrimitiveSchemaDefinitionSchema),
17634
18293
  required: array(string2()).optional()
17635
18294
  })
17636
18295
  });
@@ -17654,7 +18313,7 @@ var init_types = __esm(() => {
17654
18313
  });
17655
18314
  ElicitResultSchema = ResultSchema.extend({
17656
18315
  action: _enum2(["accept", "decline", "cancel"]),
17657
- content: preprocess((val) => val === null ? undefined : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
18316
+ content: preprocess((val) => val === null ? undefined : val, record2(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
17658
18317
  });
17659
18318
  ResourceTemplateReferenceSchema = object2({
17660
18319
  type: literal("ref/resource"),
@@ -17671,7 +18330,7 @@ var init_types = __esm(() => {
17671
18330
  value: string2()
17672
18331
  }),
17673
18332
  context: object2({
17674
- arguments: record(string2(), string2()).optional()
18333
+ arguments: record2(string2(), string2()).optional()
17675
18334
  }).optional()
17676
18335
  });
17677
18336
  CompleteRequestSchema = RequestSchema.extend({
@@ -17688,7 +18347,7 @@ var init_types = __esm(() => {
17688
18347
  RootSchema = object2({
17689
18348
  uri: string2().startsWith("file://"),
17690
18349
  name: string2().optional(),
17691
- _meta: record(string2(), unknown()).optional()
18350
+ _meta: record2(string2(), unknown()).optional()
17692
18351
  });
17693
18352
  ListRootsRequestSchema = RequestSchema.extend({
17694
18353
  method: literal("roots/list"),
@@ -23041,11 +23700,11 @@ var require_core3 = __commonJS((exports) => {
23041
23700
  Ajv.ValidationError = validation_error_1.default;
23042
23701
  Ajv.MissingRefError = ref_error_1.default;
23043
23702
  exports.default = Ajv;
23044
- function checkOptions(checkOpts, options, msg, log = "error") {
23703
+ function checkOptions(checkOpts, options, msg, log2 = "error") {
23045
23704
  for (const key in checkOpts) {
23046
23705
  const opt = key;
23047
23706
  if (opt in options)
23048
- this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
23707
+ this.logger[log2](`${msg}: option ${key}. ${checkOpts[opt]}`);
23049
23708
  }
23050
23709
  }
23051
23710
  function getSchEnv(keyRef) {
@@ -25944,7 +26603,7 @@ var init_stdio2 = __esm(() => {
25944
26603
  });
25945
26604
 
25946
26605
  // src/channel/diagnostics.ts
25947
- import { appendFileSync } from "fs";
26606
+ import { appendFileSync as appendFileSync2 } from "fs";
25948
26607
  function traceEnabled() {
25949
26608
  return process.env[TRACE_ENV] === "1";
25950
26609
  }
@@ -25955,7 +26614,7 @@ function emit(line) {
25955
26614
  const filePath = process.env[TRACE_FILE_ENV];
25956
26615
  if (filePath) {
25957
26616
  try {
25958
- appendFileSync(filePath, formatted);
26617
+ appendFileSync2(filePath, formatted);
25959
26618
  } catch {}
25960
26619
  }
25961
26620
  }
@@ -26195,9 +26854,9 @@ var init_signal_watcher = __esm(() => {
26195
26854
  // src/channel/session-manager.ts
26196
26855
  import { spawn } from "child_process";
26197
26856
  import { randomUUID } from "crypto";
26198
- import { createWriteStream, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
26199
- import { homedir as homedir4 } from "os";
26200
- import { join as join4 } from "path";
26857
+ import { createWriteStream, mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
26858
+ import { homedir as homedir6 } from "os";
26859
+ import { join as join6 } from "path";
26201
26860
 
26202
26861
  class SessionManager {
26203
26862
  sessions = new Map;
@@ -26217,10 +26876,10 @@ class SessionManager {
26217
26876
  const sessionId = randomUUID().slice(0, 8);
26218
26877
  const timeout = Math.min(opts.timeoutSeconds ?? DEFAULT_TIMEOUT, MAX_TIMEOUT);
26219
26878
  const startedAt = new Date().toISOString();
26220
- const sessionDir = join4(homedir4(), ".claudish", "sessions", sessionId);
26221
- mkdirSync2(sessionDir, { recursive: true });
26879
+ const sessionDir = join6(homedir6(), ".claudish", "sessions", sessionId);
26880
+ mkdirSync4(sessionDir, { recursive: true });
26222
26881
  if (opts.prompt) {
26223
- writeFileSync3(join4(sessionDir, "prompt.md"), opts.prompt, "utf-8");
26882
+ writeFileSync5(join6(sessionDir, "prompt.md"), opts.prompt, "utf-8");
26224
26883
  }
26225
26884
  const args = ["--model", opts.model, "-y", "--stdin", "--quiet", ...opts.claudishFlags ?? []];
26226
26885
  const proc = spawn("claudish", args, {
@@ -26247,7 +26906,7 @@ class SessionManager {
26247
26906
  });
26248
26907
  }
26249
26908
  });
26250
- const outputLogStream = createWriteStream(join4(sessionDir, "output.log"));
26909
+ const outputLogStream = createWriteStream(join6(sessionDir, "output.log"));
26251
26910
  const entry = {
26252
26911
  info: {
26253
26912
  sessionId,
@@ -26294,9 +26953,9 @@ class SessionManager {
26294
26953
  watcher.processExited(code);
26295
26954
  outputLogStream.end();
26296
26955
  if (entry.stderr) {
26297
- writeFileSync3(join4(sessionDir, "stderr.log"), entry.stderr, "utf-8");
26956
+ writeFileSync5(join6(sessionDir, "stderr.log"), entry.stderr, "utf-8");
26298
26957
  }
26299
- writeFileSync3(join4(sessionDir, "meta.json"), JSON.stringify(entry.info, null, 2), "utf-8");
26958
+ writeFileSync5(join6(sessionDir, "meta.json"), JSON.stringify(entry.info, null, 2), "utf-8");
26300
26959
  this.cleanupSigint();
26301
26960
  });
26302
26961
  proc.on("error", (err) => {
@@ -26469,9 +27128,9 @@ var init_cache_ttl = __esm(() => {
26469
27128
  });
26470
27129
 
26471
27130
  // src/model-loader.ts
26472
- import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";
26473
- import { homedir as homedir5 } from "os";
26474
- import { join as join5 } from "path";
27131
+ import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync6 } from "fs";
27132
+ import { homedir as homedir7 } from "os";
27133
+ import { join as join7 } from "path";
26475
27134
  function groupRecommendedModels(entries) {
26476
27135
  const byId = new Map;
26477
27136
  for (const entry of entries) {
@@ -26567,9 +27226,9 @@ async function getRecommendedModels(opts = {}) {
26567
27226
  if (!forceRefresh && _cachedRecommendedModels) {
26568
27227
  return _cachedRecommendedModels;
26569
27228
  }
26570
- if (!forceRefresh && existsSync4(RECOMMENDED_MODELS_CACHE_PATH)) {
27229
+ if (!forceRefresh && existsSync5(RECOMMENDED_MODELS_CACHE_PATH)) {
26571
27230
  try {
26572
- const cacheData = JSON.parse(readFileSync3(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
27231
+ const cacheData = JSON.parse(readFileSync4(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
26573
27232
  if (cacheData.models && cacheData.models.length > 0 && isFreshEnough(cacheData)) {
26574
27233
  _cachedRecommendedModels = cacheData;
26575
27234
  return cacheData;
@@ -26585,9 +27244,9 @@ async function getRecommendedModels(opts = {}) {
26585
27244
  if (data.models && data.models.length > 0) {
26586
27245
  _cachedRecommendedModels = data;
26587
27246
  try {
26588
- const cacheDir = join5(homedir5(), ".claudish");
26589
- mkdirSync3(cacheDir, { recursive: true });
26590
- writeFileSync4(RECOMMENDED_MODELS_CACHE_PATH, JSON.stringify(data), "utf-8");
27247
+ const cacheDir = join7(homedir7(), ".claudish");
27248
+ mkdirSync5(cacheDir, { recursive: true });
27249
+ writeFileSync6(RECOMMENDED_MODELS_CACHE_PATH, JSON.stringify(data), "utf-8");
26591
27250
  } catch {}
26592
27251
  return data;
26593
27252
  }
@@ -26598,9 +27257,9 @@ async function getRecommendedModels(opts = {}) {
26598
27257
  function getRecommendedModelsSync() {
26599
27258
  if (_cachedRecommendedModels)
26600
27259
  return _cachedRecommendedModels;
26601
- if (existsSync4(RECOMMENDED_MODELS_CACHE_PATH)) {
27260
+ if (existsSync5(RECOMMENDED_MODELS_CACHE_PATH)) {
26602
27261
  try {
26603
- const cacheData = JSON.parse(readFileSync3(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
27262
+ const cacheData = JSON.parse(readFileSync4(RECOMMENDED_MODELS_CACHE_PATH, "utf-8"));
26604
27263
  if (cacheData.models && cacheData.models.length > 0 && isFreshEnough(cacheData)) {
26605
27264
  _cachedRecommendedModels = cacheData;
26606
27265
  return cacheData;
@@ -26724,7 +27383,7 @@ var _cachedModelInfo = null, _cachedModelIds = null, _cachedRecommendedModels =
26724
27383
  var init_model_loader = __esm(() => {
26725
27384
  init_cache_ttl();
26726
27385
  FIREBASE_RECOMMENDED_URL = `${FIREBASE_BASE_URL}?catalog=recommended`;
26727
- RECOMMENDED_MODELS_CACHE_PATH = join5(homedir5(), ".claudish", "recommended-models-cache.json");
27386
+ RECOMMENDED_MODELS_CACHE_PATH = join7(homedir7(), ".claudish", "recommended-models-cache.json");
26728
27387
  FIREBASE_SLUG_TO_PROVIDER_NAME = {
26729
27388
  openai: "openai",
26730
27389
  google: "google",
@@ -26806,21 +27465,21 @@ __export(exports_profile_config, {
26806
27465
  configExistsForScope: () => configExistsForScope,
26807
27466
  configExists: () => configExists
26808
27467
  });
26809
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5 } from "fs";
26810
- import { homedir as homedir6 } from "os";
26811
- import { dirname as dirname2, join as join6, parse as parse6 } from "path";
27468
+ import { existsSync as existsSync6, mkdirSync as mkdirSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync7 } from "fs";
27469
+ import { homedir as homedir8 } from "os";
27470
+ import { dirname as dirname3, join as join8, parse as parse6 } from "path";
26812
27471
  function ensureConfigDir() {
26813
- if (!existsSync5(CONFIG_DIR)) {
26814
- mkdirSync4(CONFIG_DIR, { recursive: true });
27472
+ if (!existsSync6(CONFIG_DIR)) {
27473
+ mkdirSync6(CONFIG_DIR, { recursive: true });
26815
27474
  }
26816
27475
  }
26817
27476
  function loadConfig() {
26818
27477
  ensureConfigDir();
26819
- if (!existsSync5(CONFIG_FILE)) {
27478
+ if (!existsSync6(CONFIG_FILE)) {
26820
27479
  return { ...DEFAULT_CONFIG };
26821
27480
  }
26822
27481
  try {
26823
- const content = readFileSync4(CONFIG_FILE, "utf-8");
27482
+ const content = readFileSync5(CONFIG_FILE, "utf-8");
26824
27483
  const config2 = JSON.parse(content);
26825
27484
  const merged = {
26826
27485
  version: config2.version || DEFAULT_CONFIG.version,
@@ -26871,43 +27530,43 @@ function loadConfig() {
26871
27530
  }
26872
27531
  function saveConfig(config2) {
26873
27532
  ensureConfigDir();
26874
- writeFileSync5(CONFIG_FILE, JSON.stringify(config2, null, 2), "utf-8");
27533
+ writeFileSync7(CONFIG_FILE, JSON.stringify(config2, null, 2), "utf-8");
26875
27534
  }
26876
27535
  function configExists() {
26877
- return existsSync5(CONFIG_FILE);
27536
+ return existsSync6(CONFIG_FILE);
26878
27537
  }
26879
27538
  function getConfigPath() {
26880
27539
  return CONFIG_FILE;
26881
27540
  }
26882
27541
  function getLocalConfigPath() {
26883
- const home = homedir6();
27542
+ const home = homedir8();
26884
27543
  let dir = process.cwd();
26885
27544
  const root = parse6(dir).root;
26886
27545
  while (dir !== root && dir !== home) {
26887
- const candidate = join6(dir, LOCAL_CONFIG_FILENAME);
26888
- if (existsSync5(candidate))
27546
+ const candidate = join8(dir, LOCAL_CONFIG_FILENAME);
27547
+ if (existsSync6(candidate))
26889
27548
  return candidate;
26890
- if (existsSync5(join6(dir, ".git"))) {
27549
+ if (existsSync6(join8(dir, ".git"))) {
26891
27550
  return candidate;
26892
27551
  }
26893
- dir = dirname2(dir);
27552
+ dir = dirname3(dir);
26894
27553
  }
26895
- return join6(process.cwd(), LOCAL_CONFIG_FILENAME);
27554
+ return join8(process.cwd(), LOCAL_CONFIG_FILENAME);
26896
27555
  }
26897
27556
  function localConfigExists() {
26898
- return existsSync5(getLocalConfigPath());
27557
+ return existsSync6(getLocalConfigPath());
26899
27558
  }
26900
27559
  function isProjectDirectory() {
26901
27560
  const cwd = process.cwd();
26902
- return [".git", "package.json", "Cargo.toml", "go.mod", "pyproject.toml", ".claudish.json"].some((f) => existsSync5(join6(cwd, f)));
27561
+ return [".git", "package.json", "Cargo.toml", "go.mod", "pyproject.toml", ".claudish.json"].some((f) => existsSync6(join8(cwd, f)));
26903
27562
  }
26904
27563
  function loadLocalConfig() {
26905
27564
  const localPath = getLocalConfigPath();
26906
- if (!existsSync5(localPath)) {
27565
+ if (!existsSync6(localPath)) {
26907
27566
  return null;
26908
27567
  }
26909
27568
  try {
26910
- const content = readFileSync4(localPath, "utf-8");
27569
+ const content = readFileSync5(localPath, "utf-8");
26911
27570
  const config2 = JSON.parse(content);
26912
27571
  return {
26913
27572
  ...config2,
@@ -26925,7 +27584,7 @@ function saveLocalConfig(config2) {
26925
27584
  if (toWrite.routing !== undefined && Object.keys(toWrite.routing).length === 0) {
26926
27585
  delete toWrite.routing;
26927
27586
  }
26928
- writeFileSync5(getLocalConfigPath(), JSON.stringify(toWrite, null, 2), "utf-8");
27587
+ writeFileSync7(getLocalConfigPath(), JSON.stringify(toWrite, null, 2), "utf-8");
26929
27588
  }
26930
27589
  function loadConfigForScope(scope) {
26931
27590
  if (scope === "local") {
@@ -27166,8 +27825,8 @@ function disableLocalProvider(providerName) {
27166
27825
  }
27167
27826
  var CONFIG_DIR, CONFIG_FILE, LOCAL_CONFIG_FILENAME = ".claudish.json", DEFAULT_CONFIG;
27168
27827
  var init_profile_config = __esm(() => {
27169
- CONFIG_DIR = join6(homedir6(), ".claudish");
27170
- CONFIG_FILE = join6(CONFIG_DIR, "config.json");
27828
+ CONFIG_DIR = join8(homedir8(), ".claudish");
27829
+ CONFIG_FILE = join8(CONFIG_DIR, "config.json");
27171
27830
  DEFAULT_CONFIG = {
27172
27831
  version: "1.0.0",
27173
27832
  defaultProfile: "default",
@@ -30093,264 +30752,6 @@ var cors = (options) => {
30093
30752
  };
30094
30753
  var init_cors = () => {};
30095
30754
 
30096
- // src/logger.ts
30097
- var exports_logger = {};
30098
- __export(exports_logger, {
30099
- truncateContent: () => truncateContent,
30100
- structuralRedact: () => structuralRedact,
30101
- setStderrQuiet: () => setStderrQuiet,
30102
- setLogLevel: () => setLogLevel,
30103
- setDiagOutput: () => setDiagOutput,
30104
- maskCredential: () => maskCredential,
30105
- logStructured: () => logStructured,
30106
- logStderr: () => logStderr,
30107
- log: () => log,
30108
- isLoggingEnabled: () => isLoggingEnabled,
30109
- initLogger: () => initLogger,
30110
- getLogLevel: () => getLogLevel,
30111
- getLogFilePath: () => getLogFilePath,
30112
- getAlwaysOnLogPath: () => getAlwaysOnLogPath
30113
- });
30114
- import { appendFile, existsSync as existsSync6, mkdirSync as mkdirSync5, readdirSync, unlinkSync, writeFileSync as writeFileSync6 } from "fs";
30115
- import { homedir as homedir7 } from "os";
30116
- import { join as join7 } from "path";
30117
- function flushLogBuffer() {
30118
- if (!logFilePath || logBuffer.length === 0)
30119
- return;
30120
- const toWrite = logBuffer.join("");
30121
- logBuffer = [];
30122
- appendFile(logFilePath, toWrite, (err) => {
30123
- if (err) {
30124
- console.error(`[claudish] Warning: Failed to write to log file: ${err.message}`);
30125
- }
30126
- });
30127
- }
30128
- function flushAlwaysOnBuffer() {
30129
- if (!alwaysOnLogPath || alwaysOnBuffer.length === 0)
30130
- return;
30131
- const toWrite = alwaysOnBuffer.join("");
30132
- alwaysOnBuffer = [];
30133
- appendFile(alwaysOnLogPath, toWrite, () => {});
30134
- }
30135
- function scheduleFlush() {
30136
- if (flushTimer)
30137
- return;
30138
- flushTimer = setInterval(() => {
30139
- flushLogBuffer();
30140
- flushAlwaysOnBuffer();
30141
- }, FLUSH_INTERVAL_MS);
30142
- process.on("exit", () => {
30143
- if (flushTimer) {
30144
- clearInterval(flushTimer);
30145
- flushTimer = null;
30146
- }
30147
- if (logFilePath && logBuffer.length > 0) {
30148
- writeFileSync6(logFilePath, logBuffer.join(""), { flag: "a" });
30149
- logBuffer = [];
30150
- }
30151
- if (alwaysOnLogPath && alwaysOnBuffer.length > 0) {
30152
- writeFileSync6(alwaysOnLogPath, alwaysOnBuffer.join(""), { flag: "a" });
30153
- alwaysOnBuffer = [];
30154
- }
30155
- });
30156
- }
30157
- function rotateOldLogs(dir, keep) {
30158
- try {
30159
- const files = readdirSync(dir).filter((f) => f.startsWith("claudish_") && f.endsWith(".log")).sort().reverse();
30160
- for (const file2 of files.slice(keep)) {
30161
- try {
30162
- unlinkSync(join7(dir, file2));
30163
- } catch {}
30164
- }
30165
- } catch {}
30166
- }
30167
- function structuralRedact(jsonStr) {
30168
- try {
30169
- const obj = JSON.parse(jsonStr);
30170
- return JSON.stringify(redactDeep(obj));
30171
- } catch {
30172
- return jsonStr.replace(/"[^"]{20,}"/g, (m) => `"<${m.length - 2} chars>"`);
30173
- }
30174
- }
30175
- function redactDeep(val, key) {
30176
- if (val === null || val === undefined)
30177
- return val;
30178
- if (typeof val === "boolean" || typeof val === "number")
30179
- return val;
30180
- if (typeof val === "string") {
30181
- if (key && CONTENT_KEYS.has(key)) {
30182
- return `<${val.length} chars>`;
30183
- }
30184
- return val.length <= 20 ? val : `<${val.length} chars>`;
30185
- }
30186
- if (Array.isArray(val))
30187
- return val.map((v) => redactDeep(v));
30188
- if (typeof val === "object") {
30189
- const result = {};
30190
- for (const [k, v] of Object.entries(val)) {
30191
- result[k] = redactDeep(v, k);
30192
- }
30193
- return result;
30194
- }
30195
- return val;
30196
- }
30197
- function isStructuralLogWorthy(msg) {
30198
- return msg.startsWith("[SSE:") || msg.startsWith("[Proxy]") || msg.startsWith("[Fallback]") || msg.startsWith("[Streaming] ===") || msg.startsWith("[Streaming] Chunk:") || msg.startsWith("[Streaming] Received") || msg.startsWith("[Streaming] Text-based tool calls") || msg.startsWith("[Streaming] Final usage") || msg.startsWith("[Streaming] Sending") || msg.startsWith("[AnthropicSSE] Stream complete") || msg.startsWith("[AnthropicSSE] Tool use:") || msg.includes("Response status:") || msg.includes("Error") || msg.includes("error") || msg.includes("[Auto-route]");
30199
- }
30200
- function redactLogLine(message, timestamp) {
30201
- if (message.startsWith("[SSE:")) {
30202
- const prefixEnd = message.indexOf("] ") + 2;
30203
- const prefix = message.substring(0, prefixEnd);
30204
- const payload = message.substring(prefixEnd);
30205
- return `[${timestamp}] ${prefix}${structuralRedact(payload)}
30206
- `;
30207
- }
30208
- return `[${timestamp}] ${message}
30209
- `;
30210
- }
30211
- function initLogger(debugMode, level = "info", noLogs = false) {
30212
- if (!noLogs) {
30213
- const logsDir = join7(homedir7(), ".claudish", "logs");
30214
- if (!existsSync6(logsDir)) {
30215
- mkdirSync5(logsDir, { recursive: true });
30216
- }
30217
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-").split("T").join("_").slice(0, -5);
30218
- alwaysOnLogPath = join7(logsDir, `claudish_${timestamp}.log`);
30219
- writeFileSync6(alwaysOnLogPath, `Claudish Session Log - ${new Date().toISOString()}
30220
- Mode: structural (content redacted)
30221
- ${"=".repeat(60)}
30222
-
30223
- `);
30224
- rotateOldLogs(logsDir, 20);
30225
- scheduleFlush();
30226
- }
30227
- if (debugMode) {
30228
- logLevel = level;
30229
- const logsDir = join7(process.cwd(), "logs");
30230
- if (!existsSync6(logsDir)) {
30231
- mkdirSync5(logsDir, { recursive: true });
30232
- }
30233
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-").split("T").join("_").slice(0, -5);
30234
- logFilePath = join7(logsDir, `claudish_${timestamp}.log`);
30235
- writeFileSync6(logFilePath, `Claudish Debug Log - ${new Date().toISOString()}
30236
- Log Level: ${level}
30237
- ${"=".repeat(80)}
30238
-
30239
- `);
30240
- scheduleFlush();
30241
- } else {
30242
- logFilePath = null;
30243
- if (noLogs && flushTimer) {
30244
- clearInterval(flushTimer);
30245
- flushTimer = null;
30246
- }
30247
- }
30248
- }
30249
- function log(message, forceConsole = false) {
30250
- const timestamp = new Date().toISOString();
30251
- const logLine = `[${timestamp}] ${message}
30252
- `;
30253
- if (logFilePath) {
30254
- logBuffer.push(logLine);
30255
- if (logBuffer.length >= MAX_BUFFER_SIZE) {
30256
- flushLogBuffer();
30257
- }
30258
- }
30259
- if (alwaysOnLogPath && isStructuralLogWorthy(message)) {
30260
- const redactedLine = redactLogLine(message, timestamp);
30261
- alwaysOnBuffer.push(redactedLine);
30262
- if (alwaysOnBuffer.length >= MAX_BUFFER_SIZE) {
30263
- flushAlwaysOnBuffer();
30264
- }
30265
- }
30266
- if (forceConsole) {
30267
- console.log(message);
30268
- }
30269
- }
30270
- function logStderr(message) {
30271
- if (diagOutput) {
30272
- diagOutput.write(message);
30273
- } else if (!stderrQuiet) {
30274
- process.stderr.write(`[claudish] ${message}
30275
- `);
30276
- }
30277
- log(message);
30278
- }
30279
- function setDiagOutput(output) {
30280
- diagOutput = output;
30281
- }
30282
- function setStderrQuiet(quiet) {
30283
- stderrQuiet = quiet;
30284
- }
30285
- function getLogFilePath() {
30286
- return logFilePath;
30287
- }
30288
- function getAlwaysOnLogPath() {
30289
- return alwaysOnLogPath;
30290
- }
30291
- function isLoggingEnabled() {
30292
- return logFilePath !== null || alwaysOnLogPath !== null;
30293
- }
30294
- function maskCredential(credential) {
30295
- if (!credential || credential.length <= 8) {
30296
- return "***";
30297
- }
30298
- return `${credential.substring(0, 4)}...${credential.substring(credential.length - 4)}`;
30299
- }
30300
- function setLogLevel(level) {
30301
- logLevel = level;
30302
- if (logFilePath) {
30303
- log(`[Logger] Log level changed to: ${level}`);
30304
- }
30305
- }
30306
- function getLogLevel() {
30307
- return logLevel;
30308
- }
30309
- function truncateContent(content, maxLength = 200) {
30310
- if (content === undefined || content === null)
30311
- return "[empty]";
30312
- const str = typeof content === "string" ? content : JSON.stringify(content) ?? "[empty]";
30313
- if (str.length <= maxLength) {
30314
- return str;
30315
- }
30316
- return `${str.substring(0, maxLength)}... [truncated ${str.length - maxLength} chars]`;
30317
- }
30318
- function logStructured(label, data) {
30319
- if (!logFilePath)
30320
- return;
30321
- if (logLevel === "minimal") {
30322
- log(`[${label}]`);
30323
- return;
30324
- }
30325
- if (logLevel === "info") {
30326
- const structured = {};
30327
- for (const [key, value] of Object.entries(data)) {
30328
- if (typeof value === "string" || typeof value === "object") {
30329
- structured[key] = truncateContent(value, 150);
30330
- } else {
30331
- structured[key] = value;
30332
- }
30333
- }
30334
- log(`[${label}] ${JSON.stringify(structured, null, 2)}`);
30335
- return;
30336
- }
30337
- log(`[${label}] ${JSON.stringify(data, null, 2)}`);
30338
- }
30339
- var logFilePath = null, logLevel = "info", stderrQuiet = false, diagOutput = null, logBuffer, flushTimer = null, FLUSH_INTERVAL_MS = 100, MAX_BUFFER_SIZE = 50, alwaysOnLogPath = null, alwaysOnBuffer, CONTENT_KEYS;
30340
- var init_logger = __esm(() => {
30341
- logBuffer = [];
30342
- alwaysOnBuffer = [];
30343
- CONTENT_KEYS = new Set([
30344
- "content",
30345
- "reasoning_content",
30346
- "text",
30347
- "thinking",
30348
- "partial_json",
30349
- "arguments",
30350
- "input"
30351
- ]);
30352
- });
30353
-
30354
30755
  // src/handlers/shared/remote-provider-types.ts
30355
30756
  function registerDynamicPricingLookup(fn) {
30356
30757
  _dynamicLookup = fn;
@@ -30396,15 +30797,15 @@ var init_remote_provider_types = __esm(() => {
30396
30797
  });
30397
30798
 
30398
30799
  // src/providers/all-models-cache.ts
30399
- import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync7 } from "fs";
30400
- import { homedir as homedir8 } from "os";
30401
- import { dirname as dirname3, join as join8 } from "path";
30800
+ import { existsSync as existsSync7, mkdirSync as mkdirSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync8 } from "fs";
30801
+ import { homedir as homedir9 } from "os";
30802
+ import { dirname as dirname4, join as join9 } from "path";
30402
30803
  function readAllModelsCache(path = ALL_MODELS_CACHE_PATH) {
30403
30804
  if (!existsSync7(path))
30404
30805
  return null;
30405
30806
  let raw2;
30406
30807
  try {
30407
- raw2 = JSON.parse(readFileSync5(path, "utf-8"));
30808
+ raw2 = JSON.parse(readFileSync6(path, "utf-8"));
30408
30809
  } catch {
30409
30810
  return null;
30410
30811
  }
@@ -30429,12 +30830,12 @@ function writeAllModelsCache(data, path = ALL_MODELS_CACHE_PATH) {
30429
30830
  entries: data.entries ?? existing?.entries ?? [],
30430
30831
  models: data.models ?? existing?.models ?? []
30431
30832
  };
30432
- mkdirSync6(dirname3(path), { recursive: true });
30433
- writeFileSync7(path, JSON.stringify(merged), "utf-8");
30833
+ mkdirSync7(dirname4(path), { recursive: true });
30834
+ writeFileSync8(path, JSON.stringify(merged), "utf-8");
30434
30835
  }
30435
30836
  var ALL_MODELS_CACHE_PATH;
30436
30837
  var init_all_models_cache = __esm(() => {
30437
- ALL_MODELS_CACHE_PATH = join8(homedir8(), ".claudish", "all-models.json");
30838
+ ALL_MODELS_CACHE_PATH = join9(homedir9(), ".claudish", "all-models.json");
30438
30839
  });
30439
30840
 
30440
30841
  // src/adapters/model-catalog.ts
@@ -32629,10 +33030,13 @@ var init_grok_model_dialect = __esm(() => {
32629
33030
  }
32630
33031
  effortToReasoningEffort(effort) {
32631
33032
  const model = this.modelId.toLowerCase();
32632
- if (model.includes("non-reasoning") || model.includes("grok-2") || this.isOriginalGrok4()) {
33033
+ const isMini = model.includes("mini");
33034
+ const isGrok43 = /grok-4\.3(\b|[-.]|$)/.test(model);
33035
+ const isFastReasoning = model.includes("fast-reasoning");
33036
+ if (!(isMini || isGrok43 || isFastReasoning)) {
32633
33037
  return;
32634
33038
  }
32635
- if (model.includes("mini")) {
33039
+ if (isMini) {
32636
33040
  switch (effort) {
32637
33041
  case "high":
32638
33042
  case "xhigh":
@@ -32650,20 +33054,10 @@ var init_grok_model_dialect = __esm(() => {
32650
33054
  return "low";
32651
33055
  case "medium":
32652
33056
  return "medium";
32653
- case "high":
32654
- case "xhigh":
32655
- case "max":
32656
- return "high";
32657
33057
  default:
32658
33058
  return "high";
32659
33059
  }
32660
33060
  }
32661
- isOriginalGrok4() {
32662
- const model = this.modelId.toLowerCase();
32663
- if (model.includes("fast") || model.includes("mini"))
32664
- return false;
32665
- return /grok-4(?![.\d])/.test(model);
32666
- }
32667
33061
  parseXmlParameters(xmlContent) {
32668
33062
  const params = {};
32669
33063
  const paramPattern = /<xai:parameter name="([^"]+)">([^<]*)<\/xai:parameter>/g;
@@ -33351,8 +33745,8 @@ ${text}`;
33351
33745
 
33352
33746
  // src/auth/credentials/api-key-credential.ts
33353
33747
  import { existsSync as existsSync8 } from "fs";
33354
- import { homedir as homedir9 } from "os";
33355
- import { join as join9 } from "path";
33748
+ import { homedir as homedir10 } from "os";
33749
+ import { join as join10 } from "path";
33356
33750
 
33357
33751
  class ApiKeyCredentialProvider {
33358
33752
  catalogName;
@@ -33370,7 +33764,7 @@ class ApiKeyCredentialProvider {
33370
33764
  this.aliases = descriptor.aliases ?? [];
33371
33765
  this.authScheme = descriptor.authScheme ?? "bearer";
33372
33766
  this.staticHeaders = descriptor.staticHeaders ?? {};
33373
- this.publicKeyFallback = descriptor.publicKeyFallback ?? false;
33767
+ this.publicKeyFallback = descriptor.publicKeyFallback;
33374
33768
  this.oauthFallback = descriptor.oauthFallback;
33375
33769
  }
33376
33770
  resolveFromEnvConfig() {
@@ -33380,7 +33774,7 @@ class ApiKeyCredentialProvider {
33380
33774
  if (!this.oauthFallback)
33381
33775
  return false;
33382
33776
  try {
33383
- return existsSync8(join9(homedir9(), ".claudish", this.oauthFallback));
33777
+ return existsSync8(join10(homedir10(), ".claudish", this.oauthFallback));
33384
33778
  } catch {
33385
33779
  return false;
33386
33780
  }
@@ -33434,7 +33828,7 @@ class ApiKeyCredentialProvider {
33434
33828
  this.resolving = undefined;
33435
33829
  }
33436
33830
  async getRequestAuth(ctx) {
33437
- const key = await this.resolveKey({ allowOpPrompt: ctx.allowOpPrompt });
33831
+ const key = await this.resolveKey({ allowOpPrompt: ctx.allowOpPrompt }) || this.publicKeyFallback || "";
33438
33832
  let headers;
33439
33833
  if (this.authScheme === "x-api-key") {
33440
33834
  headers = { "x-api-key": key, ...this.staticHeaders };
@@ -33454,10 +33848,10 @@ var init_api_key_credential = __esm(() => {
33454
33848
  // src/auth/codex-oauth.ts
33455
33849
  import { exec } from "child_process";
33456
33850
  import { createHash as createHash2, randomBytes } from "crypto";
33457
- import { closeSync, existsSync as existsSync9, openSync, readFileSync as readFileSync6, unlinkSync as unlinkSync2, writeSync } from "fs";
33851
+ import { closeSync, existsSync as existsSync9, openSync, readFileSync as readFileSync7, unlinkSync as unlinkSync2, writeSync } from "fs";
33458
33852
  import { createServer as createServer2 } from "http";
33459
- import { homedir as homedir10 } from "os";
33460
- import { join as join10 } from "path";
33853
+ import { homedir as homedir11 } from "os";
33854
+ import { join as join11 } from "path";
33461
33855
  import { promisify } from "util";
33462
33856
 
33463
33857
  class CodexOAuth {
@@ -33483,8 +33877,8 @@ class CodexOAuth {
33483
33877
  return this.credentials !== null && !!this.credentials.refresh_token;
33484
33878
  }
33485
33879
  getCredentialsPath() {
33486
- const claudishDir = join10(homedir10(), ".claudish");
33487
- return join10(claudishDir, "codex-oauth.json");
33880
+ const claudishDir = join11(homedir11(), ".claudish");
33881
+ return join11(claudishDir, "codex-oauth.json");
33488
33882
  }
33489
33883
  async login() {
33490
33884
  log("[CodexOAuth] Starting OAuth login flow");
@@ -33592,7 +33986,7 @@ Details: ${e.message}`);
33592
33986
  return null;
33593
33987
  }
33594
33988
  try {
33595
- const data = readFileSync6(credPath, "utf-8");
33989
+ const data = readFileSync7(credPath, "utf-8");
33596
33990
  const credentials = JSON.parse(data);
33597
33991
  if (!credentials.access_token || !credentials.refresh_token || !credentials.expires_at) {
33598
33992
  log("[CodexOAuth] Invalid credentials file structure");
@@ -33607,10 +34001,10 @@ Details: ${e.message}`);
33607
34001
  }
33608
34002
  saveCredentials(credentials) {
33609
34003
  const credPath = this.getCredentialsPath();
33610
- const claudishDir = join10(homedir10(), ".claudish");
34004
+ const claudishDir = join11(homedir11(), ".claudish");
33611
34005
  if (!existsSync9(claudishDir)) {
33612
- const { mkdirSync: mkdirSync7 } = __require("fs");
33613
- mkdirSync7(claudishDir, { recursive: true });
34006
+ const { mkdirSync: mkdirSync8 } = __require("fs");
34007
+ mkdirSync8(claudishDir, { recursive: true });
33614
34008
  }
33615
34009
  const fd = openSync(credPath, "w", 384);
33616
34010
  try {
@@ -33918,10 +34312,10 @@ var init_codex_credential = __esm(() => {
33918
34312
  // src/auth/gemini-oauth.ts
33919
34313
  import { exec as exec2 } from "child_process";
33920
34314
  import { createHash as createHash3, randomBytes as randomBytes2 } from "crypto";
33921
- import { closeSync as closeSync2, existsSync as existsSync10, openSync as openSync2, readFileSync as readFileSync7, unlinkSync as unlinkSync3, writeSync as writeSync2 } from "fs";
34315
+ import { closeSync as closeSync2, existsSync as existsSync10, openSync as openSync2, readFileSync as readFileSync8, unlinkSync as unlinkSync3, writeSync as writeSync2 } from "fs";
33922
34316
  import { createServer as createServer3 } from "http";
33923
- import { homedir as homedir11 } from "os";
33924
- import { join as join11 } from "path";
34317
+ import { homedir as homedir12 } from "os";
34318
+ import { join as join12 } from "path";
33925
34319
  import { promisify as promisify2 } from "util";
33926
34320
 
33927
34321
  class GeminiOAuth {
@@ -33947,8 +34341,8 @@ class GeminiOAuth {
33947
34341
  return this.credentials !== null && !!this.credentials.refresh_token;
33948
34342
  }
33949
34343
  getCredentialsPath() {
33950
- const claudishDir = join11(homedir11(), ".claudish");
33951
- return join11(claudishDir, "gemini-oauth.json");
34344
+ const claudishDir = join12(homedir12(), ".claudish");
34345
+ return join12(claudishDir, "gemini-oauth.json");
33952
34346
  }
33953
34347
  async login() {
33954
34348
  log("[GeminiOAuth] Starting OAuth login flow");
@@ -34050,7 +34444,7 @@ Details: ${e.message}`);
34050
34444
  return null;
34051
34445
  }
34052
34446
  try {
34053
- const data = readFileSync7(credPath, "utf-8");
34447
+ const data = readFileSync8(credPath, "utf-8");
34054
34448
  const credentials = JSON.parse(data);
34055
34449
  if (!credentials.access_token || !credentials.refresh_token || !credentials.expires_at) {
34056
34450
  log("[GeminiOAuth] Invalid credentials file structure");
@@ -34065,10 +34459,10 @@ Details: ${e.message}`);
34065
34459
  }
34066
34460
  saveCredentials(credentials) {
34067
34461
  const credPath = this.getCredentialsPath();
34068
- const claudishDir = join11(homedir11(), ".claudish");
34462
+ const claudishDir = join12(homedir12(), ".claudish");
34069
34463
  if (!existsSync10(claudishDir)) {
34070
- const { mkdirSync: mkdirSync7 } = __require("fs");
34071
- mkdirSync7(claudishDir, { recursive: true });
34464
+ const { mkdirSync: mkdirSync8 } = __require("fs");
34465
+ mkdirSync8(claudishDir, { recursive: true });
34072
34466
  }
34073
34467
  const fd = openSync2(credPath, "w", 384);
34074
34468
  try {
@@ -34429,18 +34823,18 @@ var init_gemini_oauth = __esm(() => {
34429
34823
  });
34430
34824
 
34431
34825
  // src/auth/oauth-registry.ts
34432
- import { existsSync as existsSync11, readFileSync as readFileSync8 } from "fs";
34433
- import { homedir as homedir12 } from "os";
34434
- import { join as join12 } from "path";
34826
+ import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
34827
+ import { homedir as homedir13 } from "os";
34828
+ import { join as join13 } from "path";
34435
34829
  function hasValidOAuthCredentials(descriptor) {
34436
- const credPath = join12(homedir12(), ".claudish", descriptor.credentialFile);
34830
+ const credPath = join13(homedir13(), ".claudish", descriptor.credentialFile);
34437
34831
  if (!existsSync11(credPath))
34438
34832
  return false;
34439
34833
  if (descriptor.validationMode === "file-exists") {
34440
34834
  return true;
34441
34835
  }
34442
34836
  try {
34443
- const data = JSON.parse(readFileSync8(credPath, "utf-8"));
34837
+ const data = JSON.parse(readFileSync9(credPath, "utf-8"));
34444
34838
  if (!data.access_token)
34445
34839
  return false;
34446
34840
  if (data.refresh_token)
@@ -34550,9 +34944,9 @@ var init_gemini_credential = __esm(() => {
34550
34944
  // src/auth/kimi-oauth.ts
34551
34945
  import { exec as exec3 } from "child_process";
34552
34946
  import { randomBytes as randomBytes3 } from "crypto";
34553
- import { closeSync as closeSync3, existsSync as existsSync12, openSync as openSync3, readFileSync as readFileSync9, unlinkSync as unlinkSync4, writeSync as writeSync3 } from "fs";
34554
- import { homedir as homedir13, hostname as hostname3, platform, release } from "os";
34555
- import { join as join13 } from "path";
34947
+ import { closeSync as closeSync3, existsSync as existsSync12, openSync as openSync3, readFileSync as readFileSync10, unlinkSync as unlinkSync4, writeSync as writeSync3 } from "fs";
34948
+ import { homedir as homedir14, hostname as hostname3, platform, release } from "os";
34949
+ import { join as join14 } from "path";
34556
34950
  import { promisify as promisify3 } from "util";
34557
34951
 
34558
34952
  class KimiOAuth {
@@ -34580,23 +34974,23 @@ class KimiOAuth {
34580
34974
  return this.credentials !== null && !!this.credentials.refresh_token;
34581
34975
  }
34582
34976
  getCredentialsPath() {
34583
- const claudishDir = join13(homedir13(), ".claudish");
34584
- return join13(claudishDir, "kimi-oauth.json");
34977
+ const claudishDir = join14(homedir14(), ".claudish");
34978
+ return join14(claudishDir, "kimi-oauth.json");
34585
34979
  }
34586
34980
  getDeviceIdPath() {
34587
- const claudishDir = join13(homedir13(), ".claudish");
34588
- return join13(claudishDir, "kimi-device-id");
34981
+ const claudishDir = join14(homedir14(), ".claudish");
34982
+ return join14(claudishDir, "kimi-device-id");
34589
34983
  }
34590
34984
  loadOrCreateDeviceId() {
34591
34985
  const deviceIdPath = this.getDeviceIdPath();
34592
- const claudishDir = join13(homedir13(), ".claudish");
34986
+ const claudishDir = join14(homedir14(), ".claudish");
34593
34987
  if (!existsSync12(claudishDir)) {
34594
- const { mkdirSync: mkdirSync7 } = __require("fs");
34595
- mkdirSync7(claudishDir, { recursive: true });
34988
+ const { mkdirSync: mkdirSync8 } = __require("fs");
34989
+ mkdirSync8(claudishDir, { recursive: true });
34596
34990
  }
34597
34991
  if (existsSync12(deviceIdPath)) {
34598
34992
  try {
34599
- const deviceId2 = readFileSync9(deviceIdPath, "utf-8").trim();
34993
+ const deviceId2 = readFileSync10(deviceIdPath, "utf-8").trim();
34600
34994
  if (deviceId2) {
34601
34995
  return deviceId2;
34602
34996
  }
@@ -34855,7 +35249,7 @@ Details: ${e.message}`);
34855
35249
  return null;
34856
35250
  }
34857
35251
  try {
34858
- const data = readFileSync9(credPath, "utf-8");
35252
+ const data = readFileSync10(credPath, "utf-8");
34859
35253
  const credentials = JSON.parse(data);
34860
35254
  if (!credentials.access_token || !credentials.refresh_token || !credentials.expires_at || !credentials.scope || !credentials.token_type) {
34861
35255
  log("[KimiOAuth] Invalid credentials file structure");
@@ -34870,10 +35264,10 @@ Details: ${e.message}`);
34870
35264
  }
34871
35265
  saveCredentials(credentials) {
34872
35266
  const credPath = this.getCredentialsPath();
34873
- const claudishDir = join13(homedir13(), ".claudish");
35267
+ const claudishDir = join14(homedir14(), ".claudish");
34874
35268
  if (!existsSync12(claudishDir)) {
34875
- const { mkdirSync: mkdirSync7 } = __require("fs");
34876
- mkdirSync7(claudishDir, { recursive: true });
35269
+ const { mkdirSync: mkdirSync8 } = __require("fs");
35270
+ mkdirSync8(claudishDir, { recursive: true });
34877
35271
  }
34878
35272
  const fd = openSync3(credPath, "w", 384);
34879
35273
  try {
@@ -35046,8 +35440,8 @@ var init_native_anthropic_credential = __esm(() => {
35046
35440
  // src/auth/vertex-auth.ts
35047
35441
  import { exec as exec4 } from "child_process";
35048
35442
  import { existsSync as existsSync13 } from "fs";
35049
- import { homedir as homedir14 } from "os";
35050
- import { join as join14 } from "path";
35443
+ import { homedir as homedir15 } from "os";
35444
+ import { join as join15 } from "path";
35051
35445
  import { promisify as promisify4 } from "util";
35052
35446
 
35053
35447
  class VertexAuthManager {
@@ -35102,7 +35496,7 @@ class VertexAuthManager {
35102
35496
  }
35103
35497
  async tryADC() {
35104
35498
  try {
35105
- const adcPath = join14(homedir14(), ".config/gcloud/application_default_credentials.json");
35499
+ const adcPath = join15(homedir15(), ".config/gcloud/application_default_credentials.json");
35106
35500
  if (!existsSync13(adcPath)) {
35107
35501
  log("[VertexAuth] ADC credentials file not found");
35108
35502
  return null;
@@ -35166,7 +35560,7 @@ function validateVertexOAuthConfig() {
35166
35560
  ` + ` export VERTEX_PROJECT='your-gcp-project-id'
35167
35561
  ` + " export VERTEX_LOCATION='us-central1' # optional";
35168
35562
  }
35169
- const adcPath = join14(homedir14(), ".config/gcloud/application_default_credentials.json");
35563
+ const adcPath = join15(homedir15(), ".config/gcloud/application_default_credentials.json");
35170
35564
  const hasADC = existsSync13(adcPath);
35171
35565
  const hasServiceAccount = !!process.env.GOOGLE_APPLICATION_CREDENTIALS;
35172
35566
  if (!hasADC && !hasServiceAccount) {
@@ -35284,7 +35678,7 @@ class CredentialAuthority {
35284
35678
  static buildDefault() {
35285
35679
  const authority = new CredentialAuthority;
35286
35680
  authority.register(makeCodexCredential(), ["openai-codex"]);
35287
- authority.register(new GeminiCodeAssistCredentialProvider, ["gemini-codeassist", "google"]);
35681
+ authority.register(new GeminiCodeAssistCredentialProvider, ["gemini-codeassist"]);
35288
35682
  authority.register(makeKimiCredential(), ["kimi"]);
35289
35683
  authority.register(makeKimiCodingCredential(), ["kimi-coding"]);
35290
35684
  authority.register(new VertexCredentialProvider, ["vertex"]);
@@ -35295,7 +35689,6 @@ class CredentialAuthority {
35295
35689
  const alreadyRegistered = new Set([
35296
35690
  "openai-codex",
35297
35691
  "gemini-codeassist",
35298
- "google",
35299
35692
  "kimi",
35300
35693
  "kimi-coding",
35301
35694
  "vertex",
@@ -35314,14 +35707,14 @@ class CredentialAuthority {
35314
35707
  envVar: def.apiKeyEnvVar,
35315
35708
  aliases: def.apiKeyAliases,
35316
35709
  authScheme: def.authScheme === "x-api-key" ? "x-api-key" : "bearer",
35317
- publicKeyFallback: !!def.publicKeyFallback,
35710
+ publicKeyFallback: def.publicKeyFallback,
35318
35711
  oauthFallback: def.oauthFallback
35319
- }), [def.name]);
35712
+ }), [def.name, ...RUNTIME_NAME_ALIASES[def.name] ?? []]);
35320
35713
  }
35321
35714
  return authority;
35322
35715
  }
35323
35716
  }
35324
- var LOCAL_PROVIDER_NAMES, credentials;
35717
+ var LOCAL_PROVIDER_NAMES, RUNTIME_NAME_ALIASES, credentials;
35325
35718
  var init_authority = __esm(() => {
35326
35719
  init_provider_definitions();
35327
35720
  init_api_key_credential();
@@ -35332,6 +35725,9 @@ var init_authority = __esm(() => {
35332
35725
  init_native_anthropic_credential();
35333
35726
  init_vertex_credential();
35334
35727
  LOCAL_PROVIDER_NAMES = ["ollama", "lmstudio", "vllm", "mlx"];
35728
+ RUNTIME_NAME_ALIASES = {
35729
+ google: ["gemini"]
35730
+ };
35335
35731
  credentials = CredentialAuthority.buildDefault();
35336
35732
  });
35337
35733
 
@@ -36010,24 +36406,24 @@ var init_model_parser = __esm(() => {
36010
36406
  // src/stats-buffer.ts
36011
36407
  import {
36012
36408
  existsSync as existsSync14,
36013
- mkdirSync as mkdirSync7,
36014
- readFileSync as readFileSync10,
36409
+ mkdirSync as mkdirSync8,
36410
+ readFileSync as readFileSync11,
36015
36411
  renameSync,
36016
36412
  unlinkSync as unlinkSync5,
36017
- writeFileSync as writeFileSync8
36413
+ writeFileSync as writeFileSync9
36018
36414
  } from "fs";
36019
- import { homedir as homedir15 } from "os";
36020
- import { join as join15 } from "path";
36415
+ import { homedir as homedir16 } from "os";
36416
+ import { join as join16 } from "path";
36021
36417
  function ensureDir() {
36022
36418
  if (!existsSync14(CLAUDISH_DIR)) {
36023
- mkdirSync7(CLAUDISH_DIR, { recursive: true });
36419
+ mkdirSync8(CLAUDISH_DIR, { recursive: true });
36024
36420
  }
36025
36421
  }
36026
36422
  function readFromDisk() {
36027
36423
  try {
36028
36424
  if (!existsSync14(BUFFER_FILE))
36029
36425
  return [];
36030
- const raw2 = readFileSync10(BUFFER_FILE, "utf-8");
36426
+ const raw2 = readFileSync11(BUFFER_FILE, "utf-8");
36031
36427
  const parsed = JSON.parse(raw2);
36032
36428
  if (!Array.isArray(parsed.events))
36033
36429
  return [];
@@ -36052,8 +36448,8 @@ function writeToDisk(events) {
36052
36448
  ensureDir();
36053
36449
  const trimmed = enforceSizeCap([...events]);
36054
36450
  const payload = { version: 1, events: trimmed };
36055
- const tmpFile = join15(CLAUDISH_DIR, `stats-buffer.tmp.${process.pid}.json`);
36056
- writeFileSync8(tmpFile, JSON.stringify(payload, null, 2), "utf-8");
36451
+ const tmpFile = join16(CLAUDISH_DIR, `stats-buffer.tmp.${process.pid}.json`);
36452
+ writeFileSync9(tmpFile, JSON.stringify(payload, null, 2), "utf-8");
36057
36453
  renameSync(tmpFile, BUFFER_FILE);
36058
36454
  memoryCache = trimmed;
36059
36455
  } catch {}
@@ -36125,8 +36521,8 @@ function syncFlushOnExit() {
36125
36521
  var BUFFER_MAX_BYTES, CLAUDISH_DIR, BUFFER_FILE, memoryCache = null, eventsSinceLastFlush = 0, flushScheduled = false;
36126
36522
  var init_stats_buffer = __esm(() => {
36127
36523
  BUFFER_MAX_BYTES = 64 * 1024;
36128
- CLAUDISH_DIR = join15(homedir15(), ".claudish");
36129
- BUFFER_FILE = join15(CLAUDISH_DIR, "stats-buffer.json");
36524
+ CLAUDISH_DIR = join16(homedir16(), ".claudish");
36525
+ BUFFER_FILE = join16(CLAUDISH_DIR, "stats-buffer.json");
36130
36526
  process.on("exit", syncFlushOnExit);
36131
36527
  process.on("SIGTERM", () => {
36132
36528
  try {
@@ -37010,12 +37406,12 @@ function statusToErrorType(status) {
37010
37406
  return "api_error";
37011
37407
  }
37012
37408
  }
37013
- function wrapAnthropicError(status, message, errorType) {
37409
+ function wrapAnthropicError(status, message, errorType, upstreamStatus) {
37014
37410
  const type = errorType || statusToErrorType(status);
37015
- return {
37016
- type: "error",
37017
- error: { type, message }
37018
- };
37411
+ const error46 = { type, message };
37412
+ if (upstreamStatus !== undefined)
37413
+ error46.upstream_status = upstreamStatus;
37414
+ return { type: "error", error: error46 };
37019
37415
  }
37020
37416
  function extractProviderMessage(body) {
37021
37417
  if (body == null)
@@ -37334,7 +37730,7 @@ data: ${JSON.stringify(data)}
37334
37730
  };
37335
37731
  const msgId = `msg_${Date.now()}_${Math.random().toString(36).slice(2)}`;
37336
37732
  let usage = null;
37337
- let finalized = false;
37733
+ let finalized2 = false;
37338
37734
  let textStarted = false;
37339
37735
  let textIdx = -1;
37340
37736
  let thinkingStarted = false;
@@ -37363,9 +37759,9 @@ data: ${JSON.stringify(data)}
37363
37759
  }
37364
37760
  }, 1000);
37365
37761
  const finalize = async (reason, err) => {
37366
- if (finalized)
37762
+ if (finalized2)
37367
37763
  return;
37368
- finalized = true;
37764
+ finalized2 = true;
37369
37765
  if (thinkingStarted) {
37370
37766
  send("content_block_stop", { type: "content_block_stop", index: thinkingIdx });
37371
37767
  }
@@ -37995,9 +38391,9 @@ var init_openai_responses_sse = __esm(() => {
37995
38391
  });
37996
38392
 
37997
38393
  // src/handlers/shared/token-tracker.ts
37998
- import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync9 } from "fs";
37999
- import { homedir as homedir16 } from "os";
38000
- import { join as join16 } from "path";
38394
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync10 } from "fs";
38395
+ import { homedir as homedir17 } from "os";
38396
+ import { join as join17 } from "path";
38001
38397
 
38002
38398
  class TokenTracker {
38003
38399
  port;
@@ -38131,9 +38527,9 @@ class TokenTracker {
38131
38527
  if (this.quotaRemaining !== undefined) {
38132
38528
  data.quota_remaining = this.quotaRemaining;
38133
38529
  }
38134
- const claudishDir = join16(homedir16(), ".claudish");
38135
- mkdirSync8(claudishDir, { recursive: true });
38136
- writeFileSync9(join16(claudishDir, `tokens-${this.port}.json`), JSON.stringify(data), "utf-8");
38530
+ const claudishDir = join17(homedir17(), ".claudish");
38531
+ mkdirSync9(claudishDir, { recursive: true });
38532
+ writeFileSync10(join17(claudishDir, `tokens-${this.port}.json`), JSON.stringify(data), "utf-8");
38137
38533
  } catch (e) {
38138
38534
  log(`[TokenTracker] Error writing token file: ${e}`);
38139
38535
  }
@@ -38563,7 +38959,7 @@ class ComposedHandler {
38563
38959
  hint,
38564
38960
  providerMessage: providerMsg
38565
38961
  });
38566
- return c.json(wrapAnthropicError(400, surfaced, "invalid_request_error"), 400);
38962
+ return c.json(wrapAnthropicError(400, surfaced, "invalid_request_error", response.status), 400);
38567
38963
  }
38568
38964
  return c.json(ensureAnthropicErrorFormat(response.status, errorBody), response.status);
38569
38965
  }
@@ -39066,7 +39462,7 @@ var init_model_catalog_resolver = __esm(() => {
39066
39462
  });
39067
39463
 
39068
39464
  // src/handlers/native-handler-advisor.ts
39069
- import { appendFileSync as appendFileSync2 } from "fs";
39465
+ import { appendFileSync as appendFileSync3 } from "fs";
39070
39466
  function loadAdvisorSwapConfig(cliModels, cliCollector) {
39071
39467
  return {
39072
39468
  enabled: process.env.CLAUDISH_SWAP_ADVISOR === "1" || (cliModels?.length ?? 0) > 0,
@@ -39121,7 +39517,7 @@ function logAdvisorEvent(cfg, event) {
39121
39517
  const line = `${JSON.stringify({ ts: new Date().toISOString(), ...event })}
39122
39518
  `;
39123
39519
  try {
39124
- appendFileSync2(cfg.logPath, line);
39520
+ appendFileSync3(cfg.logPath, line);
39125
39521
  } catch {}
39126
39522
  }
39127
39523
  function recordAdvisorEventsFromChunk(cfg, chunkText) {
@@ -40720,9 +41116,9 @@ var init_ollama_api_format = __esm(() => {
40720
41116
  });
40721
41117
 
40722
41118
  // src/providers/api-key-provenance.ts
40723
- import { existsSync as existsSync15, readFileSync as readFileSync11 } from "fs";
40724
- import { homedir as homedir17 } from "os";
40725
- import { join as join17, resolve } from "path";
41119
+ import { existsSync as existsSync15, readFileSync as readFileSync12 } from "fs";
41120
+ import { homedir as homedir18 } from "os";
41121
+ import { join as join18, resolve } from "path";
40726
41122
  function maskKey(key) {
40727
41123
  if (!key)
40728
41124
  return null;
@@ -40797,7 +41193,7 @@ function readDotenvKey(envVars) {
40797
41193
  const dotenvPath = resolve(".env");
40798
41194
  if (!existsSync15(dotenvPath))
40799
41195
  return null;
40800
- const parsed = import_dotenv.parse(readFileSync11(dotenvPath, "utf-8"));
41196
+ const parsed = import_dotenv.parse(readFileSync12(dotenvPath, "utf-8"));
40801
41197
  for (const v of envVars) {
40802
41198
  if (parsed[v])
40803
41199
  return parsed[v];
@@ -40809,10 +41205,10 @@ function readDotenvKey(envVars) {
40809
41205
  }
40810
41206
  function readConfigKey(envVar) {
40811
41207
  try {
40812
- const configPath = join17(homedir17(), ".claudish", "config.json");
41208
+ const configPath = join18(homedir18(), ".claudish", "config.json");
40813
41209
  if (!existsSync15(configPath))
40814
41210
  return null;
40815
- const cfg = JSON.parse(readFileSync11(configPath, "utf-8"));
41211
+ const cfg = JSON.parse(readFileSync12(configPath, "utf-8"));
40816
41212
  return cfg.apiKeys?.[envVar] || null;
40817
41213
  } catch {
40818
41214
  return null;
@@ -41586,7 +41982,7 @@ var init_provider_profiles = __esm(() => {
41586
41982
  };
41587
41983
  openCodeZenProfile = {
41588
41984
  createHandler(ctx) {
41589
- const zenApiKey = ctx.apiKey || "public";
41985
+ const zenApiKey = ctx.apiKey;
41590
41986
  const isGoProvider = ctx.provider.name === "opencode-zen-go";
41591
41987
  if (ctx.modelName.toLowerCase().includes("minimax")) {
41592
41988
  const transport2 = new AnthropicProviderTransport(ctx.provider, zenApiKey);
@@ -43148,9 +43544,9 @@ var init_poe = __esm(() => {
43148
43544
  });
43149
43545
 
43150
43546
  // src/services/pricing-cache.ts
43151
- import { existsSync as existsSync16, readFileSync as readFileSync12, statSync as statSync2 } from "fs";
43152
- import { homedir as homedir18 } from "os";
43153
- import { join as join18 } from "path";
43547
+ import { existsSync as existsSync16, readFileSync as readFileSync13, statSync as statSync2 } from "fs";
43548
+ import { homedir as homedir19 } from "os";
43549
+ import { join as join19 } from "path";
43154
43550
  function prefixMatch(modelName) {
43155
43551
  for (const [key, pricing] of pricingMap) {
43156
43552
  if (modelName.startsWith(key))
@@ -43193,7 +43589,7 @@ function loadDiskCache() {
43193
43589
  const stat = statSync2(CACHE_FILE);
43194
43590
  const age = Date.now() - stat.mtimeMs;
43195
43591
  const isFresh = age < CACHE_TTL_MS2;
43196
- const raw2 = readFileSync12(CACHE_FILE, "utf-8");
43592
+ const raw2 = readFileSync13(CACHE_FILE, "utf-8");
43197
43593
  const data = JSON.parse(raw2);
43198
43594
  for (const [key, pricing] of Object.entries(data)) {
43199
43595
  pricingMap.set(key, pricing);
@@ -43209,8 +43605,8 @@ var init_pricing_cache = __esm(() => {
43209
43605
  init_logger();
43210
43606
  init_catalog_query();
43211
43607
  pricingMap = new Map;
43212
- CACHE_DIR = join18(homedir18(), ".claudish");
43213
- CACHE_FILE = join18(CACHE_DIR, "pricing-cache.json");
43608
+ CACHE_DIR = join19(homedir19(), ".claudish");
43609
+ CACHE_FILE = join19(CACHE_DIR, "pricing-cache.json");
43214
43610
  CACHE_TTL_MS2 = 24 * 60 * 60 * 1000;
43215
43611
  });
43216
43612
 
@@ -43334,6 +43730,11 @@ async function createProxyServer(port, _openrouterApiKey, model, monitorMode = f
43334
43730
  }
43335
43731
  let apiKey = "";
43336
43732
  if (resolved.provider.apiKeyEnvVar) {
43733
+ if (!credentials.get(resolved.provider.name)) {
43734
+ console.error(`[Proxy] No credential provider registered for "${resolved.provider.name}" \u2014 treating as missing credential (authority registration gap)`);
43735
+ log(`[Proxy] Credential authority has no provider registered under "${resolved.provider.name}"`);
43736
+ return null;
43737
+ }
43337
43738
  const auth = await credentials.getRequestAuth(resolved.provider.name, {
43338
43739
  model: resolved.modelName
43339
43740
  });
@@ -43658,12 +44059,12 @@ import { spawn as spawn2 } from "child_process";
43658
44059
  import {
43659
44060
  createWriteStream as createWriteStream2,
43660
44061
  existsSync as existsSync17,
43661
- mkdirSync as mkdirSync9,
43662
- readFileSync as readFileSync13,
44062
+ mkdirSync as mkdirSync10,
44063
+ readFileSync as readFileSync14,
43663
44064
  readdirSync as readdirSync2,
43664
- writeFileSync as writeFileSync10
44065
+ writeFileSync as writeFileSync11
43665
44066
  } from "fs";
43666
- import { join as join19, resolve as resolve2 } from "path";
44067
+ import { join as join20, resolve as resolve2 } from "path";
43667
44068
  function validateSessionPath(sessionPath) {
43668
44069
  const resolved = resolve2(sessionPath);
43669
44070
  const cwd = process.cwd();
@@ -43684,18 +44085,18 @@ function setupSession(sessionPath, models, input) {
43684
44085
  if (models.length === 0) {
43685
44086
  throw new Error("At least one model is required");
43686
44087
  }
43687
- if (existsSync17(join19(sessionPath, "manifest.json"))) {
44088
+ if (existsSync17(join20(sessionPath, "manifest.json"))) {
43688
44089
  throw new Error(`Session already exists at ${sessionPath}. Use a new directory path or delete the existing session first.`);
43689
44090
  }
43690
44091
  const sentinels = models.filter(isSentinelModel);
43691
44092
  if (sentinels.length > 0) {
43692
44093
  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.`);
43693
44094
  }
43694
- mkdirSync9(join19(sessionPath, "work"), { recursive: true });
43695
- mkdirSync9(join19(sessionPath, "errors"), { recursive: true });
44095
+ mkdirSync10(join20(sessionPath, "work"), { recursive: true });
44096
+ mkdirSync10(join20(sessionPath, "errors"), { recursive: true });
43696
44097
  if (input !== undefined) {
43697
- writeFileSync10(join19(sessionPath, "input.md"), input, "utf-8");
43698
- } else if (!existsSync17(join19(sessionPath, "input.md"))) {
44098
+ writeFileSync11(join20(sessionPath, "input.md"), input, "utf-8");
44099
+ } else if (!existsSync17(join20(sessionPath, "input.md"))) {
43699
44100
  throw new Error(`No input.md found at ${sessionPath} and no input provided`);
43700
44101
  }
43701
44102
  const ids = models.map((_, i) => String(i + 1).padStart(2, "0"));
@@ -43712,9 +44113,9 @@ function setupSession(sessionPath, models, input) {
43712
44113
  model: models[i],
43713
44114
  assignedAt: now
43714
44115
  };
43715
- mkdirSync9(join19(sessionPath, "work", anonId), { recursive: true });
44116
+ mkdirSync10(join20(sessionPath, "work", anonId), { recursive: true });
43716
44117
  }
43717
- writeFileSync10(join19(sessionPath, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
44118
+ writeFileSync11(join20(sessionPath, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
43718
44119
  const status = {
43719
44120
  startedAt: now,
43720
44121
  models: Object.fromEntries(Object.keys(manifest.models).map((id) => [
@@ -43728,19 +44129,19 @@ function setupSession(sessionPath, models, input) {
43728
44129
  }
43729
44130
  ]))
43730
44131
  };
43731
- writeFileSync10(join19(sessionPath, "status.json"), JSON.stringify(status, null, 2), "utf-8");
44132
+ writeFileSync11(join20(sessionPath, "status.json"), JSON.stringify(status, null, 2), "utf-8");
43732
44133
  return manifest;
43733
44134
  }
43734
44135
  async function runModels(sessionPath, opts = {}) {
43735
44136
  const timeoutMs = (opts.timeout ?? 300) * 1000;
43736
- const manifest = JSON.parse(readFileSync13(join19(sessionPath, "manifest.json"), "utf-8"));
43737
- const statusPath = join19(sessionPath, "status.json");
43738
- const inputPath = join19(sessionPath, "input.md");
43739
- const inputContent = readFileSync13(inputPath, "utf-8");
43740
- const statusCache = JSON.parse(readFileSync13(statusPath, "utf-8"));
44137
+ const manifest = JSON.parse(readFileSync14(join20(sessionPath, "manifest.json"), "utf-8"));
44138
+ const statusPath = join20(sessionPath, "status.json");
44139
+ const inputPath = join20(sessionPath, "input.md");
44140
+ const inputContent = readFileSync14(inputPath, "utf-8");
44141
+ const statusCache = JSON.parse(readFileSync14(statusPath, "utf-8"));
43741
44142
  function updateModelStatus(id, update) {
43742
44143
  statusCache.models[id] = { ...statusCache.models[id], ...update };
43743
- writeFileSync10(statusPath, JSON.stringify(statusCache, null, 2), "utf-8");
44144
+ writeFileSync11(statusPath, JSON.stringify(statusCache, null, 2), "utf-8");
43744
44145
  }
43745
44146
  const processes = new Map;
43746
44147
  const sigintHandler = () => {
@@ -43753,8 +44154,8 @@ async function runModels(sessionPath, opts = {}) {
43753
44154
  process.on("SIGINT", sigintHandler);
43754
44155
  const completionPromises = [];
43755
44156
  for (const [anonId, entry] of Object.entries(manifest.models)) {
43756
- const outputPath = join19(sessionPath, `response-${anonId}.md`);
43757
- const errorLogPath = join19(sessionPath, "errors", `${anonId}.log`);
44157
+ const outputPath = join20(sessionPath, `response-${anonId}.md`);
44158
+ const errorLogPath = join20(sessionPath, "errors", `${anonId}.log`);
43758
44159
  const args = ["--model", entry.model, "-y", "--stdin", "--quiet", ...opts.claudeFlags ?? []];
43759
44160
  updateModelStatus(anonId, {
43760
44161
  state: "RUNNING",
@@ -43815,7 +44216,7 @@ async function runModels(sessionPath, opts = {}) {
43815
44216
  return;
43816
44217
  }
43817
44218
  if (stderr) {
43818
- writeFileSync10(errorLogPath, stderr, "utf-8");
44219
+ writeFileSync11(errorLogPath, stderr, "utf-8");
43819
44220
  }
43820
44221
  exitCode = code;
43821
44222
  if (outputStream.destroyed) {
@@ -43860,23 +44261,23 @@ async function judgeResponses(sessionPath, opts = {}) {
43860
44261
  const responses = {};
43861
44262
  for (const file2 of responseFiles) {
43862
44263
  const id = file2.replace(/^response-/, "").replace(/\.md$/, "");
43863
- responses[id] = readFileSync13(join19(sessionPath, file2), "utf-8");
44264
+ responses[id] = readFileSync14(join20(sessionPath, file2), "utf-8");
43864
44265
  }
43865
- const input = readFileSync13(join19(sessionPath, "input.md"), "utf-8");
44266
+ const input = readFileSync14(join20(sessionPath, "input.md"), "utf-8");
43866
44267
  const judgePrompt = buildJudgePrompt(input, responses);
43867
- writeFileSync10(join19(sessionPath, "judge-prompt.md"), judgePrompt, "utf-8");
44268
+ writeFileSync11(join20(sessionPath, "judge-prompt.md"), judgePrompt, "utf-8");
43868
44269
  const judgeModels = opts.judges ?? getDefaultJudgeModels(sessionPath);
43869
- const judgePath = join19(sessionPath, "judging");
43870
- mkdirSync9(judgePath, { recursive: true });
44270
+ const judgePath = join20(sessionPath, "judging");
44271
+ mkdirSync10(judgePath, { recursive: true });
43871
44272
  setupSession(judgePath, judgeModels, judgePrompt);
43872
44273
  await runModels(judgePath, { claudeFlags: opts.claudeFlags });
43873
44274
  const votes = parseJudgeVotes(judgePath, Object.keys(responses));
43874
44275
  const verdict = aggregateVerdict(votes, Object.keys(responses));
43875
- writeFileSync10(join19(sessionPath, "verdict.md"), formatVerdict(verdict, sessionPath), "utf-8");
44276
+ writeFileSync11(join20(sessionPath, "verdict.md"), formatVerdict(verdict, sessionPath), "utf-8");
43876
44277
  return verdict;
43877
44278
  }
43878
44279
  function getStatus(sessionPath) {
43879
- return JSON.parse(readFileSync13(join19(sessionPath, "status.json"), "utf-8"));
44280
+ return JSON.parse(readFileSync14(join20(sessionPath, "status.json"), "utf-8"));
43880
44281
  }
43881
44282
  function fisherYatesShuffle(arr) {
43882
44283
  for (let i = arr.length - 1;i > 0; i--) {
@@ -43886,7 +44287,7 @@ function fisherYatesShuffle(arr) {
43886
44287
  return arr;
43887
44288
  }
43888
44289
  function getDefaultJudgeModels(sessionPath) {
43889
- const manifest = JSON.parse(readFileSync13(join19(sessionPath, "manifest.json"), "utf-8"));
44290
+ const manifest = JSON.parse(readFileSync14(join20(sessionPath, "manifest.json"), "utf-8"));
43890
44291
  return Object.values(manifest.models).map((e) => e.model);
43891
44292
  }
43892
44293
  function buildJudgePrompt(input, responses) {
@@ -43949,7 +44350,7 @@ function parseJudgeVotes(judgePath, responseIds) {
43949
44350
  const judgeId = file2.replace(/^response-/, "").replace(/\.md$/, "");
43950
44351
  let content;
43951
44352
  try {
43952
- content = readFileSync13(join19(judgePath, file2), "utf-8");
44353
+ content = readFileSync14(join20(judgePath, file2), "utf-8");
43953
44354
  } catch {
43954
44355
  continue;
43955
44356
  }
@@ -44001,7 +44402,7 @@ function aggregateVerdict(votes, responseIds) {
44001
44402
  function formatVerdict(verdict, sessionPath) {
44002
44403
  let manifest = null;
44003
44404
  try {
44004
- manifest = JSON.parse(readFileSync13(join19(sessionPath, "manifest.json"), "utf-8"));
44405
+ manifest = JSON.parse(readFileSync14(join20(sessionPath, "manifest.json"), "utf-8"));
44005
44406
  } catch {}
44006
44407
  let output = `# Team Verdict
44007
44408
 
@@ -44050,14 +44451,14 @@ __export(exports_mcp_server, {
44050
44451
  runPromptViaProxy: () => runPromptViaProxy,
44051
44452
  parseAnthropicSse: () => parseAnthropicSse
44052
44453
  });
44053
- import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync14, readdirSync as readdirSync3, writeFileSync as writeFileSync11 } from "fs";
44054
- import { homedir as homedir19 } from "os";
44055
- import { dirname as dirname4, join as join20 } from "path";
44454
+ import { existsSync as existsSync18, mkdirSync as mkdirSync11, readFileSync as readFileSync15, readdirSync as readdirSync3, writeFileSync as writeFileSync12 } from "fs";
44455
+ import { homedir as homedir20 } from "os";
44456
+ import { dirname as dirname5, join as join21 } from "path";
44056
44457
  import { fileURLToPath } from "url";
44057
44458
  async function loadAllModels(forceRefresh = false) {
44058
44459
  if (!forceRefresh && existsSync18(ALL_MODELS_CACHE_PATH2)) {
44059
44460
  try {
44060
- const cacheData = JSON.parse(readFileSync14(ALL_MODELS_CACHE_PATH2, "utf-8"));
44461
+ const cacheData = JSON.parse(readFileSync15(ALL_MODELS_CACHE_PATH2, "utf-8"));
44061
44462
  const lastUpdated = new Date(cacheData.lastUpdated);
44062
44463
  const ageInDays = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60 * 24);
44063
44464
  if (ageInDays <= CACHE_MAX_AGE_DAYS) {
@@ -44071,12 +44472,12 @@ async function loadAllModels(forceRefresh = false) {
44071
44472
  throw new Error(`API returned ${response.status}`);
44072
44473
  const data = await response.json();
44073
44474
  const models = data.data || [];
44074
- mkdirSync10(CLAUDISH_CACHE_DIR, { recursive: true });
44075
- writeFileSync11(ALL_MODELS_CACHE_PATH2, JSON.stringify({ lastUpdated: new Date().toISOString(), models }), "utf-8");
44475
+ mkdirSync11(CLAUDISH_CACHE_DIR, { recursive: true });
44476
+ writeFileSync12(ALL_MODELS_CACHE_PATH2, JSON.stringify({ lastUpdated: new Date().toISOString(), models }), "utf-8");
44076
44477
  return models;
44077
44478
  } catch {
44078
44479
  if (existsSync18(ALL_MODELS_CACHE_PATH2)) {
44079
- const cacheData = JSON.parse(readFileSync14(ALL_MODELS_CACHE_PATH2, "utf-8"));
44480
+ const cacheData = JSON.parse(readFileSync15(ALL_MODELS_CACHE_PATH2, "utf-8"));
44080
44481
  return cacheData.models || [];
44081
44482
  }
44082
44483
  return [];
@@ -44640,7 +45041,7 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
44640
45041
  let stderrFull = stderr_snippet || "";
44641
45042
  if (error_log_path) {
44642
45043
  try {
44643
- stderrFull = readFileSync14(error_log_path, "utf-8");
45044
+ stderrFull = readFileSync15(error_log_path, "utf-8");
44644
45045
  } catch {}
44645
45046
  }
44646
45047
  const sessionData = {};
@@ -44648,16 +45049,16 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
44648
45049
  const sp = session_path;
44649
45050
  for (const file2 of ["status.json", "manifest.json", "input.md"]) {
44650
45051
  try {
44651
- sessionData[file2] = readFileSync14(join20(sp, file2), "utf-8");
45052
+ sessionData[file2] = readFileSync15(join21(sp, file2), "utf-8");
44652
45053
  } catch {}
44653
45054
  }
44654
45055
  try {
44655
- const errorDir = join20(sp, "errors");
45056
+ const errorDir = join21(sp, "errors");
44656
45057
  if (existsSync18(errorDir)) {
44657
45058
  for (const f of readdirSync3(errorDir)) {
44658
45059
  if (f.endsWith(".log")) {
44659
45060
  try {
44660
- sessionData[`errors/${f}`] = readFileSync14(join20(errorDir, f), "utf-8");
45061
+ sessionData[`errors/${f}`] = readFileSync15(join21(errorDir, f), "utf-8");
44661
45062
  } catch {}
44662
45063
  }
44663
45064
  }
@@ -44667,7 +45068,7 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
44667
45068
  for (const f of readdirSync3(sp)) {
44668
45069
  if (f.startsWith("response-") && f.endsWith(".md")) {
44669
45070
  try {
44670
- const content = readFileSync14(join20(sp, f), "utf-8");
45071
+ const content = readFileSync15(join21(sp, f), "utf-8");
44671
45072
  sessionData[f] = content.slice(0, 200) + (content.length > 200 ? "... (truncated)" : "");
44672
45073
  } catch {}
44673
45074
  }
@@ -44676,9 +45077,9 @@ Use with: run_prompt(model="${results[0].model.id}", prompt="your prompt")`;
44676
45077
  }
44677
45078
  let version2 = "unknown";
44678
45079
  try {
44679
- const pkgPath = join20(__dirname2, "../package.json");
45080
+ const pkgPath = join21(__dirname2, "../package.json");
44680
45081
  if (existsSync18(pkgPath)) {
44681
- version2 = JSON.parse(readFileSync14(pkgPath, "utf-8")).version;
45082
+ version2 = JSON.parse(readFileSync15(pkgPath, "utf-8")).version;
44682
45083
  }
44683
45084
  } catch {}
44684
45085
  const report = {
@@ -45048,9 +45449,9 @@ var init_mcp_server = __esm(() => {
45048
45449
  import_dotenv2 = __toESM(require_main(), 1);
45049
45450
  import_dotenv2.config();
45050
45451
  __filename2 = fileURLToPath(import.meta.url);
45051
- __dirname2 = dirname4(__filename2);
45052
- CLAUDISH_CACHE_DIR = join20(homedir19(), ".claudish");
45053
- ALL_MODELS_CACHE_PATH2 = join20(CLAUDISH_CACHE_DIR, "all-models.json");
45452
+ __dirname2 = dirname5(__filename2);
45453
+ CLAUDISH_CACHE_DIR = join21(homedir20(), ".claudish");
45454
+ ALL_MODELS_CACHE_PATH2 = join21(CLAUDISH_CACHE_DIR, "all-models.json");
45054
45455
  EVENT_TO_TASK_STATUS = new Map([
45055
45456
  ["starting", "working"],
45056
45457
  ["running", "working"],
@@ -45067,7 +45468,7 @@ var exports_serve_command = {};
45067
45468
  __export(exports_serve_command, {
45068
45469
  serveCommand: () => serveCommand
45069
45470
  });
45070
- import { existsSync as existsSync19, readFileSync as readFileSync15 } from "fs";
45471
+ import { existsSync as existsSync19, readFileSync as readFileSync16 } from "fs";
45071
45472
  function parseServeArgs(args) {
45072
45473
  const out = {};
45073
45474
  for (let i = 0;i < args.length; i++) {
@@ -45091,7 +45492,7 @@ function loadModelMap(path) {
45091
45492
  }
45092
45493
  let raw2;
45093
45494
  try {
45094
- raw2 = readFileSync15(path, "utf-8");
45495
+ raw2 = readFileSync16(path, "utf-8");
45095
45496
  } catch (e) {
45096
45497
  throw new Error(`failed to read --models file ${path}: ${e instanceof Error ? e.message : String(e)}`);
45097
45498
  }
@@ -56545,7 +56946,7 @@ var init_RemoveFileError = __esm(() => {
56545
56946
 
56546
56947
  // ../../node_modules/.bun/@inquirer+external-editor@2.0.1+04f2146be16c61ef/node_modules/@inquirer/external-editor/dist/index.js
56547
56948
  import { spawn as spawn3, spawnSync as spawnSync2 } from "child_process";
56548
- import { readFileSync as readFileSync16, unlinkSync as unlinkSync6, writeFileSync as writeFileSync12 } from "fs";
56949
+ import { readFileSync as readFileSync17, unlinkSync as unlinkSync6, writeFileSync as writeFileSync13 } from "fs";
56549
56950
  import path from "path";
56550
56951
  import os from "os";
56551
56952
  import { randomUUID as randomUUID4 } from "crypto";
@@ -56654,14 +57055,14 @@ class ExternalEditor {
56654
57055
  if (Object.prototype.hasOwnProperty.call(this.fileOptions, "mode")) {
56655
57056
  opt.mode = this.fileOptions.mode;
56656
57057
  }
56657
- writeFileSync12(this.tempFile, this.text, opt);
57058
+ writeFileSync13(this.tempFile, this.text, opt);
56658
57059
  } catch (createFileError) {
56659
57060
  throw new CreateFileError(createFileError);
56660
57061
  }
56661
57062
  }
56662
57063
  readTemporaryFile() {
56663
57064
  try {
56664
- const tempFileBuffer = readFileSync16(this.tempFile);
57065
+ const tempFileBuffer = readFileSync17(this.tempFile);
56665
57066
  if (tempFileBuffer.length === 0) {
56666
57067
  this.text = "";
56667
57068
  } else {
@@ -57856,15 +58257,15 @@ async function geminiQuotaHandler() {
57856
58257
  }
57857
58258
  }
57858
58259
  async function codexQuotaHandler() {
57859
- const { readFileSync: readFileSync17, existsSync: existsSync20 } = await import("fs");
57860
- const { join: join21 } = await import("path");
57861
- const { homedir: homedir20 } = await import("os");
57862
- const credPath = join21(homedir20(), ".claudish", "codex-oauth.json");
58260
+ const { readFileSync: readFileSync18, existsSync: existsSync20 } = await import("fs");
58261
+ const { join: join22 } = await import("path");
58262
+ const { homedir: homedir21 } = await import("os");
58263
+ const credPath = join22(homedir21(), ".claudish", "codex-oauth.json");
57863
58264
  if (!existsSync20(credPath)) {
57864
58265
  console.error(`${RED}No Codex credentials found.${R} Run: ${B}claudish login codex${R}`);
57865
58266
  process.exit(1);
57866
58267
  }
57867
- const creds = JSON.parse(readFileSync17(credPath, "utf-8"));
58268
+ const creds = JSON.parse(readFileSync18(credPath, "utf-8"));
57868
58269
  let email3 = "";
57869
58270
  try {
57870
58271
  const parts = creds.access_token.split(".");
@@ -57916,9 +58317,9 @@ async function codexQuotaHandler() {
57916
58317
  }
57917
58318
  let modelSlugs = [];
57918
58319
  try {
57919
- const modelsPath = join21(homedir20(), ".codex", "models_cache.json");
58320
+ const modelsPath = join22(homedir21(), ".codex", "models_cache.json");
57920
58321
  if (existsSync20(modelsPath)) {
57921
- const cache = JSON.parse(readFileSync17(modelsPath, "utf-8"));
58322
+ const cache = JSON.parse(readFileSync18(modelsPath, "utf-8"));
57922
58323
  modelSlugs = (cache.models || []).map((m) => m.slug || m.id).filter(Boolean);
57923
58324
  }
57924
58325
  } catch {}
@@ -59174,6 +59575,7 @@ async function probeLink(proxyUrl, link, timeoutMs) {
59174
59575
  system: "You are a helpful assistant.",
59175
59576
  messages: [{ role: "user", content: PROBE_PROMPT }],
59176
59577
  max_tokens: PROBE_MAX_TOKENS,
59578
+ output_config: { effort: "minimal" },
59177
59579
  stream: true
59178
59580
  }),
59179
59581
  signal: AbortSignal.timeout(timeoutMs)
@@ -59234,14 +59636,27 @@ async function safeReadBody(response) {
59234
59636
  return "";
59235
59637
  }
59236
59638
  }
59639
+ function extractUpstreamStatus(body) {
59640
+ if (!body)
59641
+ return;
59642
+ try {
59643
+ const parsed = JSON.parse(body);
59644
+ const status = parsed?.error?.upstream_status;
59645
+ return typeof status === "number" ? status : undefined;
59646
+ } catch {
59647
+ return;
59648
+ }
59649
+ }
59237
59650
  function classifyHttpError(status, body, latencyMs) {
59238
59651
  const lowered = body.toLowerCase();
59239
- if (status === 401 || status === 403) {
59652
+ const upstream = status === 400 ? extractUpstreamStatus(body) : undefined;
59653
+ if (status === 401 || status === 403 || upstream === 401 || upstream === 403) {
59654
+ const authStatus = upstream ?? status;
59240
59655
  return {
59241
59656
  state: "auth-failed",
59242
59657
  latencyMs,
59243
- httpStatus: status,
59244
- errorMessage: extractErrorMessage(body) || `HTTP ${status}`
59658
+ httpStatus: authStatus,
59659
+ errorMessage: extractErrorMessage(body) || `HTTP ${authStatus}`
59245
59660
  };
59246
59661
  }
59247
59662
  if (status === 404 || /model[_ ]not[_ ]found|no such model|unknown model/.test(lowered)) {
@@ -59260,12 +59675,12 @@ function classifyHttpError(status, body, latencyMs) {
59260
59675
  errorMessage: extractErrorMessage(body) || "Rate limited"
59261
59676
  };
59262
59677
  }
59263
- if (status === 402) {
59678
+ if (upstream === 429 || status === 402) {
59264
59679
  return {
59265
- state: "error",
59680
+ state: "out-of-credit",
59266
59681
  latencyMs,
59267
- httpStatus: status,
59268
- errorMessage: extractErrorMessage(body) || "Payment required \u2014 subscription expired or no credit"
59682
+ httpStatus: upstream ?? status,
59683
+ errorMessage: extractErrorMessage(body) || "Out of credit \u2014 account balance or plan exhausted"
59269
59684
  };
59270
59685
  }
59271
59686
  if (status >= 500) {
@@ -59311,6 +59726,7 @@ async function consumeProbeStream(response, timeoutMs, startedAt) {
59311
59726
  let sawContent = false;
59312
59727
  let textChars = 0;
59313
59728
  let reportedTokens;
59729
+ let stopReason;
59314
59730
  let errorVerdict = null;
59315
59731
  let completed = false;
59316
59732
  try {
@@ -59341,6 +59757,8 @@ async function consumeProbeStream(response, timeoutMs, startedAt) {
59341
59757
  textChars += acct.textChars;
59342
59758
  if (acct.outputTokens !== undefined)
59343
59759
  reportedTokens = acct.outputTokens;
59760
+ if (acct.stopReason)
59761
+ stopReason = acct.stopReason;
59344
59762
  }
59345
59763
  if (errorVerdict)
59346
59764
  break;
@@ -59360,6 +59778,14 @@ async function consumeProbeStream(response, timeoutMs, startedAt) {
59360
59778
  const tokens = reportedTokens ?? Math.max(1, Math.round(textChars / 4));
59361
59779
  return { state: "live", ttftMs, tokens, truncated: !completed };
59362
59780
  }
59781
+ const truncationReason = stopReason === "max_tokens" || stopReason === "length" ? stopReason : undefined;
59782
+ if (truncationReason || reportedTokens !== undefined && reportedTokens >= PROBE_MAX_TOKENS) {
59783
+ const cause = truncationReason ? `finish: ${truncationReason}` : `${reportedTokens} tokens consumed, none visible`;
59784
+ return {
59785
+ state: "error",
59786
+ errorMessage: `no visible output within probe budget (${cause})`
59787
+ };
59788
+ }
59363
59789
  return { state: "error", errorMessage: "stream ended without content" };
59364
59790
  }
59365
59791
  function accountStreamEvent(rawEvent) {
@@ -59388,10 +59814,12 @@ function accountStreamEvent(rawEvent) {
59388
59814
  contentDelta = true;
59389
59815
  }
59390
59816
  const outputTokens = parsed?.usage?.output_tokens ?? parsed?.message?.usage?.output_tokens ?? parsed?.usage?.completion_tokens;
59817
+ const stopReason = parsed?.delta?.stop_reason ?? (Array.isArray(parsed?.choices) ? parsed.choices[0]?.finish_reason : undefined);
59391
59818
  return {
59392
59819
  contentDelta,
59393
59820
  textChars,
59394
- outputTokens: typeof outputTokens === "number" ? outputTokens : undefined
59821
+ outputTokens: typeof outputTokens === "number" ? outputTokens : undefined,
59822
+ stopReason: typeof stopReason === "string" ? stopReason : undefined
59395
59823
  };
59396
59824
  }
59397
59825
  function interpretSseEvent(rawEvent) {
@@ -59466,23 +59894,27 @@ function describeProbeState(result) {
59466
59894
  return `model not found \xB7 ${result.httpStatus ?? ""}${result.latencyMs ? ` \xB7 ${result.latencyMs}ms` : ""}`.trim();
59467
59895
  case "rate-limited":
59468
59896
  return `rate limited \xB7 ${result.latencyMs}ms`;
59897
+ case "out-of-credit":
59898
+ return `out of credit \xB7 ${result.httpStatus ?? ""}${result.latencyMs ? ` \xB7 ${result.latencyMs}ms` : ""}`.trim();
59469
59899
  case "server-error":
59470
59900
  return `server error \xB7 ${result.httpStatus ?? ""} \xB7 ${result.latencyMs}ms`;
59471
59901
  case "timeout":
59472
59902
  return `timeout \xB7 ${result.latencyMs}ms`;
59473
59903
  case "network-error":
59474
59904
  return `network error \xB7 ${result.latencyMs}ms`;
59475
- case "error":
59476
- return `error${result.httpStatus ? ` \xB7 ${result.httpStatus}` : ""}${result.latencyMs ? ` \xB7 ${result.latencyMs}ms` : ""}`;
59905
+ case "error": {
59906
+ const base = `error${result.httpStatus ? ` \xB7 ${result.httpStatus}` : ""}${result.latencyMs ? ` \xB7 ${result.latencyMs}ms` : ""}`;
59907
+ return result.errorMessage ? `${base} \u2014 ${result.errorMessage}` : base;
59908
+ }
59477
59909
  }
59478
59910
  }
59479
59911
  function isReadyState(state) {
59480
59912
  return state === "live";
59481
59913
  }
59482
59914
  function isFailureState(state) {
59483
- return state === "auth-failed" || state === "model-not-found" || state === "rate-limited" || state === "server-error" || state === "timeout" || state === "network-error" || state === "error";
59915
+ return state === "auth-failed" || state === "model-not-found" || state === "rate-limited" || state === "out-of-credit" || state === "server-error" || state === "timeout" || state === "network-error" || state === "error";
59484
59916
  }
59485
- var STREAM_MS_FLOOR = 50, OAUTH_PROVIDERS2, PROBE_PROMPT = "Count from one to twenty in words, one per line.", PROBE_MAX_TOKENS = 64;
59917
+ var STREAM_MS_FLOOR = 50, OAUTH_PROVIDERS2, PROBE_PROMPT = "Count from one to twenty in words, one per line.", PROBE_MAX_TOKENS = 512;
59486
59918
  var init_probe_live = __esm(() => {
59487
59919
  OAUTH_PROVIDERS2 = new Set(["vertex", "gemini-codeassist"]);
59488
59920
  });
@@ -59828,6 +60260,8 @@ function shortStatusLabel(probe, hasCreds, _hint) {
59828
60260
  return `${pc.red}\u2297 not found${pc.reset}`;
59829
60261
  case "rate-limited":
59830
60262
  return `${pc.red}\u2297 rate-limited${pc.reset}`;
60263
+ case "out-of-credit":
60264
+ return `${pc.red}\u2297 no credit${pc.reset}`;
59831
60265
  case "server-error":
59832
60266
  return `${pc.red}\u2297 server ${probe.httpStatus ?? ""}${pc.reset}`;
59833
60267
  case "timeout":
@@ -59836,8 +60270,9 @@ function shortStatusLabel(probe, hasCreds, _hint) {
59836
60270
  return `${pc.red}\u2297 network${pc.reset}`;
59837
60271
  case "error":
59838
60272
  return `${pc.red}\u2297 error${probe.httpStatus ? ` ${probe.httpStatus}` : ""}${pc.reset}`;
60273
+ default:
60274
+ return `${pc.red}\u2297 unknown${pc.reset}`;
59839
60275
  }
59840
- return `${pc.red}\u2297 unknown${pc.reset}`;
59841
60276
  }
59842
60277
  function renderBorderTop(title, summary, width) {
59843
60278
  const titleSeg = ` ${title} `;
@@ -61758,20 +62193,20 @@ __export(exports_cli, {
61758
62193
  import {
61759
62194
  copyFileSync as copyFileSync2,
61760
62195
  existsSync as existsSync20,
61761
- mkdirSync as mkdirSync11,
61762
- readFileSync as readFileSync17,
62196
+ mkdirSync as mkdirSync12,
62197
+ readFileSync as readFileSync18,
61763
62198
  readdirSync as readdirSync4,
61764
62199
  unlinkSync as unlinkSync7,
61765
- writeFileSync as writeFileSync13
62200
+ writeFileSync as writeFileSync14
61766
62201
  } from "fs";
61767
- import { homedir as homedir20 } from "os";
61768
- import { dirname as dirname5, join as join21 } from "path";
62202
+ import { homedir as homedir21 } from "os";
62203
+ import { dirname as dirname6, join as join22 } from "path";
61769
62204
  import { fileURLToPath as fileURLToPath2 } from "url";
61770
62205
  function getVersion3() {
61771
62206
  return VERSION;
61772
62207
  }
61773
62208
  function clearAllModelCaches() {
61774
- const cacheDir = join21(homedir20(), ".claudish");
62209
+ const cacheDir = join22(homedir21(), ".claudish");
61775
62210
  if (!existsSync20(cacheDir))
61776
62211
  return;
61777
62212
  const cachePatterns = ["pricing-cache.json", "recommended-models-cache.json"];
@@ -61780,7 +62215,7 @@ function clearAllModelCaches() {
61780
62215
  const files = readdirSync4(cacheDir);
61781
62216
  for (const file2 of files) {
61782
62217
  if (cachePatterns.includes(file2)) {
61783
- unlinkSync7(join21(cacheDir, file2));
62218
+ unlinkSync7(join22(cacheDir, file2));
61784
62219
  cleared++;
61785
62220
  }
61786
62221
  }
@@ -62167,15 +62602,15 @@ Usage: claudish --models --provider <slug>`);
62167
62602
  });
62168
62603
  config3.resolvedDefaultProvider = resolved;
62169
62604
  if (resolved.legacyAutoPromoted && !config3.quiet) {
62170
- const markerFile = join21(homedir20(), ".claudish", ".legacy-litellm-hint-shown");
62605
+ const markerFile = join22(homedir21(), ".claudish", ".legacy-litellm-hint-shown");
62171
62606
  if (!existsSync20(markerFile)) {
62172
62607
  const hint = buildLegacyHint(resolved);
62173
62608
  if (hint) {
62174
62609
  console.error(hint);
62175
62610
  }
62176
62611
  try {
62177
- mkdirSync11(dirname5(markerFile), { recursive: true });
62178
- writeFileSync13(markerFile, new Date().toISOString(), "utf-8");
62612
+ mkdirSync12(dirname6(markerFile), { recursive: true });
62613
+ writeFileSync14(markerFile, new Date().toISOString(), "utf-8");
62179
62614
  } catch {}
62180
62615
  }
62181
62616
  }
@@ -63223,8 +63658,8 @@ ${h("MORE INFO")}
63223
63658
  }
63224
63659
  function printAIAgentGuide() {
63225
63660
  try {
63226
- const guidePath = join21(__dirname3, "../AI_AGENT_GUIDE.md");
63227
- const guideContent = readFileSync17(guidePath, "utf-8");
63661
+ const guidePath = join22(__dirname3, "../AI_AGENT_GUIDE.md");
63662
+ const guideContent = readFileSync18(guidePath, "utf-8");
63228
63663
  console.log(guideContent);
63229
63664
  } catch (error46) {
63230
63665
  console.error("Error reading AI Agent Guide:");
@@ -63240,10 +63675,10 @@ async function initializeClaudishSkill() {
63240
63675
  console.log(`\uD83D\uDD27 Initializing Claudish skill in current project...
63241
63676
  `);
63242
63677
  const cwd = process.cwd();
63243
- const claudeDir = join21(cwd, ".claude");
63244
- const skillsDir = join21(claudeDir, "skills");
63245
- const claudishSkillDir = join21(skillsDir, "claudish-usage");
63246
- const skillFile = join21(claudishSkillDir, "SKILL.md");
63678
+ const claudeDir = join22(cwd, ".claude");
63679
+ const skillsDir = join22(claudeDir, "skills");
63680
+ const claudishSkillDir = join22(skillsDir, "claudish-usage");
63681
+ const skillFile = join22(claudishSkillDir, "SKILL.md");
63247
63682
  if (existsSync20(skillFile)) {
63248
63683
  console.log("\u2705 Claudish skill already installed at:");
63249
63684
  console.log(` ${skillFile}
@@ -63251,7 +63686,7 @@ async function initializeClaudishSkill() {
63251
63686
  console.log("\uD83D\uDCA1 To reinstall, delete the file and run 'claudish --init' again.");
63252
63687
  return;
63253
63688
  }
63254
- const sourceSkillPath = join21(__dirname3, "../skills/claudish-usage/SKILL.md");
63689
+ const sourceSkillPath = join22(__dirname3, "../skills/claudish-usage/SKILL.md");
63255
63690
  if (!existsSync20(sourceSkillPath)) {
63256
63691
  console.error("\u274C Error: Claudish skill file not found in installation.");
63257
63692
  console.error(` Expected at: ${sourceSkillPath}`);
@@ -63262,15 +63697,15 @@ async function initializeClaudishSkill() {
63262
63697
  }
63263
63698
  try {
63264
63699
  if (!existsSync20(claudeDir)) {
63265
- mkdirSync11(claudeDir, { recursive: true });
63700
+ mkdirSync12(claudeDir, { recursive: true });
63266
63701
  console.log("\uD83D\uDCC1 Created .claude/ directory");
63267
63702
  }
63268
63703
  if (!existsSync20(skillsDir)) {
63269
- mkdirSync11(skillsDir, { recursive: true });
63704
+ mkdirSync12(skillsDir, { recursive: true });
63270
63705
  console.log("\uD83D\uDCC1 Created .claude/skills/ directory");
63271
63706
  }
63272
63707
  if (!existsSync20(claudishSkillDir)) {
63273
- mkdirSync11(claudishSkillDir, { recursive: true });
63708
+ mkdirSync12(claudishSkillDir, { recursive: true });
63274
63709
  console.log("\uD83D\uDCC1 Created .claude/skills/claudish-usage/ directory");
63275
63710
  }
63276
63711
  copyFileSync2(sourceSkillPath, skillFile);
@@ -63342,7 +63777,7 @@ var init_cli = __esm(() => {
63342
63777
  init_routing_rules();
63343
63778
  init_provider_resolver();
63344
63779
  __filename3 = fileURLToPath2(import.meta.url);
63345
- __dirname3 = dirname5(__filename3);
63780
+ __dirname3 = dirname6(__filename3);
63346
63781
  });
63347
63782
 
63348
63783
  // src/update-checker.ts
@@ -63353,24 +63788,24 @@ __export(exports_update_checker, {
63353
63788
  clearCache: () => clearCache,
63354
63789
  checkForUpdates: () => checkForUpdates
63355
63790
  });
63356
- import { existsSync as existsSync21, mkdirSync as mkdirSync12, readFileSync as readFileSync18, unlinkSync as unlinkSync8, writeFileSync as writeFileSync14 } from "fs";
63357
- import { homedir as homedir21, platform as platform2, tmpdir } from "os";
63358
- import { join as join22 } from "path";
63791
+ import { existsSync as existsSync21, mkdirSync as mkdirSync13, readFileSync as readFileSync19, unlinkSync as unlinkSync8, writeFileSync as writeFileSync15 } from "fs";
63792
+ import { homedir as homedir22, platform as platform2, tmpdir } from "os";
63793
+ import { join as join23 } from "path";
63359
63794
  function getCacheFilePath() {
63360
63795
  let cacheDir;
63361
63796
  if (isWindows) {
63362
- const localAppData = process.env.LOCALAPPDATA || join22(homedir21(), "AppData", "Local");
63363
- cacheDir = join22(localAppData, "claudish");
63797
+ const localAppData = process.env.LOCALAPPDATA || join23(homedir22(), "AppData", "Local");
63798
+ cacheDir = join23(localAppData, "claudish");
63364
63799
  } else {
63365
- cacheDir = join22(homedir21(), ".cache", "claudish");
63800
+ cacheDir = join23(homedir22(), ".cache", "claudish");
63366
63801
  }
63367
63802
  try {
63368
63803
  if (!existsSync21(cacheDir)) {
63369
- mkdirSync12(cacheDir, { recursive: true });
63804
+ mkdirSync13(cacheDir, { recursive: true });
63370
63805
  }
63371
- return join22(cacheDir, "update-check.json");
63806
+ return join23(cacheDir, "update-check.json");
63372
63807
  } catch {
63373
- return join22(tmpdir(), "claudish-update-check.json");
63808
+ return join23(tmpdir(), "claudish-update-check.json");
63374
63809
  }
63375
63810
  }
63376
63811
  function readCache() {
@@ -63379,7 +63814,7 @@ function readCache() {
63379
63814
  if (!existsSync21(cachePath)) {
63380
63815
  return null;
63381
63816
  }
63382
- const data = JSON.parse(readFileSync18(cachePath, "utf-8"));
63817
+ const data = JSON.parse(readFileSync19(cachePath, "utf-8"));
63383
63818
  return data;
63384
63819
  } catch {
63385
63820
  return null;
@@ -63392,7 +63827,7 @@ function writeCache(latestVersion) {
63392
63827
  lastCheck: Date.now(),
63393
63828
  latestVersion
63394
63829
  };
63395
- writeFileSync14(cachePath, JSON.stringify(data), "utf-8");
63830
+ writeFileSync15(cachePath, JSON.stringify(data), "utf-8");
63396
63831
  } catch {}
63397
63832
  }
63398
63833
  function isCacheValid(cache) {
@@ -64228,15 +64663,15 @@ var init_local_liveness = __esm(() => {
64228
64663
  });
64229
64664
 
64230
64665
  // src/providers/probe-catalog.ts
64231
- import { existsSync as existsSync22, mkdirSync as mkdirSync13, readFileSync as readFileSync19, writeFileSync as writeFileSync15 } from "fs";
64232
- import { homedir as homedir22 } from "os";
64233
- import { dirname as dirname6, join as join23 } from "path";
64666
+ import { existsSync as existsSync22, mkdirSync as mkdirSync14, readFileSync as readFileSync20, writeFileSync as writeFileSync16 } from "fs";
64667
+ import { homedir as homedir23 } from "os";
64668
+ import { dirname as dirname7, join as join24 } from "path";
64234
64669
  function readProbeModelsCache(path2 = PROBE_MODELS_CACHE_PATH) {
64235
64670
  if (!existsSync22(path2))
64236
64671
  return null;
64237
64672
  let raw2;
64238
64673
  try {
64239
- raw2 = JSON.parse(readFileSync19(path2, "utf-8"));
64674
+ raw2 = JSON.parse(readFileSync20(path2, "utf-8"));
64240
64675
  } catch {
64241
64676
  return null;
64242
64677
  }
@@ -64245,8 +64680,8 @@ function readProbeModelsCache(path2 = PROBE_MODELS_CACHE_PATH) {
64245
64680
  return raw2;
64246
64681
  }
64247
64682
  function writeProbeModelsCache(data, path2 = PROBE_MODELS_CACHE_PATH) {
64248
- mkdirSync13(dirname6(path2), { recursive: true });
64249
- writeFileSync15(path2, JSON.stringify(data), "utf-8");
64683
+ mkdirSync14(dirname7(path2), { recursive: true });
64684
+ writeFileSync16(path2, JSON.stringify(data), "utf-8");
64250
64685
  }
64251
64686
  function isCacheFresh(data, ttlMs = CACHE_TTL_MS3) {
64252
64687
  if (!data?.generatedAt)
@@ -64365,7 +64800,7 @@ function isValidResponse(raw2) {
64365
64800
  var PROBE_MODELS_URL = "https://us-central1-claudish-6da10.cloudfunctions.net/probeModels", CACHE_TTL_MS3, FETCH_TIMEOUT_MS2 = 15000, PROBE_MODELS_CACHE_PATH, _inFlight = null;
64366
64801
  var init_probe_catalog = __esm(() => {
64367
64802
  CACHE_TTL_MS3 = 60 * 60 * 1000;
64368
- PROBE_MODELS_CACHE_PATH = join23(homedir22(), ".claudish", "probe-models.json");
64803
+ PROBE_MODELS_CACHE_PATH = join24(homedir23(), ".claudish", "probe-models.json");
64369
64804
  });
64370
64805
 
64371
64806
  // src/tui/constants.ts
@@ -66778,6 +67213,23 @@ function ProviderDetail({
66778
67213
  fg: C.green,
66779
67214
  children: displayKey
66780
67215
  }, undefined, false, undefined, this),
67216
+ !hasKey && !selectedProvider.isLocal && selectedProvider.apiKeyEnvVar && /* @__PURE__ */ jsxDEV11(Fragment7, {
67217
+ children: [
67218
+ /* @__PURE__ */ jsxDEV11("span", {
67219
+ fg: C.dim,
67220
+ children: " "
67221
+ }, undefined, false, undefined, this),
67222
+ /* @__PURE__ */ jsxDEV11("span", {
67223
+ fg: C.blue,
67224
+ attributes: A.bold,
67225
+ children: "Env: "
67226
+ }, undefined, false, undefined, this),
67227
+ /* @__PURE__ */ jsxDEV11("span", {
67228
+ fg: C.yellow,
67229
+ children: [selectedProvider.apiKeyEnvVar, ...selectedProvider.aliases ?? []].join(" | ")
67230
+ }, undefined, false, undefined, this)
67231
+ ]
67232
+ }, undefined, true, undefined, this),
66781
67233
  hasKey && selectedProvider.isLocal && /* @__PURE__ */ jsxDEV11(Fragment7, {
66782
67234
  children: [
66783
67235
  /* @__PURE__ */ jsxDEV11("span", {
@@ -69058,7 +69510,7 @@ function App({ requestLogin } = {}) {
69058
69510
  try {
69059
69511
  const auth = await acquireOpAuth();
69060
69512
  const parsed = parseGlobImport(g.value);
69061
- const fields = await withSdkRetry(() => discoverItemFields(parsed.vault, parsed.item, { auth }));
69513
+ const fields = await withSdkRetry(() => discoverItemFields(parsed.vault, parsed.item, { auth }), "tui:glob-expand");
69062
69514
  const keys = filterGlobFields(fields, parsed).filter((m) => m.valid).map((m) => ({ name: m.envName, tail: m.field.valueTail }));
69063
69515
  setOpExpansions((prev) => ({ ...prev, [g.value]: { status: "ready", keys } }));
69064
69516
  } catch (err) {
@@ -69129,15 +69581,15 @@ function App({ requestLogin } = {}) {
69129
69581
  if (entry.kind === "account") {
69130
69582
  note = "account ok";
69131
69583
  } else if (entry.kind === "environment") {
69132
- const vars = await withSdkRetry(() => readEnvironment(entry.value, { auth }));
69584
+ const vars = await withSdkRetry(() => readEnvironment(entry.value, { auth }), "tui:test-entry");
69133
69585
  note = `${Object.keys(vars).length} vars`;
69134
69586
  } else if (entry.kind === "glob" || isGlobImport(entry.value)) {
69135
69587
  const g = parseGlobImport(entry.value);
69136
- const fields = await withSdkRetry(() => discoverItemFields(g.vault, g.item, { auth }));
69588
+ const fields = await withSdkRetry(() => discoverItemFields(g.vault, g.item, { auth }), "tui:test-entry");
69137
69589
  const matches = filterGlobFields(fields, g).filter((m) => m.valid);
69138
69590
  note = `${matches.length} fields`;
69139
69591
  } else {
69140
- const r = await withSdkRetry(() => resolveSecrets({ T: entry.value }, { auth }));
69592
+ const r = await withSdkRetry(() => resolveSecrets({ T: entry.value }, { auth }), "tui:test-entry");
69141
69593
  note = maskSecret(r.T);
69142
69594
  }
69143
69595
  setOpTestResults((prev) => ({
@@ -69206,22 +69658,23 @@ function App({ requestLogin } = {}) {
69206
69658
  }
69207
69659
  };
69208
69660
  if (kind === "environment") {
69209
- const vars = await withSdkRetry(() => readEnvironment(value, { auth }));
69661
+ const vars = await withSdkRetry(() => readEnvironment(value, { auth }), "tui:confirm-add");
69210
69662
  apply(vars);
69211
69663
  setStatusMsg(`1Password environment saved (${scope}) \u2192 ${Object.keys(vars).length} vars, ${hydrated} applied.`);
69212
69664
  } else if (isGlob) {
69213
- const resolved = await withSdkRetry(() => resolveGlobImport(value, { auth }));
69665
+ const resolved = await withSdkRetry(() => resolveGlobImport(value, { auth }), "tui:confirm-add");
69214
69666
  apply(resolved);
69215
69667
  const names = Object.keys(resolved).slice(0, 3).join(", ");
69216
69668
  const n = Object.keys(resolved).length;
69217
69669
  setStatusMsg(n > 0 ? `1Password set saved (${scope}) \u2192 ${n} key${n === 1 ? "" : "s"} applied (${names})` : `1Password set saved (${scope}) \u2014 but it matched no importable fields right now.`);
69218
69670
  } else {
69219
- const r = await withSdkRetry(() => resolveSecrets({ T: value }, { auth }));
69671
+ const r = await withSdkRetry(() => resolveSecrets({ T: value }, { auth }), "tui:confirm-add");
69220
69672
  const name = envNameFromOpRef(value);
69221
69673
  if (name)
69222
69674
  apply({ [name]: r.T });
69223
69675
  setStatusMsg(`1Password key saved (${scope}) \u2192 ${name ?? "?"} = ${maskSecret(r.T)}${hydrated ? " (applied)" : ""}`);
69224
69676
  }
69677
+ invalidateOpResolutionCache();
69225
69678
  invalidateProbeProxyHandlers();
69226
69679
  refreshConfig();
69227
69680
  } catch (testErr) {
@@ -69248,7 +69701,7 @@ function App({ requestLogin } = {}) {
69248
69701
  setMode("pick_op_vault");
69249
69702
  try {
69250
69703
  const auth = await acquireOpAuth();
69251
- const vaults = await withSdkRetry(() => listVaults({ auth }));
69704
+ const vaults = await withSdkRetry(() => listVaults({ auth }), "tui:list-vaults");
69252
69705
  setOpVaults(vaults);
69253
69706
  setStatusMsg(`1Password: ${vaults.length} vault${vaults.length === 1 ? "" : "s"}.`);
69254
69707
  } catch (err) {
@@ -69270,7 +69723,7 @@ function App({ requestLogin } = {}) {
69270
69723
  setMode("pick_op_item");
69271
69724
  try {
69272
69725
  const auth = await acquireOpAuth();
69273
- const items = await withSdkRetry(() => listItems(vaultId, { auth }));
69726
+ const items = await withSdkRetry(() => listItems(vaultId, { auth }), "tui:list-items");
69274
69727
  setOpItems(items);
69275
69728
  setStatusMsg(`1Password: ${items.length} item${items.length === 1 ? "" : "s"}.`);
69276
69729
  } catch (err) {
@@ -69298,7 +69751,7 @@ function App({ requestLogin } = {}) {
69298
69751
  setStatusMsg(`1Password: loading fields for '${itemTitle}'\u2026`);
69299
69752
  try {
69300
69753
  const auth = await acquireOpAuth();
69301
- const fields = await withSdkRetry(() => discoverItemFieldsById(vaultId, itemId, vaultTitle, itemTitle, { auth }));
69754
+ const fields = await withSdkRetry(() => discoverItemFieldsById(vaultId, itemId, vaultTitle, itemTitle, { auth }), "tui:load-fields");
69302
69755
  opFieldsCache.current.set(cacheKey2, fields);
69303
69756
  setOpFields(fields);
69304
69757
  setStatusMsg(`1Password: ${fields.length} field${fields.length === 1 ? "" : "s"}.`);
@@ -69315,7 +69768,7 @@ function App({ requestLogin } = {}) {
69315
69768
  setStatusMsg("1Password: reading environment\u2026");
69316
69769
  try {
69317
69770
  const auth = await acquireOpAuth();
69318
- const vars = await withSdkRetry(() => readEnvironment(id, { auth }));
69771
+ const vars = await withSdkRetry(() => readEnvironment(id, { auth }), "tui:preview-environment");
69319
69772
  const names = Object.keys(vars);
69320
69773
  setOpEnvPreview(names);
69321
69774
  setStatusMsg(`1Password environment \u2192 ${names.length} var${names.length === 1 ? "" : "s"}. Enter to save.`);
@@ -70507,6 +70960,7 @@ function App({ requestLogin } = {}) {
70507
70960
  }, undefined, true, undefined, this);
70508
70961
  }
70509
70962
  var init_App = __esm(() => {
70963
+ init_op_source();
70510
70964
  init_profile_config();
70511
70965
  init_default_routing_rules();
70512
70966
  init_local_liveness();
@@ -70619,20 +71073,23 @@ var init_tui = __esm(() => {
70619
71073
  var exports_claude_runner = {};
70620
71074
  __export(exports_claude_runner, {
70621
71075
  runClaudeWithProxy: () => runClaudeWithProxy,
70622
- checkClaudeInstalled: () => checkClaudeInstalled
71076
+ managedSettingsForcesClaudeAi: () => managedSettingsForcesClaudeAi,
71077
+ isProxyAuthMode: () => isProxyAuthMode,
71078
+ checkClaudeInstalled: () => checkClaudeInstalled,
71079
+ buildClaudishSettingsOverlay: () => buildClaudishSettingsOverlay
70623
71080
  });
70624
71081
  import { spawn as spawn4 } from "child_process";
70625
71082
  import {
70626
71083
  closeSync as closeSync4,
70627
71084
  existsSync as existsSync23,
70628
- mkdirSync as mkdirSync14,
71085
+ mkdirSync as mkdirSync15,
70629
71086
  openSync as openSync4,
70630
- readFileSync as readFileSync20,
71087
+ readFileSync as readFileSync21,
70631
71088
  unlinkSync as unlinkSync9,
70632
- writeFileSync as writeFileSync16
71089
+ writeFileSync as writeFileSync17
70633
71090
  } from "fs";
70634
- import { homedir as homedir23, tmpdir as tmpdir2 } from "os";
70635
- import { join as join24 } from "path";
71091
+ import { homedir as homedir24, tmpdir as tmpdir2 } from "os";
71092
+ import { join as join25 } from "path";
70636
71093
  import { isatty } from "tty";
70637
71094
  function hasNativeAnthropicMapping(config3) {
70638
71095
  const models = [
@@ -70644,14 +71101,35 @@ function hasNativeAnthropicMapping(config3) {
70644
71101
  ];
70645
71102
  return models.some((m) => m && parseModelSpec(m).provider === "native-anthropic");
70646
71103
  }
71104
+ function isProxyAuthMode(config3) {
71105
+ return !config3.monitor && !hasNativeAnthropicMapping(config3);
71106
+ }
71107
+ function managedSettingsPath() {
71108
+ if (isWindows2()) {
71109
+ return join25(process.env.PROGRAMDATA || "C:\\ProgramData", "ClaudeCode", "managed-settings.json");
71110
+ }
71111
+ if (process.platform === "darwin") {
71112
+ return "/Library/Application Support/ClaudeCode/managed-settings.json";
71113
+ }
71114
+ return "/etc/claude-code/managed-settings.json";
71115
+ }
71116
+ function managedSettingsForcesClaudeAi(readFile = readFileSync21) {
71117
+ try {
71118
+ const raw2 = readFile(managedSettingsPath(), "utf-8");
71119
+ const parsed = JSON.parse(raw2);
71120
+ return parsed.forceLoginMethod === "claudeai";
71121
+ } catch {
71122
+ return false;
71123
+ }
71124
+ }
70647
71125
  function isWindows2() {
70648
71126
  return process.platform === "win32";
70649
71127
  }
70650
71128
  function createStatusLineScript(tokenFilePath) {
70651
71129
  const homeDir = process.env.HOME || process.env.USERPROFILE || tmpdir2();
70652
- const claudishDir = join24(homeDir, ".claudish");
71130
+ const claudishDir = join25(homeDir, ".claudish");
70653
71131
  const timestamp = Date.now();
70654
- const scriptPath = join24(claudishDir, `status-${timestamp}.js`);
71132
+ const scriptPath = join25(claudishDir, `status-${timestamp}.js`);
70655
71133
  const escapedTokenPath = tokenFilePath.replace(/\\/g, "\\\\");
70656
71134
  const script = `
70657
71135
  const fs = require('fs');
@@ -70743,18 +71221,18 @@ process.stdin.on('end', () => {
70743
71221
  }
70744
71222
  });
70745
71223
  `;
70746
- writeFileSync16(scriptPath, script, "utf-8");
71224
+ writeFileSync17(scriptPath, script, "utf-8");
70747
71225
  return scriptPath;
70748
71226
  }
70749
- function createTempSettingsFile(_modelDisplay, port) {
71227
+ function createTempSettingsFile(_modelDisplay, port, proxyAuthMode) {
70750
71228
  const homeDir = process.env.HOME || process.env.USERPROFILE || tmpdir2();
70751
- const claudishDir = join24(homeDir, ".claudish");
71229
+ const claudishDir = join25(homeDir, ".claudish");
70752
71230
  try {
70753
- mkdirSync14(claudishDir, { recursive: true });
71231
+ mkdirSync15(claudishDir, { recursive: true });
70754
71232
  } catch {}
70755
71233
  const timestamp = Date.now();
70756
- const tempPath = join24(claudishDir, `settings-${timestamp}.json`);
70757
- const tokenFilePath = join24(claudishDir, `tokens-${port}.json`);
71234
+ const tempPath = join25(claudishDir, `settings-${timestamp}.json`);
71235
+ const tokenFilePath = join25(claudishDir, `tokens-${port}.json`);
70758
71236
  let statusCommand;
70759
71237
  if (isWindows2()) {
70760
71238
  const scriptPath = createStatusLineScript(tokenFilePath);
@@ -70775,11 +71253,18 @@ function createTempSettingsFile(_modelDisplay, port) {
70775
71253
  command: statusCommand,
70776
71254
  padding: 0
70777
71255
  };
70778
- const settings = { statusLine, disableClaudeAiConnectors: true };
70779
- writeFileSync16(tempPath, JSON.stringify(settings, null, 2), "utf-8");
71256
+ const settings = buildClaudishSettingsOverlay(statusLine, proxyAuthMode);
71257
+ writeFileSync17(tempPath, JSON.stringify(settings, null, 2), "utf-8");
70780
71258
  return { path: tempPath, statusLine };
70781
71259
  }
70782
- function mergeUserSettingsIfPresent(config3, tempSettingsPath, statusLine) {
71260
+ function buildClaudishSettingsOverlay(statusLine, proxyAuthMode) {
71261
+ const settings = { statusLine, disableClaudeAiConnectors: true };
71262
+ if (proxyAuthMode) {
71263
+ settings.forceLoginMethod = "console";
71264
+ }
71265
+ return settings;
71266
+ }
71267
+ function mergeUserSettingsIfPresent(config3, tempSettingsPath, statusLine, proxyAuthMode) {
70783
71268
  const idx = config3.claudeArgs.indexOf("--settings");
70784
71269
  if (idx === -1 || !config3.claudeArgs[idx + 1]) {
70785
71270
  return;
@@ -70790,14 +71275,17 @@ function mergeUserSettingsIfPresent(config3, tempSettingsPath, statusLine) {
70790
71275
  if (userSettingsValue.trimStart().startsWith("{")) {
70791
71276
  userSettings = JSON.parse(userSettingsValue);
70792
71277
  } else {
70793
- const rawUserSettings = readFileSync20(userSettingsValue, "utf-8");
71278
+ const rawUserSettings = readFileSync21(userSettingsValue, "utf-8");
70794
71279
  userSettings = JSON.parse(rawUserSettings);
70795
71280
  }
70796
71281
  userSettings.statusLine = statusLine;
70797
71282
  if (!("disableClaudeAiConnectors" in userSettings)) {
70798
71283
  userSettings.disableClaudeAiConnectors = true;
70799
71284
  }
70800
- writeFileSync16(tempSettingsPath, JSON.stringify(userSettings, null, 2), "utf-8");
71285
+ if (proxyAuthMode && !("forceLoginMethod" in userSettings)) {
71286
+ userSettings.forceLoginMethod = "console";
71287
+ }
71288
+ writeFileSync17(tempSettingsPath, JSON.stringify(userSettings, null, 2), "utf-8");
70801
71289
  } catch {
70802
71290
  if (!config3.quiet) {
70803
71291
  console.warn(`[claudish] Warning: could not merge user settings: ${userSettingsValue}`);
@@ -70810,8 +71298,16 @@ async function runClaudeWithProxy(config3, proxyUrl, onCleanup) {
70810
71298
  const modelId = config3.model || (hasProfileMappings || config3.monitor ? undefined : "unknown");
70811
71299
  const portMatch = proxyUrl.match(/:(\d+)/);
70812
71300
  const port = portMatch ? portMatch[1] : "unknown";
70813
- const { path: tempSettingsPath, statusLine } = createTempSettingsFile(modelId ?? "default", port);
70814
- mergeUserSettingsIfPresent(config3, tempSettingsPath, statusLine);
71301
+ const proxyAuthMode = isProxyAuthMode(config3);
71302
+ if (proxyAuthMode && managedSettingsForcesClaudeAi()) {
71303
+ console.error("[claudish] Error: your organization's managed Claude Code settings force the " + `claude.ai login method (forceLoginMethod: "claudeai").
71304
+ ` + " claudish routes Claude Code through its local proxy using API-key auth, which " + `that policy blocks at startup, and managed settings cannot be overridden.
71305
+ ` + " Ask your Claude Code administrator to relax this policy, or run a native " + "Anthropic model (which uses your real claude.ai subscription).");
71306
+ onCleanup?.();
71307
+ return 1;
71308
+ }
71309
+ const { path: tempSettingsPath, statusLine } = createTempSettingsFile(modelId ?? "default", port, proxyAuthMode);
71310
+ mergeUserSettingsIfPresent(config3, tempSettingsPath, statusLine, proxyAuthMode);
70815
71311
  const claudeArgs = [];
70816
71312
  claudeArgs.push("--settings", tempSettingsPath);
70817
71313
  if (config3.interactive) {
@@ -70885,8 +71381,8 @@ async function runClaudeWithProxy(config3, proxyUrl, onCleanup) {
70885
71381
  console.error("Install it from: https://claude.com/claude-code");
70886
71382
  console.error(`
70887
71383
  Or set CLAUDE_PATH to your custom installation:`);
70888
- const home = homedir23();
70889
- const localPath = isWindows2() ? join24(home, ".claude", "local", "claude.exe") : join24(home, ".claude", "local", "claude");
71384
+ const home = homedir24();
71385
+ const localPath = isWindows2() ? join25(home, ".claude", "local", "claude.exe") : join25(home, ".claude", "local", "claude");
70890
71386
  console.error(` export CLAUDE_PATH=${localPath}`);
70891
71387
  process.exit(1);
70892
71388
  }
@@ -70963,16 +71459,16 @@ async function findClaudeBinary() {
70963
71459
  return process.env.CLAUDE_PATH;
70964
71460
  }
70965
71461
  }
70966
- const home = homedir23();
70967
- const localPath = isWindows3 ? join24(home, ".claude", "local", "claude.exe") : join24(home, ".claude", "local", "claude");
71462
+ const home = homedir24();
71463
+ const localPath = isWindows3 ? join25(home, ".claude", "local", "claude.exe") : join25(home, ".claude", "local", "claude");
70968
71464
  if (existsSync23(localPath)) {
70969
71465
  return localPath;
70970
71466
  }
70971
71467
  if (isWindows3) {
70972
71468
  const windowsPaths = [
70973
- join24(home, "AppData", "Roaming", "npm", "claude.cmd"),
70974
- join24(home, ".npm-global", "claude.cmd"),
70975
- join24(home, "node_modules", ".bin", "claude.cmd")
71469
+ join25(home, "AppData", "Roaming", "npm", "claude.cmd"),
71470
+ join25(home, ".npm-global", "claude.cmd"),
71471
+ join25(home, "node_modules", ".bin", "claude.cmd")
70976
71472
  ];
70977
71473
  for (const path2 of windowsPaths) {
70978
71474
  if (existsSync23(path2)) {
@@ -70983,11 +71479,11 @@ async function findClaudeBinary() {
70983
71479
  const commonPaths = [
70984
71480
  "/usr/local/bin/claude",
70985
71481
  "/opt/homebrew/bin/claude",
70986
- join24(home, ".npm-global/bin/claude"),
70987
- join24(home, ".local/bin/claude"),
70988
- join24(home, "node_modules/.bin/claude"),
71482
+ join25(home, ".npm-global/bin/claude"),
71483
+ join25(home, ".local/bin/claude"),
71484
+ join25(home, "node_modules/.bin/claude"),
70989
71485
  "/data/data/com.termux/files/usr/bin/claude",
70990
- join24(home, "../usr/bin/claude")
71486
+ join25(home, "../usr/bin/claude")
70991
71487
  ];
70992
71488
  for (const path2 of commonPaths) {
70993
71489
  if (existsSync23(path2)) {
@@ -71040,18 +71536,18 @@ __export(exports_diag_output, {
71040
71536
  NullDiagOutput: () => NullDiagOutput,
71041
71537
  LogFileDiagOutput: () => LogFileDiagOutput
71042
71538
  });
71043
- import { createWriteStream as createWriteStream3, mkdirSync as mkdirSync15, unlinkSync as unlinkSync10, writeFileSync as writeFileSync17 } from "fs";
71044
- import { homedir as homedir24 } from "os";
71045
- import { join as join25 } from "path";
71539
+ import { createWriteStream as createWriteStream3, mkdirSync as mkdirSync16, unlinkSync as unlinkSync10, writeFileSync as writeFileSync18 } from "fs";
71540
+ import { homedir as homedir25 } from "os";
71541
+ import { join as join26 } from "path";
71046
71542
  function getClaudishDir() {
71047
- const dir = join25(homedir24(), ".claudish");
71543
+ const dir = join26(homedir25(), ".claudish");
71048
71544
  try {
71049
- mkdirSync15(dir, { recursive: true });
71545
+ mkdirSync16(dir, { recursive: true });
71050
71546
  } catch {}
71051
71547
  return dir;
71052
71548
  }
71053
71549
  function getDiagLogPath() {
71054
- return join25(getClaudishDir(), `diag-${process.pid}.log`);
71550
+ return join26(getClaudishDir(), `diag-${process.pid}.log`);
71055
71551
  }
71056
71552
 
71057
71553
  class LogFileDiagOutput {
@@ -71060,7 +71556,7 @@ class LogFileDiagOutput {
71060
71556
  constructor() {
71061
71557
  this.logPath = getDiagLogPath();
71062
71558
  try {
71063
- writeFileSync17(this.logPath, `--- claudish diag session ${new Date().toISOString()} ---
71559
+ writeFileSync18(this.logPath, `--- claudish diag session ${new Date().toISOString()} ---
71064
71560
  `);
71065
71561
  } catch {}
71066
71562
  this.stream = createWriteStream3(this.logPath, { flags: "a" });
@@ -71262,9 +71758,9 @@ __export(exports_team_grid, {
71262
71758
  });
71263
71759
  import { spawn as spawn5 } from "child_process";
71264
71760
  import { execSync as execSync2 } from "child_process";
71265
- import { existsSync as existsSync24, readFileSync as readFileSync21, writeFileSync as writeFileSync18 } from "fs";
71761
+ import { existsSync as existsSync24, readFileSync as readFileSync22, writeFileSync as writeFileSync19 } from "fs";
71266
71762
  import { connect as netConnect } from "net";
71267
- import { dirname as dirname7, join as join26 } from "path";
71763
+ import { dirname as dirname8, join as join27 } from "path";
71268
71764
  import { setTimeout as wait } from "timers/promises";
71269
71765
  import { fileURLToPath as fileURLToPath3 } from "url";
71270
71766
  function resolveRouteInfo(modelId) {
@@ -71357,21 +71853,21 @@ function buildPaneHeader(model, prompt, bg) {
71357
71853
  }
71358
71854
  function findMagmuxBinary() {
71359
71855
  const thisFile = fileURLToPath3(import.meta.url);
71360
- const thisDir = dirname7(thisFile);
71361
- const pkgRoot = join26(thisDir, "..");
71856
+ const thisDir = dirname8(thisFile);
71857
+ const pkgRoot = join27(thisDir, "..");
71362
71858
  const platform3 = process.platform;
71363
71859
  const arch = process.arch;
71364
- const bundledMagmux = join26(pkgRoot, "native", `magmux-${platform3}-${arch}`);
71860
+ const bundledMagmux = join27(pkgRoot, "native", `magmux-${platform3}-${arch}`);
71365
71861
  if (existsSync24(bundledMagmux))
71366
71862
  return bundledMagmux;
71367
71863
  try {
71368
71864
  const pkgName = `@claudish/magmux-${platform3}-${arch}`;
71369
71865
  let searchDir = pkgRoot;
71370
71866
  for (let i = 0;i < 5; i++) {
71371
- const candidate = join26(searchDir, "node_modules", pkgName, "bin", "magmux");
71867
+ const candidate = join27(searchDir, "node_modules", pkgName, "bin", "magmux");
71372
71868
  if (existsSync24(candidate))
71373
71869
  return candidate;
71374
- const parent = dirname7(searchDir);
71870
+ const parent = dirname8(searchDir);
71375
71871
  if (parent === searchDir)
71376
71872
  break;
71377
71873
  searchDir = parent;
@@ -71475,9 +71971,9 @@ async function runWithGrid(sessionPath, models, input, opts) {
71475
71971
  const keep = opts?.keep ?? false;
71476
71972
  const manifest = setupSession(sessionPath, models, input);
71477
71973
  const startedAt = new Date().toISOString();
71478
- const gridfilePath = join26(sessionPath, "gridfile.txt");
71479
- const prompt = readFileSync21(join26(sessionPath, "input.md"), "utf-8").replace(/'/g, "'\\''").replace(/\n/g, " ");
71480
- const rawPrompt = readFileSync21(join26(sessionPath, "input.md"), "utf-8");
71974
+ const gridfilePath = join27(sessionPath, "gridfile.txt");
71975
+ const prompt = readFileSync22(join27(sessionPath, "input.md"), "utf-8").replace(/'/g, "'\\''").replace(/\n/g, " ");
71976
+ const rawPrompt = readFileSync22(join27(sessionPath, "input.md"), "utf-8");
71481
71977
  const usedBannerColors = new Set;
71482
71978
  const gridLines = Object.entries(manifest.models).map(([anonId]) => {
71483
71979
  const model = manifest.models[anonId].model;
@@ -71488,7 +71984,7 @@ async function runWithGrid(sessionPath, models, input, opts) {
71488
71984
  const header = buildPaneHeader(model, rawPrompt, bg);
71489
71985
  return `${header} claudish --model ${model} -y --quiet '${prompt}'`;
71490
71986
  });
71491
- writeFileSync18(gridfilePath, `${gridLines.join(`
71987
+ writeFileSync19(gridfilePath, `${gridLines.join(`
71492
71988
  `)}
71493
71989
  `, "utf-8");
71494
71990
  const magmuxPath = findMagmuxBinary();
@@ -71508,8 +72004,8 @@ async function runWithGrid(sessionPath, models, input, opts) {
71508
72004
  });
71509
72005
  const [{ results }] = await Promise.all([subscription, procExit]);
71510
72006
  const status = buildTeamStatus(manifest, startedAt, results?.panes ?? null);
71511
- const statusPath = join26(sessionPath, "status.json");
71512
- writeFileSync18(statusPath, JSON.stringify(status, null, 2), "utf-8");
72007
+ const statusPath = join27(sessionPath, "status.json");
72008
+ writeFileSync19(statusPath, JSON.stringify(status, null, 2), "utf-8");
71513
72009
  return status;
71514
72010
  }
71515
72011
  var BANNER_BG_COLORS;
@@ -71531,10 +72027,40 @@ var init_team_grid = __esm(() => {
71531
72027
  // src/index.ts
71532
72028
  init_op_source();
71533
72029
  init_onepassword_config();
72030
+ init_startup_trace();
71534
72031
  var import_dotenv3 = __toESM(require_main(), 1);
71535
- import { readFileSync as readFileSync22 } from "fs";
71536
- import { join as join27 } from "path";
72032
+ import { readFileSync as readFileSync23 } from "fs";
72033
+ import { join as join28 } from "path";
71537
72034
  import_dotenv3.config({ quiet: true });
72035
+ function classifyStartupKind() {
72036
+ const argv = process.argv.slice(2);
72037
+ const first = argv.find((a) => !a.startsWith("-"));
72038
+ if (first === "config")
72039
+ return "config";
72040
+ const management = new Set([
72041
+ "update",
72042
+ "init",
72043
+ "profile",
72044
+ "telemetry",
72045
+ "stats",
72046
+ "providers",
72047
+ "login",
72048
+ "logout",
72049
+ "quota",
72050
+ "usage"
72051
+ ]);
72052
+ if (first && management.has(first) || argv.includes("--mcp") || first === "serve") {
72053
+ return "other";
72054
+ }
72055
+ return "run";
72056
+ }
72057
+ process.on("exit", () => {
72058
+ const argv = process.argv.slice(2);
72059
+ const longRunningServer = argv.includes("--mcp") || argv.find((a) => !a.startsWith("-")) === "serve";
72060
+ if (longRunningServer)
72061
+ return;
72062
+ finalizeStartupTrace(classifyStartupKind(), { quiet: true });
72063
+ });
71538
72064
  async function applyOpEnvironment() {
71539
72065
  const argv = process.argv.slice(2);
71540
72066
  let flagEnvId;
@@ -71626,8 +72152,8 @@ async function applyOpImport() {
71626
72152
  }
71627
72153
  process.argv = [...head, ...rebuilt];
71628
72154
  }
71629
- await applyOpEnvironment();
71630
- await applyOpImport();
72155
+ await traceSpan("startup:op-env-flags", () => applyOpEnvironment());
72156
+ await traceSpan("startup:op-import-flag", () => applyOpImport());
71631
72157
  var isMcpMode = process.argv.includes("--mcp");
71632
72158
  function handlePromptExit(err) {
71633
72159
  if (err && typeof err === "object" && "name" in err && err.name === "ExitPromptError") {
@@ -71705,16 +72231,19 @@ if (isMcpMode) {
71705
72231
  return stats.handleStatsCommand(subcommand);
71706
72232
  });
71707
72233
  } else if (isConfigCommand) {
71708
- Promise.resolve().then(() => (init_tui(), exports_tui)).then(async (m) => {
72234
+ traceSpan("startup:tui-import", () => Promise.resolve().then(() => (init_tui(), exports_tui))).then(async (m) => {
71709
72235
  const { credentials: credentials2 } = await Promise.resolve().then(() => (init_authority(), exports_authority));
71710
72236
  const { PROVIDERS: PROVIDERS2 } = await Promise.resolve().then(() => (init_providers(), exports_providers));
71711
- await Promise.all(PROVIDERS2.map((p) => credentials2.isAvailable(p.catalogName, { allowOpPrompt: true })));
72237
+ await traceSpan("startup:credential-resolution", () => Promise.all(PROVIDERS2.map((p) => credentials2.isAvailable(p.catalogName, { allowOpPrompt: true }))), { providers: PROVIDERS2.length });
72238
+ finalizeStartupTrace("config");
72239
+ suppressStartupTraceTerminalOutput();
71712
72240
  return m.startConfigTui().catch(handlePromptExit);
71713
72241
  });
71714
72242
  } else {
71715
72243
  runCli();
71716
72244
  }
71717
72245
  async function runCli() {
72246
+ const endImports = beginSpan("startup:cli-imports");
71718
72247
  const { checkClaudeInstalled: checkClaudeInstalled2, runClaudeWithProxy: runClaudeWithProxy2 } = await Promise.resolve().then(() => (init_claude_runner(), exports_claude_runner));
71719
72248
  const { parseArgs: parseArgs2, getVersion: getVersion4 } = await Promise.resolve().then(() => (init_cli(), exports_cli));
71720
72249
  const { DEFAULT_PORT_RANGE: DEFAULT_PORT_RANGE2 } = await Promise.resolve().then(() => (init_config(), exports_config));
@@ -71731,6 +72260,7 @@ async function runCli() {
71731
72260
  const { createProxyServer: createProxyServer2 } = await Promise.resolve().then(() => (init_proxy_server(), exports_proxy_server));
71732
72261
  const { checkForUpdates: checkForUpdates2 } = await Promise.resolve().then(() => (init_update_checker(), exports_update_checker));
71733
72262
  const { warmCatalogIfNeeded: warmCatalogIfNeeded2 } = await Promise.resolve().then(() => (init_catalog_warm(), exports_catalog_warm));
72263
+ endImports();
71734
72264
  async function readStdin() {
71735
72265
  const chunks = [];
71736
72266
  for await (const chunk of process.stdin) {
@@ -71739,18 +72269,18 @@ async function runCli() {
71739
72269
  return Buffer.concat(chunks).toString("utf-8");
71740
72270
  }
71741
72271
  try {
71742
- const cliConfig = await parseArgs2(process.argv.slice(2));
72272
+ const cliConfig = await traceSpan("startup:parse-args", () => parseArgs2(process.argv.slice(2)));
71743
72273
  if (cliConfig.team && cliConfig.team.length > 0) {
71744
72274
  let prompt = cliConfig.claudeArgs.join(" ");
71745
72275
  if (cliConfig.inputFile) {
71746
- prompt = readFileSync22(cliConfig.inputFile, "utf-8");
72276
+ prompt = readFileSync23(cliConfig.inputFile, "utf-8");
71747
72277
  }
71748
72278
  if (!prompt.trim()) {
71749
72279
  console.error("Error: --team requires a prompt (positional args or -f <file>)");
71750
72280
  process.exit(1);
71751
72281
  }
71752
72282
  const mode = cliConfig.teamMode ?? "default";
71753
- const sessionPath = join27(process.cwd(), `.claudish-team-${Date.now()}`);
72283
+ const sessionPath = join28(process.cwd(), `.claudish-team-${Date.now()}`);
71754
72284
  if (mode === "json") {
71755
72285
  const { setupSession: setupSession2, runModels: runModels2 } = await Promise.resolve().then(() => (init_team_orchestrator(), exports_team_orchestrator));
71756
72286
  setupSession2(sessionPath, cliConfig.team, prompt);
@@ -71760,9 +72290,9 @@ async function runCli() {
71760
72290
  });
71761
72291
  const result = { ...status2, responses: {} };
71762
72292
  for (const anonId of Object.keys(status2.models)) {
71763
- const responsePath = join27(sessionPath, `response-${anonId}.md`);
72293
+ const responsePath = join28(sessionPath, `response-${anonId}.md`);
71764
72294
  try {
71765
- const raw2 = readFileSync22(responsePath, "utf-8").trim();
72295
+ const raw2 = readFileSync23(responsePath, "utf-8").trim();
71766
72296
  try {
71767
72297
  result.responses[anonId] = JSON.parse(raw2);
71768
72298
  } catch {
@@ -71799,6 +72329,9 @@ Team Status`);
71799
72329
  try {
71800
72330
  const cfg = loadConfig2();
71801
72331
  if (!cfg.autoApproveConfirmedAt) {
72332
+ const endConfirm = beginSpan("startup:first-run-confirm", {
72333
+ mayIncludeUserPrompt: true
72334
+ });
71802
72335
  const { createInterface: createInterface2 } = await import("readline");
71803
72336
  process.stderr.write(`
71804
72337
  [claudish] Auto-approve is enabled by default.
@@ -71826,6 +72359,7 @@ Team Status`);
71826
72359
  }
71827
72360
  cfg.autoApproveConfirmedAt = new Date().toISOString();
71828
72361
  saveConfig2(cfg);
72362
+ endConfirm();
71829
72363
  }
71830
72364
  } catch {}
71831
72365
  }
@@ -71842,9 +72376,9 @@ Team Status`);
71842
72376
  }
71843
72377
  }
71844
72378
  if (cliConfig.interactive && !cliConfig.jsonOutput) {
71845
- await checkForUpdates2(getVersion4(), { quiet: cliConfig.quiet });
72379
+ await traceSpan("startup:update-check", () => checkForUpdates2(getVersion4(), { quiet: cliConfig.quiet }));
71846
72380
  }
71847
- if (!await checkClaudeInstalled2()) {
72381
+ if (!await traceSpan("startup:claude-detect", () => checkClaudeInstalled2())) {
71848
72382
  console.error("Error: Claude Code CLI not found");
71849
72383
  console.error("Install it from: https://claude.com/claude-code");
71850
72384
  console.error("");
@@ -71854,7 +72388,7 @@ Team Status`);
71854
72388
  }
71855
72389
  const hasProfileTiers = cliConfig.modelOpus || cliConfig.modelSonnet || cliConfig.modelHaiku || cliConfig.modelSubagent;
71856
72390
  if (cliConfig.interactive && !cliConfig.monitor && !cliConfig.model && !hasProfileTiers) {
71857
- cliConfig.model = await selectModel2({ freeOnly: cliConfig.freeOnly }).catch(handlePromptExit);
72391
+ cliConfig.model = await traceSpan("startup:model-select", () => selectModel2({ freeOnly: cliConfig.freeOnly }).catch(handlePromptExit), { mayIncludeUserPrompt: true });
71858
72392
  console.log("");
71859
72393
  }
71860
72394
  if (!cliConfig.interactive && !cliConfig.monitor && !cliConfig.model && !hasProfileTiers) {
@@ -71872,7 +72406,7 @@ Team Status`);
71872
72406
  cliConfig.modelHaiku,
71873
72407
  cliConfig.modelSubagent
71874
72408
  ];
71875
- const resolutions = await validateApiKeysForModels2(modelsToValidate);
72409
+ const resolutions = await traceSpan("startup:validate-api-keys", () => validateApiKeysForModels2(modelsToValidate), { models: modelsToValidate.filter((m) => typeof m === "string").length });
71876
72410
  const missingKeys = getMissingKeyResolutions2(resolutions);
71877
72411
  if (missingKeys.length > 0) {
71878
72412
  if (cliConfig.interactive) {
@@ -71918,16 +72452,16 @@ Team Status`);
71918
72452
  }
71919
72453
  }
71920
72454
  if (cliConfig.stdin) {
71921
- const stdinInput = await readStdin();
72455
+ const stdinInput = await traceSpan("startup:stdin-read", () => readStdin());
71922
72456
  if (stdinInput.trim()) {
71923
72457
  cliConfig.claudeArgs = [stdinInput, ...cliConfig.claudeArgs];
71924
72458
  }
71925
72459
  }
71926
- const warmOutcome = await warmCatalogIfNeeded2(cliConfig);
72460
+ const warmOutcome = await traceSpan("startup:catalog-warm", () => warmCatalogIfNeeded2(cliConfig));
71927
72461
  if (warmOutcome === "hard_fail") {
71928
72462
  process.exit(1);
71929
72463
  }
71930
- const port = cliConfig.port || await findAvailablePort2(DEFAULT_PORT_RANGE2.start, DEFAULT_PORT_RANGE2.end);
72464
+ const port = cliConfig.port || await traceSpan("startup:find-port", () => findAvailablePort2(DEFAULT_PORT_RANGE2.start, DEFAULT_PORT_RANGE2.end));
71931
72465
  const explicitModel = typeof cliConfig.model === "string" ? cliConfig.model : undefined;
71932
72466
  const modelMap = {
71933
72467
  opus: cliConfig.modelOpus,
@@ -71935,13 +72469,13 @@ Team Status`);
71935
72469
  haiku: cliConfig.modelHaiku,
71936
72470
  subagent: cliConfig.modelSubagent
71937
72471
  };
71938
- const proxy = await createProxyServer2(port, cliConfig.monitor ? undefined : cliConfig.openrouterApiKey, cliConfig.monitor ? undefined : explicitModel, cliConfig.monitor, cliConfig.anthropicApiKey, modelMap, {
72472
+ const proxy = await traceSpan("startup:proxy-start", () => createProxyServer2(port, cliConfig.monitor ? undefined : cliConfig.openrouterApiKey, cliConfig.monitor ? undefined : explicitModel, cliConfig.monitor, cliConfig.anthropicApiKey, modelMap, {
71939
72473
  summarizeTools: cliConfig.summarizeTools,
71940
72474
  quiet: cliConfig.quiet,
71941
72475
  isInteractive: cliConfig.interactive,
71942
72476
  advisorModels: cliConfig.advisorModels,
71943
72477
  advisorCollector: cliConfig.advisorCollector
71944
- });
72478
+ }));
71945
72479
  const diag = createDiagOutput2({
71946
72480
  interactive: cliConfig.interactive,
71947
72481
  diagMode: cliConfig.diagMode
@@ -71949,6 +72483,7 @@ Team Status`);
71949
72483
  if (cliConfig.interactive) {
71950
72484
  setDiagOutput2(diag);
71951
72485
  }
72486
+ finalizeStartupTrace("run", { quiet: cliConfig.quiet });
71952
72487
  let exitCode = 0;
71953
72488
  try {
71954
72489
  exitCode = await runClaudeWithProxy2(cliConfig, proxy.url, () => diag.cleanup());