repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

claude/statusline.js

Raw
File outline
#!/usr/bin/env node
// Claude Code statusline (Node). Reads session JSON from stdin, prints one line.
//
//   <dir> · <model> · <effort> · <git|jj> · <5h bar> · <7d bar> · <cost> · <cm> · <extra>
//
// Cost shows turn (Δ since last user prompt), session, and month-to-date.
// Month-to-date is a cross-session ledger: each render adds the session's new
// spend (delta) into the current month's bucket (~/.claude/.cc-cost-ledger.json).
//
// Must NEVER throw — a crash blanks the bar. Every optional part is its own
// try/catch. Schema: https://code.claude.com/docs/en/statusline.md

"use strict";

const fs = require("fs");
const os = require("os");
const path = require("path");
const crypto = require("crypto");
const { execFileSync } = require("child_process");

// ─── CONFIG ──────────────────────────────────────────────────────────────────
const CONFIG = {
  sep: "  ·  ", // segment padding
  barWidth: 8, // usage bar cells
  contextWarnPct: 70,
  contextCritPct: 90,
  usageAlways: true,
  usageWarnPct: 50,
  usageCritPct: 80,
  costStyle: "icon", // "slash" → $0.15/turn   |   "icon" → ⟳$0.15
  gitCacheTtlMs: 3000,
  extraTtlMs: 120000,
  cmdTimeoutMs: 2500,
  ledgerPruneDays: 40,
  // burn rate ($/hr): recent-window spend rate, decay-proof (idle samples age out)
  burnWindowMs: 10 * 60000, // sliding window of cost samples to rate over
  burnMinSpanMs: 60000, // need ≥ this much elapsed inside window before showing
  burnMaxSamples: 60, // cap stored samples per session (keeps ledger small)
};

const claudeDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");

// ─── ANSI ────────────────────────────────────────────────────────────────────
const E = "\x1b";
const R = `${E}[0m`;
const c = {
  cyan: (s) => `${E}[36m${s}${R}`,
  magenta: (s) => `${E}[35m${s}${R}`,
  green: (s) => `${E}[32m${s}${R}`,
  yellow: (s) => `${E}[33m${s}${R}`,
  red: (s) => `${E}[31m${s}${R}`,
  blue: (s) => `${E}[34m${s}${R}`,
  dim: (s) => `${E}[2m${s}${R}`,
  white: (s) => `${E}[97m${s}${R}`,
  orange: (s) => `${E}[38;5;172m${s}${R}`,
};
const pctColor = (p, warn, crit) => (p >= crit ? c.red : p >= warn ? c.yellow : c.green);

const PARTIALS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];
function bar(pct, width, color) {
  let p = Math.max(0, Math.min(100, pct));
  let filled = (p / 100) * width;
  let full = Math.floor(filled);
  let pIdx = Math.round((filled - full) * 8);
  if (pIdx === 8) {
    full += 1;
    pIdx = 0;
  }
  if (full > width) full = width;
  const partial = pIdx > 0 && full < width ? PARTIALS[pIdx] : "";
  const used = full + (partial ? 1 : 0);
  const empty = Math.max(0, width - used);
  return color("█".repeat(full) + partial) + c.dim("░".repeat(empty));
}
const money = (n) => (n < 1 ? n.toFixed(3) : n.toFixed(2));

// ─── stdin ───────────────────────────────────────────────────────────────────
let d = {};
try {
  const raw = fs.readFileSync(0, "utf8");
  if (raw && raw.trim()) d = JSON.parse(raw);
} catch {
  d = {};
}

const parts = [];
const push = (s) => {
  if (s) parts.push(s);
};

// ─── 1. dir ──────────────────────────────────────────────────────────────────
try {
  const cwd = d?.workspace?.current_dir || d?.cwd;
  if (cwd) push(c.cyan(path.basename(cwd) || cwd));
} catch {}

// ─── 2. model ──────────────────────────────────────────────────────────────────
try {
  if (d?.model?.display_name) push(c.magenta(d.model.display_name));
} catch {}

// ─── 3. effort / thinking ──────────────────────────────────────────────────────
try {
  const lvl = d?.effort?.level;
  if (lvl) {
    const on = d?.thinking?.enabled !== false;
    const col = lvl === "max" || lvl === "xhigh" ? c.magenta : lvl === "high" ? c.blue : c.dim;
    push(on ? col(`⚡${lvl}`) : c.dim(`⚡${lvl}`));
  }
} catch {}

