ccusage 15.9.7 → 15.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, BURN_RATE_THRESHOLDS, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PROJECT_ALIASES_ENV, PricingFetcher, WEEK_DAYS, __commonJSMin, __require, __toESM, inspectError, isFailure, map, pipe, require_usingCtx, try_ } from "./pricing-fetcher-CLjmfFHB.js";
2
+ import { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, BURN_RATE_THRESHOLDS, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PROJECT_ALIASES_ENV, PricingFetcher, WEEK_DAYS, __commonJSMin, __require, __toESM, inspectError, isFailure, isSuccess, map, pipe, require_usingCtx, succeed, try_ } from "./pricing-fetcher-CbLCyFQr.js";
3
3
  import { getTotalTokens } from "./_token-utils-WjkbrjKv.js";
4
4
  import { CostModes, SortOrders, filterDateSchema, statuslineHookJsonSchema } from "./_types-BbEk8t2a.js";
5
5
  import { calculateTotals, createTotalsObject } from "./calculate-cost-BDqO4yWA.js";
6
- import { DEFAULT_SESSION_DURATION_HOURS, calculateBurnRate, calculateContextTokens, calculateCostForEntry, createUniqueHash, filterRecentBlocks, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, identifySessionBlocks, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, projectBlockUsage, sortFilesByTimestamp, uniq, unwrap, usageDataSchema } from "./data-loader-G78wtKpU.js";
7
- import { description, log, logger, name, version } from "./logger-CHezuMoN.js";
8
- import { detectMismatches, printMismatchReport } from "./debug-BFlA56YT.js";
9
- import { createMcpHttpApp, createMcpServer, startMcpServerStdio } from "./mcp-BEHYXSQT.js";
10
- import a, { readFile } from "node:fs/promises";
11
- import path from "node:path";
6
+ import { DEFAULT_SESSION_DURATION_HOURS, calculateBurnRate, calculateContextTokens, calculateCostForEntry, createUniqueHash, filterRecentBlocks, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, identifySessionBlocks, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, projectBlockUsage, sortFilesByTimestamp, uniq, unwrap, usageDataSchema } from "./data-loader-CM8RKePp.js";
7
+ import { description, log, logger, name, version } from "./logger-m79TqYfY.js";
8
+ import { detectMismatches, printMismatchReport } from "./debug-D5u7ZVKi.js";
9
+ import { createMcpHttpApp, createMcpServer, startMcpServerStdio } from "./mcp-r529IhIF.js";
10
+ import a, { readFile, stat } from "node:fs/promises";
11
+ import path, { join } from "node:path";
12
12
  import process$1 from "node:process";
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
13
15
  import { stripVTControlCharacters } from "node:util";
14
16
  import { fileURLToPath } from "node:url";
15
17
  import { spawn } from "node:child_process";
@@ -81,8 +83,8 @@ async function resolveExamples(ctx, examples) {
81
83
  return typeof examples === "string" ? examples : typeof examples === "function" ? await examples(ctx) : "";
82
84
  }