// ─── 4. git / jj (smart-cached) ────────────────────────────────────────────────
push(gitOrJjSegment(d?.workspace?.current_dir || d?.cwd));

// ─── 5. context (gated) ────────────────────────────────────────────────────────
try {
  const cw = d?.context_window || {};
  let pct = cw.used_percentage;
  if (pct == null && cw.context_window_size && cw.total_input_tokens != null) {
    pct = (cw.total_input_tokens / cw.context_window_size) * 100;
  }
  const exceeds = d?.exceeds_200k_tokens === true;
  if (exceeds || (pct != null && pct >= CONFIG.contextWarnPct)) {
    const shown = pct != null ? Math.round(pct) : 100;
    const col = exceeds || shown >= CONFIG.contextCritPct ? c.red : c.yellow;
    push(`${c.dim("ctx")} ${bar(shown, CONFIG.barWidth, col)} ${col(shown + "%")}`);
  }
} catch {}

// ─── 6. usage bars (rate limits) ───────────────────────────────────────────────
try {
  const rl = d?.rate_limits;
  if (rl) {
    const add = (label, win, withReset) => {
      if (win && typeof win.used_percentage === "number") {
        const p = Math.round(win.used_percentage);
        if (CONFIG.usageAlways || p >= CONFIG.usageWarnPct) {
          const col = pctColor(p, CONFIG.usageWarnPct, CONFIG.usageCritPct);
          let seg = `${c.dim(label)} ${bar(p, CONFIG.barWidth, col)} ${col(p + "%")}`;
          // resets_at is UNIX EPOCH SECONDS — ×1000 to compare with Date.now() (ms)
          if (withReset && typeof win.resets_at === "number") {
            const left = win.resets_at * 1000 - Date.now();
            if (left > 0) seg += c.dim("·" + fmtDuration(left));
          }
          push(seg);
        }
      }
    };
    add("5h", rl.five_hour, true);
    add("7d", rl.seven_day, false);
  }
} catch {}

// ─── 7. cost: turn · session · month ───────────────────────────────────────────
try {
  const total = d?.cost?.total_cost_usd;
  const sid = d?.session_id || "default";
  if (typeof total === "number") {
    const { turn, month, burnRate } = updateLedger(sid, total);
    // 🔥 burn rate: own segment, before the cost cluster (matches bars · 🔥 · cost)
    if (burnRate > 0) push(c.orange(`🔥$${burnRate.toFixed(2)}/hr`));
    // icon: semantic glyph (⟳ turn / Σ session / ☾ month). slash: <num>/<type>.
    const fmt = (n, type, icon, color) =>
      CONFIG.costStyle === "icon" ? color(`${icon}$${money(n)}`) : color(`$${money(n)}/${type}`);
    const seg = [];
    if (turn > 0) seg.push(fmt(turn, "turn", "⟳", c.white));
    seg.push(fmt(total, "session", "Σ", c.dim));
    if (month > 0) seg.push(fmt(month, "month", "☾", c.dim));
    push(seg.join(" "));
  }
} catch {}

// ─── 8. caveman badge (terse) ──────────────────────────────────────────────────
push(cavemanBadge());

// ─── 9. extra badges (hooks: workflow, …) ──────────────────────────────────────
try {
  const f = path.join(claudeDir, ".cc-statusline-extra");
  const st = fs.lstatSync(f);
  if (!st.isSymbolicLink() && st.size <= 4096) {
    const now = Date.now();
    for (const line of fs.readFileSync(f, "utf8").split(/\r?\n/)) {
      const i = line.indexOf("|");
      if (i <= 0) continue;
      const ts = Number(line.slice(0, i));
      if (!Number.isFinite(ts) || now - ts > CONFIG.extraTtlMs) continue;
      const text = line.slice(i + 1).replace(/[\x00-\x1F]/g, "").slice(0, 60);
      if (text) push(c.orange(text));
    }
  }
} catch {}

// ─── emit ──────────────────────────────────────────────────────────────────────
process.stdout.write(parts.join(CONFIG.sep));