83
85
  function mapResourceWithBuiltinKey(resource) {
84
- return Object.entries(resource).reduce((acc, [key, value]) => {
85
- return acc[resolveBuiltInKey(key)] = value, acc;
86
+ return Object.entries(resource).reduce((acc, [key, value$1]) => {
87
+ return acc[resolveBuiltInKey(key)] = value$1, acc;
86
88
  }, create());
87
89
  }
88
90
  function create(obj = null) {
@@ -94,8 +96,8 @@ function log$1(...args) {
94
96
  function deepFreeze(obj) {
95
97
  if (obj === null || typeof obj !== "object") return obj;
96
98
  for (const key of Object.keys(obj)) {
97
- const value = obj[key];
98
- if (typeof value === "object" && value !== null) deepFreeze(value);
99
+ const value$1 = obj[key];
100
+ if (typeof value$1 === "object" && value$1 !== null) deepFreeze(value$1);
99
101
  }
100
102
  return Object.freeze(obj);
101
103
  }
@@ -143,8 +145,8 @@ var DefaultTranslation = class {
143
145
  };
144
146
  const BUILT_IN_PREFIX_CODE = BUILT_IN_PREFIX.codePointAt(0);
145
147
  async function createCommandContext({ args, values, positionals, rest, argv: argv$1, tokens, command, cliOptions, callMode = "entry", omitted = false }) {
146
- const _args = Object.entries(args).reduce((acc, [key, value]) => {
147
- return acc[key] = Object.assign(create(), value), acc;
148
+ const _args = Object.entries(args).reduce((acc, [key, value$1]) => {
149
+ return acc[key] = Object.assign(create(), value$1), acc;
148
150
  }, create()), env$2 = Object.assign(create(), COMMAND_OPTIONS_DEFAULT, cliOptions), locale = resolveLocale(cliOptions.locale), localeStr = locale.toString(), translationAdapterFactory = cliOptions.translationAdapterFactory || createTranslationAdapter, adapter = translationAdapterFactory({
149
151
  locale: localeStr,
150
152
  fallbackLocale: DEFAULT_LOCALE
@@ -186,8 +188,8 @@ async function createCommandContext({ args, values, positionals, rest, argv: arg
186
188
  })), loadedOptionsResources = Object.entries(args).map(([key, arg]) => {
187
189
  const description$1 = arg.description || "";
188
190
  return [key, description$1];
189
- }), defaultCommandResource = loadedOptionsResources.reduce((res, [key, value]) => {
190
- return res[resolveArgKey(key)] = value, res;
191
+ }), defaultCommandResource = loadedOptionsResources.reduce((res, [key, value$1]) => {
192
+ return res[resolveArgKey(key)] = value$1, res;
191
193
  }, create());
192
194
  defaultCommandResource.description = command.description || "", defaultCommandResource.examples = await resolveExamples(ctx, command.examples), adapter.setResource(DEFAULT_LOCALE, defaultCommandResource);
193
195
  const originalResource = await loadCommandResource(ctx, command);
@@ -218,8 +220,8 @@ function define(definition) {
218
220
  * @author kazuya kawaguchi (a.k.a. kazupon)
219
221
  * @license MIT
220
222
  */
221
- function kebabnize(str) {
222
- return str.replace(/[A-Z]/g, (match, offset) => (offset > 0 ? "-" : "") + match.toLowerCase());
223
+ function kebabnize(str$1) {
224
+ return str$1.replace(/[A-Z]/g, (match, offset) => (offset > 0 ? "-" : "") + match.toLowerCase());
223
225
  }
224
226
  function renderHeader(ctx) {
225
227
  const title = ctx.env.description || ctx.env.name || "";
@@ -349,13 +351,13 @@ function resolveDisplayValue(ctx, key) {
349
351
  return "";
350
352
  }
351
353
  async function generateOptionalArgsUsage(ctx, optionsPairs) {
352
- const optionsMaxLength = Math.max(...Object.entries(optionsPairs).map(([_, value]) => value.length)), optionSchemaMaxLength = ctx.env.usageOptionType ? Math.max(...Object.entries(optionsPairs).map(([key]) => resolveNegatableType(key, ctx).length)) : 0, usages = await Promise.all(Object.entries(optionsPairs).map(([key, value]) => {
354
+ const optionsMaxLength = Math.max(...Object.entries(optionsPairs).map(([_, value$1]) => value$1.length)), optionSchemaMaxLength = ctx.env.usageOptionType ? Math.max(...Object.entries(optionsPairs).map(([key]) => resolveNegatableType(key, ctx).length)) : 0, usages = await Promise.all(Object.entries(optionsPairs).map(([key, value$1]) => {
353
355
  let rawDesc = ctx.translate(resolveArgKey(key));
354
356
  if (!rawDesc && key.startsWith("no-")) {
355
357
  const name$1 = resolveNegatableKey(key), schema = ctx.args[name$1], optionKey = makeShortLongOptionPair(schema, name$1, ctx.toKebab);
356
358
  rawDesc = `${ctx.translate(resolveBuiltInKey("NEGATABLE"))} ${optionKey}`;
357
359
  }
358
- const optionsSchema = ctx.env.usageOptionType ? `[${resolveNegatableType(key, ctx)}] ` : "", valueDesc = key.startsWith("no-") ? "" : resolveDisplayValue(ctx, key), desc = `${optionsSchema ? optionsSchema.padEnd(optionSchemaMaxLength + 3) : ""}${rawDesc}`, option = `${value.padEnd(optionsMaxLength + ctx.env.middleMargin)}${desc}${valueDesc ? ` ${valueDesc}` : ""}`;
360
+ const optionsSchema = ctx.env.usageOptionType ? `[${resolveNegatableType(key, ctx)}] ` : "", valueDesc = key.startsWith("no-") ? "" : resolveDisplayValue(ctx, key), desc = `${optionsSchema ? optionsSchema.padEnd(optionSchemaMaxLength + 3) : ""}${rawDesc}`, option = `${value$1.padEnd(optionsMaxLength + ctx.env.middleMargin)}${desc}${valueDesc ? ` ${valueDesc}` : ""}`;
359
361
  return `${option.padStart(ctx.env.leftMargin + option.length)}`;
360
362
  }));
361
363
  return usages.join("\n");
@@ -405,21 +407,21 @@ function parseArgs(args, options = {}) {
405
407
  }
406
408
  if (isShortOption(arg)) {
407
409
  const shortOption = arg.charAt(1);
408
- let value, inlineValue;
410
+ let value$1, inlineValue;
409
411
  if (groupCount) {
410
412
  if (tokens.push({
411
413
  kind: "option",
412
414
  name: shortOption,
413
415
  rawName: arg,
414
416
  index,
415
- value,
417
+ value: value$1,
416
418
  inlineValue
417
419
  }), groupCount === 1 && hasOptionValue(nextArg)) {
418
- if (value = remainings.shift(), hasShortValueSeparator) inlineValue = true, hasShortValueSeparator = false;
420
+ if (value$1 = remainings.shift(), hasShortValueSeparator) inlineValue = true, hasShortValueSeparator = false;
419
421
  tokens.push({
420
422
  kind: "option",
421
423
  index,
422
- value,
424
+ value: value$1,
423
425
  inlineValue
424
426
  });
425
427
  }
@@ -428,10 +430,10 @@ function parseArgs(args, options = {}) {
428
430
  name: shortOption,
429
431
  rawName: arg,
430
432
  index,
431
- value,
433
+ value: value$1,
432
434
  inlineValue
433
435
  });
434
- if (value != null) ++index;
436
+ if (value$1 != null) ++index;
435
437
  continue;
436
438
  }
437
439
  if (isShortOptionGroup(arg)) {
@@ -460,13 +462,13 @@ function parseArgs(args, options = {}) {
460
462
  continue;
461
463
  }
462
464
  if (isLongOptionAndValue(arg)) {
463
- const equalIndex = arg.indexOf(EQUAL_CHAR), longOption = arg.slice(2, equalIndex), value = arg.slice(equalIndex + 1);
465
+ const equalIndex = arg.indexOf(EQUAL_CHAR), longOption = arg.slice(2, equalIndex), value$1 = arg.slice(equalIndex + 1);
464
466
  tokens.push({
465
467
  kind: "option",
466
468
  name: longOption,
467
469
  rawName: `${LONG_OPTION_PREFIX}${longOption}`,
468
470
  index,
469
- value,
471
+ value: value$1,
470
472
  inlineValue: true
471
473
  });
472
474
  continue;
@@ -494,8 +496,8 @@ function isLongOptionAndValue(arg) {
494
496
  function hasLongOptionPrefix(arg) {
495
497
  return arg.length > 2 && ~arg.indexOf(LONG_OPTION_PREFIX);
496
498
  }
497
- function hasOptionValue(value) {
498
- return !(value == null) && value.codePointAt(0) !== HYPHEN_CODE;
499
+ function hasOptionValue(value$1) {
500
+ return !(value$1 == null) && value$1.codePointAt(0) !== HYPHEN_CODE;
499
501
  }
500
502
  const SKIP_POSITIONAL_DEFAULT = -1;
501
503
  function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKIP_POSITIONAL_DEFAULT, toKebab = false } = {}) {
@@ -505,15 +507,15 @@ function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKI
505
507
  function toShortValue() {
506
508
  if (expandableShortOptions.length === 0) return void 0;
507
509
  {
508
- const value = expandableShortOptions.map((token) => token.name).join("");
509
- return expandableShortOptions.length = 0, value;
510
+ const value$1 = expandableShortOptions.map((token) => token.name).join("");
511
+ return expandableShortOptions.length = 0, value$1;
510
512
  }
511
513
  }
512
- function applyLongOptionValue(value = void 0) {
513
- if (currentLongOption) currentLongOption.value = value, optionTokens.push({ ...currentLongOption }), currentLongOption = void 0;
514
+ function applyLongOptionValue(value$1 = void 0) {
515
+ if (currentLongOption) currentLongOption.value = value$1, optionTokens.push({ ...currentLongOption }), currentLongOption = void 0;
514
516
  }
515
- function applyShortOptionValue(value = void 0) {
516
- if (currentShortOption) currentShortOption.value = value || toShortValue(), optionTokens.push({ ...currentShortOption }), currentShortOption = void 0;
517
+ function applyShortOptionValue(value$1 = void 0) {
518
+ if (currentShortOption) currentShortOption.value = value$1 || toShortValue(), optionTokens.push({ ...currentShortOption }), currentShortOption = void 0;
517
519
  }
518
520
  const schemas = Object.values(args);
519
521
  let terminated = false;
@@ -636,8 +638,8 @@ var ArgResolveError = class extends Error {
636
638
  function validateRequire(token, option, schema) {
637
639
  if (schema.required && schema.type !== "boolean" && !token.value) return createRequireError(option, schema);
638
640
  }
639
- function isNumeric(str) {
640
- return str.trim() !== "" && !isNaN(str);
641
+ function isNumeric(str$1) {
642
+ return str$1.trim() !== "" && !isNaN(str$1);
641
643
  }
642
644
  function createTypeError(option, schema) {
643
645
  return new ArgResolveError(`Optional argument '--${option}' ${schema.short ? `or '-${schema.short}' ` : ""}should be '${schema.type}'`, option, "type", schema);
@@ -951,8 +953,8 @@ const getErrorOutput = ({ exitCode, signalCode }) => ({
951
953
  let promises = [];
952
954
  while (iterators.length > 0) {
953
955
  promises = iterators.map((iterator$1, index$1) => promises[index$1] ?? getNext(iterator$1));
954
- const [{ value, done }, index] = await Promise.race(promises.map((promise, index$1) => Promise.all([promise, index$1]))), [iterator] = iterators.splice(index, 1);
955
- if (promises.splice(index, 1), !done) iterators.push(iterator), yield value;
956
+ const [{ value: value$1, done }, index] = await Promise.race(promises.map((promise, index$1) => Promise.all([promise, index$1]))), [iterator] = iterators.splice(index, 1);
957
+ if (promises.splice(index, 1), !done) iterators.push(iterator), yield value$1;
956
958
  }
957
959
  } finally {
958
960
  await Promise.all(iterators.map((iterator) => iterator.return()));
@@ -989,8 +991,8 @@ async function processWithJq(jsonData, jqCommand) {
989
991
  });
990
992
  return result();
991
993
  }
992
- function parseDateArg(value) {
993
- const result = filterDateSchema.safeParse(value);
994
+ function parseDateArg(value$1) {
995
+ const result = filterDateSchema.safeParse(value$1);
994
996
  if (!result.success) throw new TypeError(result.error.issues[0]?.message ?? "Invalid date format");
995
997
  return result.data;
996
998
  }
@@ -1126,34 +1128,34 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1126
1128
  function codeRegex(capture) {
1127
1129
  return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g;
1128
1130
  }
1129
- function strlen(str) {
1130
- let code = codeRegex(), stripped = ("" + str).replace(code, ""), split = stripped.split("\n");
1131
+ function strlen(str$1) {
1132
+ let code = codeRegex(), stripped = ("" + str$1).replace(code, ""), split = stripped.split("\n");
1131
1133
  return split.reduce(function(memo, s) {
1132
1134
  return stringWidth$1(s) > memo ? stringWidth$1(s) : memo;
1133
1135
  }, 0);
1134
1136
  }
1135
- function repeat(str, times) {
1136
- return Array(times + 1).join(str);
1137
+ function repeat(str$1, times) {
1138
+ return Array(times + 1).join(str$1);
1137
1139
  }
1138
- function pad(str, len, pad$1, dir) {
1139
- let length = strlen(str);
1140
+ function pad(str$1, len, pad$1, dir) {
1141
+ let length = strlen(str$1);
1140
1142
  if (len + 1 >= length) {
1141
1143
  let padlen = len - length;
1142
1144
  switch (dir) {
1143
1145
  case "right":
1144
- str = repeat(pad$1, padlen) + str;
1146
+ str$1 = repeat(pad$1, padlen) + str$1;
1145
1147
  break;
1146
1148
  case "center": {
1147
1149
  let right = Math.ceil(padlen / 2), left = padlen - right;
1148
- str = repeat(pad$1, left) + str + repeat(pad$1, right);
1150
+ str$1 = repeat(pad$1, left) + str$1 + repeat(pad$1, right);
1149
1151
  break;
1150
1152
  }
1151
1153
  default:
1152
- str = str + repeat(pad$1, padlen);
1154
+ str$1 = str$1 + repeat(pad$1, padlen);
1153
1155
  break;
1154
1156
  }
1155
1157
  }
1156
- return str;
1158
+ return str$1;
1157
1159
  }
1158
1160
  let codeCache = {};
1159
1161
  function addToCodeCache(name$1, on$1, off) {
@@ -1209,15 +1211,15 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1209
1211
  if (lastForegroundAdded && lastForegroundAdded != "\x1B[39m") ret = lastForegroundAdded + ret;
1210
1212
  return ret;
1211
1213
  }
1212
- function truncateWidth(str, desiredLength) {
1213
- if (str.length === strlen(str)) return str.substr(0, desiredLength);
1214
- while (strlen(str) > desiredLength) str = str.slice(0, -1);
1215
- return str;
1214
+ function truncateWidth(str$1, desiredLength) {
1215
+ if (str$1.length === strlen(str$1)) return str$1.substr(0, desiredLength);
1216
+ while (strlen(str$1) > desiredLength) str$1 = str$1.slice(0, -1);
1217
+ return str$1;
1216
1218
  }
1217
- function truncateWidthWithAnsi(str, desiredLength) {
1218
- let code = codeRegex(true), split = str.split(codeRegex()), splitIndex = 0, retLen = 0, ret = "", myArray, state = {};
1219
+ function truncateWidthWithAnsi(str$1, desiredLength) {
1220
+ let code = codeRegex(true), split = str$1.split(codeRegex()), splitIndex = 0, retLen = 0, ret = "", myArray, state = {};
1219
1221
  while (retLen < desiredLength) {
1220
- myArray = code.exec(str);
1222
+ myArray = code.exec(str$1);
1221
1223
  let toAdd = split[splitIndex];
1222
1224
  if (splitIndex++, retLen + strlen(toAdd) > desiredLength) toAdd = truncateWidth(toAdd, desiredLength - retLen);
1223
1225
  if (ret += toAdd, retLen += strlen(toAdd), retLen < desiredLength) {
@@ -1227,15 +1229,15 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1227
1229
  }
1228
1230
  return unwindState(state, ret);
1229
1231
  }
1230
- function truncate(str, desiredLength, truncateChar) {
1232
+ function truncate(str$1, desiredLength, truncateChar) {
1231
1233
  truncateChar = truncateChar || "…";
1232
- let lengthOfStr = strlen(str);
1233
- if (lengthOfStr <= desiredLength) return str;
1234
+ let lengthOfStr = strlen(str$1);
1235
+ if (lengthOfStr <= desiredLength) return str$1;
1234
1236
  desiredLength -= strlen(truncateChar);
1235
- let ret = truncateWidthWithAnsi(str, desiredLength);
1237
+ let ret = truncateWidthWithAnsi(str$1, desiredLength);
1236
1238
  ret += truncateChar;
1237
1239
  const hrefTag = "\x1B]8;;\x07";
1238
- if (str.includes(hrefTag) && !ret.includes(hrefTag)) ret += hrefTag;
1240
+ if (str$1.includes(hrefTag) && !ret.includes(hrefTag)) ret += hrefTag;
1239
1241
  return ret;
1240
1242
  }
1241
1243
  function defaultOptions() {
@@ -1293,9 +1295,9 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1293
1295
  }
1294
1296
  function textWrap(maxLength, input) {
1295
1297
  let lines = [], line = "";
1296
- function pushLine(str, ws) {
1298
+ function pushLine(str$1, ws) {
1297
1299
  if (line.length && ws) line += ws;
1298
- line += str;
1300
+ line += str$1;
1299
1301
  while (line.length > maxLength) lines.push(line.slice(0, maxLength)), line = line.slice(maxLength);
1300
1302
  }
1301
1303
  let split = input.split(/(\s+)/g);
@@ -1730,11 +1732,11 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1730
1732
  var r = Math.floor(Math.random() * range);
1731
1733
  return r;
1732
1734
  }
1733
- function isChar(character) {
1734
- var bool = false;
1735
+ function isChar(character$1) {
1736
+ var bool$1 = false;
1735
1737
  return all.filter(function(i) {
1736
- bool = i === character;
1737
- }), bool;
1738
+ bool$1 = i === character$1;
1739
+ }), bool$1;
1738
1740
  }
1739
1741
  function heComes(text$1, options$1) {
1740
1742
  var result = "", counts, l;
@@ -1830,16 +1832,16 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1830
1832
  colors$1.enabled = true;
1831
1833
  }, colors$1.disable = function() {
1832
1834
  colors$1.enabled = false;
1833
- }, colors$1.stripColors = colors$1.strip = function(str) {
1834
- return ("" + str).replace(/\x1B\[\d+m/g, "");
1835
- }, colors$1.stylize = function stylize(str, style) {
1836
- if (!colors$1.enabled) return str + "";
1835
+ }, colors$1.stripColors = colors$1.strip = function(str$1) {
1836
+ return ("" + str$1).replace(/\x1B\[\d+m/g, "");
1837
+ }, colors$1.stylize = function stylize(str$1, style) {
1838
+ if (!colors$1.enabled) return str$1 + "";
1837
1839
  var styleMap = ansiStyles[style];
1838
- return !styleMap && style in colors$1 ? colors$1[style](str) : styleMap.open + str + styleMap.close;
1840
+ return !styleMap && style in colors$1 ? colors$1[style](str$1) : styleMap.open + str$1 + styleMap.close;
1839
1841
  };
1840
- var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g, escapeStringRegexp = function(str) {
1841
- if (typeof str !== "string") throw new TypeError("Expected a string");
1842
- return str.replace(matchOperatorsRe, "\\$&");
1842
+ var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g, escapeStringRegexp = function(str$1) {
1843
+ if (typeof str$1 !== "string") throw new TypeError("Expected a string");
1844
+ return str$1.replace(matchOperatorsRe, "\\$&");
1843
1845
  };
1844
1846
  function build(_styles) {
1845
1847
  var builder = function builder$1() {
@@ -1856,18 +1858,18 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1856
1858
  }), ret;
1857
1859
  })(), proto = defineProps(function colors$2() {}, styles);
1858
1860
  function applyStyle() {
1859
- var args = Array.prototype.slice.call(arguments), str = args.map(function(arg) {
1861
+ var args = Array.prototype.slice.call(arguments), str$1 = args.map(function(arg) {
1860
1862
  return arg != null && arg.constructor === String ? arg : util.inspect(arg);
1861
1863
  }).join(" ");
1862
- if (!colors$1.enabled || !str) return str;
1863
- var newLinesPresent = str.indexOf("\n") != -1, nestedStyles = this._styles, i = nestedStyles.length;
1864
+ if (!colors$1.enabled || !str$1) return str$1;
1865
+ var newLinesPresent = str$1.indexOf("\n") != -1, nestedStyles = this._styles, i = nestedStyles.length;
1864
1866
  while (i--) {
1865
1867
  var code = ansiStyles[nestedStyles[i]];
1866
- if (str = code.open + str.replace(code.closeRe, code.open) + code.close, newLinesPresent) str = str.replace(newLineRegex, function(match) {
1868
+ if (str$1 = code.open + str$1.replace(code.closeRe, code.open) + code.close, newLinesPresent) str$1 = str$1.replace(newLineRegex, function(match) {
1867
1869
  return code.close + match + code.open;
1868
1870
  });
1869
1871
  }
1870
- return str;
1872
+ return str$1;
1871
1873
  }
1872
1874
  colors$1.setTheme = function(theme) {
1873
1875
  if (typeof theme === "string") {
@@ -1875,13 +1877,13 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1875
1877
  return;
1876
1878
  }
1877
1879
  for (var style in theme) (function(style$1) {
1878
- colors$1[style$1] = function(str) {
1880
+ colors$1[style$1] = function(str$1) {
1879
1881
  if (typeof theme[style$1] === "object") {
1880
- var out = str;
1882
+ var out = str$1;
1881
1883
  for (var i in theme[style$1]) out = colors$1[theme[style$1][i]](out);
1882
1884
  return out;
1883
1885
  }
1884
- return colors$1[theme[style$1]](str);
1886
+ return colors$1[theme[style$1]](str$1);
1885
1887
  };
1886
1888
  })(style);
1887
1889
  };
@@ -1893,15 +1895,15 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1893
1895
  } };
1894
1896
  }), ret;
1895
1897
  }
1896
- var sequencer = function sequencer$1(map$2, str) {
1897
- var exploded = str.split("");
1898
- return exploded = exploded.map(map$2), exploded.join("");
1898
+ var sequencer = function sequencer$1(map$3, str$1) {
1899
+ var exploded = str$1.split("");
1900
+ return exploded = exploded.map(map$3), exploded.join("");
1899
1901
  };
1900
- for (var map$1 in colors$1.trap = require_trap(), colors$1.zalgo = require_zalgo(), colors$1.maps = {}, colors$1.maps.america = require_america()(colors$1), colors$1.maps.zebra = require_zebra()(colors$1), colors$1.maps.rainbow = require_rainbow()(colors$1), colors$1.maps.random = require_random()(colors$1), colors$1.maps) (function(map$2) {
1901
- colors$1[map$2] = function(str) {
1902
- return sequencer(colors$1.maps[map$2], str);
1902
+ for (var map$2 in colors$1.trap = require_trap(), colors$1.zalgo = require_zalgo(), colors$1.maps = {}, colors$1.maps.america = require_america()(colors$1), colors$1.maps.zebra = require_zebra()(colors$1), colors$1.maps.rainbow = require_rainbow()(colors$1), colors$1.maps.random = require_random()(colors$1), colors$1.maps) (function(map$3) {
1903
+ colors$1[map$3] = function(str$1) {
1904
+ return sequencer(colors$1.maps[map$3], str$1);
1903
1905
  };
1904
- })(map$1);
1906
+ })(map$2);
1905
1907
  defineProps(colors$1, init());
1906
1908
  })), require_safe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1907
1909
  var colors = require_colors();
@@ -2079,8 +2081,8 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2079
2081
  for (let i = 1; i < span; i++) ret += 1 + dimensionTable[startingIndex + i];
2080
2082
  return ret;
2081
2083
  }
2082
- function sumPlusOne(a$1, b) {
2083
- return a$1 + b + 1;
2084
+ function sumPlusOne(a$1, b$1) {
2085
+ return a$1 + b$1 + 1;
2084
2086
  }
2085
2087
  let CHAR_NAMES = [
2086
2088
  "top",
@@ -2304,8 +2306,8 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2304
2306
  return result.join("\n");
2305
2307
  }
2306
2308
  get width() {
2307
- let str = this.toString().split("\n");
2308
- return str[0].length;
2309
+ let str$1 = this.toString().split("\n");
2310
+ return str$1[0].length;
2309
2311
  }
2310
2312
  };
2311
2313
  Table$1.reset = () => debug.reset();
@@ -2314,8 +2316,8 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2314
2316
  row.forEach(function(cell) {
2315
2317
  line.push(cell.draw(lineNum));
2316
2318
  });
2317
- let str = line.join("");
2318
- if (str.length) result.push(str);
2319
+ let str$1 = line.join("");
2320
+ if (str$1.length) result.push(str$1);
2319
2321
  }
2320
2322
  module.exports = Table$1;
2321
2323
  })), require_cli_table3 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -2358,10 +2360,10 @@ function stringWidth(string, options = {}) {
2358
2360
  if (string.length === 0) return 0;
2359
2361
  let width = 0;
2360
2362
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
2361
- for (const { segment: character } of segmenter.segment(string)) {
2362
- const codePoint = character.codePointAt(0);
2363
- if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279 || codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071 || codePoint >= 55296 && codePoint <= 57343 || codePoint >= 65024 && codePoint <= 65039 || defaultIgnorableCodePointRegex.test(character)) continue;
2364
- if ((0, import_emoji_regex.default)().test(character)) {
2363
+ for (const { segment: character$1 } of segmenter.segment(string)) {
2364
+ const codePoint = character$1.codePointAt(0);
2365
+ if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279 || codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071 || codePoint >= 55296 && codePoint <= 57343 || codePoint >= 65024 && codePoint <= 65039 || defaultIgnorableCodePointRegex.test(character$1)) continue;
2366
+ if ((0, import_emoji_regex.default)().test(character$1)) {
2365
2367
  width += 2;
2366
2368
  continue;
2367
2369
  }
@@ -2369,7 +2371,7 @@ function stringWidth(string, options = {}) {
2369
2371
  }
2370
2372
  return width;
2371
2373
  }
2372
- var ResponsiveTable = class {
2374
+ var import_usingCtx$2 = /* @__PURE__ */ __toESM(require_usingCtx(), 1), ResponsiveTable = class {
2373
2375
  head;
2374
2376
  rows = [];
2375
2377
  colAligns;
@@ -2498,6 +2500,12 @@ function pushBreakdownRows(table, breakdowns, extraColumns = 1, trailingColumns
2498
2500
  table.push(row);
2499
2501
  }
2500
2502
  }
2503
+ async function getFileModifiedTime(filePath) {
2504
+ return pipe(try_({
2505
+ try: stat(filePath),
2506
+ catch: (error) => error
2507
+ }), map((stats) => stats.mtime.getTime()), unwrap(0));
2508
+ }
2501
2509
  var LiveMonitor = class {
2502
2510
  config;
2503
2511
  fetcher = null;
@@ -2515,8 +2523,8 @@ var LiveMonitor = class {
2515
2523
  if (allFiles.length === 0) return null;
2516
2524
  const filesToRead = [];
2517
2525
  for (const file of allFiles) {
2518
- const timestamp = await getEarliestTimestamp(file), lastTimestamp = this.lastFileTimestamps.get(file);
2519
- if (timestamp != null && (lastTimestamp == null || timestamp.getTime() > lastTimestamp)) filesToRead.push(file), this.lastFileTimestamps.set(file, timestamp.getTime());
2526
+ const timestamp$1 = await getEarliestTimestamp(file), lastTimestamp = this.lastFileTimestamps.get(file);
2527
+ if (timestamp$1 != null && (lastTimestamp == null || timestamp$1.getTime() > lastTimestamp)) filesToRead.push(file), this.lastFileTimestamps.set(file, timestamp$1.getTime());
2520
2528
  }
2521
2529
  if (filesToRead.length > 0) {
2522
2530
  const sortedFiles = await sortFilesByTimestamp(filesToRead);
@@ -2580,12 +2588,47 @@ function setArbitraryLengthTimeout(callback, delay$1) {
2580
2588
  };
2581
2589
  return queueTimeout(), { valueOf: () => timeoutId };
2582
2590
  }
2591
+ var _computedKey$1;
2592
+ _computedKey$1 = Symbol.asyncIterator;
2593
+ var MuxAsyncIterator = class {
2594
+ #iteratorCount = 0;
2595
+ #yields = [];
2596
+ #throws = [];
2597
+ #signal = Promise.withResolvers();
2598
+ add(iterable) {
2599
+ ++this.#iteratorCount, this.#callIteratorNext(iterable[Symbol.asyncIterator]());
2600
+ }
2601
+ async #callIteratorNext(iterator) {
2602
+ try {
2603
+ const { value: value$1, done } = await iterator.next();
2604
+ if (done) --this.#iteratorCount;
2605
+ else this.#yields.push({
2606
+ iterator,
2607
+ value: value$1
2608
+ });
2609
+ } catch (e) {
2610
+ this.#throws.push(e);
2611
+ }
2612
+ this.#signal.resolve();
2613
+ }
2614
+ async *iterate() {
2615
+ while (this.#iteratorCount > 0) {
2616
+ await this.#signal.promise;
2617
+ for (const { iterator, value: value$1 } of this.#yields) yield value$1, this.#callIteratorNext(iterator);
2618
+ if (this.#throws.length) for (const e of this.#throws) throw e;
2619
+ this.#yields.length = 0, this.#signal = Promise.withResolvers();
2620
+ }
2621
+ }
2622
+ [_computedKey$1]() {
2623
+ return this.iterate();
2624
+ }
2625
+ };
2583
2626
  const isBrowser = globalThis.window?.document !== void 0, isNode = globalThis.process?.versions?.node !== void 0, isBun = globalThis.process?.versions?.bun !== void 0, isDeno = globalThis.Deno?.version?.deno !== void 0, isElectron = globalThis.process?.versions?.electron !== void 0, isJsDom = globalThis.navigator?.userAgent?.includes("jsdom") === true, isWebWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope, isDedicatedWorker = typeof DedicatedWorkerGlobalScope !== "undefined" && globalThis instanceof DedicatedWorkerGlobalScope, isSharedWorker = typeof SharedWorkerGlobalScope !== "undefined" && globalThis instanceof SharedWorkerGlobalScope, isServiceWorker = typeof ServiceWorkerGlobalScope !== "undefined" && globalThis instanceof ServiceWorkerGlobalScope, platform = globalThis.navigator?.userAgentData?.platform, isMacOs = platform === "macOS" || globalThis.navigator?.platform === "MacIntel" || globalThis.navigator?.userAgent?.includes(" Mac ") === true || globalThis.process?.platform === "darwin", isWindows$1 = platform === "Windows" || globalThis.navigator?.platform === "Win32" || globalThis.process?.platform === "win32", isLinux = platform === "Linux" || globalThis.navigator?.platform?.startsWith("Linux") === true || globalThis.navigator?.userAgent?.includes(" Linux ") === true || globalThis.process?.platform === "linux", isIos = platform === "iOS" || globalThis.navigator?.platform === "MacIntel" && globalThis.navigator?.maxTouchPoints > 1 || /iPad|iPhone|iPod/.test(globalThis.navigator?.platform), isAndroid = platform === "Android" || globalThis.navigator?.platform === "Android" || globalThis.navigator?.userAgent?.includes(" Android ") === true || globalThis.process?.platform === "android", ESC = "\x1B[", SEP = ";", isTerminalApp = !isBrowser && process$1.env.TERM_PROGRAM === "Apple_Terminal", isWindows = !isBrowser && process$1.platform === "win32", cwdFunction = isBrowser ? () => {
2584
2627
  throw new Error("`process.cwd()` only works in Node.js, not the browser.");
2585
2628
  } : process$1.cwd, cursorTo = (x, y) => {
2586
2629
  if (typeof x !== "number") throw new TypeError("The `x` argument is required");
2587
2630
  return typeof y === "number" ? ESC + (y + 1) + SEP + (x + 1) + "H" : ESC + (x + 1) + "G";
2588
- }, cursorForward = (count = 1) => ESC + count + "C", cursorLeft = ESC + "G", cursorSavePosition = isTerminalApp ? "\x1B7" : ESC + "s", cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC + "u", cursorGetPosition = ESC + "6n", cursorNextLine = ESC + "E", cursorPrevLine = ESC + "F", cursorHide = ESC + "?25l", cursorShow = ESC + "?25h", eraseEndLine = ESC + "K", eraseStartLine = ESC + "1K", eraseLine = ESC + "2K", eraseDown = ESC + "J", eraseUp = ESC + "1J", eraseScreen = ESC + "2J", scrollUp = ESC + "S", scrollDown = ESC + "T", clearScreen = "\x1Bc", clearTerminal = isWindows ? `${eraseScreen}${ESC}0f` : `${eraseScreen}${ESC}3J${ESC}H`, enterAlternativeScreen = ESC + "?1049h", exitAlternativeScreen = ESC + "?1049l", toZeroIfInfinity = (value) => Number.isFinite(value) ? value : 0;
2631
+ }, cursorForward = (count = 1) => ESC + count + "C", cursorLeft = ESC + "G", cursorSavePosition = isTerminalApp ? "\x1B7" : ESC + "s", cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC + "u", cursorGetPosition = ESC + "6n", cursorNextLine = ESC + "E", cursorPrevLine = ESC + "F", cursorHide = ESC + "?25l", cursorShow = ESC + "?25h", eraseEndLine = ESC + "K", eraseStartLine = ESC + "1K", eraseLine = ESC + "2K", eraseDown = ESC + "J", eraseUp = ESC + "1J", eraseScreen = ESC + "2J", scrollUp = ESC + "S", scrollDown = ESC + "T", clearScreen = "\x1Bc", clearTerminal = isWindows ? `${eraseScreen}${ESC}0f` : `${eraseScreen}${ESC}3J${ESC}H`, enterAlternativeScreen = ESC + "?1049h", exitAlternativeScreen = ESC + "?1049l", toZeroIfInfinity = (value$1) => Number.isFinite(value$1) ? value$1 : 0;
2589
2632
  function parseNumber(milliseconds) {
2590
2633
  return {
2591
2634
  days: Math.trunc(milliseconds / 864e5),
@@ -2617,7 +2660,7 @@ function parseMilliseconds(milliseconds) {
2617
2660
  }
2618
2661
  throw new TypeError("Expected a finite number or bigint");
2619
2662
  }
2620
- const isZero = (value) => value === 0 || value === 0n, pluralize = (word, count) => count === 1 || count === 1n ? word : `${word}s`, SECOND_ROUNDING_EPSILON = 1e-7, ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
2663
+ const isZero = (value$1) => value$1 === 0 || value$1 === 0n, pluralize = (word, count) => count === 1 || count === 1n ? word : `${word}s`, SECOND_ROUNDING_EPSILON = 1e-7, ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
2621
2664
  function prettyMilliseconds(milliseconds, options) {
2622
2665
  const isBigInt = typeof milliseconds === "bigint";
2623
2666
  if (!isBigInt && !Number.isFinite(milliseconds)) throw new TypeError("Expected a finite number or bigint");
@@ -2626,15 +2669,15 @@ function prettyMilliseconds(milliseconds, options) {
2626
2669
  if (milliseconds = milliseconds < 0 ? -milliseconds : milliseconds, options.colonNotation) options.compact = false, options.formatSubMilliseconds = false, options.separateMilliseconds = false, options.verbose = false;
2627
2670
  if (options.compact) options.unitCount = 1, options.secondsDecimalDigits = 0, options.millisecondsDecimalDigits = 0;
2628
2671
  let result = [];
2629
- const floorDecimals = (value, decimalDigits) => {
2630
- const flooredInterimValue = Math.floor(value * 10 ** decimalDigits + SECOND_ROUNDING_EPSILON), flooredValue = Math.round(flooredInterimValue) / 10 ** decimalDigits;
2672
+ const floorDecimals = (value$1, decimalDigits) => {
2673
+ const flooredInterimValue = Math.floor(value$1 * 10 ** decimalDigits + SECOND_ROUNDING_EPSILON), flooredValue = Math.round(flooredInterimValue) / 10 ** decimalDigits;
2631
2674
  return flooredValue.toFixed(decimalDigits);
2632
- }, add = (value, long, short, valueString) => {
2633
- if (!((result.length === 0 || !options.colonNotation) && isZero(value) && !(options.colonNotation && short === "m"))) {
2634
- if (valueString ??= String(value), options.colonNotation) {
2675
+ }, add = (value$1, long, short, valueString) => {
2676
+ if (!((result.length === 0 || !options.colonNotation) && isZero(value$1) && !(options.colonNotation && short === "m"))) {
2677
+ if (valueString ??= String(value$1), options.colonNotation) {
2635
2678
  const wholeDigits = valueString.includes(".") ? valueString.split(".")[0].length : valueString.length, minLength = result.length > 0 ? 2 : 1;
2636
2679
  valueString = "0".repeat(Math.max(0, minLength - wholeDigits)) + valueString;
2637
- } else valueString += options.verbose ? " " + pluralize(long, value) : short;
2680
+ } else valueString += options.verbose ? " " + pluralize(long, value$1) : short;
2638
2681
  result.push(valueString);
2639
2682
  }
2640
2683
  }, parsed = parseMilliseconds(milliseconds), days = BigInt(parsed.days);
@@ -2720,8 +2763,8 @@ var TerminalManager = class {
2720
2763
  this.showCursor(), this.exitAlternateScreen(), this.disableSyncMode();
2721
2764
  }
2722
2765
  };
2723
- function createProgressBar(value, max, width, options = {}) {
2724
- const { showPercentage = true, showValues = false, fillChar = "█", emptyChar = "░", leftBracket = "[", rightBracket = "]", colors: colors$2 = {} } = options, percentage = max > 0 ? Math.min(100, value / max * 100) : 0, fillWidth = Math.round(percentage / 100 * width), emptyWidth = width - fillWidth;
2766
+ function createProgressBar(value$1, max, width, options = {}) {
2767
+ const { showPercentage = true, showValues = false, fillChar = "█", emptyChar = "░", leftBracket = "[", rightBracket = "]", colors: colors$2 = {} } = options, percentage = max > 0 ? Math.min(100, value$1 / max * 100) : 0, fillWidth = Math.round(percentage / 100 * width), emptyWidth = width - fillWidth;
2725
2768
  let color = "";
2726
2769
  if (colors$2.critical != null && percentage >= 90) color = colors$2.critical;
2727
2770
  else if (colors$2.high != null && percentage >= 80) color = colors$2.high;
@@ -2731,7 +2774,7 @@ function createProgressBar(value, max, width, options = {}) {
2731
2774
  if (color !== "") bar += color;
2732
2775
  if (bar += fillChar.repeat(fillWidth), bar += emptyChar.repeat(emptyWidth), color !== "") bar += ANSI_RESET;
2733
2776
  if (bar += rightBracket, showPercentage) bar += ` ${percentage.toFixed(1)}%`;
2734
- if (showValues) bar += ` (${value}/${max})`;
2777
+ if (showValues) bar += ` (${value$1}/${max})`;
2735
2778
  return bar;
2736
2779
  }
2737
2780
  function centerText(text, width) {
@@ -2898,10 +2941,10 @@ function renderCompactLiveDisplay(terminal, block, config, totalTokens, elapsed,
2898
2941
  if (burnRate != null) terminal.write(`Rate: ${formatNumber(burnRate.tokensPerMinute)}/min\n`);
2899
2942
  terminal.write(`${"─".repeat(width)}\n`), terminal.write(import_picocolors$7.default.gray(`Refresh: ${config.refreshInterval / 1e3}s | Ctrl+C: stop\n`));
2900
2943
  }
2901
- var import_picocolors$6 = /* @__PURE__ */ __toESM(require_picocolors(), 1), import_usingCtx = /* @__PURE__ */ __toESM(require_usingCtx(), 1);
2944
+ var import_picocolors$6 = /* @__PURE__ */ __toESM(require_picocolors(), 1), import_usingCtx$1 = /* @__PURE__ */ __toESM(require_usingCtx(), 1);
2902
2945
  async function startLiveMonitoring(config) {
2903
2946
  try {
2904
- var _usingCtx = (0, import_usingCtx.default)();
2947
+ var _usingCtx = (0, import_usingCtx$1.default)();
2905
2948
  const terminal = new TerminalManager(), abortController = new AbortController();
2906
2949
  let lastRenderTime = 0;
2907
2950
  const cleanup = () => {
@@ -2977,9 +3020,9 @@ function formatBlockTime(block, compact = false, locale) {
2977
3020
  function formatModels(models) {
2978
3021
  return models.length === 0 ? "-" : formatModelsDisplayMultiline(models);
2979
3022
  }
2980
- function parseTokenLimit(value, maxFromAll) {
2981
- if (value == null || value === "" || value === "max") return maxFromAll > 0 ? maxFromAll : void 0;
2982
- const limit = Number.parseInt(value, 10);
3023
+ function parseTokenLimit(value$1, maxFromAll) {
3024
+ if (value$1 == null || value$1 === "" || value$1 === "max") return maxFromAll > 0 ? maxFromAll : void 0;
3025
+ const limit = Number.parseInt(value$1, 10);
2983
3026
  return Number.isNaN(limit) ? void 0 : limit;
2984
3027
  }
2985
3028
  const blocksCommand = define({
@@ -3242,9 +3285,9 @@ function getProjectAliases() {
3242
3285
  aliasCache = /* @__PURE__ */ new Map();
3243
3286
  const aliasEnv = (process$1.env[PROJECT_ALIASES_ENV] ?? "").trim();
3244
3287
  if (aliasEnv === "") return aliasCache;
3245
- const pairs = aliasEnv.split(",").map((pair) => pair.trim()).filter((pair) => pair !== "");
3246
- for (const pair of pairs) {
3247
- const parts = pair.split("=").map((s) => s.trim()), rawName = parts[0], alias = parts[1];
3288
+ const pairs$1 = aliasEnv.split(",").map((pair$1) => pair$1.trim()).filter((pair$1) => pair$1 !== "");
3289
+ for (const pair$1 of pairs$1) {
3290
+ const parts = pair$1.split("=").map((s) => s.trim()), rawName = parts[0], alias = parts[1];
3248
3291
  if (rawName != null && alias != null && rawName !== "" && alias !== "") aliasCache.set(rawName, alias);
3249
3292
  }
3250
3293
  return aliasCache;
@@ -3476,8 +3519,8 @@ var RequestError = class extends Error {
3476
3519
  }, wrapBodyStream = Symbol("wrapBodyStream"), newRequestFromIncoming = (method, url, incoming, abortController) => {
3477
3520
  const headerRecord = [], rawHeaders = incoming.rawHeaders;
3478
3521
  for (let i = 0; i < rawHeaders.length; i += 2) {
3479
- const { [i]: key, [i + 1]: value } = rawHeaders;
3480
- if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
3522
+ const { [i]: key, [i + 1]: value$1 } = rawHeaders;
3523
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, value$1]);
3481
3524
  }
3482
3525
  const init$1 = {
3483
3526
  method,
@@ -3499,9 +3542,9 @@ var RequestError = class extends Error {
3499
3542
  init$1.body = new ReadableStream({ async pull(controller) {
3500
3543
  try {
3501
3544
  reader ||= Readable.toWeb(incoming).getReader();
3502
- const { done, value } = await reader.read();
3545
+ const { done, value: value$1 } = await reader.read();
3503
3546
  if (done) controller.close();
3504
- else controller.enqueue(value);
3547
+ else controller.enqueue(value$1);
3505
3548
  } catch (error) {
3506
3549
  controller.error(error);
3507
3550
  }
@@ -3650,10 +3693,10 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
3650
3693
  function onDrain() {
3651
3694
  reader.read().then(flow, handleStreamError);
3652
3695
  }
3653
- function flow({ done, value }) {
3696
+ function flow({ done, value: value$1 }) {
3654
3697
  try {
3655
3698
  if (done) writable.end();
3656
- else if (!writable.write(value)) writable.once("drain", onDrain);
3699
+ else if (!writable.write(value$1)) writable.once("drain", onDrain);
3657
3700
  else return reader.read().then(flow, handleStreamError);
3658
3701
  } catch (e) {
3659
3702
  handleStreamError(e);
@@ -3733,10 +3776,10 @@ var outgoingEnded = Symbol("outgoingEnded"), handleRequestError = () => new Resp
3733
3776
  break;
3734
3777
  }
3735
3778
  }
3736
- if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
3779
+ if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value$1) => acc + value$1.length, 0);
3737
3780
  }
3738
- if (outgoing.writeHead(res.status, resHeaderRecord), values.forEach((value) => {
3739
- outgoing.write(value);
3781
+ if (outgoing.writeHead(res.status, resHeaderRecord), values.forEach((value$1) => {
3782
+ outgoing.write(value$1);
3740
3783
  }), done) outgoing.end();
3741
3784
  else {
3742
3785
  if (values.length === 0) flushHeaders(outgoing);
@@ -4199,7 +4242,862 @@ const sessionCommand = define({
4199
4242
  ]), log(table.toString()), table.isCompactMode()) logger.info("\nRunning in Compact Mode"), logger.info("Expand terminal width to see cache metrics and total tokens");
4200
4243
  }
4201
4244
  }
4202
- }), { stdin: stdin$1 } = process;
4245
+ });
4246
+ function filterInPlace(array, predicate) {
4247
+ let outputIndex = 0;
4248
+ for (const cur of array) {
4249
+ if (!predicate(cur)) continue;
4250
+ array[outputIndex] = cur, outputIndex += 1;
4251
+ }
4252
+ return array.splice(outputIndex), array;
4253
+ }
4254
+ function deepMerge(record, other, options) {
4255
+ return deepMergeInternal(record, other, /* @__PURE__ */ new Set(), options);
4256
+ }
4257
+ function deepMergeInternal(record, other, seen, options) {
4258
+ const result = {}, keys = new Set([...getKeys(record), ...getKeys(other)]);
4259
+ for (const key of keys) {
4260
+ if (key === "__proto__") continue;
4261
+ const a$1 = record[key];
4262
+ if (!Object.hasOwn(other, key)) {
4263
+ result[key] = a$1;
4264
+ continue;
4265
+ }
4266
+ const b$1 = other[key];
4267
+ if (isNonNullObject(a$1) && isNonNullObject(b$1) && !seen.has(a$1) && !seen.has(b$1)) {
4268
+ seen.add(a$1), seen.add(b$1), result[key] = mergeObjects(a$1, b$1, seen, options);
4269
+ continue;
4270
+ }
4271
+ result[key] = b$1;
4272
+ }
4273
+ return result;
4274
+ }
4275
+ function mergeObjects(left, right, seen, options = {
4276
+ arrays: "merge",
4277
+ sets: "merge",
4278
+ maps: "merge"
4279
+ }) {
4280
+ if (isMergeable(left) && isMergeable(right)) return deepMergeInternal(left, right, seen, options);
4281
+ if (isIterable(left) && isIterable(right)) {
4282
+ if (Array.isArray(left) && Array.isArray(right)) return options.arrays === "merge" ? left.concat(right) : right;
4283
+ if (left instanceof Map && right instanceof Map) return options.maps === "merge" ? new Map([...left, ...right]) : right;
4284
+ if (left instanceof Set && right instanceof Set) return options.sets === "merge" ? new Set([...left, ...right]) : right;
4285
+ }
4286
+ return right;
4287
+ }
4288
+ function isMergeable(value$1) {
4289
+ return Object.getPrototypeOf(value$1) === Object.prototype;
4290
+ }
4291
+ function isIterable(value$1) {
4292
+ return typeof value$1[Symbol.iterator] === "function";
4293
+ }
4294
+ function isNonNullObject(value$1) {
4295
+ return value$1 !== null && typeof value$1 === "object";
4296
+ }
4297
+ function getKeys(record) {
4298
+ const result = Object.getOwnPropertySymbols(record);
4299
+ return filterInPlace(result, (key) => Object.prototype.propertyIsEnumerable.call(record, key)), result.push(...Object.keys(record)), result;
4300
+ }
4301
+ function isLeap(yearNumber) {
4302
+ return yearNumber % 4 === 0 && yearNumber % 100 !== 0 || yearNumber % 400 === 0;
4303
+ }
4304
+ function success(body) {
4305
+ return {
4306
+ ok: true,
4307
+ body
4308
+ };
4309
+ }
4310
+ function failure() {
4311
+ return { ok: false };
4312
+ }
4313
+ function unflat(keys, values = { __proto__: null }) {
4314
+ return keys.reduceRight((acc, key) => ({ [key]: acc }), values);
4315
+ }
4316
+ function or(parsers) {
4317
+ return (scanner) => {
4318
+ for (const parse$1 of parsers) {
4319
+ const result = parse$1(scanner);
4320
+ if (result.ok) return result;
4321
+ }
4322
+ return failure();
4323
+ };
4324
+ }
4325
+ function join$1(parser, separator) {
4326
+ const Separator = character(separator);
4327
+ return (scanner) => {
4328
+ const out = [], first = parser(scanner);
4329
+ if (!first.ok) return success(out);
4330
+ out.push(first.body);
4331
+ while (!scanner.eof()) {
4332
+ if (!Separator(scanner).ok) break;
4333
+ const result = parser(scanner);
4334
+ if (!result.ok) throw new SyntaxError(`Invalid token after "${separator}"`);
4335
+ out.push(result.body);
4336
+ }
4337
+ return success(out);
4338
+ };
4339
+ }
4340
+ function join1(parser, separator) {
4341
+ const Separator = character(separator);
4342
+ return (scanner) => {
4343
+ const first = parser(scanner);
4344
+ if (!first.ok) return failure();
4345
+ const out = [first.body];
4346
+ while (!scanner.eof()) {
4347
+ if (!Separator(scanner).ok) break;
4348
+ const result = parser(scanner);
4349
+ if (!result.ok) throw new SyntaxError(`Invalid token after "${separator}"`);
4350
+ out.push(result.body);
4351
+ }
4352
+ return success(out);
4353
+ };
4354
+ }
4355
+ function kv(keyParser, separator, valueParser) {
4356
+ const Separator = character(separator);
4357
+ return (scanner) => {
4358
+ const position = scanner.position, key = keyParser(scanner);
4359
+ if (!key.ok) return failure();
4360
+ const sep$1 = Separator(scanner);
4361
+ if (!sep$1.ok) throw new SyntaxError(`key/value pair doesn't have "${separator}"`);
4362
+ const value$1 = valueParser(scanner);
4363
+ if (!value$1.ok) {
4364
+ const lineEndIndex = scanner.source.indexOf("\n", scanner.position), endPosition = lineEndIndex > 0 ? lineEndIndex : scanner.source.length, line = scanner.source.slice(position, endPosition);
4365
+ throw new SyntaxError(`Cannot parse value on line '${line}'`);
4366
+ }
4367
+ return success(unflat(key.body, value$1.body));
4368
+ };
4369
+ }
4370
+ function surround(left, parser, right) {
4371
+ const Left = character(left), Right = character(right);
4372
+ return (scanner) => {
4373
+ if (!Left(scanner).ok) return failure();
4374
+ const result = parser(scanner);
4375
+ if (!result.ok) throw new SyntaxError(`Invalid token after "${left}"`);
4376
+ if (!Right(scanner).ok) throw new SyntaxError(`Not closed by "${right}" after started with "${left}"`);
4377
+ return success(result.body);
4378
+ };
4379
+ }
4380
+ function character(str$1) {
4381
+ return (scanner) => {
4382
+ return scanner.skipWhitespaces(), scanner.startsWith(str$1) ? (scanner.next(str$1.length), scanner.skipWhitespaces(), success(void 0)) : failure();
4383
+ };
4384
+ }
4385
+ const BARE_KEY_REGEXP = /[A-Za-z0-9_-]+/y;
4386
+ function bareKey(scanner) {
4387
+ scanner.skipWhitespaces();
4388
+ const key = scanner.match(BARE_KEY_REGEXP)?.[0];
4389
+ return key ? (scanner.next(key.length), success(key)) : failure();
4390
+ }
4391
+ function escapeSequence(scanner) {
4392
+ if (scanner.char() !== "\\") return failure();
4393
+ switch (scanner.next(), scanner.char()) {
4394
+ case "b": return scanner.next(), success("\b");
4395
+ case "t": return scanner.next(), success(" ");
4396
+ case "n": return scanner.next(), success("\n");
4397
+ case "f": return scanner.next(), success("\f");
4398
+ case "r": return scanner.next(), success("\r");
4399
+ case "u":
4400
+ case "U": {
4401
+ const codePointLen = scanner.char() === "u" ? 4 : 6, codePoint = parseInt("0x" + scanner.slice(1, 1 + codePointLen), 16), str$1 = String.fromCodePoint(codePoint);
4402
+ return scanner.next(codePointLen + 1), success(str$1);
4403
+ }
4404
+ case "\"": return scanner.next(), success("\"");
4405
+ case "\\": return scanner.next(), success("\\");
4406
+ default: throw new SyntaxError(`Invalid escape sequence: \\${scanner.char()}`);
4407
+ }
4408
+ }
4409
+ function basicString(scanner) {
4410
+ if (scanner.skipWhitespaces(), scanner.char() !== "\"") return failure();
4411
+ scanner.next();
4412
+ const acc = [];
4413
+ while (scanner.char() !== "\"" && !scanner.eof()) {
4414
+ if (scanner.char() === "\n") throw new SyntaxError("Single-line string cannot contain EOL");
4415
+ const escapedChar = escapeSequence(scanner);
4416
+ if (escapedChar.ok) acc.push(escapedChar.body);
4417
+ else acc.push(scanner.char()), scanner.next();
4418
+ }
4419
+ if (scanner.eof()) throw new SyntaxError(`Single-line string is not closed:\n${acc.join("")}`);
4420
+ return scanner.next(), success(acc.join(""));
4421
+ }
4422
+ function literalString(scanner) {
4423
+ if (scanner.skipWhitespaces(), scanner.char() !== "'") return failure();
4424
+ scanner.next();
4425
+ const acc = [];
4426
+ while (scanner.char() !== "'" && !scanner.eof()) {
4427
+ if (scanner.char() === "\n") throw new SyntaxError("Single-line string cannot contain EOL");
4428
+ acc.push(scanner.char()), scanner.next();
4429
+ }
4430
+ if (scanner.eof()) throw new SyntaxError(`Single-line string is not closed:\n${acc.join("")}`);
4431
+ return scanner.next(), success(acc.join(""));
4432
+ }
4433
+ function multilineBasicString(scanner) {
4434
+ if (scanner.skipWhitespaces(), !scanner.startsWith("\"\"\"")) return failure();
4435
+ if (scanner.next(3), scanner.char() === "\n") scanner.next();
4436
+ else if (scanner.startsWith("\r\n")) scanner.next(2);
4437
+ const acc = [];
4438
+ while (!scanner.startsWith("\"\"\"") && !scanner.eof()) {
4439
+ if (scanner.startsWith("\\\n")) {
4440
+ scanner.next(), scanner.nextUntilChar({ skipComments: false });
4441
+ continue;
4442
+ } else if (scanner.startsWith("\\\r\n")) {
4443
+ scanner.next(), scanner.nextUntilChar({ skipComments: false });
4444
+ continue;
4445
+ }
4446
+ const escapedChar = escapeSequence(scanner);
4447
+ if (escapedChar.ok) acc.push(escapedChar.body);
4448
+ else acc.push(scanner.char()), scanner.next();
4449
+ }
4450
+ if (scanner.eof()) throw new SyntaxError(`Multi-line string is not closed:\n${acc.join("")}`);
4451
+ if (scanner.char(3) === "\"") acc.push("\""), scanner.next();
4452
+ return scanner.next(3), success(acc.join(""));
4453
+ }
4454
+ function multilineLiteralString(scanner) {
4455
+ if (scanner.skipWhitespaces(), !scanner.startsWith("'''")) return failure();
4456
+ if (scanner.next(3), scanner.char() === "\n") scanner.next();
4457
+ else if (scanner.startsWith("\r\n")) scanner.next(2);
4458
+ const acc = [];
4459
+ while (!scanner.startsWith("'''") && !scanner.eof()) acc.push(scanner.char()), scanner.next();
4460
+ if (scanner.eof()) throw new SyntaxError(`Multi-line string is not closed:\n${acc.join("")}`);
4461
+ if (scanner.char(3) === "'") acc.push("'"), scanner.next();
4462
+ return scanner.next(3), success(acc.join(""));
4463
+ }
4464
+ const BOOLEAN_REGEXP = /(?:true|false)\b/y;
4465
+ function boolean(scanner) {
4466
+ scanner.skipWhitespaces();
4467
+ const match = scanner.match(BOOLEAN_REGEXP);
4468
+ if (!match) return failure();
4469
+ const string = match[0];
4470
+ scanner.next(string.length);
4471
+ const value$1 = string === "true";
4472
+ return success(value$1);
4473
+ }
4474
+ const INFINITY_MAP = new Map([
4475
+ ["inf", Infinity],
4476
+ ["+inf", Infinity],
4477
+ ["-inf", -Infinity]
4478
+ ]), INFINITY_REGEXP = /[+-]?inf\b/y;
4479
+ function infinity(scanner) {
4480
+ scanner.skipWhitespaces();
4481
+ const match = scanner.match(INFINITY_REGEXP);
4482
+ if (!match) return failure();
4483
+ const string = match[0];
4484
+ scanner.next(string.length);
4485
+ const value$1 = INFINITY_MAP.get(string);
4486
+ return success(value$1);
4487
+ }
4488
+ const NAN_REGEXP = /[+-]?nan\b/y;
4489
+ function nan(scanner) {
4490
+ scanner.skipWhitespaces();
4491
+ const match = scanner.match(NAN_REGEXP);
4492
+ if (!match) return failure();
4493
+ const string = match[0];
4494
+ scanner.next(string.length);
4495
+ const value$1 = NaN;
4496
+ return success(value$1);
4497
+ }
4498
+ const dottedKey = join1(or([
4499
+ bareKey,
4500
+ basicString,
4501
+ literalString
4502
+ ]), "."), BINARY_REGEXP = /0b[01]+(?:_[01]+)*\b/y;
4503
+ function binary$1(scanner) {
4504
+ scanner.skipWhitespaces();
4505
+ const match = scanner.match(BINARY_REGEXP)?.[0];
4506
+ if (!match) return failure();
4507
+ scanner.next(match.length);
4508
+ const value$1 = match.slice(2).replaceAll("_", ""), number = parseInt(value$1, 2);
4509
+ return isNaN(number) ? failure() : success(number);
4510
+ }
4511
+ const OCTAL_REGEXP = /0o[0-7]+(?:_[0-7]+)*\b/y;
4512
+ function octal(scanner) {
4513
+ scanner.skipWhitespaces();
4514
+ const match = scanner.match(OCTAL_REGEXP)?.[0];
4515
+ if (!match) return failure();
4516
+ scanner.next(match.length);
4517
+ const value$1 = match.slice(2).replaceAll("_", ""), number = parseInt(value$1, 8);
4518
+ return isNaN(number) ? failure() : success(number);
4519
+ }
4520
+ const HEX_REGEXP = /0x[0-9a-f]+(?:_[0-9a-f]+)*\b/iy;
4521
+ function hex(scanner) {
4522
+ scanner.skipWhitespaces();
4523
+ const match = scanner.match(HEX_REGEXP)?.[0];
4524
+ if (!match) return failure();
4525
+ scanner.next(match.length);
4526
+ const value$1 = match.slice(2).replaceAll("_", ""), number = parseInt(value$1, 16);
4527
+ return isNaN(number) ? failure() : success(number);
4528
+ }
4529
+ const INTEGER_REGEXP = /[+-]?(?:0|[1-9][0-9]*(?:_[0-9]+)*)\b/y;
4530
+ function integer(scanner) {
4531
+ scanner.skipWhitespaces();
4532
+ const match = scanner.match(INTEGER_REGEXP)?.[0];
4533
+ if (!match) return failure();
4534
+ scanner.next(match.length);
4535
+ const value$1 = match.replaceAll("_", ""), int$1 = parseInt(value$1, 10);
4536
+ return success(int$1);
4537
+ }
4538
+ const FLOAT_REGEXP = /[+-]?(?:0|[1-9][0-9]*(?:_[0-9]+)*)(?:\.[0-9]+(?:_[0-9]+)*)?(?:e[+-]?[0-9]+(?:_[0-9]+)*)?\b/iy;
4539
+ function float$1(scanner) {
4540
+ scanner.skipWhitespaces();
4541
+ const match = scanner.match(FLOAT_REGEXP)?.[0];
4542
+ if (!match) return failure();
4543
+ scanner.next(match.length);
4544
+ const value$1 = match.replaceAll("_", ""), float$2 = parseFloat(value$1);
4545
+ return isNaN(float$2) ? failure() : success(float$2);
4546
+ }
4547
+ const DATE_TIME_REGEXP = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})(?:[ 0-9TZ.:+-]+)?\b/y;
4548
+ function dateTime(scanner) {
4549
+ scanner.skipWhitespaces();
4550
+ const match = scanner.match(DATE_TIME_REGEXP);
4551
+ if (!match) return failure();
4552
+ const string = match[0];
4553
+ scanner.next(string.length);
4554
+ const groups = match.groups;
4555
+ if (groups.month == "02") {
4556
+ const days = parseInt(groups.day);
4557
+ if (days > 29) throw new SyntaxError(`Invalid date string "${match}"`);
4558
+ const year = parseInt(groups.year);
4559
+ if (days > 28 && !isLeap(year)) throw new SyntaxError(`Invalid date string "${match}"`);
4560
+ }
4561
+ const date = new Date(string.trim());
4562
+ if (isNaN(date.getTime())) throw new SyntaxError(`Invalid date string "${match}"`);
4563
+ return success(date);
4564
+ }
4565
+ const LOCAL_TIME_REGEXP = /(\d{2}):(\d{2}):(\d{2})(?:\.[0-9]+)?\b/y;
4566
+ function localTime(scanner) {
4567
+ scanner.skipWhitespaces();
4568
+ const match = scanner.match(LOCAL_TIME_REGEXP)?.[0];
4569
+ return match ? (scanner.next(match.length), success(match)) : failure();
4570
+ }
4571
+ function arrayValue(scanner) {
4572
+ if (scanner.skipWhitespaces(), scanner.char() !== "[") return failure();
4573
+ scanner.next();
4574
+ const array = [];
4575
+ while (!scanner.eof()) {
4576
+ scanner.nextUntilChar();
4577
+ const result = value(scanner);
4578
+ if (!result.ok || (array.push(result.body), scanner.skipWhitespaces(), scanner.char() !== ",")) break;
4579
+ scanner.next();
4580
+ }
4581
+ if (scanner.nextUntilChar(), scanner.char() !== "]") throw new SyntaxError("Array is not closed");
4582
+ return scanner.next(), success(array);
4583
+ }
4584
+ function inlineTable(scanner) {
4585
+ if (scanner.nextUntilChar(), scanner.char(1) === "}") return scanner.next(2), success({ __proto__: null });
4586
+ const pairs$1 = surround("{", join$1(pair, ","), "}")(scanner);
4587
+ if (!pairs$1.ok) return failure();
4588
+ let table = { __proto__: null };
4589
+ for (const pair$1 of pairs$1.body) table = deepMerge(table, pair$1);
4590
+ return success(table);
4591
+ }
4592
+ const value = or([
4593
+ multilineBasicString,
4594
+ multilineLiteralString,
4595
+ basicString,
4596
+ literalString,
4597
+ boolean,
4598
+ infinity,
4599
+ nan,
4600
+ dateTime,
4601
+ localTime,
4602
+ binary$1,
4603
+ octal,
4604
+ hex,
4605
+ float$1,
4606
+ integer,
4607
+ arrayValue,
4608
+ inlineTable
4609
+ ]), pair = kv(dottedKey, "=", value), tableHeader = surround("[", dottedKey, "]"), tableArrayHeader = surround("[[", dottedKey, "]]"), BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
4610
+ function resolveYamlBinary(data) {
4611
+ if (data === null) return false;
4612
+ let code, bitlen = 0;
4613
+ const max = data.length, map$3 = BASE64_MAP;
4614
+ for (let idx = 0; idx < max; idx++) if (code = map$3.indexOf(data.charAt(idx)), !(code > 64)) {
4615
+ if (code < 0) return false;
4616
+ bitlen += 6;
4617
+ }
4618
+ return bitlen % 8 === 0;
4619
+ }
4620
+ function constructYamlBinary(data) {
4621
+ const input = data.replace(/[\r\n=]/g, ""), max = input.length, map$3 = BASE64_MAP, result = [];
4622
+ let bits = 0;
4623
+ for (let idx = 0; idx < max; idx++) {
4624
+ if (idx % 4 === 0 && idx) result.push(bits >> 16 & 255), result.push(bits >> 8 & 255), result.push(bits & 255);
4625
+ bits = bits << 6 | map$3.indexOf(input.charAt(idx));
4626
+ }
4627
+ const tailbits = max % 4 * 6;
4628
+ if (tailbits === 0) result.push(bits >> 16 & 255), result.push(bits >> 8 & 255), result.push(bits & 255);
4629
+ else if (tailbits === 18) result.push(bits >> 10 & 255), result.push(bits >> 2 & 255);
4630
+ else if (tailbits === 12) result.push(bits >> 4 & 255);
4631
+ return new Uint8Array(result);
4632
+ }
4633
+ function representYamlBinary(object) {
4634
+ const max = object.length, map$3 = BASE64_MAP;
4635
+ let result = "", bits = 0;
4636
+ for (let idx = 0; idx < max; idx++) {
4637
+ if (idx % 3 === 0 && idx) result += map$3[bits >> 18 & 63], result += map$3[bits >> 12 & 63], result += map$3[bits >> 6 & 63], result += map$3[bits & 63];
4638
+ bits = (bits << 8) + object[idx];
4639
+ }
4640
+ const tail = max % 3;
4641
+ if (tail === 0) result += map$3[bits >> 18 & 63], result += map$3[bits >> 12 & 63], result += map$3[bits >> 6 & 63], result += map$3[bits & 63];
4642
+ else if (tail === 2) result += map$3[bits >> 10 & 63], result += map$3[bits >> 4 & 63], result += map$3[bits << 2 & 63], result += map$3[64];
4643
+ else if (tail === 1) result += map$3[bits >> 2 & 63], result += map$3[bits << 4 & 63], result += map$3[64], result += map$3[64];
4644
+ return result;
4645
+ }
4646
+ function isBinary(obj) {
4647
+ return obj instanceof Uint8Array;
4648
+ }
4649
+ const binary = {
4650
+ tag: "tag:yaml.org,2002:binary",
4651
+ construct: constructYamlBinary,
4652
+ kind: "scalar",
4653
+ predicate: isBinary,
4654
+ represent: representYamlBinary,
4655
+ resolve: resolveYamlBinary
4656
+ }, YAML_TRUE_BOOLEANS = [
4657
+ "true",
4658
+ "True",
4659
+ "TRUE"
4660
+ ], YAML_FALSE_BOOLEANS = [
4661
+ "false",
4662
+ "False",
4663
+ "FALSE"
4664
+ ], YAML_BOOLEANS = [...YAML_TRUE_BOOLEANS, ...YAML_FALSE_BOOLEANS], bool = {
4665
+ tag: "tag:yaml.org,2002:bool",
4666
+ kind: "scalar",
4667
+ defaultStyle: "lowercase",
4668
+ predicate: (value$1) => typeof value$1 === "boolean" || value$1 instanceof Boolean,
4669
+ construct: (data) => YAML_TRUE_BOOLEANS.includes(data),
4670
+ resolve: (data) => YAML_BOOLEANS.includes(data),
4671
+ represent: {
4672
+ lowercase: (object) => {
4673
+ const value$1 = object instanceof Boolean ? object.valueOf() : object;
4674
+ return value$1 ? "true" : "false";
4675
+ },
4676
+ uppercase: (object) => {
4677
+ const value$1 = object instanceof Boolean ? object.valueOf() : object;
4678
+ return value$1 ? "TRUE" : "FALSE";
4679
+ },
4680
+ camelcase: (object) => {
4681
+ const value$1 = object instanceof Boolean ? object.valueOf() : object;
4682
+ return value$1 ? "True" : "False";
4683
+ }
4684
+ }
4685
+ };
4686
+ function isNegativeZero(i) {
4687
+ return i === 0 && Number.NEGATIVE_INFINITY === 1 / i;
4688
+ }
4689
+ function isPlainObject(object) {
4690
+ return Object.prototype.toString.call(object) === "[object Object]";
4691
+ }
4692
+ const YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
4693
+ function resolveYamlFloat(data) {
4694
+ return !(!YAML_FLOAT_PATTERN.test(data) || data[data.length - 1] === "_");
4695
+ }
4696
+ function constructYamlFloat(data) {
4697
+ let value$1 = data.replace(/_/g, "").toLowerCase();
4698
+ const sign = value$1[0] === "-" ? -1 : 1;
4699
+ if (value$1[0] && "+-".includes(value$1[0])) value$1 = value$1.slice(1);
4700
+ return value$1 === ".inf" ? sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY : value$1 === ".nan" ? NaN : sign * parseFloat(value$1);
4701
+ }
4702
+ const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
4703
+ function representYamlFloat(object, style) {
4704
+ const value$1 = object instanceof Number ? object.valueOf() : object;
4705
+ if (isNaN(value$1)) switch (style) {
4706
+ case "lowercase": return ".nan";
4707
+ case "uppercase": return ".NAN";
4708
+ case "camelcase": return ".NaN";
4709
+ }
4710
+ else if (Number.POSITIVE_INFINITY === value$1) switch (style) {
4711
+ case "lowercase": return ".inf";
4712
+ case "uppercase": return ".INF";
4713
+ case "camelcase": return ".Inf";
4714
+ }
4715
+ else if (Number.NEGATIVE_INFINITY === value$1) switch (style) {
4716
+ case "lowercase": return "-.inf";
4717
+ case "uppercase": return "-.INF";
4718
+ case "camelcase": return "-.Inf";
4719
+ }
4720
+ else if (isNegativeZero(value$1)) return "-0.0";
4721
+ const res = value$1.toString(10);
4722
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
4723
+ }
4724
+ function isFloat(object) {
4725
+ if (object instanceof Number) object = object.valueOf();
4726
+ return typeof object === "number" && (object % 1 !== 0 || isNegativeZero(object));
4727
+ }
4728
+ const float = {
4729
+ tag: "tag:yaml.org,2002:float",
4730
+ construct: constructYamlFloat,
4731
+ defaultStyle: "lowercase",
4732
+ kind: "scalar",
4733
+ predicate: isFloat,
4734
+ represent: representYamlFloat,
4735
+ resolve: resolveYamlFloat
4736
+ };
4737
+ function isCharCodeInRange(c, lower, upper) {
4738
+ return lower <= c && c <= upper;
4739
+ }
4740
+ function isHexCode(c) {
4741
+ return isCharCodeInRange(c, 48, 57) || isCharCodeInRange(c, 65, 70) || isCharCodeInRange(c, 97, 102);
4742
+ }
4743
+ function isOctCode(c) {
4744
+ return isCharCodeInRange(c, 48, 55);
4745
+ }
4746
+ function isDecCode(c) {
4747
+ return isCharCodeInRange(c, 48, 57);
4748
+ }
4749
+ function resolveYamlInteger(data) {
4750
+ const max = data.length;
4751
+ let index = 0, hasDigits = false;
4752
+ if (!max) return false;
4753
+ let ch = data[index];
4754
+ if (ch === "-" || ch === "+") ch = data[++index];
4755
+ if (ch === "0") {
4756
+ if (index + 1 === max) return true;
4757
+ if (ch = data[++index], ch === "b") {
4758
+ for (index++; index < max; index++) if (ch = data[index], ch !== "_") {
4759
+ if (ch !== "0" && ch !== "1") return false;
4760
+ hasDigits = true;
4761
+ }
4762
+ return hasDigits && ch !== "_";
4763
+ }
4764
+ if (ch === "x") {
4765
+ for (index++; index < max; index++) if (ch = data[index], ch !== "_") {
4766
+ if (!isHexCode(data.charCodeAt(index))) return false;
4767
+ hasDigits = true;
4768
+ }
4769
+ return hasDigits && ch !== "_";
4770
+ }
4771
+ for (; index < max; index++) if (ch = data[index], ch !== "_") {
4772
+ if (!isOctCode(data.charCodeAt(index))) return false;
4773
+ hasDigits = true;
4774
+ }
4775
+ return hasDigits && ch !== "_";
4776
+ }
4777
+ if (ch === "_") return false;
4778
+ for (; index < max; index++) if (ch = data[index], ch !== "_") {
4779
+ if (!isDecCode(data.charCodeAt(index))) return false;
4780
+ hasDigits = true;
4781
+ }
4782
+ return !hasDigits || ch === "_" ? false : /^(:[0-5]?[0-9])+$/.test(data.slice(index));
4783
+ }
4784
+ function constructYamlInteger(data) {
4785
+ let value$1 = data;
4786
+ if (value$1.includes("_")) value$1 = value$1.replace(/_/g, "");
4787
+ let sign = 1, ch = value$1[0];
4788
+ if (ch === "-" || ch === "+") {
4789
+ if (ch === "-") sign = -1;
4790
+ value$1 = value$1.slice(1), ch = value$1[0];
4791
+ }
4792
+ return value$1 === "0" ? 0 : ch === "0" ? value$1[1] === "b" ? sign * parseInt(value$1.slice(2), 2) : value$1[1] === "x" ? sign * parseInt(value$1, 16) : sign * parseInt(value$1, 8) : sign * parseInt(value$1, 10);
4793
+ }
4794
+ function isInteger(object) {
4795
+ if (object instanceof Number) object = object.valueOf();
4796
+ return typeof object === "number" && object % 1 === 0 && !isNegativeZero(object);
4797
+ }
4798
+ const int = {
4799
+ tag: "tag:yaml.org,2002:int",
4800
+ construct: constructYamlInteger,
4801
+ defaultStyle: "decimal",
4802
+ kind: "scalar",
4803
+ predicate: isInteger,
4804
+ represent: {
4805
+ binary(object) {
4806
+ const value$1 = object instanceof Number ? object.valueOf() : object;
4807
+ return value$1 >= 0 ? `0b${value$1.toString(2)}` : `-0b${value$1.toString(2).slice(1)}`;
4808
+ },
4809
+ octal(object) {
4810
+ const value$1 = object instanceof Number ? object.valueOf() : object;
4811
+ return value$1 >= 0 ? `0${value$1.toString(8)}` : `-0${value$1.toString(8).slice(1)}`;
4812
+ },
4813
+ decimal(object) {
4814
+ const value$1 = object instanceof Number ? object.valueOf() : object;
4815
+ return value$1.toString(10);
4816
+ },
4817
+ hexadecimal(object) {
4818
+ const value$1 = object instanceof Number ? object.valueOf() : object;
4819
+ return value$1 >= 0 ? `0x${value$1.toString(16).toUpperCase()}` : `-0x${value$1.toString(16).toUpperCase().slice(1)}`;
4820
+ }
4821
+ },
4822
+ resolve: resolveYamlInteger
4823
+ }, map$1 = {
4824
+ tag: "tag:yaml.org,2002:map",
4825
+ resolve() {
4826
+ return true;
4827
+ },
4828
+ construct(data) {
4829
+ return data !== null ? data : {};
4830
+ },
4831
+ kind: "mapping"
4832
+ }, merge = {
4833
+ tag: "tag:yaml.org,2002:merge",
4834
+ kind: "scalar",
4835
+ resolve: (data) => data === "<<" || data === null,
4836
+ construct: (data) => data
4837
+ }, nil = {
4838
+ tag: "tag:yaml.org,2002:null",
4839
+ kind: "scalar",
4840
+ defaultStyle: "lowercase",
4841
+ predicate: (object) => object === null,
4842
+ construct: () => null,
4843
+ resolve: (data) => {
4844
+ return data === "~" || data === "null" || data === "Null" || data === "NULL";
4845
+ },
4846
+ represent: {
4847
+ lowercase: () => "null",
4848
+ uppercase: () => "NULL",
4849
+ camelcase: () => "Null"
4850
+ }
4851
+ };
4852
+ function resolveYamlOmap(data) {
4853
+ const objectKeys = /* @__PURE__ */ new Set();
4854
+ for (const object of data) {
4855
+ if (!isPlainObject(object)) return false;
4856
+ const keys = Object.keys(object);
4857
+ if (keys.length !== 1) return false;
4858
+ for (const key of keys) {
4859
+ if (objectKeys.has(key)) return false;
4860
+ objectKeys.add(key);
4861
+ }
4862
+ }
4863
+ return true;
4864
+ }
4865
+ const omap = {
4866
+ tag: "tag:yaml.org,2002:omap",
4867
+ kind: "sequence",
4868
+ resolve: resolveYamlOmap,
4869
+ construct(data) {
4870
+ return data;
4871
+ }
4872
+ };
4873
+ function resolveYamlPairs(data) {
4874
+ return data === null ? true : data.every((it) => isPlainObject(it) && Object.keys(it).length === 1);
4875
+ }
4876
+ const pairs = {
4877
+ tag: "tag:yaml.org,2002:pairs",
4878
+ construct(data) {
4879
+ return data?.flatMap(Object.entries) ?? [];
4880
+ },
4881
+ kind: "sequence",
4882
+ resolve: resolveYamlPairs
4883
+ }, REGEXP = /^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/, regexp = {
4884
+ tag: "tag:yaml.org,2002:js/regexp",
4885
+ kind: "scalar",
4886
+ resolve(data) {
4887
+ if (data === null || !data.length) return false;
4888
+ if (data.charAt(0) === "/") {
4889
+ const groups = data.match(REGEXP)?.groups;
4890
+ if (!groups) return false;
4891
+ const modifiers = groups.modifiers ?? "";
4892
+ if (new Set(modifiers).size < modifiers.length) return false;
4893
+ }
4894
+ return true;
4895
+ },
4896
+ construct(data) {
4897
+ const { regexp: regexp$1 = data, modifiers = "" } = data.match(REGEXP)?.groups ?? {};
4898
+ return new RegExp(regexp$1, modifiers);
4899
+ },
4900
+ predicate: (object) => object instanceof RegExp,
4901
+ represent: (object) => object.toString()
4902
+ }, seq = {
4903
+ tag: "tag:yaml.org,2002:seq",
4904
+ kind: "sequence",
4905
+ resolve: () => true,
4906
+ construct: (data) => data !== null ? data : []
4907
+ }, set = {
4908
+ tag: "tag:yaml.org,2002:set",
4909
+ kind: "mapping",
4910
+ construct: (data) => data !== null ? data : {},
4911
+ resolve: (data) => {
4912
+ return data === null ? true : Object.values(data).every((it) => it === null);
4913
+ }
4914
+ }, str = {
4915
+ tag: "tag:yaml.org,2002:str",
4916
+ kind: "scalar",
4917
+ resolve: () => true,
4918
+ construct: (data) => data !== null ? data : ""
4919
+ }, YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"), YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");
4920
+ function resolveYamlTimestamp(data) {
4921
+ return data === null ? false : YAML_DATE_REGEXP.exec(data) !== null || YAML_TIMESTAMP_REGEXP.exec(data) !== null;
4922
+ }
4923
+ function constructYamlTimestamp(data) {
4924
+ let match = YAML_DATE_REGEXP.exec(data);
4925
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
4926
+ if (match === null) throw new Error("Cannot construct YAML timestamp: date resolve error");
4927
+ const year = +match[1], month = +match[2] - 1, day = +match[3];
4928
+ if (!match[4]) return new Date(Date.UTC(year, month, day));
4929
+ const hour = +match[4], minute = +match[5], second = +match[6];
4930
+ let fraction = 0;
4931
+ if (match[7]) {
4932
+ let partFraction = match[7].slice(0, 3);
4933
+ while (partFraction.length < 3) partFraction += "0";
4934
+ fraction = +partFraction;
4935
+ }
4936
+ let delta = null;
4937
+ if (match[9] && match[10]) {
4938
+ const tzHour = +match[10], tzMinute = +(match[11] || 0);
4939
+ if (delta = (tzHour * 60 + tzMinute) * 6e4, match[9] === "-") delta = -delta;
4940
+ }
4941
+ const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
4942
+ if (delta) date.setTime(date.getTime() - delta);
4943
+ return date;
4944
+ }
4945
+ function representYamlTimestamp(date) {
4946
+ return date.toISOString();
4947
+ }
4948
+ const timestamp = {
4949
+ tag: "tag:yaml.org,2002:timestamp",
4950
+ construct: constructYamlTimestamp,
4951
+ predicate(object) {
4952
+ return object instanceof Date;
4953
+ },
4954
+ kind: "scalar",
4955
+ represent: representYamlTimestamp,
4956
+ resolve: resolveYamlTimestamp
4957
+ }, undefinedType = {
4958
+ tag: "tag:yaml.org,2002:js/undefined",
4959
+ kind: "scalar",
4960
+ resolve() {
4961
+ return true;
4962
+ },
4963
+ construct() {
4964
+ return void 0;
4965
+ },
4966
+ predicate(object) {
4967
+ return typeof object === "undefined";
4968
+ },
4969
+ represent() {
4970
+ return "";
4971
+ }
4972
+ };
4973
+ function createTypeMap(implicitTypes, explicitTypes) {
4974
+ const result = {
4975
+ fallback: /* @__PURE__ */ new Map(),
4976
+ mapping: /* @__PURE__ */ new Map(),
4977
+ scalar: /* @__PURE__ */ new Map(),
4978
+ sequence: /* @__PURE__ */ new Map()
4979
+ }, fallbackMap = result.fallback;
4980
+ for (const type of [...implicitTypes, ...explicitTypes]) {
4981
+ const map$3 = result[type.kind];
4982
+ map$3.set(type.tag, type), fallbackMap.set(type.tag, type);
4983
+ }
4984
+ return result;
4985
+ }
4986
+ function createSchema({ explicitTypes = [], implicitTypes = [], include }) {
4987
+ if (include) implicitTypes.push(...include.implicitTypes), explicitTypes.push(...include.explicitTypes);
4988
+ const typeMap = createTypeMap(implicitTypes, explicitTypes);
4989
+ return {
4990
+ implicitTypes,
4991
+ explicitTypes,
4992
+ typeMap
4993
+ };
4994
+ }
4995
+ const FAILSAFE_SCHEMA = createSchema({ explicitTypes: [
4996
+ str,
4997
+ seq,
4998
+ map$1
4999
+ ] }), JSON_SCHEMA = createSchema({
5000
+ implicitTypes: [
5001
+ nil,
5002
+ bool,
5003
+ int,
5004
+ float
5005
+ ],
5006
+ include: FAILSAFE_SCHEMA
5007
+ }), CORE_SCHEMA = createSchema({ include: JSON_SCHEMA }), DEFAULT_SCHEMA = createSchema({
5008
+ explicitTypes: [
5009
+ binary,
5010
+ omap,
5011
+ pairs,
5012
+ set
5013
+ ],
5014
+ implicitTypes: [timestamp, merge],
5015
+ include: CORE_SCHEMA
5016
+ }), EXTENDED_SCHEMA = createSchema({
5017
+ explicitTypes: [regexp, undefinedType],
5018
+ include: DEFAULT_SCHEMA
5019
+ });
5020
+ var _computedKey;
5021
+ function resolveOptions(options) {
5022
+ return {
5023
+ validator: options.validator,
5024
+ allowNoExist: options.allowNoExist ?? true,
5025
+ allowValidatorFailure: options.allowValidatorFailure
5026
+ };
5027
+ }
5028
+ _computedKey = Symbol.dispose;
5029
+ var LimoFile = class {
5030
+ #data;
5031
+ #oldData;
5032
+ #path;
5033
+ #text;
5034
+ #options;
5035
+ #parseOptions;
5036
+ constructor(path$1, options) {
5037
+ this.#options = resolveOptions(options), this.#parseOptions = options.parseOptions, this.#path = path$1;
5038
+ const { data, text } = this._read();
5039
+ this.#data = this.#oldData = data, this.#text = text;
5040
+ }
5041
+ [_computedKey]() {
5042
+ this._write();
5043
+ }
5044
+ get data() {
5045
+ return this.#data;
5046
+ }
5047
+ set data(value$1) {
5048
+ this.#data = value$1;
5049
+ }
5050
+ _read() {
5051
+ if (existsSync(this.#path)) {
5052
+ const text = readFileSync(this.#path, { encoding: "utf8" });
5053
+ if (text.trim() === "") return {
5054
+ data: void 0,
5055
+ text
5056
+ };
5057
+ try {
5058
+ const data = this.#parseOptions.parse(text), { validator, allowValidatorFailure } = this.#options;
5059
+ if (validator != null && !validator(data)) {
5060
+ if (allowValidatorFailure) return {
5061
+ data: void 0,
5062
+ text
5063
+ };
5064
+ throw new Error(`Invalid data: ${text}`);
5065
+ }
5066
+ return {
5067
+ data,
5068
+ text
5069
+ };
5070
+ } catch (error) {
5071
+ throw new Error(`Failed to parse ${this.#path}: ${error}`);
5072
+ }
5073
+ }
5074
+ if (!this.#options.allowNoExist) throw new Error(`File not found: ${this.#path}`);
5075
+ return {
5076
+ data: void 0,
5077
+ text: void 0
5078
+ };
5079
+ }
5080
+ _write() {
5081
+ if (this.#data != null) try {
5082
+ let content;
5083
+ if (this.#parseOptions.preserveFormat && this.#text != null && this.#oldData != null) content = this.#parseOptions.preserveFormat(this.#text, this.#oldData, this.#data);
5084
+ else content = this.#parseOptions.stringify(this.#data);
5085
+ writeFileSync(this.#path, content);
5086
+ } catch (error) {
5087
+ throw new Error(`Failed to write ${this.#path}: ${error}`);
5088
+ }
5089
+ }
5090
+ };
5091
+ function createLimoJson(path$1, options = {}) {
5092
+ return new LimoFile(path$1, {
5093
+ ...options,
5094
+ parseOptions: {
5095
+ parse: (text) => JSON.parse(text),
5096
+ stringify: (data) => JSON.stringify(data, null, 2)
5097
+ }
5098
+ });
5099
+ }
5100
+ const { stdin: stdin$1 } = process;
4203
5101
  async function getStdin() {
4204
5102
  let result = "";
4205
5103
  if (stdin$1.isTTY) return result;
@@ -4214,86 +5112,186 @@ getStdin.buffer = async () => {
4214
5112
  for await (const chunk of stdin$1) result.push(chunk), length += chunk.length;
4215
5113
  return Buffer.concat(result, length);
4216
5114
  };
4217
- var import_picocolors$1 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
5115
+ var import_picocolors$1 = /* @__PURE__ */ __toESM(require_picocolors(), 1), import_usingCtx = /* @__PURE__ */ __toESM(require_usingCtx(), 1);
4218
5116
  function formatRemainingTime(remaining) {
4219
5117
  const remainingHours = Math.floor(remaining / 60), remainingMins = remaining % 60;
4220
5118
  return remainingHours > 0 ? `${remainingHours}h ${remainingMins}m left` : `${remainingMins}m left`;
4221
5119
  }
5120
+ function getSemaphore(sessionId) {
5121
+ const semaphoreDir = join(tmpdir(), "ccusage-semaphore"), semaphorePath = join(semaphoreDir, `${sessionId}.lock`);
5122
+ mkdirSync(semaphoreDir, { recursive: true });
5123
+ const semaphore = createLimoJson(semaphorePath);
5124
+ return semaphore;
5125
+ }
4222
5126
  const statuslineCommand = define({
4223
5127
  name: "statusline",
4224
- description: "Display compact status line for Claude Code hooks (Beta)",
4225
- args: { offline: {
4226
- ...sharedArgs.offline,
4227
- default: true
4228
- } },
5128
+ description: "Display compact status line for Claude Code hooks with hybrid time+file caching (Beta)",
5129
+ toKebab: true,
5130
+ args: {
5131
+ offline: {
5132
+ ...sharedArgs.offline,
5133
+ default: true
5134
+ },
5135
+ cache: {
5136
+ type: "boolean",
5137
+ description: "Enable cache for status line output (default: true)",
5138
+ default: true
5139
+ },
5140
+ refreshInterval: {
5141
+ type: "number",
5142
+ description: `Refresh interval in seconds for cache expiry (default: ${DEFAULT_REFRESH_INTERVAL_SECONDS})`,
5143
+ default: DEFAULT_REFRESH_INTERVAL_SECONDS
5144
+ }
5145
+ },
4229
5146
  async run(ctx) {
4230
5147
  logger.level = 0;
4231
- const stdin$2 = await getStdin();
5148
+ const refreshInterval = ctx.values.refreshInterval, stdin$2 = await getStdin();
4232
5149
  if (stdin$2.length === 0) log("❌ No input provided"), process$1.exit(1);
4233
5150
  const hookDataJson = JSON.parse(stdin$2.trim()), hookDataParseResult = statuslineHookJsonSchema.safeParse(hookDataJson);
4234
5151
  if (!hookDataParseResult.success) log("❌ Invalid input format:", hookDataParseResult.error.message), process$1.exit(1);
4235
- const hookData = hookDataParseResult.data, claudePaths = getClaudePaths();
4236
- if (claudePaths.length === 0) log("❌ No Claude data directory found"), process$1.exit(1);
4237
- const sessionId = hookData.session_id, sessionCost = await pipe(try_({
4238
- try: loadSessionUsageById(sessionId, {
4239
- mode: "auto",
4240
- offline: ctx.values.offline
4241
- }),
4242
- catch: (error) => error
4243
- }), map((sessionCost$1) => sessionCost$1?.totalCost), inspectError((error) => logger.error("Failed to load session data:", error)), unwrap(void 0)), today = /* @__PURE__ */ new Date(), todayStr = today.toISOString().split("T")[0]?.replace(/-/g, "") ?? "", todayCost = await pipe(try_({
4244
- try: loadDailyUsageData({
4245
- since: todayStr,
4246
- until: todayStr,
4247
- mode: "auto",
4248
- offline: ctx.values.offline
4249
- }),
4250
- catch: (error) => error
4251
- }), map((dailyData) => {
4252
- if (dailyData.length > 0) {
4253
- const totals = calculateTotals(dailyData);
4254
- return totals.totalCost;
5152
+ const hookData = hookDataParseResult.data, sessionId = hookData.session_id, initialSemaphoreState = pipe(succeed(getSemaphore(sessionId)), map((semaphore) => semaphore.data), unwrap(void 0)), currentMtime = await getFileModifiedTime(hookData.transcript_path);
5153
+ if (ctx.values.cache && initialSemaphoreState != null) {
5154
+ const now = Date.now(), timeElapsed = now - (initialSemaphoreState.lastUpdateTime ?? 0), isExpired = timeElapsed >= refreshInterval * 1e3, isFileModified = initialSemaphoreState.transcriptMtime !== currentMtime;
5155
+ if (!isExpired && !isFileModified) {
5156
+ log(initialSemaphoreState.lastOutput);
5157
+ return;
4255
5158
  }
4256
- return 0;
4257
- }), inspectError((error) => logger.error("Failed to load daily data:", error)), unwrap(0)), { blockInfo, burnRateInfo } = await pipe(try_({
4258
- try: loadSessionBlockData({
4259
- mode: "auto",
4260
- offline: ctx.values.offline
4261
- }),
4262
- catch: (error) => error
4263
- }), map((blocks) => {
4264
- if (blocks.length === 0) return {
4265
- blockInfo: "No active block",
4266
- burnRateInfo: ""
5159
+ if (initialSemaphoreState.isUpdating === true) {
5160
+ const pid = initialSemaphoreState.pid;
5161
+ let isProcessAlive = false;
5162
+ if (pid != null) try {
5163
+ process$1.kill(pid, 0), isProcessAlive = true;
5164
+ } catch {
5165
+ isProcessAlive = false;
5166
+ }
5167
+ if (isProcessAlive) {
5168
+ log(initialSemaphoreState.lastOutput);
5169
+ return;
5170
+ }
5171
+ }
5172
+ }
5173
+ try {
5174
+ var _usingCtx = (0, import_usingCtx.default)();
5175
+ const currentPid = process$1.pid, semaphore = _usingCtx.u(getSemaphore(sessionId));
5176
+ if (semaphore.data != null) semaphore.data = {
5177
+ ...semaphore.data,
5178
+ isUpdating: true,
5179
+ pid: currentPid
4267
5180
  };
4268
- const activeBlock = blocks.find((block) => {
4269
- return !!block.isActive;
4270
- });
4271
- if (activeBlock != null) {
4272
- const now = /* @__PURE__ */ new Date(), remaining = Math.round((activeBlock.endTime.getTime() - now.getTime()) / (1e3 * 60)), blockCost = activeBlock.costUSD, blockInfo$1 = `${formatCurrency(blockCost)} block (${formatRemainingTime(remaining)})`, burnRate = calculateBurnRate(activeBlock), burnRateInfo$1 = burnRate != null ? (() => {
4273
- const costPerHour = burnRate.costPerHour, costPerHourStr = `${formatCurrency(costPerHour)}/hr`, coloredBurnRate = burnRate.tokensPerMinuteForIndicator < 2e3 ? import_picocolors$1.default.green(costPerHourStr) : burnRate.tokensPerMinuteForIndicator < 5e3 ? import_picocolors$1.default.yellow(costPerHourStr) : import_picocolors$1.default.red(costPerHourStr);
4274
- return ` | 🔥 ${coloredBurnRate}`;
4275
- })() : "";
4276
- return {
4277
- blockInfo: blockInfo$1,
4278
- burnRateInfo: burnRateInfo$1
5181
+ else {
5182
+ const currentMtimeForInit = await getFileModifiedTime(hookData.transcript_path);
5183
+ semaphore.data = {
5184
+ date: (/* @__PURE__ */ new Date()).toISOString(),
5185
+ lastOutput: "",
5186
+ lastUpdateTime: 0,
5187
+ transcriptPath: hookData.transcript_path,
5188
+ transcriptMtime: currentMtimeForInit,
5189
+ isUpdating: true,
5190
+ pid: currentPid
4279
5191
  };
4280
5192
  }
4281
- return {
4282
- blockInfo: "No active block",
4283
- burnRateInfo: ""
4284
- };
4285
- }), inspectError((error) => logger.error("Failed to load block data:", error)), unwrap({
4286
- blockInfo: "No active block",
4287
- burnRateInfo: ""
4288
- })), contextInfo = await pipe(try_({
4289
- try: calculateContextTokens(hookData.transcript_path, hookData.model.id, ctx.values.offline),
5193
+ } catch (_) {
5194
+ _usingCtx.e = _;
5195
+ } finally {
5196
+ _usingCtx.d();
5197
+ }
5198
+ const mainProcessingResult = pipe(await try_({
5199
+ try: async () => {
5200
+ const sessionCost = await pipe(try_({
5201
+ try: loadSessionUsageById(sessionId, {
5202
+ mode: "auto",
5203
+ offline: ctx.values.offline
5204
+ }),
5205
+ catch: (error) => error
5206
+ }), map((sessionCost$1) => sessionCost$1?.totalCost), inspectError((error) => logger.error("Failed to load session data:", error)), unwrap(void 0)), today = /* @__PURE__ */ new Date(), todayStr = today.toISOString().split("T")[0]?.replace(/-/g, "") ?? "", todayCost = await pipe(try_({
5207
+ try: loadDailyUsageData({
5208
+ since: todayStr,
5209
+ until: todayStr,
5210
+ mode: "auto",
5211
+ offline: ctx.values.offline
5212
+ }),
5213
+ catch: (error) => error
5214
+ }), map((dailyData) => {
5215
+ if (dailyData.length > 0) {
5216
+ const totals = calculateTotals(dailyData);
5217
+ return totals.totalCost;
5218
+ }
5219
+ return 0;
5220
+ }), inspectError((error) => logger.error("Failed to load daily data:", error)), unwrap(0)), { blockInfo, burnRateInfo } = await pipe(try_({
5221
+ try: loadSessionBlockData({
5222
+ mode: "auto",
5223
+ offline: ctx.values.offline
5224
+ }),
5225
+ catch: (error) => error
5226
+ }), map((blocks) => {
5227
+ if (blocks.length === 0) return {
5228
+ blockInfo: "No active block",
5229
+ burnRateInfo: ""
5230
+ };
5231
+ const activeBlock = blocks.find((block) => {
5232
+ return !!block.isActive;
5233
+ });
5234
+ if (activeBlock != null) {
5235
+ const now = /* @__PURE__ */ new Date(), remaining = Math.round((activeBlock.endTime.getTime() - now.getTime()) / (1e3 * 60)), blockCost = activeBlock.costUSD, blockInfo$1 = `${formatCurrency(blockCost)} block (${formatRemainingTime(remaining)})`, burnRate = calculateBurnRate(activeBlock), burnRateInfo$1 = burnRate != null ? (() => {
5236
+ const costPerHour = burnRate.costPerHour, costPerHourStr = `${formatCurrency(costPerHour)}/hr`, coloredBurnRate = burnRate.tokensPerMinuteForIndicator < 2e3 ? import_picocolors$1.default.green(costPerHourStr) : burnRate.tokensPerMinuteForIndicator < 5e3 ? import_picocolors$1.default.yellow(costPerHourStr) : import_picocolors$1.default.red(costPerHourStr);
5237
+ return ` | 🔥 ${coloredBurnRate}`;
5238
+ })() : "";
5239
+ return {
5240
+ blockInfo: blockInfo$1,
5241
+ burnRateInfo: burnRateInfo$1
5242
+ };
5243
+ }
5244
+ return {
5245
+ blockInfo: "No active block",
5246
+ burnRateInfo: ""
5247
+ };
5248
+ }), inspectError((error) => logger.error("Failed to load block data:", error)), unwrap({
5249
+ blockInfo: "No active block",
5250
+ burnRateInfo: ""
5251
+ })), contextInfo = await pipe(try_({
5252
+ try: calculateContextTokens(hookData.transcript_path, hookData.model.id, ctx.values.offline),
5253
+ catch: (error) => error
5254
+ }), inspectError((error) => logger.debug(`Failed to calculate context tokens: ${error instanceof Error ? error.message : String(error)}`)), map((ctx$1) => {
5255
+ if (ctx$1 == null) return void 0;
5256
+ const thresholds = getContextUsageThresholds(), color = ctx$1.percentage < thresholds.LOW ? import_picocolors$1.default.green : ctx$1.percentage < thresholds.MEDIUM ? import_picocolors$1.default.yellow : import_picocolors$1.default.red, coloredPercentage = color(`${ctx$1.percentage}%`), tokenDisplay = ctx$1.inputTokens.toLocaleString();
5257
+ return `${tokenDisplay} (${coloredPercentage})`;
5258
+ }), unwrap(void 0)), modelName = hookData.model.display_name, sessionDisplay = sessionCost != null ? formatCurrency(sessionCost) : "N/A", statusLine = `🤖 ${modelName} | 💰 ${sessionDisplay} session / ${formatCurrency(todayCost)} today / ${blockInfo}${burnRateInfo} | 🧠 ${contextInfo ?? "N/A"}`;
5259
+ return statusLine;
5260
+ },
4290
5261
  catch: (error) => error
4291
- }), inspectError((error) => logger.debug(`Failed to calculate context tokens: ${error instanceof Error ? error.message : String(error)}`)), map((ctx$1) => {
4292
- if (ctx$1 == null) return void 0;
4293
- const thresholds = getContextUsageThresholds(), color = ctx$1.percentage < thresholds.LOW ? import_picocolors$1.default.green : ctx$1.percentage < thresholds.MEDIUM ? import_picocolors$1.default.yellow : import_picocolors$1.default.red, coloredPercentage = color(`${ctx$1.percentage}%`), tokenDisplay = ctx$1.inputTokens.toLocaleString();
4294
- return `${tokenDisplay} (${coloredPercentage})`;
4295
- }), unwrap(void 0)), modelName = hookData.model.display_name, sessionDisplay = sessionCost != null ? formatCurrency(sessionCost) : "N/A", statusLine = `🤖 ${modelName} | 💰 ${sessionDisplay} session / ${formatCurrency(todayCost)} today / ${blockInfo}${burnRateInfo} | 🧠 ${contextInfo ?? "N/A"}`;
4296
- log(statusLine);
5262
+ })());
5263
+ if (isSuccess(mainProcessingResult)) try {
5264
+ var _usingCtx3 = (0, import_usingCtx.default)();
5265
+ const statusLine = mainProcessingResult.value;
5266
+ if (log(statusLine), !ctx.values.cache) return;
5267
+ const semaphore = _usingCtx3.u(getSemaphore(sessionId));
5268
+ semaphore.data = {
5269
+ date: (/* @__PURE__ */ new Date()).toISOString(),
5270
+ lastOutput: statusLine,
5271
+ lastUpdateTime: Date.now(),
5272
+ transcriptPath: hookData.transcript_path,
5273
+ transcriptMtime: currentMtime,
5274
+ isUpdating: false,
5275
+ pid: void 0
5276
+ };
5277
+ return;
5278
+ } catch (_) {
5279
+ _usingCtx3.e = _;
5280
+ } finally {
5281
+ _usingCtx3.d();
5282
+ }
5283
+ if (isFailure(mainProcessingResult)) try {
5284
+ var _usingCtx4 = (0, import_usingCtx.default)();
5285
+ if (initialSemaphoreState?.lastOutput != null && initialSemaphoreState.lastOutput !== "") log(initialSemaphoreState.lastOutput);
5286
+ else log("❌ Error generating status");
5287
+ if (logger.error("Error in statusline command:", mainProcessingResult.error), !ctx.values.cache) return;
5288
+ const semaphore = _usingCtx4.u(getSemaphore(sessionId));
5289
+ if (semaphore.data != null) semaphore.data.isUpdating = false, semaphore.data.pid = void 0;
5290
+ } catch (_) {
5291
+ _usingCtx4.e = _;
5292
+ } finally {
5293
+ _usingCtx4.d();
5294
+ }
4297
5295
  }
4298
5296
  });
4299
5297
  var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);