// ════════════════════════════════════════════════════════════════════════════
// cost ledger — cross-session month-to-date + per-session turn baseline
// ════════════════════════════════════════════════════════════════════════════
function monthKey() {
  const dt = new Date();
  return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, "0")}`;
}

function updateLedger(sid, total) {
  const file = path.join(claudeDir, ".cc-cost-ledger.json");
  const now = Date.now();
  const mk = monthKey();
  let L = { month: mk, monthTotal: 0, sessions: {} };
  try {
    L = JSON.parse(fs.readFileSync(file, "utf8"));
  } catch {}
  if (!L.sessions) L.sessions = {};

  // New month → reset the bucket, KEEP per-session baselines so a session that
  // straddles midnight only contributes its post-boundary spend.
  if (L.month !== mk) {
    L.month = mk;
    L.monthTotal = 0;
  }

  // Prune stale sessions.
  const cutoff = now - CONFIG.ledgerPruneDays * 864e5;
  for (const k of Object.keys(L.sessions)) {
    if ((L.sessions[k]?.ts ?? 0) < cutoff) delete L.sessions[k];
  }

  const s = L.sessions[sid] || { total: 0, turnStart: total, ts: now };

  // Turn boundary: UserPromptSubmit hook drops a marker; first render after a
  // prompt rebaselines turnStart, then consumes the marker.
  try {
    const marker = path.join(claudeDir, `.cc-turn-${sid}`);
    if (fs.existsSync(marker)) {
      s.turnStart = total;
      fs.unlinkSync(marker);
    }
  } catch {}

  // Month bucket gets only the new spend since this session was last seen.
  const delta = total - (s.total ?? 0);
  if (delta > 0) L.monthTotal = (L.monthTotal || 0) + delta;

  const turn = Math.max(0, total - (s.turnStart ?? total));
  s.total = total;
  s.ts = now;

  // Timestamped cost samples for the burn rate. Append, drop anything older than
  // the window (so idle time falls off instead of dragging the rate down), cap.
  if (!Array.isArray(s.samples)) s.samples = [];
  s.samples.push([now, total]);
  const wcut = now - CONFIG.burnWindowMs;
  s.samples = s.samples.filter((p) => p[0] >= wcut);
  if (s.samples.length > CONFIG.burnMaxSamples) s.samples = s.samples.slice(-CONFIG.burnMaxSamples);
  const burnRate = computeBurnRate(s.samples);

  L.sessions[sid] = s;

  try {
    const tmp = `${file}.${process.pid}.tmp`;
    fs.writeFileSync(tmp, JSON.stringify(L));
    fs.renameSync(tmp, file);
  } catch {}

  return { turn, month: L.monthTotal || 0, burnRate };
}

// ── burn rate ($/hr) ──────────────────────────────────────────────────────────
// DESIGN KNOB (yours to tune): turn timestamped cost samples into a "right now"
// $/hr. Default = window endpoints — cheap, robust: spend / span across the kept
// window. Stale samples are already pruned in updateLedger, so idle time drops
// out naturally rather than decaying the rate toward zero (the classic
// cost÷duration bug). Alternatives if you want a different feel:
//   • EWMA over per-sample rates → smoother, slower to react
//   • least-squares slope of (ts,total) → noise-resistant, a few more lines
function computeBurnRate(samples) {
  if (!Array.isArray(samples) || samples.length < 2) return 0;
  const first = samples[0];
  const last = samples[samples.length - 1];
  const span = last[0] - first[0];
  const spend = last[1] - first[1];
  if (span < CONFIG.burnMinSpanMs || spend <= 0) return 0;
  return (spend / span) * 3600000; // $/ms → $/hr
}

// Compact duration: "2h45m" (minutes zero-padded) above an hour, else "45m".
function fmtDuration(ms) {
  const m = Math.floor(ms / 60000);
  if (m >= 60) return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}m`;
  return `${m}m`;
}

// ════════════════════════════════════════════════════════════════════════════
// git / jj
// ════════════════════════════════════════════════════════════════════════════
function findRepo(startDir) {
  try {
    let dir = startDir && fs.existsSync(startDir) ? startDir : process.cwd();
    for (let i = 0; i < 40; i++) {
      if (fs.existsSync(path.join(dir, ".jj"))) return { kind: "jj", root: dir };
      if (fs.existsSync(path.join(dir, ".git"))) return { kind: "git", root: dir };
      const up = path.dirname(dir);
      if (up === dir) break;
      dir = up;
    }
  } catch {}
  return null;
}

function gitOrJjSegment(cwd) {
  let repo;
  try {
    repo = findRepo(cwd);
  } catch {
    return "";
  }
  if (!repo) return "";
  const key = crypto.createHash("sha1").update(repo.kind + ":" + repo.root).digest("hex").slice(0, 12);
  const cacheFile = path.join(os.tmpdir(), `cc-statusline-${key}.json`);
  try {
    const o = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
    if (Date.now() - o.ts < CONFIG.gitCacheTtlMs) return o.text;
  } catch {}
  let text = "";
  try {
    text = repo.kind === "jj" ? jjSegment(repo.root) : gitSegment(repo.root);
  } catch {
    text = "";
  }
  try {
    const tmp = `${cacheFile}.${process.pid}.tmp`;
    fs.writeFileSync(tmp, JSON.stringify({ ts: Date.now(), text }));
    fs.renameSync(tmp, cacheFile);
  } catch {}
  return text;
}

function gitSegment(root) {
  const out = execFileSync("git", ["-C", root, "status", "--porcelain=v2", "--branch"], {
    encoding: "utf8",
    timeout: CONFIG.cmdTimeoutMs,
    windowsHide: true,
  });
  let branch = "?";
  let ahead = 0;
  let behind = 0;
  let dirty = 0;
  for (const line of out.split(/\r?\n/)) {
    if (line.startsWith("# branch.head ")) branch = line.slice(14).trim();
    else if (line.startsWith("# branch.ab ")) {
      const m = line.match(/\+(\d+)\s+-(\d+)/);
      if (m) {
        ahead = +m[1];
        behind = +m[2];
      }
    } else if (line && !line.startsWith("#")) dirty++;
  }
  if (branch === "(detached)") branch = "detached";
  const col = dirty > 0 ? c.yellow : c.green;
  let s = col(`⎇${branch}`);
  if (dirty > 0) s += c.yellow(`●${dirty}`);
  if (ahead) s += c.cyan(`↑${ahead}`);
  if (behind) s += c.cyan(`↓${behind}`);
  return s;
}

function jjSegment(root) {
  const tmpl = 'change_id.shortest(8) ++ "|" ++ bookmarks ++ "|" ++ if(empty, "clean", "dirty")';
  const out = execFileSync(
    "jj",
    ["--no-pager", "log", "--no-graph", "--color", "never", "-r", "@", "-T", tmpl],
    { cwd: root, encoding: "utf8", timeout: CONFIG.cmdTimeoutMs, windowsHide: true }
  ).trim();
  const [change = "?", bookmarks = "", state = ""] = out.split("|");
  const label = bookmarks.trim() || change;
  const dirty = state.trim() === "dirty";
  const col = dirty ? c.yellow : c.green;
  return col(`jj:${label}`) + (dirty ? c.yellow("✗") : "");
}

// ════════════════════════════════════════════════════════════════════════════
// caveman badge — terse: full→"cm", else "cm:<first-letter>"
// ════════════════════════════════════════════════════════════════════════════
function cavemanBadge() {
  try {
    const flag = path.join(claudeDir, ".caveman-active");
    const st = fs.lstatSync(flag);
    if (st.isSymbolicLink() || st.size > 64) return "";
    let mode = (fs.readFileSync(flag, "utf8").split(/\r?\n/)[0] ?? "")
      .trim()
      .toLowerCase()
      .replace(/[^a-z0-9-]/g, "");
    const valid = new Set([
      "off", "lite", "full", "ultra",
      "wenyan-lite", "wenyan", "wenyan-full", "wenyan-ultra",
      "commit", "review", "compress",
    ]);
    if (!valid.has(mode) || mode === "off") return "";
    let out = c.orange(mode || "full");
    if (process.env.CAVEMAN_STATUSLINE_SAVINGS !== "0") {
      try {
        const sf = path.join(claudeDir, ".caveman-statusline-suffix");
        const sst = fs.lstatSync(sf);
        if (!sst.isSymbolicLink() && sst.size <= 64) {
          const sv = fs.readFileSync(sf, "utf8").replace(/[\x00-\x1F]/g, "").trimEnd();
          if (sv) out += " " + c.orange(sv);
        }
      } catch {}
    }
    return out;
  } catch {
    return "";
  }
}