@owloops/claude-powerline 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +18 -3
  2. package/dist/index.js +10 -10
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -286,15 +286,30 @@ Config files reload automatically and no restart needed.
286
286
  ```json
287
287
  "context": {
288
288
  "enabled": true,
289
- "showPercentageOnly": false
289
+ "showPercentageOnly": false,
290
+ "displayStyle": "text"
290
291
  }
291
292
  ```
292
293
 
293
294
  **Options:**
294
295
 
295
296
  - `showPercentageOnly`: Show only percentage remaining (default: false)
296
-
297
- **Display:** `◔ 34,040 (79%)` or `◔ 79%` (percentage only)
297
+ - `displayStyle`: Visual style for context display (default: `"text"`)
298
+
299
+ **Display Styles:**
300
+
301
+ | Style | Example | Description |
302
+ |-------|---------|-------------|
303
+ | `text` | `◔ 34,040 (79%)` | Text with token count (default) |
304
+ | `bar` | `▪▪▪▪▫▫▫▫▫▫ 40%` | Bar using theme symbols |
305
+ | `blocks` | `████░░░░░░ 40%` | Solid/shaded blocks |
306
+ | `squares` | `◼◼◼◼◻◻◻◻◻◻ 40%` | Filled/empty squares |
307
+ | `dots` | `●●●●○○○○○○ 40%` | Filled/empty circles |
308
+ | `line` | `━━━━┄┄┄┄┄┄ 40%` | Thick/dashed line |
309
+ | `capped` | `━━━╸┄┄┄┄┄┄ 40%` | Line with boundary cap |
310
+ | `ball` | `───●────── 40%` | Position marker on a track |
311
+ | `filled` | `■■■■□□□□□□ 40%` | Filled/empty squares (alt) |
312
+ | `geometric` | `▰▰▰▰▱▱▱▱▱▱ 40%` | Geometric triangles |
298
313
 
299
314
  **Symbols:** `◔` Context (unicode) • `C` Context (text)
300
315
 
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import x from'process';import {json}from'stream/consumers';import N from'tty';import {exec,execSync}from'child_process';import {promisify}from'util';import w,{existsSync,readFileSync,createReadStream}from'fs';import _,{join,posix,dirname}from'path';import {get}from'https';import {URL}from'url';import he,{homedir}from'os';import {createHash}from'crypto';import {setTimeout}from'timers/promises';import {readdir,stat,readFile}from'fs/promises';import {createInterface}from'readline';function se(s,e){if(e&&(s.toLowerCase()==="transparent"||s.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),o=parseInt(s.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${n};${o}m`}function j(s,e=false){if(!s||s==="")return "";let t=s.match(/48;2;(\d+);(\d+);(\d+)/);if(t)return `\x1B[38;2;${t[1]};${t[2]};${t[3]}m`;if(e)return "\x1B[37m";if(s.includes("\x1B[")&&s.includes("m")){let n=s.match(/\[(\d+)m/);if(n&&n[1]){let o=parseInt(n[1],10);if(o>=40&&o<=47)return `\x1B[${o-10}m`;if(o>=100&&o<=107)return `\x1B[${o-10}m`}}return s.replace("48","38")}function H(){let{env:s}=x,e=true;s.NO_COLOR&&s.NO_COLOR!==""&&(e=false);let t=s.FORCE_COLOR;if(t&&t!=="")return t==="false"||t==="0"?"none":t==="true"||t==="1"?"ansi":t==="2"?"ansi256":t==="3"?"truecolor":"ansi";if(!e||s.TERM==="dumb")return "none";if(s.CI)return ["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in s)?"truecolor":"ansi";if(s.COLORTERM==="truecolor"||["xterm-kitty","xterm-ghostty","wezterm","alacritty","foot","contour"].includes(s.TERM||""))return "truecolor";if(s.TERM_PROGRAM)switch(s.TERM_PROGRAM){case "iTerm.app":return "truecolor";case "Apple_Terminal":return "ansi256";case "vscode":return "truecolor";case "Tabby":return "truecolor"}if(/-256(color)?$/i.test(s.TERM||""))return "ansi256";if(/-truecolor$/i.test(s.TERM||""))return "truecolor";if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(s.TERM||"")||s.COLORTERM)return "ansi";if(N?.WriteStream?.prototype?.hasColors)try{if(!N.WriteStream.prototype.hasColors())return "none";let r=N.WriteStream.prototype.hasColors(256);return N.WriteStream.prototype.hasColors(16777216)?"truecolor":r?"ansi256":"ansi"}catch{}return "ansi"}function ie(s,e){if(e&&(s.toLowerCase()==="transparent"||s.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),o=parseInt(s.slice(5,7),16),i=((a,c,g)=>a===c&&c===g?a<8?16:a>248?231:Math.round((a-8)/247*24)+232:16+36*Math.round(a/255*5)+6*Math.round(c/255*5)+Math.round(g/255*5))(t,n,o);return `\x1B[${e?"48":"38"};5;${i}m`}function ae(s,e){if(e&&(s.toLowerCase()==="transparent"||s.toLowerCase()==="none"))return "\x1B[49m";if(e)return "";let t=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),o=parseInt(s.slice(5,7),16);return n>t&&n>o&&n>120?"\x1B[32m":t>n&&t>o&&t>120?"\x1B[31m":o>t&&o>n&&o>120?"\x1B[34m":(t+n+o)/3>150?"\x1B[37m":"\x1B[90m"}var ye={directory:{bg:"#8b4513",fg:"#ffffff"},git:{bg:"#404040",fg:"#ffffff"},model:{bg:"#2d2d2d",fg:"#ffffff"},session:{bg:"#202020",fg:"#00ffff"},block:{bg:"#2a2a2a",fg:"#87ceeb"},today:{bg:"#1a1a1a",fg:"#98fb98"},tmux:{bg:"#2f4f2f",fg:"#90ee90"},context:{bg:"#4a5568",fg:"#cbd5e0"},contextWarning:{bg:"#92400e",fg:"#fbbf24"},contextCritical:{bg:"#991b1b",fg:"#fca5a5"},metrics:{bg:"#374151",fg:"#d1d5db"},version:{bg:"#3a3a4a",fg:"#b8b8d0"}},Ce={directory:{bg:"#af5f00",fg:"#ffffff"},git:{bg:"#444444",fg:"#ffffff"},model:{bg:"#3a3a3a",fg:"#ffffff"},session:{bg:"#262626",fg:"#00ffff"},block:{bg:"#303030",fg:"#87ceeb"},today:{bg:"#1c1c1c",fg:"#87ff87"},tmux:{bg:"#444444",fg:"#87ff87"},context:{bg:"#585858",fg:"#d0d0d0"},contextWarning:{bg:"#af5f00",fg:"#ffaf00"},contextCritical:{bg:"#870000",fg:"#ff8787"},metrics:{bg:"#4e4e4e",fg:"#d0d0d0"},version:{bg:"#444444",fg:"#d7afff"}},_e={directory:{bg:"#d75f00",fg:"#ffffff"},git:{bg:"#585858",fg:"#ffffff"},model:{bg:"#444444",fg:"#ffffff"},session:{bg:"#303030",fg:"#00ffff"},block:{bg:"#3a3a3a",fg:"#5fafff"},today:{bg:"#262626",fg:"#00ff00"},tmux:{bg:"#585858",fg:"#00ff00"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d75f00",fg:"#ffff00"},contextCritical:{bg:"#af0000",fg:"#ff0000"},metrics:{bg:"#666666",fg:"#ffffff"},version:{bg:"#585858",fg:"#af87ff"}};var we={directory:{bg:"#ff6b47",fg:"#ffffff"},git:{bg:"#4fb3d9",fg:"#ffffff"},model:{bg:"#87ceeb",fg:"#000000"},session:{bg:"#da70d6",fg:"#ffffff"},block:{bg:"#6366f1",fg:"#ffffff"},today:{bg:"#10b981",fg:"#ffffff"},tmux:{bg:"#32cd32",fg:"#ffffff"},context:{bg:"#718096",fg:"#ffffff"},contextWarning:{bg:"#d97706",fg:"#ffffff"},contextCritical:{bg:"#dc2626",fg:"#ffffff"},metrics:{bg:"#6b7280",fg:"#ffffff"},version:{bg:"#8b7dd8",fg:"#ffffff"}},xe={directory:{bg:"#ff5f5f",fg:"#ffffff"},git:{bg:"#5fafff",fg:"#ffffff"},model:{bg:"#87d7ff",fg:"#000000"},session:{bg:"#ff5fff",fg:"#ffffff"},block:{bg:"#5f5fff",fg:"#ffffff"},today:{bg:"#00d787",fg:"#ffffff"},tmux:{bg:"#00ff5f",fg:"#ffffff"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d78700",fg:"#ffffff"},contextCritical:{bg:"#d70000",fg:"#ffffff"},metrics:{bg:"#767676",fg:"#ffffff"},version:{bg:"#af87ff",fg:"#ffffff"}},ke={directory:{bg:"#ff5f5f",fg:"#ffffff"},git:{bg:"#5fafff",fg:"#ffffff"},model:{bg:"#87d7ff",fg:"#000000"},session:{bg:"#ff5fff",fg:"#ffffff"},block:{bg:"#5f5fff",fg:"#ffffff"},today:{bg:"#00d787",fg:"#ffffff"},tmux:{bg:"#00ff5f",fg:"#ffffff"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d78700",fg:"#ffffff"},contextCritical:{bg:"#d70000",fg:"#ffffff"},metrics:{bg:"#767676",fg:"#ffffff"},version:{bg:"#af87ff",fg:"#ffffff"}};var Se={directory:{bg:"#434c5e",fg:"#d8dee9"},git:{bg:"#3b4252",fg:"#a3be8c"},model:{bg:"#4c566a",fg:"#81a1c1"},session:{bg:"#2e3440",fg:"#88c0d0"},block:{bg:"#3b4252",fg:"#81a1c1"},today:{bg:"#2e3440",fg:"#8fbcbb"},tmux:{bg:"#2e3440",fg:"#8fbcbb"},context:{bg:"#5e81ac",fg:"#eceff4"},contextWarning:{bg:"#d08770",fg:"#2e3440"},contextCritical:{bg:"#bf616a",fg:"#eceff4"},metrics:{bg:"#b48ead",fg:"#2e3440"},version:{bg:"#434c5e",fg:"#88c0d0"}},Te={directory:{bg:"#5f87af",fg:"#e4e4e4"},git:{bg:"#4e4e4e",fg:"#87d787"},model:{bg:"#6c6c6c",fg:"#87afd7"},session:{bg:"#3a3a3a",fg:"#5fafaf"},block:{bg:"#4e4e4e",fg:"#87afd7"},today:{bg:"#3a3a3a",fg:"#5fd7d7"},tmux:{bg:"#3a3a3a",fg:"#5fd7d7"},context:{bg:"#5f87d7",fg:"#ffffff"},contextWarning:{bg:"#d7875f",fg:"#3a3a3a"},contextCritical:{bg:"#d75f5f",fg:"#ffffff"},metrics:{bg:"#d787af",fg:"#3a3a3a"},version:{bg:"#5f87af",fg:"#5fafaf"}},ve={directory:{bg:"#0087af",fg:"#ffffff"},git:{bg:"#585858",fg:"#87d700"},model:{bg:"#808080",fg:"#87afff"},session:{bg:"#444444",fg:"#00d7d7"},block:{bg:"#585858",fg:"#87afff"},today:{bg:"#444444",fg:"#00ffff"},tmux:{bg:"#444444",fg:"#00ffff"},context:{bg:"#0087ff",fg:"#ffffff"},contextWarning:{bg:"#d78700",fg:"#000000"},contextCritical:{bg:"#d75f5f",fg:"#ffffff"},metrics:{bg:"#ff87d7",fg:"#444444"},version:{bg:"#0087af",fg:"#00d7d7"}};var Pe={directory:{bg:"#2f334d",fg:"#82aaff"},git:{bg:"#1e2030",fg:"#c3e88d"},model:{bg:"#191b29",fg:"#fca7ea"},session:{bg:"#222436",fg:"#86e1fc"},block:{bg:"#2d3748",fg:"#7aa2f7"},today:{bg:"#1a202c",fg:"#4fd6be"},tmux:{bg:"#191b29",fg:"#4fd6be"},context:{bg:"#414868",fg:"#c0caf5"},contextWarning:{bg:"#ff9e64",fg:"#1a1b26"},contextCritical:{bg:"#f7768e",fg:"#1a1b26"},metrics:{bg:"#3d59a1",fg:"#c0caf5"},version:{bg:"#292e42",fg:"#bb9af7"}},Ee={directory:{bg:"#444478",fg:"#87afff"},git:{bg:"#262640",fg:"#afff87"},model:{bg:"#1c1c30",fg:"#ff87ff"},session:{bg:"#3a3a50",fg:"#5fd7ff"},block:{bg:"#4e4e68",fg:"#5f87ff"},today:{bg:"#262640",fg:"#00d7af"},tmux:{bg:"#1c1c30",fg:"#00d7af"},context:{bg:"#5f5f87",fg:"#d7d7ff"},contextWarning:{bg:"#ffaf5f",fg:"#262626"},contextCritical:{bg:"#ff5f87",fg:"#262626"},metrics:{bg:"#5f5faf",fg:"#d7d7ff"},version:{bg:"#444460",fg:"#d787ff"}},$e={directory:{bg:"#5f5faf",fg:"#87afff"},git:{bg:"#303050",fg:"#87ff87"},model:{bg:"#262640",fg:"#ff87ff"},session:{bg:"#444470",fg:"#00d7ff"},block:{bg:"#666680",fg:"#5f87ff"},today:{bg:"#303050",fg:"#00d787"},tmux:{bg:"#262640",fg:"#00d787"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#ffaf00",fg:"#000000"},contextCritical:{bg:"#ff5f5f",fg:"#000000"},metrics:{bg:"#8787d7",fg:"#ffffff"},version:{bg:"#585870",fg:"#d787ff"}};var Re={directory:{bg:"#26233a",fg:"#c4a7e7"},git:{bg:"#1f1d2e",fg:"#9ccfd8"},model:{bg:"#191724",fg:"#ebbcba"},session:{bg:"#26233a",fg:"#f6c177"},block:{bg:"#2a273f",fg:"#eb6f92"},today:{bg:"#232136",fg:"#9ccfd8"},tmux:{bg:"#26233a",fg:"#908caa"},context:{bg:"#393552",fg:"#e0def4"},contextWarning:{bg:"#f6c177",fg:"#191724"},contextCritical:{bg:"#eb6f92",fg:"#191724"},metrics:{bg:"#524f67",fg:"#e0def4"},version:{bg:"#2a273f",fg:"#c4a7e7"}},Be={directory:{bg:"#444444",fg:"#d787d7"},git:{bg:"#262626",fg:"#87d7d7"},model:{bg:"#1c1c1c",fg:"#ffaf87"},session:{bg:"#444444",fg:"#d7af5f"},block:{bg:"#4e4e4e",fg:"#ff5f87"},today:{bg:"#3a3a3a",fg:"#87d7d7"},tmux:{bg:"#444444",fg:"#9e9e9e"},context:{bg:"#585858",fg:"#e4e4e4"},contextWarning:{bg:"#d7af5f",fg:"#1c1c1c"},contextCritical:{bg:"#ff5f87",fg:"#1c1c1c"},metrics:{bg:"#767676",fg:"#e4e4e4"},version:{bg:"#4e4e4e",fg:"#d787d7"}},Ae={directory:{bg:"#585858",fg:"#ff87ff"},git:{bg:"#303030",fg:"#00d7d7"},model:{bg:"#262626",fg:"#ffaf87"},session:{bg:"#585858",fg:"#d7af00"},block:{bg:"#666666",fg:"#ff5f87"},today:{bg:"#444444",fg:"#00d7d7"},tmux:{bg:"#585858",fg:"#bcbcbc"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d7af00",fg:"#000000"},contextCritical:{bg:"#ff5f5f",fg:"#000000"},metrics:{bg:"#a8a8a8",fg:"#000000"},version:{bg:"#666666",fg:"#ff87ff"}};var De={directory:{bg:"#504945",fg:"#ebdbb2"},git:{bg:"#3c3836",fg:"#b8bb26"},model:{bg:"#665c54",fg:"#83a598"},session:{bg:"#282828",fg:"#8ec07c"},block:{bg:"#3c3836",fg:"#83a598"},today:{bg:"#282828",fg:"#fabd2f"},tmux:{bg:"#282828",fg:"#fe8019"},context:{bg:"#458588",fg:"#ebdbb2"},contextWarning:{bg:"#d79921",fg:"#282828"},contextCritical:{bg:"#cc241d",fg:"#ebdbb2"},metrics:{bg:"#d3869b",fg:"#282828"},version:{bg:"#504945",fg:"#8ec07c"}},Fe={directory:{bg:"#585858",fg:"#ffffaf"},git:{bg:"#444444",fg:"#afaf00"},model:{bg:"#6c6c6c",fg:"#87afaf"},session:{bg:"#303030",fg:"#87af87"},block:{bg:"#444444",fg:"#87afaf"},today:{bg:"#303030",fg:"#ffaf00"},tmux:{bg:"#303030",fg:"#ff8700"},context:{bg:"#5f8787",fg:"#ffffaf"},contextWarning:{bg:"#d7af00",fg:"#303030"},contextCritical:{bg:"#d70000",fg:"#ffffaf"},metrics:{bg:"#d787af",fg:"#303030"},version:{bg:"#585858",fg:"#87af87"}},Me={directory:{bg:"#808080",fg:"#ffff00"},git:{bg:"#585858",fg:"#00ff00"},model:{bg:"#808080",fg:"#00afff"},session:{bg:"#444444",fg:"#00d787"},block:{bg:"#585858",fg:"#00afff"},today:{bg:"#444444",fg:"#ffaf00"},tmux:{bg:"#444444",fg:"#ff8700"},context:{bg:"#008787",fg:"#ffffff"},contextWarning:{bg:"#d7af00",fg:"#000000"},contextCritical:{bg:"#d70000",fg:"#ffffff"},metrics:{bg:"#ff87af",fg:"#444444"},version:{bg:"#808080",fg:"#00d787"}};var ce={dark:ye,"dark-ansi256":Ce,"dark-ansi":_e,light:we,"light-ansi256":xe,"light-ansi":ke,nord:Se,"nord-ansi256":Te,"nord-ansi":ve,"tokyo-night":Pe,"tokyo-night-ansi256":Ee,"tokyo-night-ansi":$e,"rose-pine":Re,"rose-pine-ansi256":Be,"rose-pine-ansi":Ae,gruvbox:De,"gruvbox-ansi256":Fe,"gruvbox-ansi":Me};function W(s,e){let t=ce[s];if(!t)return null;if(e==="none"||e==="ansi"){let n=ce[`${s}-ansi`];if(n)return n}if(e==="ansi256"){let n=ce[`${s}-ansi256`];if(n)return n}return t}var l=(s,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${s}`,...e);};var nt=promisify(exec),D=class{isGitRepo(e){try{return w.existsSync(_.join(e,".git"))}catch{return false}}async execGitAsync(e,t){return nt(e,{...t,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}})}async findGitRoot(e){try{return (await this.execGitAsync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getGitInfo(e,t={},n){let o;if(n&&this.isGitRepo(n))o=n;else if(this.isGitRepo(e))o=e;else {let r=await this.findGitRoot(e);if(!r)return null;o=r;}try{let r=await this.getStatusWithBranchAsync(o),i=await this.getAheadBehindAsync(o),a={branch:r.branch||"detached",status:r.status,ahead:i.ahead,behind:i.behind};t.showWorkingTree&&r.workingTree&&(a.staged=r.workingTree.staged,a.unstaged=r.workingTree.unstaged,a.untracked=r.workingTree.untracked,a.conflicts=r.workingTree.conflicts);let c={},g={};t.showSha&&(c.sha=this.getShaAsync(o)),t.showTag&&(c.tag=this.getNearestTagAsync(o)),t.showTimeSinceCommit&&(c.timeSinceCommit=this.getTimeSinceLastCommitAsync(o)),t.showStashCount&&(g.stashCount=this.getStashCountAsync(o)),t.showUpstream&&(g.upstream=this.getUpstreamAsync(o)),t.showRepoName&&(g.repoName=this.getRepoNameAsync(o));let u=new Map;for(let[m,f]of Object.entries(c))try{let d=await f;u.set(m,d);}catch{}return Object.keys(g).length>0&&(await Promise.allSettled(Object.entries(g).map(async([f,d])=>({key:f,value:await d})))).forEach(f=>{f.status==="fulfilled"&&u.set(f.value.key,f.value.value);}),t.showSha&&(a.sha=u.get("sha")||void 0),t.showOperation&&(a.operation=this.getOngoingOperation(o)||void 0),t.showTag&&(a.tag=u.get("tag")||void 0),t.showTimeSinceCommit&&(a.timeSinceCommit=u.get("timeSinceCommit")||void 0),t.showStashCount&&(a.stashCount=u.get("stashCount")||0),t.showUpstream&&(a.upstream=u.get("upstream")||void 0),t.showRepoName&&(a.repoName=u.get("repoName")||void 0,a.isWorktree=this.isWorktree(o)),a}catch{return null}}async getShaAsync(e){try{return (await this.execGitAsync("git rev-parse --short=7 HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}getOngoingOperation(e){try{let t=_.join(e,".git");return w.existsSync(_.join(t,"MERGE_HEAD"))?"MERGE":w.existsSync(_.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":w.existsSync(_.join(t,"REVERT_HEAD"))?"REVERT":w.existsSync(_.join(t,"BISECT_LOG"))?"BISECT":w.existsSync(_.join(t,"rebase-merge"))||w.existsSync(_.join(t,"rebase-apply"))?"REBASE":null}catch{return null}}async getNearestTagAsync(e){try{return (await this.execGitAsync("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getTimeSinceLastCommitAsync(e){try{let n=(await this.execGitAsync("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!n)return null;let o=parseInt(n)*1e3,r=Date.now();return Math.floor((r-o)/1e3)}catch{return null}}async getStashCountAsync(e){try{let n=(await this.execGitAsync("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.split(`
3
- `).length:0}catch{return 0}}async getUpstreamAsync(e){try{return (await this.execGitAsync("git rev-parse --abbrev-ref @{u}",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getRepoNameAsync(e){try{let n=(await this.execGitAsync("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.match(/\/([^/]+?)(\.git)?$/)?.[1]||_.basename(e):_.basename(e)}catch{return _.basename(e)}}isWorktree(e){try{let t=_.join(e,".git");return !!(w.existsSync(t)&&w.statSync(t).isFile())}catch{return false}}async getStatusWithBranchAsync(e){try{l(`[GIT-EXEC] Running git status in ${e}`);let o=(await this.execGitAsync("git status --porcelain -b",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.split(`
4
- `),r=null,i="clean",a=0,c=0,g=0,u=0;for(let m of o)if(m){if(m.startsWith("## ")){let d=m.substring(3).split("...")[0];d&&d!=="HEAD (no branch)"&&(r=d);continue}if(m.length>=2){let f=m.charAt(0),d=m.charAt(1);if(f==="?"&&d==="?"){g++,i==="clean"&&(i="dirty");continue}let h=f+d;if(["DD","AU","UD","UA","DU","AA","UU"].includes(h)){u++,i="conflicts";continue}f!==" "&&f!=="?"&&(a++,i==="clean"&&(i="dirty")),d!==" "&&d!=="?"&&(c++,i==="clean"&&(i="dirty"));}}return {branch:r||await this.getFallbackBranch(e),status:i,workingTree:{staged:a,unstaged:c,untracked:g,conflicts:u}}}catch(t){return l(`Git status with branch command failed in ${e}:`,t),{branch:await this.getFallbackBranch(e),status:"clean"}}}async getFallbackBranch(e){try{let n=(await this.execGitAsync("git branch --show-current",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{try{let n=(await this.execGitAsync("git symbolic-ref --short HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{return null}}return null}async getAheadBehindAsync(e){try{l(`[GIT-EXEC] Running git ahead/behind in ${e}`);let[t,n]=await Promise.all([this.execGitAsync("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:2e3}),this.execGitAsync("git rev-list --count HEAD..@{u}",{cwd:e,encoding:"utf8",timeout:2e3})]);return {ahead:parseInt(t.stdout.trim())||0,behind:parseInt(n.stdout.trim())||0}}catch(t){return l(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}};var st=promisify(exec),F=class{async getSessionId(){try{if(!process.env.TMUX_PANE)return l("TMUX_PANE not set, not in tmux session"),null;l(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let t=(await st("tmux display-message -p '#S'",{encoding:"utf8",timeout:1e3})).stdout.trim();return l(`Tmux session ID: ${t||"empty"}`),t||null}catch(e){return l("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};function V(){let s=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let n=t.trim();existsSync(n)&&s.push(n);}),s.length===0){let t=homedir(),n=join(t,".config","claude"),o=join(t,".claude");existsSync(n)?s.push(n):existsSync(o)&&s.push(o);}return s}async function Y(s){let e=[];for(let t of s){let n=join(t,"projects");if(existsSync(n))try{let o=await readdir(n,{withFileTypes:!0});for(let r of o)if(r.isDirectory()){let i=posix.join(n,r.name);e.push(i);}}catch(o){l(`Failed to read projects directory ${n}:`,o);}}return e}async function J(s){let e=V(),t=await Y(e);for(let n of t){let o=posix.join(n,`${s}.jsonl`);if(existsSync(o))return o}return null}async function Ie(s,e){let t=[];try{let o=(await readdir(e)).filter(r=>r.startsWith("agent-")&&r.endsWith(".jsonl"));for(let r of o){let i=posix.join(e,r);try{let c=(await readFile(i,"utf-8")).split(`
5
- `)[0];c&&JSON.parse(c).sessionId===s&&t.push(i);}catch{l(`Failed to check agent file ${i}`);}}}catch(n){l(`Failed to read project directory ${e}:`,n);}return t}async function ue(s){try{return (await stat(s)).mtime}catch{return null}}function lt(s){let e=s.message?.id||(typeof s.raw.message=="object"&&s.raw.message!==null&&"id"in s.raw.message?s.raw.message.id:void 0),t="requestId"in s.raw?s.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var gt=1024*1024;async function B(s){try{let t=(await stat(s)).size,n;return t>gt?(l(`Using streaming parser for large file ${s} (${Math.round(t/1024)}KB)`),n=await ft(s)):n=await ut(s),l(`Parsed ${n.length} entries from ${s}`),n}catch(e){return l(`Failed to read file ${s}:`,e),[]}}async function ut(s){let t=(await readFile(s,"utf-8")).trim().split(`
6
- `).filter(o=>o.trim()),n=[];for(let o of t)try{let r=JSON.parse(o);if(!r.timestamp)continue;let i={timestamp:new Date(r.timestamp),message:r.message,costUSD:typeof r.costUSD=="number"?r.costUSD:void 0,isSidechain:r.isSidechain===!0,raw:r};n.push(i);}catch(r){l(`Failed to parse JSONL line: ${r}`);continue}return n}async function ft(s){return new Promise((e,t)=>{let n=[],o=createReadStream(s,{encoding:"utf8"}),r=createInterface({input:o,crlfDelay:1/0});r.on("line",i=>{let a=i.trim();if(a)try{let c=JSON.parse(a);if(!c.timestamp)return;let g={timestamp:new Date(c.timestamp),message:c.message,costUSD:typeof c.costUSD=="number"?c.costUSD:void 0,isSidechain:c.isSidechain===!0,raw:c};n.push(g);}catch(c){l(`Failed to parse JSONL line: ${c}`);}}),r.on("close",()=>{e(n);}),r.on("error",i=>{l(`Streaming parser error for ${s}:`,i),t(i);}),o.on("error",i=>{l(`File stream error for ${s}:`,i),t(i);});})}async function z(s,e,t=false){let n=V(),o=await Y(n),r=new Set,i=o.map(async h=>{try{let b=(await readdir(h)).filter(C=>C.endsWith(".jsonl")).map(async C=>{let k=posix.join(h,C);if(existsSync(k)){let Ze=await ue(k);return {filePath:k,mtime:Ze}}return null});return (await Promise.all(b)).filter(C=>C?.mtime&&(!e||e(C.filePath,C.mtime)))}catch(p){return l(`Failed to read project directory ${h}:`,p),[]}}),c=(await Promise.all(i)).flat().filter(h=>h!==null);t&&c.sort((h,p)=>p.mtime.getTime()-h.mtime.getTime());let g=c.map(h=>h.filePath),u=[],m=g.map(async h=>(await B(h)).filter(y=>!s||s(y))),f=await Promise.all(m);for(let h of f)u.push(...h);u.sort((h,p)=>h.timestamp.getTime()-p.timestamp.getTime());let d=[];for(let h of u){let p=lt(h);p&&r.has(p)||(p&&r.add(p),d.push(h));}return d}var v=class{static CACHE_DIR=_.join(homedir(),".claude","powerline");static USAGE_CACHE_DIR=_.join(this.CACHE_DIR,"usage");static LOCKS_DIR=_.join(this.CACHE_DIR,"locks");static isLocked(e){let t=_.join(this.LOCKS_DIR,e);if(!w.existsSync(t))return false;try{let n=w.readFileSync(t,"utf-8"),o=parseInt(n.trim(),10);if(isNaN(o))return l(`Invalid PID in lock file ${e}, removing stale lock`),w.unlinkSync(t),!1;try{return process.kill(o,0),!0}catch(r){return r.code==="ESRCH"?(l(`Removing stale lock file ${e} for dead process ${o}`),w.unlinkSync(t),!1):(l(`Error checking process ${o} for lock ${e}:`,r),!0)}}catch(n){return l(`Error reading lock file ${e}:`,n),true}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let r=_.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await w.promises.writeFile(r,a,{flag:"wx"}),l(`Lock acquired for ${e}`),!0}catch(c){if(c.code==="EEXIST")await setTimeout(50);else throw c}return l(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=_.join(this.LOCKS_DIR,e);try{await w.promises.unlink(t),l(`Lock released for ${e}`);}catch(n){n.code!=="ENOENT"&&l(`Error releasing lock for ${e}:`,n);}}static async ensureCacheDirectories(){try{await Promise.all([w.promises.mkdir(this.CACHE_DIR,{recursive:!0}),w.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),w.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){l("Failed to create cache directories:",e);}}static createProjectHash(e){return createHash("md5").update(e).digest("hex").substring(0,8)}static async getUsageCache(e,t){let r="utf-8";await this.ensureCacheDirectories();let i=_.join(this.USAGE_CACHE_DIR,`${e}.json`),a=`${e}.usage.lock`;for(let c=0;c<3;c++){if(this.isLocked(a)){l(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let u=await w.promises.readFile(i,r),m=JSON.parse(u);return !t||m.timestamp>=t?(l(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(m.data)):(l(`${e} cache outdated: cache=${m.timestamp}, latest=${t}`),null)}catch(u){if(u.code==="ENOENT")return l(`No shared ${e} usage cache found`),null;let m=c+1;l(`Attempt ${m} failed to read ${e} cache: ${u.message}. Retrying...`),await setTimeout(75);}}return l(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(t=>({...t,timestamp:new Date(t.timestamp)})):e}static async setUsageCache(e,t,n){let o=`${e}.usage.lock`;if(!await this.acquireLock(o)){l(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=_.join(this.USAGE_CACHE_DIR,`${e}.json`),a=n||Date.now(),g=JSON.stringify({data:t,timestamp:a});await w.promises.writeFile(i,g,"utf-8"),l(`[CACHE-SET] ${e} disk cache stored`);}catch(i){l(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(o);}}static async getLatestTranscriptMtime(){try{let e=V(),t=await Y(e),n=0;for(let o of t)try{let i=(await w.promises.readdir(o)).filter(a=>a.endsWith(".jsonl"));for(let a of i){let c=_.join(o,a),g=await ue(c);g&&g.getTime()>n&&(n=g.getTime());}}catch(r){l(`Failed to read project directory ${o}:`,r);continue}return n}catch(e){return l("Failed to get latest transcript mtime:",e),Date.now()}}};var q={"claude-3-haiku-20240307":{name:"Claude 3 Haiku",input:.25,output:1.25,cache_write_5m:.3,cache_write_1h:.5,cache_read:.03},"claude-3-5-haiku-20241022":{name:"Claude 3.5 Haiku",input:.8,output:4,cache_write_5m:1,cache_write_1h:1.6,cache_read:.08},"claude-3-5-haiku-latest":{name:"Claude 3.5 Haiku Latest",input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5-20251001":{name:"Claude Haiku 4.5",input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:"Claude Haiku 4.5",input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-3-opus-latest":{name:"Claude 3 Opus Latest",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-3-opus-20240229":{name:"Claude 3 Opus",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-3-5-sonnet-latest":{name:"Claude 3.5 Sonnet Latest",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-5-sonnet-20240620":{name:"Claude 3.5 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-5-sonnet-20241022":{name:"Claude 3.5 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-20250514":{name:"Claude Opus 4",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:"Claude Opus 4.1",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:"Claude Opus 4.1",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:"Claude Sonnet 4",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:"Claude 4 Opus",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:"Claude 4 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:"Claude Sonnet 4.5",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:"Claude Sonnet 4.5",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-7-sonnet-latest":{name:"Claude 3.7 Sonnet Latest",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-7-sonnet-20250219":{name:"Claude 3.7 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}},E=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL="https://raw.githubusercontent.com/Owloops/claude-powerline/main/pricing.json";static async loadDiskCache(){let t=Date.now()-864e5;return await v.getUsageCache("pricing",t)}static async saveDiskCache(e){await v.setUsageCache("pricing",e);}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},o=>{if(o.statusCode!==200){l(`HTTP ${o.statusCode}: ${o.statusMessage}`),e(null);return}let r="",i=0,a=1024*1024;o.on("data",c=>{if(i+=c.length,i>a){l("Response too large"),n.destroy(),e(null);return}r+=c;}),o.on("end",()=>{try{let g=JSON.parse(r),u=g._meta,m={};for(let[f,d]of Object.entries(g))f!=="_meta"&&(m[f]=d);this.validatePricingData(m)?(l(`Fetched fresh pricing from GitHub for ${Object.keys(m).length} models`),l(`Pricing last updated: ${u?.updated||"unknown"}`),e(m)):(l("Invalid pricing data structure"),e(null));}catch(c){l("Failed to parse JSON:",c),e(null);}}),o.on("error",c=>{l("Response error:",c),e(null);});});n.on("error",o=>{l("Request error:",o),e(null);}),n.on("timeout",()=>{l("Request timeout"),n.destroy(),e(null);}),n.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return l(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return l(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,l(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),l(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,l(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(l(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(q).length} models`),this.executionCache=q,l(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(q).length} models`),q)}static validatePricingData(e){if(!e||typeof e!="object")return false;for(let[,t]of Object.entries(e)){if(!t||typeof t!="object")return false;let n=t;if(typeof n.input!="number"||typeof n.output!="number"||typeof n.cache_read!="number")return false}return true}static async getModelPricing(e){if(this.modelPricingCache.has(e))return l(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return t[e]?n=t[e]:n=this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),l(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[r,i]of Object.entries(t))if(r.toLowerCase()===n)return i;let o=[{pattern:["opus-4-1","claude-opus-4-1"],fallback:"claude-opus-4-1-20250805"},{pattern:["opus-4","claude-opus-4"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet-4.5","4-5-sonnet","sonnet-4-5"],fallback:"claude-sonnet-4-5-20250929"},{pattern:["sonnet-4","claude-sonnet-4"],fallback:"claude-sonnet-4-20250514"},{pattern:["sonnet-3.7","3-7-sonnet"],fallback:"claude-3-7-sonnet-20250219"},{pattern:["3-5-sonnet","sonnet-3.5"],fallback:"claude-3-5-sonnet-20241022"},{pattern:["haiku-4.5","4-5-haiku","haiku-4-5"],fallback:"claude-haiku-4-5-20251001"},{pattern:["3-5-haiku","haiku-3.5"],fallback:"claude-3-5-haiku-20241022"},{pattern:["haiku","3-haiku"],fallback:"claude-3-haiku-20240307"},{pattern:["opus"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet"],fallback:"claude-3-5-sonnet-20241022"}];for(let{pattern:r,fallback:i}of o)if(r.some(a=>n.includes(a))&&t[i])return t[i];return t["claude-3-5-sonnet-20241022"]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let n=e.message?.usage;if(!n)return 0;let o=this.extractModelId(e),r=await this.getModelPricing(o),i=n.input_tokens||0,a=n.output_tokens||0,c=n.cache_creation_input_tokens||0,g=n.cache_read_input_tokens||0,u=i/1e6*r.input,m=a/1e6*r.output,f=g/1e6*r.cache_read,d=c/1e6*r.cache_write_5m;return u+m+d+f}static extractModelId(e){if(e.model&&typeof e.model=="string")return e.model;let t=e.message;if(t?.model){let n=t.model;return typeof n=="string"?n:n?.id||"claude-3-5-sonnet-20241022"}return e.model_id&&typeof e.model_id=="string"?e.model_id:"claude-3-5-sonnet-20241022"}};function yt(s){return {timestamp:s.timestamp.toISOString(),message:{usage:{input_tokens:s.message?.usage?.input_tokens||0,output_tokens:s.message?.usage?.output_tokens||0,cache_creation_input_tokens:s.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:s.message?.usage?.cache_read_input_tokens}},costUSD:s.costUSD}}var X=class{async getSessionUsage(e){try{let t=await J(e);if(!t)return l(`No transcript found for session: ${e}`),null;l(`Found transcript at: ${t}`);let n=await B(t),o=dirname(t),r=await Ie(e,o);l(`Found ${r.length} agent transcripts for session`);for(let c of r){let g=await B(c);n.push(...g);}if(n.length===0)return {totalCost:0,entries:[]};let i=[],a=0;for(let c of n)if(c.message?.usage){let g=yt(c);if(g.costUSD!==void 0)a+=g.costUSD;else {let u=await E.calculateCostForEntry(c.raw);g.costUSD=u,a+=u;}i.push(g);}return l(`Parsed ${i.length} usage entries, total cost: $${a.toFixed(4)}`),{totalCost:a,entries:i}}catch(t){return l(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,n)=>({input:t.input+(n.message.usage.input_tokens||0),output:t.output+(n.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(n.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(n.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e,t){let n=await this.getSessionUsage(e);if(!n||n.entries.length===0)return {cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};let o=this.calculateTokenBreakdown(n.entries),r=o.input+o.output+o.cacheCreation+o.cacheRead,i=n.totalCost,a=t?.cost?.total_cost_usd??null;return {cost:i??a,calculatedCost:i,officialCost:a,tokens:r,tokenBreakdown:o}}},M=class{sessionProvider=new X;async getUsageInfo(e,t){try{return l(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e,t)}}catch(n){return l(`Error getting usage info for session ${e}:`,n),{session:{cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null}}}}};var U=class{thresholds={LOW:50,MEDIUM:80};config;constructor(e){this.config=e;}getContextUsageThresholds(){return this.thresholds}getContextLimit(e){let t=this.config.modelContextLimits||{default:2e5},n=this.getModelType(e);return t[n]||t.default||2e5}getModelType(e){let t=e.toLowerCase();return t.includes("sonnet")?"sonnet":t.includes("opus")?"opus":"default"}calculatePercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100))),o=Math.round(t*.75),r=Math.min(100,Math.max(0,Math.round(e/o*100))),i=Math.max(0,100-r);return {percentage:n,usablePercentage:r,contextLeftPercentage:i,usableTokens:o}}calculateContextFromHookData(e){let t=e.context_window?.current_usage;if(!t)return l("No current_usage in hook data, falling back to transcript parsing"),null;let n=e.context_window?.context_window_size||2e5,o=(t.input_tokens||0)+(t.cache_creation_input_tokens||0)+(t.cache_read_input_tokens||0);l(`Native current_usage: input=${t.input_tokens}, cache_create=${t.cache_creation_input_tokens}, cache_read=${t.cache_read_input_tokens}, total=${o} (limit: ${n})`);let r=this.calculatePercentages(o,n);return {totalTokens:o,maxTokens:n,...r}}async calculateContextTokensFromTranscript(e,t){try{l(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return l("Transcript file is empty"),null}catch{return l("Could not read transcript file"),null}let n=await B(e);if(n.length===0)return l("No entries in transcript"),null;let o=null;for(let r=n.length-1;r>=0;r--){let i=n[r];if(i&&i.message?.usage?.input_tokens&&i.isSidechain!==!0){o=i,l(`Context segment: Found most recent entry at ${i.timestamp.toISOString()}, stopping search`);break}}if(o?.message?.usage){let r=o.message.usage,i=(r.input_tokens||0)+(r.cache_read_input_tokens||0)+(r.cache_creation_input_tokens||0),a=t?this.getContextLimit(t):2e5;l(`Most recent main chain context: ${i} tokens (limit: ${a})`);let c=this.calculatePercentages(i,a);return {totalTokens:i,maxTokens:a,...c}}return l("No main chain entries with usage data found"),null}catch(n){return l(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t||this.calculateContextTokensFromTranscript(e.transcript_path,e.model?.id)}};var L=class{async loadTranscriptEntries(e){try{let t=await J(e);if(!t)return l(`No transcript found for session: ${e}`),[];l(`Loading transcript from: ${t}`);let o=(await readFile(t,"utf-8")).trim().split(`
7
- `).filter(i=>i.trim()),r=[];for(let i of o)try{let a=JSON.parse(i);if(a.isSidechain===!0)continue;r.push(a);}catch(a){l(`Failed to parse JSONL line: ${a}`);continue}return l(`Loaded ${r.length} transcript entries`),r}catch(t){return l(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,o=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!o}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,o=null;for(let r of t)if(r.timestamp)try{let i=new Date(r.timestamp),a=r.type||r.message?.role||r.message?.type,c=r.type==="user"&&r.message?.content?.[0]?.type==="tool_result";if(a==="user"&&!c)n=i;else if(a==="assistant"&&n){let u=(i.getTime()-n.getTime())/1e3;u>.1&&u<300&&(o=u);}}catch{continue}return o}async getMetricsInfo(e,t){try{if(l(`Getting metrics from hook data for session: ${e}`),!t.cost)return l("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let n=await this.loadTranscriptEntries(e),o=this.calculateMessageCount(n),r=this.calculateLastResponseTime(n);return {responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:r,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:o,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed}}catch(n){return l(`Error getting metrics from hook data for session ${e}:`,n),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function K(s){return s===null?"$0.00":s<.01?"<$0.01":`$${s.toFixed(2)}`}function P(s){return s===null||s===0?"0 tokens":s>=1e6?`${(s/1e6).toFixed(1)}M tokens`:s>=1e3?`${(s/1e3).toFixed(1)}K tokens`:`${s} tokens`}function Oe(s){if(!s)return "0 tokens";let e=[];if(s.input>0&&e.push(`${P(s.input).replace(" tokens","")}in`),s.output>0&&e.push(`${P(s.output).replace(" tokens","")}out`),s.cacheCreation>0||s.cacheRead>0){let t=s.cacheCreation+s.cacheRead;e.push(`${P(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function Ne(s){return s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:s<86400?`${Math.floor(s/3600)}h`:s<604800?`${Math.floor(s/86400)}d`:`${Math.floor(s/604800)}w`}function je(s){return s<60?`${s.toFixed(0)}s`:s<3600?`${(s/60).toFixed(0)}m`:s<86400?`${(s/3600).toFixed(1)}h`:`${(s/86400).toFixed(1)}d`}var wt=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i;function He(s){let e=s.trim().match(wt);if(!e?.groups)return s;let{family:t,newMajor:n,newMinor:o,oldMajor:r,oldMinor:i,oldFamily:a}=e.groups,c=t||a,g=n||r,u=o||i;if(c&&g){let m=c.charAt(0).toUpperCase()+c.slice(1).toLowerCase(),f=u?`${g}.${u}`:g;return `${m} ${f}`}return s}function xt(s,e){return !e||e<=0||s<0?null:Math.min(100,s/e*100)}function me(s,e,t=80){let n=xt(s,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let o=`${n.toFixed(0)}%`,r=n>=t,i="";return r?i=` !${o}`:n>=50?i=` +${o}`:i=` ${o}`,{percentage:n,isWarning:r,displayText:i}}var I=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let o=e.workspace?.current_dir||e.cwd||"/",r=e.workspace?.project_dir,i=n?.style??(n?.showBasename?"basename":"full");if(i==="basename")return {text:_.basename(o)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let a=process.env.HOME||process.env.USERPROFILE,c=o,g=r;a&&(o.startsWith(a)&&(c=o.replace(a,"~")),r&&r.startsWith(a)&&(g=r.replace(a,"~")));let u=this.getDisplayDirectoryName(c,g);return i==="fish"&&(u=this.abbreviateFishStyle(u)),{text:u,bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let o=[];if(n?.showRepoName&&e.repoName&&(o.push(e.repoName),e.isWorktree&&o.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&o.push(`[${e.operation}]`),o.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&o.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&o.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?o.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?o.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&o.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let i=[];e.staged&&e.staged>0&&i.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&i.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&i.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&i.push(`!${e.conflicts}`),i.length>0&&o.push(`(${i.join(" ")})`);}if(n?.showUpstream&&e.upstream&&o.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&o.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=Ne(e.timeSinceCommit);o.push(`${this.symbols.git_time} ${i}`);}let r=this.symbols.git_clean;return e.status==="conflicts"?r=this.symbols.git_conflicts:e.status==="dirty"&&(r=this.symbols.git_dirty),o.push(r),{text:o.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}renderModel(e,t){let n=e.model?.display_name||"Claude",o=He(n);return {text:`${this.symbols.model} ${o}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n){let o=n?.type||"cost",r=n?.costSource,i=this.config.budget?.session,a=()=>r==="calculated"?e.session.calculatedCost:r==="official"?e.session.officialCost:e.session.cost,c=this.formatUsageWithBudget(a(),e.session.tokens,e.session.tokenBreakdown,o,i?.amount,i?.warningThreshold||80,i?.type);return {text:`${this.symbols.session_cost} ${c}`,bgColor:t.sessionBg,fgColor:t.sessionFg}}renderTmux(e,t){return e?{text:`tmux:${e}`,bgColor:t.tmuxBg,fgColor:t.tmuxFg}:{text:"tmux:none",bgColor:t.tmuxBg,fgColor:t.tmuxFg}}renderContext(e,t,n){if(!e)return n?.displayStyle==="bar"?{text:`${this.symbols.bar_empty.repeat(10)} 0%`,bgColor:t.contextBg,fgColor:t.contextFg}:{text:`${this.symbols.context_time} 0 (100%)`,bgColor:t.contextBg,fgColor:t.contextFg};let r=t.contextBg,i=t.contextFg;if(e.contextLeftPercentage<=20?(r=t.contextCriticalBg,i=t.contextCriticalFg):e.contextLeftPercentage<=40&&(r=t.contextWarningBg,i=t.contextWarningFg),n?.displayStyle==="bar"){let g=e.usablePercentage,u=Math.round(g/100*10),m=10-u,f=this.symbols.bar_filled.repeat(u)+this.symbols.bar_empty.repeat(m);return {text:n?.showPercentageOnly?`${f} ${g}%`:`${f} ${e.totalTokens.toLocaleString()} (${g}%)`,bgColor:r,fgColor:i}}let a=`${e.contextLeftPercentage}%`;return {text:n?.showPercentageOnly?`${this.symbols.context_time} ${a}`:`${this.symbols.context_time} ${e.totalTokens.toLocaleString()} (${a})`,bgColor:r,fgColor:i}}renderMetrics(e,t,n,o){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let r=[];if(o?.showLastResponseTime&&e.lastResponseTime!==null){let i=e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;r.push(`${this.symbols.metrics_last_response} ${i}`);}if(o?.showResponseTime!==false&&e.responseTime!==null){let i=e.responseTime<60?`${e.responseTime.toFixed(1)}s`:`${(e.responseTime/60).toFixed(1)}m`;r.push(`${this.symbols.metrics_response} ${i}`);}if(o?.showDuration!==false&&e.sessionDuration!==null){let i=je(e.sessionDuration);r.push(`${this.symbols.metrics_duration} ${i}`);}return o?.showMessageCount!==false&&e.messageCount!==null&&r.push(`${this.symbols.metrics_messages} ${e.messageCount}`),o?.showLinesAdded!==false&&e.linesAdded!==null&&e.linesAdded>0&&r.push(`${this.symbols.metrics_lines_added} ${e.linesAdded}`),o?.showLinesRemoved!==false&&e.linesRemoved!==null&&e.linesRemoved>0&&r.push(`${this.symbols.metrics_lines_removed} ${e.linesRemoved}`),r.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:r.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,n){let o;if(e.cost===null&&e.tokens===null)o="No active block";else {let r=n?.type||"cost",i=n?.burnType,a=this.config.budget?.block,c=e.timeRemaining!==null?(()=>{let m=Math.floor(e.timeRemaining/60),f=e.timeRemaining%60;return m>0?`${m}h ${f}m`:`${f}m`})():null,g;switch(r){case "cost":g=this.formatUsageWithBudget(e.cost,null,null,"cost",a?.amount,a?.warningThreshold,a?.type);break;case "tokens":g=this.formatUsageWithBudget(null,e.tokens,null,"tokens",a?.amount,a?.warningThreshold,a?.type);break;case "weighted":let m=a?.type==="tokens"?a.amount:void 0,f=P(e.weightedTokens);if(m&&e.weightedTokens!==null){let d=me(e.weightedTokens,m,a?.warningThreshold||80);g=`${f}${d.displayText}`;}else g=`${f} (weighted)`;break;case "both":g=this.formatUsageWithBudget(e.cost,e.tokens,null,"both",a?.amount,a?.warningThreshold,a?.type);break;case "time":g=c||"N/A";break;default:g=this.formatUsageWithBudget(e.cost,null,null,"cost",a?.amount,a?.warningThreshold,a?.type);}let u="";if(i&&i!=="none")switch(i){case "cost":u=` | ${e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A"}`;break;case "tokens":u=` | ${e.tokenBurnRate!==null?`${P(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let d=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",h=e.tokenBurnRate!==null?`${P(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${d} / ${h}`;break}r==="time"?o=g:o=c?`${g}${u} (${c} left)`:`${g}${u}`;}return {text:`${this.symbols.block_cost} ${o}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let o=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,o?.amount,o?.warningThreshold,o?.type)}`,bgColor:t.todayBg,fgColor:t.todayFg}}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||_.basename(t)||"project":_.basename(e)||"root":_.basename(e)||"root"}abbreviateFishStyle(e){let t=e.split(_.sep);return t.map((n,o)=>o===t.length-1||n==="~"||n===""?n:n.charAt(0)).join(_.sep)}formatUsageDisplay(e,t,n,o){switch(o){case "cost":return K(e);case "tokens":return P(t);case "both":return `${K(e)} (${P(t)})`;case "breakdown":return Oe(n);default:return K(e)}}formatUsageWithBudget(e,t,n,o,r,i=80,a){let c=this.formatUsageDisplay(e,t,n,o);if(r&&r>0){let g=null;if(a==="tokens"&&t!==null?g=t:(a==="cost"&&e!==null||!a&&e!==null)&&(g=e),g!==null){let u=me(g,r,i);return c+u.displayText}}return c}renderVersion(e,t,n){return e.version?{text:`${this.symbols.version} v${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}:null}};function kt(s){return s.includes("opus")?5:(s.includes("sonnet")||s.includes("haiku"),1)}function St(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},costUSD:s.costUSD||0,model:s.message?.model||"unknown"}}var Z=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],o=[...e].sort((a,c)=>a.timestamp.getTime()-c.timestamp.getTime()),r=null,i=[];for(let a of o){let c=a.timestamp;if(r==null)r=this.floorToHour(c),i=[a];else {let g=c.getTime()-r.getTime(),u=i[i.length-1];if(u==null)continue;let m=u.timestamp,f=c.getTime()-m.getTime();g>t||f>t?(n.push(i),r=this.floorToHour(c),i=[a]):i.push(a);}}return r!=null&&i.length>0&&n.push(i),n}createBlockInfo(e,t){let n=new Date,o=this.sessionDurationHours*60*60*1e3,r=new Date(e.getTime()+o),i=t[t.length-1],a=i!=null?i.timestamp:e,c=n.getTime()-a.getTime()<o&&n<r;return {block:t,isActive:c}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let o=n[0];if(!o)continue;let r=this.floorToHour(o.timestamp),i=this.createBlockInfo(r,n);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{l("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await z(void 0,(c,g)=>g>=e,!0),o=[];for(let c of n)if(c.message?.usage){let g=St(c);!g.costUSD&&c.raw&&(g.costUSD=await E.calculateCostForEntry(c.raw)),o.push(g);}let r=this.identifySessionBlocks(o);l(`Block segment: Found ${r.length} session blocks`);let i=this.findActiveBlock(r),a=[];if(i&&i.length>0){l(`Block segment: Found active block with ${i.length} entries`);let c=i[0],g=i[i.length-1];c&&g&&l(`Block segment: Active block from ${c.timestamp.toISOString()} to ${g.timestamp.toISOString()}`),a=i;}else l("Block segment: No active block found"),a=[];return a}catch(e){return l("Error loading block entries:",e),[]}}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return l("Block segment: No entries in current block"),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((g,u)=>g+u.costUSD,0),n=e.reduce((g,u)=>g+u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,0),o=e.reduce((g,u)=>{let m=u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,f=kt(u.model);return g+m*f},0),r=new Date,i=null;if(e.length>0){let g=e[0];if(g){let u=this.sessionDurationHours*60*60*1e3,m=this.floorToHour(g.timestamp),f=new Date(m.getTime()+u);i=Math.max(0,Math.round((f.getTime()-r.getTime())/(1e3*60)));}}let a=null,c=null;if(e.length>=1&&(t>0||n>0)){let g=e.map(f=>f.timestamp).sort((f,d)=>f.getTime()-d.getTime()),u=g[0],m=g[g.length-1];if(u&&m){let f=(m.getTime()-u.getTime())/6e4;f>0&&(t>0&&(a=t/f*60),n>0&&(c=n/f*60));}}return l(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${i}m remaining, burn rate: ${a?"$"+a.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,weightedTokens:o,timeRemaining:i,burnRate:a,tokenBurnRate:c}}catch(e){return l("Error getting active block info:",e),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function O(s){let e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function Tt(s){return s.inputTokens+s.outputTokens+s.cacheCreationInputTokens+s.cacheReadInputTokens}function vt(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},costUSD:s.costUSD||0,model:s.message?.model||"unknown"}}var Q=class{async loadTodayEntries(){let t=O(new Date);l(`Today segment: Loading entries for date ${t}`);let n=await v.getLatestTranscriptMtime(),o=await v.getUsageCache("today",n);if(o)return l("Using shared today usage cache"),o;let r=new Date;r.setDate(r.getDate()-1),r.setHours(0,0,0,0);let i=(f,d)=>d>=r,a=new Date;a.setHours(0,0,0,0);let g=await z(f=>f.timestamp>=a,i,true),u=[],m=0;for(let f of g)if(O(f.timestamp)===t&&f.message?.usage){let h=vt(f);!h.costUSD&&f.raw&&(h.costUSD=await E.calculateCostForEntry(f.raw)),u.push(h),m++;}return l(`Today segment: Found ${m} entries for today (${t})`),await v.setUsageCache("today",u,n),u}async getTodayEntries(){try{return await this.loadTodayEntries()}catch(e){return l("Error loading today's entries:",e),[]}}async getTodayInfo(){try{let e=await this.getTodayEntries();if(e.length===0)return {cost:null,tokens:null,tokenBreakdown:null,date:O(new Date)};let t=e.reduce((r,i)=>r+i.costUSD,0),n=e.reduce((r,i)=>r+Tt(i.usage),0),o=e.reduce((r,i)=>({input:r.input+i.usage.inputTokens,output:r.output+i.usage.outputTokens,cacheCreation:r.cacheCreation+i.usage.cacheCreationInputTokens,cacheRead:r.cacheRead+i.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return l(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:o,date:O(new Date)}}catch(e){return l("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:O(new Date)}}}};var We="\x1B[0m",Ge={right:"\uE0B0",left_rounded:"\uE0B6",right_rounded:"\uE0B4",branch:"\u2387",model:"\u2731",git_clean:"\u2713",git_dirty:"\u25CF",git_conflicts:"\u26A0",git_ahead:"\u2191",git_behind:"\u2193",git_worktree:"\u29C9",git_tag:"\u2302",git_sha:"\u266F",git_upstream:"\u2192",git_stash:"\u29C7",git_time:"\u25F7",session_cost:"\xA7",block_cost:"\u25F1",today_cost:"\u2609",context_time:"\u25D4",metrics_response:"\u29D6",metrics_last_response:"\u0394",metrics_duration:"\u29D7",metrics_messages:"\u27D0",metrics_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u27E2",version:"\u25C8",bar_filled:"\u25AA",bar_empty:"\u25AB"},Ve={right:"\uE0B0",left_rounded:"\uE0B6",right_rounded:"\uE0B4",branch:"~",model:"M",git_clean:"=",git_dirty:"*",git_conflicts:"!",git_ahead:"^",git_behind:"v",git_worktree:"W",git_tag:"T",git_sha:"#",git_upstream:">>",git_stash:"S",git_time:"@",session_cost:"S",block_cost:"B",today_cost:"D",context_time:"C",metrics_response:"R",metrics_last_response:"L",metrics_duration:"T",metrics_messages:"#",metrics_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"~/h",version:"V",bar_filled:"=",bar_empty:"-"};var Pt="\x1B",Et=new RegExp(`${Pt}\\[[0-9;]*m`,"g"),$t=/^[a-zA-Z0-9/]+$/;function Rt(){if(process.platform==="win32")return null;let s=process.pid.toString();for(let e=0;e<10;e++)try{let n=execSync(`ps -o ppid=,tty= -p ${s}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(/\s+/),o=n[0],r=n[1];if(r&&r!=="?"&&r!=="??"&&$t.test(r))return r;if(!o||o==="1"||o==="0")break;s=o;}catch{break}return null}function Bt(){try{let e=execSync("mode con",{encoding:"utf8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).match(/Columns:\s*(\d+)/i);if(e?.[1]){let t=parseInt(e[1],10);if(!isNaN(t)&&t>0)return t}}catch{}return null}function At(){let s=Rt();if(s)try{let t=execSync(`stty size < /dev/${s}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"],shell:"/bin/sh"}).trim().split(" ")[1];if(t){let n=parseInt(t,10);if(!isNaN(n)&&n>0)return n}}catch{}try{let e=execSync("tput cols 2>/dev/null",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim(),t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}catch{}return null}function Ye(){let s=n=>Math.floor(n*.8),e=process.env.COLUMNS;if(e){let n=parseInt(e,10);if(!isNaN(n)&&n>0)return s(n)}if(process.stdout.columns&&process.stdout.columns>0)return s(process.stdout.columns);if(process.platform==="win32"){let n=Bt();if(n)return s(n)}let t=At();return t?s(t):null}function Dt(s){return s.replace(Et,"")}function Je(s){return Dt(s).length}var te=class{constructor(e){this.config=e;this.symbols=this.initializeSymbols();}symbols;_usageProvider;_blockProvider;_todayProvider;_contextProvider;_gitService;_tmuxService;_metricsProvider;_segmentRenderer;get usageProvider(){return this._usageProvider||(this._usageProvider=new M),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new Z),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new Q),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new U(this.config)),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new D),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new F),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new L),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new I(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id,e):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,o=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,r=this.needsSegmentInfo("context")?await this.contextProvider.getContextInfo(e):null,i=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id,e):null;return this.config.display.autoWrap?this.generateAutoWrapStatusline(e,t,n,o,r,i):(await Promise.all(this.config.display.lines.map(c=>this.renderLine(c,e,t,n,o,r,i)))).filter(c=>c.length>0).join(`
8
- `)}async generateAutoWrapStatusline(e,t,n,o,r,i){let a=this.getThemeColors(),c=e.workspace?.current_dir||e.cwd||"/",g=Ye(),u=[];for(let m of this.config.display.lines){let f=Object.entries(m.segments).filter(([y,b])=>b?.enabled).map(([y,b])=>({type:y,config:b})),d=[];for(let y of f){let b=await this.renderSegment(y,e,t,n,o,r,i,a,c);b&&d.push({type:y.type,text:b.text,bgColor:b.bgColor,fgColor:b.fgColor});}if(d.length===0)continue;if(!g||g<=0){u.push(this.buildLineFromSegments(d,a));continue}let h=[],p=0;for(let y of d){let b=this.calculateSegmentWidth(y,h.length===0);h.length>0&&p+b>g&&(u.push(this.buildLineFromSegments(h,a)),h=[],p=0),h.push(y),p+=b;}h.length>0&&u.push(this.buildLineFromSegments(h,a));}return u.join(`
9
- `)}calculateSegmentWidth(e,t){let n=this.config.display.style==="capsule",o=Je(e.text),i=(this.config.display.padding??1)*2;if(n){let c=2+i+(t?0:1);return o+c}let a=1+i;return o+a}buildLineFromSegments(e,t){let n=this.config.display.style==="capsule",o=t.reset;for(let r=0;r<e.length;r++){let i=e[r];if(!i)continue;let a=r===0,c=r===e.length-1,g=c?null:e[r+1],u=g?this.getSegmentBgColor(g.type,t):"";n&&!a&&(o+=" "),o+=this.formatSegment(i.bgColor,i.fgColor,i.text,c?void 0:u,t);}return o}async renderLine(e,t,n,o,r,i,a){let c=this.getThemeColors(),g=t.workspace?.current_dir||t.cwd||"/",u=Object.entries(e.segments).filter(([d,h])=>h?.enabled).map(([d,h])=>({type:d,config:h})),m=this.config.display.style==="capsule",f=c.reset;for(let d=0;d<u.length;d++){let h=u[d];if(!h)continue;let p=d===0,y=d===u.length-1,b=y?null:u[d+1],$=b?this.getSegmentBgColor(b.type,c):"",C=await this.renderSegment(h,t,n,o,r,i,a,c,g);C&&(m&&!p&&(f+=" "),f+=this.formatSegment(C.bgColor,C.fgColor,C.text,y?void 0:$,c));}return f}async renderSegment(e,t,n,o,r,i,a,c,g){return e.type==="directory"?this.segmentRenderer.renderDirectory(t,c,e.config):e.type==="model"?this.segmentRenderer.renderModel(t,c):e.type==="git"?await this.renderGitSegment(e.config,t,c,g):e.type==="session"?this.renderSessionSegment(e.config,n,c):e.type==="tmux"?await this.renderTmuxSegment(c):e.type==="context"?this.renderContextSegment(e.config,i,c):e.type==="metrics"?this.renderMetricsSegment(e.config,a,o,c):e.type==="block"?this.renderBlockSegment(e.config,o,c):e.type==="today"?this.renderTodaySegment(e.config,r,c):e.type==="version"?this.renderVersionSegment(e.config,t,c):null}async renderGitSegment(e,t,n,o){if(!this.needsSegmentInfo("git"))return null;let r=await this.gitService.getGitInfo(o,{showSha:e?.showSha,showWorkingTree:e?.showWorkingTree,showOperation:e?.showOperation,showTag:e?.showTag,showTimeSinceCommit:e?.showTimeSinceCommit,showStashCount:e?.showStashCount,showUpstream:e?.showUpstream,showRepoName:e?.showRepoName},t.workspace?.project_dir);return r?this.segmentRenderer.renderGit(r,n,e):null}renderSessionSegment(e,t,n){return t?this.segmentRenderer.renderSession(t,n,e):null}async renderTmuxSegment(e){if(!this.needsSegmentInfo("tmux"))return null;let t=await this.tmuxService.getSessionId();return this.segmentRenderer.renderTmux(t,e)}renderContextSegment(e,t,n){return this.needsSegmentInfo("context")?this.segmentRenderer.renderContext(t,n,e):null}renderMetricsSegment(e,t,n,o){return this.segmentRenderer.renderMetrics(t,o,n,e)}renderBlockSegment(e,t,n){return t?this.segmentRenderer.renderBlock(t,n,e):null}renderTodaySegment(e,t,n){if(!t)return null;let o=e?.type||"cost";return this.segmentRenderer.renderToday(t,n,o)}renderVersionSegment(e,t,n){return this.segmentRenderer.renderVersion(t,n,e)}initializeSymbols(){let e=this.config.display.style,t=this.config.display.charset||"unicode",n=e==="minimal",o=e==="capsule",r=t==="text"?Ve:Ge;return {right:n?"":o?r.right_rounded:r.right,left:o?r.left_rounded:"",branch:r.branch,model:r.model,git_clean:r.git_clean,git_dirty:r.git_dirty,git_conflicts:r.git_conflicts,git_ahead:r.git_ahead,git_behind:r.git_behind,git_worktree:r.git_worktree,git_tag:r.git_tag,git_sha:r.git_sha,git_upstream:r.git_upstream,git_stash:r.git_stash,git_time:r.git_time,session_cost:r.session_cost,block_cost:r.block_cost,today_cost:r.today_cost,context_time:r.context_time,metrics_response:r.metrics_response,metrics_last_response:r.metrics_last_response,metrics_duration:r.metrics_duration,metrics_messages:r.metrics_messages,metrics_lines_added:r.metrics_lines_added,metrics_lines_removed:r.metrics_lines_removed,metrics_burn:r.metrics_burn,version:r.version,bar_filled:r.bar_filled,bar_empty:r.bar_empty}}getThemeColors(){let e=this.config.theme,t,n=this.config.display.colorCompatibility||"auto",o=n==="auto"?H():n;if(e==="custom"){if(t=this.config.colors?.custom,!t)throw new Error("Custom theme selected but no colors provided in configuration")}else t=W(e,o),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=W("dark",o));let r=W("dark",o),i=C=>{let k=t[C]||r[C];return o==="none"?{bg:"",fg:""}:o==="ansi"?{bg:ae(k.bg,true),fg:ae(k.fg,false)}:o==="ansi256"?{bg:ie(k.bg,true),fg:ie(k.fg,false)}:{bg:se(k.bg,true),fg:se(k.fg,false)}},a=i("directory"),c=i("git"),g=i("model"),u=i("session"),m=i("block"),f=i("today"),d=i("tmux"),h=i("context"),p=i("contextWarning"),y=i("contextCritical"),b=i("metrics"),$=i("version");return {reset:o==="none"?"":We,modeBg:a.bg,modeFg:a.fg,gitBg:c.bg,gitFg:c.fg,modelBg:g.bg,modelFg:g.fg,sessionBg:u.bg,sessionFg:u.fg,blockBg:m.bg,blockFg:m.fg,todayBg:f.bg,todayFg:f.fg,tmuxBg:d.bg,tmuxFg:d.fg,contextBg:h.bg,contextFg:h.fg,contextWarningBg:p.bg,contextWarningFg:p.fg,contextCriticalBg:y.bg,contextCriticalFg:y.fg,metricsBg:b.bg,metricsFg:b.fg,versionBg:$.bg,versionFg:$.fg}}getSegmentBgColor(e,t){switch(e){case "directory":return t.modeBg;case "git":return t.gitBg;case "model":return t.modelBg;case "session":return t.sessionBg;case "block":return t.blockBg;case "today":return t.todayBg;case "tmux":return t.tmuxBg;case "context":return t.contextBg;case "metrics":return t.metricsBg;case "version":return t.versionBg;default:return t.modeBg}}formatSegment(e,t,n,o,r){let i=this.config.display.style==="capsule",a=" ".repeat(this.config.display.padding??1);if(i){let f=this.config.display.colorCompatibility||"auto",h=(f==="auto"?H():f)==="ansi",p=j(e,h),y=`${p}${this.symbols.left}${r.reset}`,b=`${e}${t}${a}${n}${a}${r.reset}`,$=`${p}${this.symbols.right}${r.reset}`;return `${y}${b}${$}`}let c=`${e}${t}${a}${n}${a}`,g=this.config.display.colorCompatibility||"auto",m=(g==="auto"?H():g)==="ansi";if(o){let f=j(e,m);c+=`${r.reset}${o}${f}${this.symbols.right}`;}else c+=`${r.reset}${j(e,m)}${this.symbols.right}${r.reset}`;return c}};var ze={theme:"dark",display:{style:"minimal",charset:"unicode",colorCompatibility:"auto",autoWrap:true,padding:1,lines:[{segments:{directory:{enabled:true,style:"basename"},git:{enabled:true,showSha:false,showWorkingTree:false,showOperation:false,showTag:false,showTimeSinceCommit:false,showStashCount:false,showUpstream:false,showRepoName:false},model:{enabled:true},session:{enabled:true,type:"tokens",costSource:"calculated"},today:{enabled:true,type:"cost"},block:{enabled:false,type:"cost",burnType:"cost"},version:{enabled:false},tmux:{enabled:false},context:{enabled:true,showPercentageOnly:false,displayStyle:"text"},metrics:{enabled:false,showResponseTime:true,showLastResponseTime:true,showDuration:true,showMessageCount:true,showLinesAdded:true,showLinesRemoved:true}}}]},budget:{session:{warningThreshold:80},today:{warningThreshold:80,amount:50},block:{warningThreshold:80,amount:15}},modelContextLimits:{default:2e5,sonnet:2e5,opus:2e5}};function pe(s){return ["light","dark","nord","tokyo-night","rose-pine","gruvbox","custom"].includes(s)}function be(s){return s==="minimal"||s==="powerline"||s==="capsule"}function qe(s){return s==="unicode"||s==="text"}function re(s,e){for(let t=0;t<s.length;t++){let n=s[t];if(n===e&&t+1<s.length)return s[t+1];if(n?.startsWith(`${e}=`))return n.split("=")[1]}}function oe(s,e){let t={...s};for(let n in e){let o=e[n];if(o!==void 0)if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let r=t[n]||{};t[n]=oe(r,o);}else t[n]=o;}return t}function Ft(s,e){return s?w.existsSync(s)?s:null:[...e?[_.join(e,".claude-powerline.json")]:[],_.join(process.cwd(),".claude-powerline.json"),_.join(he.homedir(),".claude","claude-powerline.json"),_.join(he.homedir(),".config","claude-powerline","config.json")].find(w.existsSync)||null}function Mt(s){try{let e=w.readFileSync(s,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${s}: ${e instanceof Error?e.message:String(e)}`)}}function Ut(){let s={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&pe(t)&&(s.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(be(n)?e.style=n:(console.warn(`Invalid display style '${n}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(s.display=e),s}function Lt(){return process.env.CLAUDE_POWERLINE_CONFIG}function It(s){let e={},t={},n=re(s,"--theme");n&&pe(n)&&(e.theme=n);let o=re(s,"--style");o&&(be(o)?t.style=o:(console.warn(`Invalid display style '${o}' from CLI argument, falling back to 'minimal'`),t.style="minimal"));let r=re(s,"--charset");return r&&(qe(r)?t.charset=r:(console.warn(`Invalid charset '${r}' from CLI argument, falling back to 'unicode'`),t.charset="unicode")),Object.keys(t).length>0&&(e.display=t),e}function Ot(s=process.argv,e){let t=JSON.parse(JSON.stringify(ze)),n=re(s,"--config")||Lt(),o=n?.startsWith("~")?n.replace("~",he.homedir()):n,r=Ft(o,e);if(r)try{let c=Mt(r);t=oe(t,c);}catch(c){console.warn(`Warning: ${c instanceof Error?c.message:String(c)}`);}t.display?.style&&!be(t.display.style)&&(console.warn(`Invalid display style '${t.display.style}' in config file, falling back to 'minimal'`),t.display.style="minimal"),t.display?.charset&&!qe(t.display.charset)&&(console.warn(`Invalid charset '${t.display.charset}' in config file, falling back to 'unicode'`),t.display.charset="unicode"),t.theme&&!pe(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let i=Ut();t=oe(t,i);let a=It(s);return t=oe(t,a),t}var Xe=Ot;function Ke(){console.log(`
2
+ import w from'process';import {json}from'stream/consumers';import N from'tty';import {exec,execSync}from'child_process';import {promisify}from'util';import _,{existsSync,readFileSync,createReadStream}from'fs';import C,{join,posix,dirname}from'path';import {get}from'https';import {URL}from'url';import pe,{homedir}from'os';import {createHash}from'crypto';import {setTimeout}from'timers/promises';import {readdir,stat,readFile}from'fs/promises';import {createInterface}from'readline';function se(s,e){if(e&&(s.toLowerCase()==="transparent"||s.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),r=parseInt(s.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${n};${r}m`}function j(s,e=false){if(!s||s==="")return "";let t=s.match(/48;2;(\d+);(\d+);(\d+)/);if(t)return `\x1B[38;2;${t[1]};${t[2]};${t[3]}m`;if(e)return "\x1B[37m";if(s.includes("\x1B[")&&s.includes("m")){let n=s.match(/\[(\d+)m/);if(n&&n[1]){let r=parseInt(n[1],10);if(r>=40&&r<=47)return `\x1B[${r-10}m`;if(r>=100&&r<=107)return `\x1B[${r-10}m`}}return s.replace("48","38")}function H(){let{env:s}=w,e=true;s.NO_COLOR&&s.NO_COLOR!==""&&(e=false);let t=s.FORCE_COLOR;if(t&&t!=="")return t==="false"||t==="0"?"none":t==="true"||t==="1"?"ansi":t==="2"?"ansi256":t==="3"?"truecolor":"ansi";if(!e||s.TERM==="dumb")return "none";if(s.CI)return ["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(r=>r in s)?"truecolor":"ansi";if(s.COLORTERM==="truecolor"||["xterm-kitty","xterm-ghostty","wezterm","alacritty","foot","contour"].includes(s.TERM||""))return "truecolor";if(s.TERM_PROGRAM)switch(s.TERM_PROGRAM){case "iTerm.app":return "truecolor";case "Apple_Terminal":return "ansi256";case "vscode":return "truecolor";case "Tabby":return "truecolor"}if(/-256(color)?$/i.test(s.TERM||""))return "ansi256";if(/-truecolor$/i.test(s.TERM||""))return "truecolor";if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(s.TERM||"")||s.COLORTERM)return "ansi";if(N?.WriteStream?.prototype?.hasColors)try{if(!N.WriteStream.prototype.hasColors())return "none";let o=N.WriteStream.prototype.hasColors(256);return N.WriteStream.prototype.hasColors(16777216)?"truecolor":o?"ansi256":"ansi"}catch{}return "ansi"}function ie(s,e){if(e&&(s.toLowerCase()==="transparent"||s.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),r=parseInt(s.slice(5,7),16),i=((a,c,g)=>a===c&&c===g?a<8?16:a>248?231:Math.round((a-8)/247*24)+232:16+36*Math.round(a/255*5)+6*Math.round(c/255*5)+Math.round(g/255*5))(t,n,r);return `\x1B[${e?"48":"38"};5;${i}m`}function ae(s,e){if(e&&(s.toLowerCase()==="transparent"||s.toLowerCase()==="none"))return "\x1B[49m";if(e)return "";let t=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),r=parseInt(s.slice(5,7),16);return n>t&&n>r&&n>120?"\x1B[32m":t>n&&t>r&&t>120?"\x1B[31m":r>t&&r>n&&r>120?"\x1B[34m":(t+n+r)/3>150?"\x1B[37m":"\x1B[90m"}var ye={directory:{bg:"#8b4513",fg:"#ffffff"},git:{bg:"#404040",fg:"#ffffff"},model:{bg:"#2d2d2d",fg:"#ffffff"},session:{bg:"#202020",fg:"#00ffff"},block:{bg:"#2a2a2a",fg:"#87ceeb"},today:{bg:"#1a1a1a",fg:"#98fb98"},tmux:{bg:"#2f4f2f",fg:"#90ee90"},context:{bg:"#4a5568",fg:"#cbd5e0"},contextWarning:{bg:"#92400e",fg:"#fbbf24"},contextCritical:{bg:"#991b1b",fg:"#fca5a5"},metrics:{bg:"#374151",fg:"#d1d5db"},version:{bg:"#3a3a4a",fg:"#b8b8d0"}},Ce={directory:{bg:"#af5f00",fg:"#ffffff"},git:{bg:"#444444",fg:"#ffffff"},model:{bg:"#3a3a3a",fg:"#ffffff"},session:{bg:"#262626",fg:"#00ffff"},block:{bg:"#303030",fg:"#87ceeb"},today:{bg:"#1c1c1c",fg:"#87ff87"},tmux:{bg:"#444444",fg:"#87ff87"},context:{bg:"#585858",fg:"#d0d0d0"},contextWarning:{bg:"#af5f00",fg:"#ffaf00"},contextCritical:{bg:"#870000",fg:"#ff8787"},metrics:{bg:"#4e4e4e",fg:"#d0d0d0"},version:{bg:"#444444",fg:"#d7afff"}},_e={directory:{bg:"#d75f00",fg:"#ffffff"},git:{bg:"#585858",fg:"#ffffff"},model:{bg:"#444444",fg:"#ffffff"},session:{bg:"#303030",fg:"#00ffff"},block:{bg:"#3a3a3a",fg:"#5fafff"},today:{bg:"#262626",fg:"#00ff00"},tmux:{bg:"#585858",fg:"#00ff00"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d75f00",fg:"#ffff00"},contextCritical:{bg:"#af0000",fg:"#ff0000"},metrics:{bg:"#666666",fg:"#ffffff"},version:{bg:"#585858",fg:"#af87ff"}};var we={directory:{bg:"#ff6b47",fg:"#ffffff"},git:{bg:"#4fb3d9",fg:"#ffffff"},model:{bg:"#87ceeb",fg:"#000000"},session:{bg:"#da70d6",fg:"#ffffff"},block:{bg:"#6366f1",fg:"#ffffff"},today:{bg:"#10b981",fg:"#ffffff"},tmux:{bg:"#32cd32",fg:"#ffffff"},context:{bg:"#718096",fg:"#ffffff"},contextWarning:{bg:"#d97706",fg:"#ffffff"},contextCritical:{bg:"#dc2626",fg:"#ffffff"},metrics:{bg:"#6b7280",fg:"#ffffff"},version:{bg:"#8b7dd8",fg:"#ffffff"}},xe={directory:{bg:"#ff5f5f",fg:"#ffffff"},git:{bg:"#5fafff",fg:"#ffffff"},model:{bg:"#87d7ff",fg:"#000000"},session:{bg:"#ff5fff",fg:"#ffffff"},block:{bg:"#5f5fff",fg:"#ffffff"},today:{bg:"#00d787",fg:"#ffffff"},tmux:{bg:"#00ff5f",fg:"#ffffff"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d78700",fg:"#ffffff"},contextCritical:{bg:"#d70000",fg:"#ffffff"},metrics:{bg:"#767676",fg:"#ffffff"},version:{bg:"#af87ff",fg:"#ffffff"}},ke={directory:{bg:"#ff5f5f",fg:"#ffffff"},git:{bg:"#5fafff",fg:"#ffffff"},model:{bg:"#87d7ff",fg:"#000000"},session:{bg:"#ff5fff",fg:"#ffffff"},block:{bg:"#5f5fff",fg:"#ffffff"},today:{bg:"#00d787",fg:"#ffffff"},tmux:{bg:"#00ff5f",fg:"#ffffff"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d78700",fg:"#ffffff"},contextCritical:{bg:"#d70000",fg:"#ffffff"},metrics:{bg:"#767676",fg:"#ffffff"},version:{bg:"#af87ff",fg:"#ffffff"}};var Se={directory:{bg:"#434c5e",fg:"#d8dee9"},git:{bg:"#3b4252",fg:"#a3be8c"},model:{bg:"#4c566a",fg:"#81a1c1"},session:{bg:"#2e3440",fg:"#88c0d0"},block:{bg:"#3b4252",fg:"#81a1c1"},today:{bg:"#2e3440",fg:"#8fbcbb"},tmux:{bg:"#2e3440",fg:"#8fbcbb"},context:{bg:"#5e81ac",fg:"#eceff4"},contextWarning:{bg:"#d08770",fg:"#2e3440"},contextCritical:{bg:"#bf616a",fg:"#eceff4"},metrics:{bg:"#b48ead",fg:"#2e3440"},version:{bg:"#434c5e",fg:"#88c0d0"}},Te={directory:{bg:"#5f87af",fg:"#e4e4e4"},git:{bg:"#4e4e4e",fg:"#87d787"},model:{bg:"#6c6c6c",fg:"#87afd7"},session:{bg:"#3a3a3a",fg:"#5fafaf"},block:{bg:"#4e4e4e",fg:"#87afd7"},today:{bg:"#3a3a3a",fg:"#5fd7d7"},tmux:{bg:"#3a3a3a",fg:"#5fd7d7"},context:{bg:"#5f87d7",fg:"#ffffff"},contextWarning:{bg:"#d7875f",fg:"#3a3a3a"},contextCritical:{bg:"#d75f5f",fg:"#ffffff"},metrics:{bg:"#d787af",fg:"#3a3a3a"},version:{bg:"#5f87af",fg:"#5fafaf"}},ve={directory:{bg:"#0087af",fg:"#ffffff"},git:{bg:"#585858",fg:"#87d700"},model:{bg:"#808080",fg:"#87afff"},session:{bg:"#444444",fg:"#00d7d7"},block:{bg:"#585858",fg:"#87afff"},today:{bg:"#444444",fg:"#00ffff"},tmux:{bg:"#444444",fg:"#00ffff"},context:{bg:"#0087ff",fg:"#ffffff"},contextWarning:{bg:"#d78700",fg:"#000000"},contextCritical:{bg:"#d75f5f",fg:"#ffffff"},metrics:{bg:"#ff87d7",fg:"#444444"},version:{bg:"#0087af",fg:"#00d7d7"}};var Pe={directory:{bg:"#2f334d",fg:"#82aaff"},git:{bg:"#1e2030",fg:"#c3e88d"},model:{bg:"#191b29",fg:"#fca7ea"},session:{bg:"#222436",fg:"#86e1fc"},block:{bg:"#2d3748",fg:"#7aa2f7"},today:{bg:"#1a202c",fg:"#4fd6be"},tmux:{bg:"#191b29",fg:"#4fd6be"},context:{bg:"#414868",fg:"#c0caf5"},contextWarning:{bg:"#ff9e64",fg:"#1a1b26"},contextCritical:{bg:"#f7768e",fg:"#1a1b26"},metrics:{bg:"#3d59a1",fg:"#c0caf5"},version:{bg:"#292e42",fg:"#bb9af7"}},Ee={directory:{bg:"#444478",fg:"#87afff"},git:{bg:"#262640",fg:"#afff87"},model:{bg:"#1c1c30",fg:"#ff87ff"},session:{bg:"#3a3a50",fg:"#5fd7ff"},block:{bg:"#4e4e68",fg:"#5f87ff"},today:{bg:"#262640",fg:"#00d7af"},tmux:{bg:"#1c1c30",fg:"#00d7af"},context:{bg:"#5f5f87",fg:"#d7d7ff"},contextWarning:{bg:"#ffaf5f",fg:"#262626"},contextCritical:{bg:"#ff5f87",fg:"#262626"},metrics:{bg:"#5f5faf",fg:"#d7d7ff"},version:{bg:"#444460",fg:"#d787ff"}},$e={directory:{bg:"#5f5faf",fg:"#87afff"},git:{bg:"#303050",fg:"#87ff87"},model:{bg:"#262640",fg:"#ff87ff"},session:{bg:"#444470",fg:"#00d7ff"},block:{bg:"#666680",fg:"#5f87ff"},today:{bg:"#303050",fg:"#00d787"},tmux:{bg:"#262640",fg:"#00d787"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#ffaf00",fg:"#000000"},contextCritical:{bg:"#ff5f5f",fg:"#000000"},metrics:{bg:"#8787d7",fg:"#ffffff"},version:{bg:"#585870",fg:"#d787ff"}};var Re={directory:{bg:"#26233a",fg:"#c4a7e7"},git:{bg:"#1f1d2e",fg:"#9ccfd8"},model:{bg:"#191724",fg:"#ebbcba"},session:{bg:"#26233a",fg:"#f6c177"},block:{bg:"#2a273f",fg:"#eb6f92"},today:{bg:"#232136",fg:"#9ccfd8"},tmux:{bg:"#26233a",fg:"#908caa"},context:{bg:"#393552",fg:"#e0def4"},contextWarning:{bg:"#f6c177",fg:"#191724"},contextCritical:{bg:"#eb6f92",fg:"#191724"},metrics:{bg:"#524f67",fg:"#e0def4"},version:{bg:"#2a273f",fg:"#c4a7e7"}},Be={directory:{bg:"#444444",fg:"#d787d7"},git:{bg:"#262626",fg:"#87d7d7"},model:{bg:"#1c1c1c",fg:"#ffaf87"},session:{bg:"#444444",fg:"#d7af5f"},block:{bg:"#4e4e4e",fg:"#ff5f87"},today:{bg:"#3a3a3a",fg:"#87d7d7"},tmux:{bg:"#444444",fg:"#9e9e9e"},context:{bg:"#585858",fg:"#e4e4e4"},contextWarning:{bg:"#d7af5f",fg:"#1c1c1c"},contextCritical:{bg:"#ff5f87",fg:"#1c1c1c"},metrics:{bg:"#767676",fg:"#e4e4e4"},version:{bg:"#4e4e4e",fg:"#d787d7"}},Ae={directory:{bg:"#585858",fg:"#ff87ff"},git:{bg:"#303030",fg:"#00d7d7"},model:{bg:"#262626",fg:"#ffaf87"},session:{bg:"#585858",fg:"#d7af00"},block:{bg:"#666666",fg:"#ff5f87"},today:{bg:"#444444",fg:"#00d7d7"},tmux:{bg:"#585858",fg:"#bcbcbc"},context:{bg:"#808080",fg:"#ffffff"},contextWarning:{bg:"#d7af00",fg:"#000000"},contextCritical:{bg:"#ff5f5f",fg:"#000000"},metrics:{bg:"#a8a8a8",fg:"#000000"},version:{bg:"#666666",fg:"#ff87ff"}};var De={directory:{bg:"#504945",fg:"#ebdbb2"},git:{bg:"#3c3836",fg:"#b8bb26"},model:{bg:"#665c54",fg:"#83a598"},session:{bg:"#282828",fg:"#8ec07c"},block:{bg:"#3c3836",fg:"#83a598"},today:{bg:"#282828",fg:"#fabd2f"},tmux:{bg:"#282828",fg:"#fe8019"},context:{bg:"#458588",fg:"#ebdbb2"},contextWarning:{bg:"#d79921",fg:"#282828"},contextCritical:{bg:"#cc241d",fg:"#ebdbb2"},metrics:{bg:"#d3869b",fg:"#282828"},version:{bg:"#504945",fg:"#8ec07c"}},Fe={directory:{bg:"#585858",fg:"#ffffaf"},git:{bg:"#444444",fg:"#afaf00"},model:{bg:"#6c6c6c",fg:"#87afaf"},session:{bg:"#303030",fg:"#87af87"},block:{bg:"#444444",fg:"#87afaf"},today:{bg:"#303030",fg:"#ffaf00"},tmux:{bg:"#303030",fg:"#ff8700"},context:{bg:"#5f8787",fg:"#ffffaf"},contextWarning:{bg:"#d7af00",fg:"#303030"},contextCritical:{bg:"#d70000",fg:"#ffffaf"},metrics:{bg:"#d787af",fg:"#303030"},version:{bg:"#585858",fg:"#87af87"}},Me={directory:{bg:"#808080",fg:"#ffff00"},git:{bg:"#585858",fg:"#00ff00"},model:{bg:"#808080",fg:"#00afff"},session:{bg:"#444444",fg:"#00d787"},block:{bg:"#585858",fg:"#00afff"},today:{bg:"#444444",fg:"#ffaf00"},tmux:{bg:"#444444",fg:"#ff8700"},context:{bg:"#008787",fg:"#ffffff"},contextWarning:{bg:"#d7af00",fg:"#000000"},contextCritical:{bg:"#d70000",fg:"#ffffff"},metrics:{bg:"#ff87af",fg:"#444444"},version:{bg:"#808080",fg:"#00d787"}};var ce={dark:ye,"dark-ansi256":Ce,"dark-ansi":_e,light:we,"light-ansi256":xe,"light-ansi":ke,nord:Se,"nord-ansi256":Te,"nord-ansi":ve,"tokyo-night":Pe,"tokyo-night-ansi256":Ee,"tokyo-night-ansi":$e,"rose-pine":Re,"rose-pine-ansi256":Be,"rose-pine-ansi":Ae,gruvbox:De,"gruvbox-ansi256":Fe,"gruvbox-ansi":Me};function W(s,e){let t=ce[s];if(!t)return null;if(e==="none"||e==="ansi"){let n=ce[`${s}-ansi`];if(n)return n}if(e==="ansi256"){let n=ce[`${s}-ansi256`];if(n)return n}return t}var l=(s,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${s}`,...e);};var nt=promisify(exec),D=class{isGitRepo(e){try{return _.existsSync(C.join(e,".git"))}catch{return false}}async execGitAsync(e,t){return nt(e,{...t,env:{...process.env,GIT_OPTIONAL_LOCKS:"0"}})}async findGitRoot(e){try{return (await this.execGitAsync("git rev-parse --show-toplevel",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getGitInfo(e,t={},n){let r;if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else {let o=await this.findGitRoot(e);if(!o)return null;r=o;}try{let o=await this.getStatusWithBranchAsync(r),i=await this.getAheadBehindAsync(r),a={branch:o.branch||"detached",status:o.status,ahead:i.ahead,behind:i.behind};t.showWorkingTree&&o.workingTree&&(a.staged=o.workingTree.staged,a.unstaged=o.workingTree.unstaged,a.untracked=o.workingTree.untracked,a.conflicts=o.workingTree.conflicts);let c={},g={};t.showSha&&(c.sha=this.getShaAsync(r)),t.showTag&&(c.tag=this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(c.timeSinceCommit=this.getTimeSinceLastCommitAsync(r)),t.showStashCount&&(g.stashCount=this.getStashCountAsync(r)),t.showUpstream&&(g.upstream=this.getUpstreamAsync(r)),t.showRepoName&&(g.repoName=this.getRepoNameAsync(r));let u=new Map;for(let[m,f]of Object.entries(c))try{let d=await f;u.set(m,d);}catch{}return Object.keys(g).length>0&&(await Promise.allSettled(Object.entries(g).map(async([f,d])=>({key:f,value:await d})))).forEach(f=>{f.status==="fulfilled"&&u.set(f.value.key,f.value.value);}),t.showSha&&(a.sha=u.get("sha")||void 0),t.showOperation&&(a.operation=this.getOngoingOperation(r)||void 0),t.showTag&&(a.tag=u.get("tag")||void 0),t.showTimeSinceCommit&&(a.timeSinceCommit=u.get("timeSinceCommit")||void 0),t.showStashCount&&(a.stashCount=u.get("stashCount")||0),t.showUpstream&&(a.upstream=u.get("upstream")||void 0),t.showRepoName&&(a.repoName=u.get("repoName")||void 0,a.isWorktree=this.isWorktree(r)),a}catch{return null}}async getShaAsync(e){try{return (await this.execGitAsync("git rev-parse --short=7 HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}getOngoingOperation(e){try{let t=C.join(e,".git");return _.existsSync(C.join(t,"MERGE_HEAD"))?"MERGE":_.existsSync(C.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":_.existsSync(C.join(t,"REVERT_HEAD"))?"REVERT":_.existsSync(C.join(t,"BISECT_LOG"))?"BISECT":_.existsSync(C.join(t,"rebase-merge"))||_.existsSync(C.join(t,"rebase-apply"))?"REBASE":null}catch{return null}}async getNearestTagAsync(e){try{return (await this.execGitAsync("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getTimeSinceLastCommitAsync(e){try{let n=(await this.execGitAsync("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!n)return null;let r=parseInt(n)*1e3,o=Date.now();return Math.floor((o-r)/1e3)}catch{return null}}async getStashCountAsync(e){try{let n=(await this.execGitAsync("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.split(`
3
+ `).length:0}catch{return 0}}async getUpstreamAsync(e){try{return (await this.execGitAsync("git rev-parse --abbrev-ref @{u}",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getRepoNameAsync(e){try{let n=(await this.execGitAsync("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.match(/\/([^/]+?)(\.git)?$/)?.[1]||C.basename(e):C.basename(e)}catch{return C.basename(e)}}isWorktree(e){try{let t=C.join(e,".git");return !!(_.existsSync(t)&&_.statSync(t).isFile())}catch{return false}}async getStatusWithBranchAsync(e){try{l(`[GIT-EXEC] Running git status in ${e}`);let r=(await this.execGitAsync("git status --porcelain -b",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.split(`
4
+ `),o=null,i="clean",a=0,c=0,g=0,u=0;for(let m of r)if(m){if(m.startsWith("## ")){let d=m.substring(3).split("...")[0];d&&d!=="HEAD (no branch)"&&(o=d);continue}if(m.length>=2){let f=m.charAt(0),d=m.charAt(1);if(f==="?"&&d==="?"){g++,i==="clean"&&(i="dirty");continue}let p=f+d;if(["DD","AU","UD","UA","DU","AA","UU"].includes(p)){u++,i="conflicts";continue}f!==" "&&f!=="?"&&(a++,i==="clean"&&(i="dirty")),d!==" "&&d!=="?"&&(c++,i==="clean"&&(i="dirty"));}}return {branch:o||await this.getFallbackBranch(e),status:i,workingTree:{staged:a,unstaged:c,untracked:g,conflicts:u}}}catch(t){return l(`Git status with branch command failed in ${e}:`,t),{branch:await this.getFallbackBranch(e),status:"clean"}}}async getFallbackBranch(e){try{let n=(await this.execGitAsync("git branch --show-current",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{try{let n=(await this.execGitAsync("git symbolic-ref --short HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{return null}}return null}async getAheadBehindAsync(e){try{l(`[GIT-EXEC] Running git ahead/behind in ${e}`);let[t,n]=await Promise.all([this.execGitAsync("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:2e3}),this.execGitAsync("git rev-list --count HEAD..@{u}",{cwd:e,encoding:"utf8",timeout:2e3})]);return {ahead:parseInt(t.stdout.trim())||0,behind:parseInt(n.stdout.trim())||0}}catch(t){return l(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}};var st=promisify(exec),F=class{async getSessionId(){try{if(!process.env.TMUX_PANE)return l("TMUX_PANE not set, not in tmux session"),null;l(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let t=(await st("tmux display-message -p '#S'",{encoding:"utf8",timeout:1e3})).stdout.trim();return l(`Tmux session ID: ${t||"empty"}`),t||null}catch(e){return l("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};function V(){let s=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let n=t.trim();existsSync(n)&&s.push(n);}),s.length===0){let t=homedir(),n=join(t,".config","claude"),r=join(t,".claude");existsSync(n)&&s.push(n),existsSync(r)&&s.push(r);}return s}async function Y(s){let e=[];for(let t of s){let n=join(t,"projects");if(existsSync(n))try{let r=await readdir(n,{withFileTypes:!0});for(let o of r)if(o.isDirectory()){let i=posix.join(n,o.name);e.push(i);}}catch(r){l(`Failed to read projects directory ${n}:`,r);}}return e}async function J(s){let e=V(),t=await Y(e);for(let n of t){let r=posix.join(n,`${s}.jsonl`);if(existsSync(r))return r}return null}async function Ie(s,e){let t=[];try{let r=(await readdir(e)).filter(o=>o.startsWith("agent-")&&o.endsWith(".jsonl"));for(let o of r){let i=posix.join(e,o);try{let c=(await readFile(i,"utf-8")).split(`
5
+ `)[0];c&&JSON.parse(c).sessionId===s&&t.push(i);}catch{l(`Failed to check agent file ${i}`);}}}catch(n){l(`Failed to read project directory ${e}:`,n);}return t}async function ue(s){try{return (await stat(s)).mtime}catch{return null}}function lt(s){let e=s.message?.id||(typeof s.raw.message=="object"&&s.raw.message!==null&&"id"in s.raw.message?s.raw.message.id:void 0),t="requestId"in s.raw?s.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var gt=1024*1024;async function R(s){try{let t=(await stat(s)).size,n;return t>gt?(l(`Using streaming parser for large file ${s} (${Math.round(t/1024)}KB)`),n=await ft(s)):n=await ut(s),l(`Parsed ${n.length} entries from ${s}`),n}catch(e){return l(`Failed to read file ${s}:`,e),[]}}async function ut(s){let t=(await readFile(s,"utf-8")).trim().split(`
6
+ `).filter(r=>r.trim()),n=[];for(let r of t)try{let o=JSON.parse(r);if(!o.timestamp)continue;let i={timestamp:new Date(o.timestamp),message:o.message,costUSD:typeof o.costUSD=="number"?o.costUSD:void 0,isSidechain:o.isSidechain===!0,raw:o};n.push(i);}catch(o){l(`Failed to parse JSONL line: ${o}`);continue}return n}async function ft(s){return new Promise((e,t)=>{let n=[],r=createReadStream(s,{encoding:"utf8"}),o=createInterface({input:r,crlfDelay:1/0});o.on("line",i=>{let a=i.trim();if(a)try{let c=JSON.parse(a);if(!c.timestamp)return;let g={timestamp:new Date(c.timestamp),message:c.message,costUSD:typeof c.costUSD=="number"?c.costUSD:void 0,isSidechain:c.isSidechain===!0,raw:c};n.push(g);}catch(c){l(`Failed to parse JSONL line: ${c}`);}}),o.on("close",()=>{e(n);}),o.on("error",i=>{l(`Streaming parser error for ${s}:`,i),t(i);}),r.on("error",i=>{l(`File stream error for ${s}:`,i),t(i);});})}async function z(s,e,t=false){let n=V(),r=await Y(n),o=new Set,i=r.map(async p=>{try{let b=(await readdir(p)).filter(x=>x.endsWith(".jsonl")).map(async x=>{let k=posix.join(p,x);if(existsSync(k)){let Ze=await ue(k);return {filePath:k,mtime:Ze}}return null});return (await Promise.all(b)).filter(x=>x?.mtime&&(!e||e(x.filePath,x.mtime)))}catch(h){return l(`Failed to read project directory ${p}:`,h),[]}}),c=(await Promise.all(i)).flat().filter(p=>p!==null);t&&c.sort((p,h)=>h.mtime.getTime()-p.mtime.getTime());let g=c.map(p=>p.filePath),u=[],m=g.map(async p=>(await R(p)).filter(y=>!s||s(y))),f=await Promise.all(m);for(let p of f)u.push(...p);u.sort((p,h)=>p.timestamp.getTime()-h.timestamp.getTime());let d=[];for(let p of u){let h=lt(p);h&&o.has(h)||(h&&o.add(h),d.push(p));}return d}var v=class{static CACHE_DIR=C.join(homedir(),".claude","powerline");static USAGE_CACHE_DIR=C.join(this.CACHE_DIR,"usage");static LOCKS_DIR=C.join(this.CACHE_DIR,"locks");static isLocked(e){let t=C.join(this.LOCKS_DIR,e);if(!_.existsSync(t))return false;try{let n=_.readFileSync(t,"utf-8"),r=parseInt(n.trim(),10);if(isNaN(r))return l(`Invalid PID in lock file ${e}, removing stale lock`),_.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(o){return o.code==="ESRCH"?(l(`Removing stale lock file ${e} for dead process ${r}`),_.unlinkSync(t),!1):(l(`Error checking process ${r} for lock ${e}:`,o),!0)}}catch(n){return l(`Error reading lock file ${e}:`,n),true}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let o=C.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await _.promises.writeFile(o,a,{flag:"wx"}),l(`Lock acquired for ${e}`),!0}catch(c){if(c.code==="EEXIST")await setTimeout(50);else throw c}return l(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=C.join(this.LOCKS_DIR,e);try{await _.promises.unlink(t),l(`Lock released for ${e}`);}catch(n){n.code!=="ENOENT"&&l(`Error releasing lock for ${e}:`,n);}}static async ensureCacheDirectories(){try{await Promise.all([_.promises.mkdir(this.CACHE_DIR,{recursive:!0}),_.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),_.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){l("Failed to create cache directories:",e);}}static createProjectHash(e){return createHash("md5").update(e).digest("hex").substring(0,8)}static async getUsageCache(e,t){let o="utf-8";await this.ensureCacheDirectories();let i=C.join(this.USAGE_CACHE_DIR,`${e}.json`),a=`${e}.usage.lock`;for(let c=0;c<3;c++){if(this.isLocked(a)){l(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let u=await _.promises.readFile(i,o),m=JSON.parse(u);return !t||m.timestamp>=t?(l(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(m.data)):(l(`${e} cache outdated: cache=${m.timestamp}, latest=${t}`),null)}catch(u){if(u.code==="ENOENT")return l(`No shared ${e} usage cache found`),null;let m=c+1;l(`Attempt ${m} failed to read ${e} cache: ${u.message}. Retrying...`),await setTimeout(75);}}return l(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(t=>({...t,timestamp:new Date(t.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){l(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=C.join(this.USAGE_CACHE_DIR,`${e}.json`),a=n||Date.now(),g=JSON.stringify({data:t,timestamp:a});await _.promises.writeFile(i,g,"utf-8"),l(`[CACHE-SET] ${e} disk cache stored`);}catch(i){l(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(r);}}static async getLatestTranscriptMtime(){try{let e=V(),t=await Y(e),n=0;for(let r of t)try{let i=(await _.promises.readdir(r)).filter(a=>a.endsWith(".jsonl"));for(let a of i){let c=C.join(r,a),g=await ue(c);g&&g.getTime()>n&&(n=g.getTime());}}catch(o){l(`Failed to read project directory ${r}:`,o);continue}return n}catch(e){return l("Failed to get latest transcript mtime:",e),Date.now()}}};var q={"claude-3-haiku-20240307":{name:"Claude 3 Haiku",input:.25,output:1.25,cache_write_5m:.3,cache_write_1h:.5,cache_read:.03},"claude-3-5-haiku-20241022":{name:"Claude 3.5 Haiku",input:.8,output:4,cache_write_5m:1,cache_write_1h:1.6,cache_read:.08},"claude-3-5-haiku-latest":{name:"Claude 3.5 Haiku Latest",input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5-20251001":{name:"Claude Haiku 4.5",input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:"Claude Haiku 4.5",input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-3-opus-latest":{name:"Claude 3 Opus Latest",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-3-opus-20240229":{name:"Claude 3 Opus",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-3-5-sonnet-latest":{name:"Claude 3.5 Sonnet Latest",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-5-sonnet-20240620":{name:"Claude 3.5 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-5-sonnet-20241022":{name:"Claude 3.5 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-20250514":{name:"Claude Opus 4",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:"Claude Opus 4.1",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:"Claude Opus 4.1",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:"Claude Sonnet 4",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:"Claude 4 Opus",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:"Claude 4 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:"Claude Sonnet 4.5",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:"Claude Sonnet 4.5",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-7-sonnet-latest":{name:"Claude 3.7 Sonnet Latest",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-7-sonnet-20250219":{name:"Claude 3.7 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}},E=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL="https://raw.githubusercontent.com/Owloops/claude-powerline/main/pricing.json";static async loadDiskCache(){let t=Date.now()-864e5;return await v.getUsageCache("pricing",t)}static async saveDiskCache(e){await v.setUsageCache("pricing",e);}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},r=>{if(r.statusCode!==200){l(`HTTP ${r.statusCode}: ${r.statusMessage}`),e(null);return}let o="",i=0,a=1024*1024;r.on("data",c=>{if(i+=c.length,i>a){l("Response too large"),n.destroy(),e(null);return}o+=c;}),r.on("end",()=>{try{let g=JSON.parse(o),u=g._meta,m={};for(let[f,d]of Object.entries(g))f!=="_meta"&&(m[f]=d);this.validatePricingData(m)?(l(`Fetched fresh pricing from GitHub for ${Object.keys(m).length} models`),l(`Pricing last updated: ${u?.updated||"unknown"}`),e(m)):(l("Invalid pricing data structure"),e(null));}catch(c){l("Failed to parse JSON:",c),e(null);}}),r.on("error",c=>{l("Response error:",c),e(null);});});n.on("error",r=>{l("Request error:",r),e(null);}),n.on("timeout",()=>{l("Request timeout"),n.destroy(),e(null);}),n.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return l(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return l(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,l(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),l(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,l(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(l(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(q).length} models`),this.executionCache=q,l(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(q).length} models`),q)}static validatePricingData(e){if(!e||typeof e!="object")return false;for(let[,t]of Object.entries(e)){if(!t||typeof t!="object")return false;let n=t;if(typeof n.input!="number"||typeof n.output!="number"||typeof n.cache_read!="number")return false}return true}static async getModelPricing(e){if(this.modelPricingCache.has(e))return l(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return t[e]?n=t[e]:n=this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),l(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[o,i]of Object.entries(t))if(o.toLowerCase()===n)return i;let r=[{pattern:["opus-4-1","claude-opus-4-1"],fallback:"claude-opus-4-1-20250805"},{pattern:["opus-4","claude-opus-4"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet-4.5","4-5-sonnet","sonnet-4-5"],fallback:"claude-sonnet-4-5-20250929"},{pattern:["sonnet-4","claude-sonnet-4"],fallback:"claude-sonnet-4-20250514"},{pattern:["sonnet-3.7","3-7-sonnet"],fallback:"claude-3-7-sonnet-20250219"},{pattern:["3-5-sonnet","sonnet-3.5"],fallback:"claude-3-5-sonnet-20241022"},{pattern:["haiku-4.5","4-5-haiku","haiku-4-5"],fallback:"claude-haiku-4-5-20251001"},{pattern:["3-5-haiku","haiku-3.5"],fallback:"claude-3-5-haiku-20241022"},{pattern:["haiku","3-haiku"],fallback:"claude-3-haiku-20240307"},{pattern:["opus"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet"],fallback:"claude-3-5-sonnet-20241022"}];for(let{pattern:o,fallback:i}of r)if(o.some(a=>n.includes(a))&&t[i])return t[i];return t["claude-3-5-sonnet-20241022"]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let n=e.message?.usage;if(!n)return 0;let r=this.extractModelId(e),o=await this.getModelPricing(r),i=n.input_tokens||0,a=n.output_tokens||0,c=n.cache_creation_input_tokens||0,g=n.cache_read_input_tokens||0,u=i/1e6*o.input,m=a/1e6*o.output,f=g/1e6*o.cache_read,d=c/1e6*o.cache_write_5m;return u+m+d+f}static extractModelId(e){if(e.model&&typeof e.model=="string")return e.model;let t=e.message;if(t?.model){let n=t.model;return typeof n=="string"?n:n?.id||"claude-3-5-sonnet-20241022"}return e.model_id&&typeof e.model_id=="string"?e.model_id:"claude-3-5-sonnet-20241022"}};function yt(s){return {timestamp:s.timestamp.toISOString(),message:{usage:{input_tokens:s.message?.usage?.input_tokens||0,output_tokens:s.message?.usage?.output_tokens||0,cache_creation_input_tokens:s.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:s.message?.usage?.cache_read_input_tokens}},costUSD:s.costUSD}}var X=class{async getSessionUsage(e){try{let t=await J(e);if(!t)return l(`No transcript found for session: ${e}`),null;l(`Found transcript at: ${t}`);let n=await R(t),r=dirname(t),o=await Ie(e,r);l(`Found ${o.length} agent transcripts for session`);for(let c of o){let g=await R(c);n.push(...g);}if(n.length===0)return {totalCost:0,entries:[]};let i=[],a=0;for(let c of n)if(c.message?.usage){let g=yt(c);if(g.costUSD!==void 0)a+=g.costUSD;else {let u=await E.calculateCostForEntry(c.raw);g.costUSD=u,a+=u;}i.push(g);}return l(`Parsed ${i.length} usage entries, total cost: $${a.toFixed(4)}`),{totalCost:a,entries:i}}catch(t){return l(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,n)=>({input:t.input+(n.message.usage.input_tokens||0),output:t.output+(n.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(n.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(n.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e,t){let n=await this.getSessionUsage(e);if(!n||n.entries.length===0)return {cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};let r=this.calculateTokenBreakdown(n.entries),o=r.input+r.output+r.cacheCreation+r.cacheRead,i=n.totalCost,a=t?.cost?.total_cost_usd??null;return {cost:i??a,calculatedCost:i,officialCost:a,tokens:o,tokenBreakdown:r}}},M=class{sessionProvider=new X;async getUsageInfo(e,t){try{return l(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e,t)}}catch(n){return l(`Error getting usage info for session ${e}:`,n),{session:{cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null}}}}};var U=class{thresholds={LOW:50,MEDIUM:80};config;constructor(e){this.config=e;}getContextUsageThresholds(){return this.thresholds}getContextLimit(e){let t=this.config.modelContextLimits||{default:2e5},n=this.getModelType(e);return t[n]||t.default||2e5}getModelType(e){let t=e.toLowerCase();return t.includes("sonnet")?"sonnet":t.includes("opus")?"opus":"default"}calculatePercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100))),r=Math.round(t*.75),o=Math.min(100,Math.max(0,Math.round(e/r*100))),i=Math.max(0,100-o);return {percentage:n,usablePercentage:o,contextLeftPercentage:i,usableTokens:r}}calculateContextFromHookData(e){let t=e.context_window?.current_usage;if(!t)return l("No current_usage in hook data, falling back to transcript parsing"),null;let n=e.context_window?.context_window_size||2e5,r=(t.input_tokens||0)+(t.cache_creation_input_tokens||0)+(t.cache_read_input_tokens||0);l(`Native current_usage: input=${t.input_tokens}, cache_create=${t.cache_creation_input_tokens}, cache_read=${t.cache_read_input_tokens}, total=${r} (limit: ${n})`);let o=this.calculatePercentages(r,n);return {totalTokens:r,maxTokens:n,...o}}async calculateContextTokensFromTranscript(e,t){try{l(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return l("Transcript file is empty"),null}catch{return l("Could not read transcript file"),null}let n=await R(e);if(n.length===0)return l("No entries in transcript"),null;let r=null;for(let o=n.length-1;o>=0;o--){let i=n[o];if(i&&i.message?.usage?.input_tokens&&i.isSidechain!==!0){r=i,l(`Context segment: Found most recent entry at ${i.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let o=r.message.usage,i=(o.input_tokens||0)+(o.cache_read_input_tokens||0)+(o.cache_creation_input_tokens||0),a=t?this.getContextLimit(t):2e5;l(`Most recent main chain context: ${i} tokens (limit: ${a})`);let c=this.calculatePercentages(i,a);return {totalTokens:i,maxTokens:a,...c}}return l("No main chain entries with usage data found"),null}catch(n){return l(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t||this.calculateContextTokensFromTranscript(e.transcript_path,e.model?.id)}};var L=class{async loadTranscriptEntries(e){try{let t=await J(e);if(!t)return l(`No transcript found for session: ${e}`),[];l(`Loading transcript from: ${t}`);let r=(await readFile(t,"utf-8")).trim().split(`
7
+ `).filter(i=>i.trim()),o=[];for(let i of r)try{let a=JSON.parse(i);if(a.isSidechain===!0)continue;o.push(a);}catch(a){l(`Failed to parse JSONL line: ${a}`);continue}return l(`Loaded ${o.length} transcript entries`),o}catch(t){return l(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,r=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!r}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let o of t)if(o.timestamp)try{let i=new Date(o.timestamp),a=o.type||o.message?.role||o.message?.type,c=o.type==="user"&&o.message?.content?.[0]?.type==="tool_result";if(a==="user"&&!c)n=i;else if(a==="assistant"&&n){let u=(i.getTime()-n.getTime())/1e3;u>.1&&u<300&&(r=u);}}catch{continue}return r}async getMetricsInfo(e,t){try{if(l(`Getting metrics from hook data for session: ${e}`),!t.cost)return l("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let n=await this.loadTranscriptEntries(e),r=this.calculateMessageCount(n),o=this.calculateLastResponseTime(n);return {responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:o,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed}}catch(n){return l(`Error getting metrics from hook data for session ${e}:`,n),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function K(s){return s===null?"$0.00":s<.01?"<$0.01":`$${s.toFixed(2)}`}function P(s){return s===null||s===0?"0 tokens":s>=1e6?`${(s/1e6).toFixed(1)}M tokens`:s>=1e3?`${(s/1e3).toFixed(1)}K tokens`:`${s} tokens`}function Oe(s){if(!s)return "0 tokens";let e=[];if(s.input>0&&e.push(`${P(s.input).replace(" tokens","")} in`),s.output>0&&e.push(`${P(s.output).replace(" tokens","")} out`),s.cacheCreation>0||s.cacheRead>0){let t=s.cacheCreation+s.cacheRead;e.push(`${P(t).replace(" tokens","")} cached`);}return e.length>0?e.join(" + "):"0 tokens"}function Ne(s){return s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:s<86400?`${Math.floor(s/3600)}h`:s<604800?`${Math.floor(s/86400)}d`:`${Math.floor(s/604800)}w`}function je(s){return s<60?`${s.toFixed(0)}s`:s<3600?`${(s/60).toFixed(0)}m`:s<86400?`${(s/3600).toFixed(1)}h`:`${(s/86400).toFixed(1)}d`}var wt=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i;function He(s){let e=s.trim().match(wt);if(!e?.groups)return s;let{family:t,newMajor:n,newMinor:r,oldMajor:o,oldMinor:i,oldFamily:a}=e.groups,c=t||a,g=n||o,u=r||i;if(c&&g){let m=c.charAt(0).toUpperCase()+c.slice(1).toLowerCase(),f=u?`${g}.${u}`:g;return `${m} ${f}`}return s}function xt(s,e){return !e||e<=0||s<0?null:Math.min(100,s/e*100)}function me(s,e,t=80){let n=xt(s,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let r=`${n.toFixed(0)}%`,o=n>=t,i="";return o?i=` !${r}`:n>=50?i=` +${r}`:i=` ${r}`,{percentage:n,isWarning:o,displayText:i}}var kt={blocks:{filled:"\u2588",empty:"\u2591"},squares:{filled:"\u25FC",empty:"\u25FB"},dots:{filled:"\u25CF",empty:"\u25CB"},line:{filled:"\u2501",empty:"\u2504"},capped:{filled:"\u2501",empty:"\u2504",cap:"\u2578"},ball:{filled:"\u2500",empty:"\u2500",marker:"\u25CF"},filled:{filled:"\u25A0",empty:"\u25A1"},geometric:{filled:"\u25B0",empty:"\u25B1"}},I=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let r=e.workspace?.current_dir||e.cwd||"/",o=e.workspace?.project_dir,i=n?.style??(n?.showBasename?"basename":"full");if(i==="basename")return {text:C.basename(r)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let a=process.env.HOME||process.env.USERPROFILE,c=r,g=o;a&&(r.startsWith(a)&&(c=r.replace(a,"~")),o&&o.startsWith(a)&&(g=o.replace(a,"~")));let u=this.getDisplayDirectoryName(c,g);return i==="fish"&&(u=this.abbreviateFishStyle(u)),{text:u,bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let r=[];if(n?.showRepoName&&e.repoName&&(r.push(e.repoName),e.isWorktree&&r.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&r.push(`[${e.operation}]`),r.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&r.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&r.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?r.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?r.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&r.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let i=[];e.staged&&e.staged>0&&i.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&i.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&i.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&i.push(`!${e.conflicts}`),i.length>0&&r.push(`(${i.join(" ")})`);}if(n?.showUpstream&&e.upstream&&r.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&r.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=Ne(e.timeSinceCommit);r.push(`${this.symbols.git_time} ${i}`);}let o=this.symbols.git_clean;return e.status==="conflicts"?o=this.symbols.git_conflicts:e.status==="dirty"&&(o=this.symbols.git_dirty),r.push(o),{text:r.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}renderModel(e,t){let n=e.model?.display_name||"Claude",r=He(n);return {text:`${this.symbols.model} ${r}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n){let r=n?.type||"cost",o=n?.costSource,i=this.config.budget?.session,a=()=>o==="calculated"?e.session.calculatedCost:o==="official"?e.session.officialCost:e.session.cost,c=this.formatUsageWithBudget(a(),e.session.tokens,e.session.tokenBreakdown,r,i?.amount,i?.warningThreshold||80,i?.type);return {text:`${this.symbols.session_cost} ${c}`,bgColor:t.sessionBg,fgColor:t.sessionFg}}renderTmux(e,t){return e?{text:`tmux:${e}`,bgColor:t.tmuxBg,fgColor:t.tmuxFg}:{text:"tmux:none",bgColor:t.tmuxBg,fgColor:t.tmuxFg}}renderContext(e,t,n){let o=n?.displayStyle??"text",i=o==="bar"?{filled:this.symbols.bar_filled,empty:this.symbols.bar_empty}:kt[o]??null;if(!e)return i?{text:`${i.empty.repeat(10)} 0%`,bgColor:t.contextBg,fgColor:t.contextFg}:{text:`${this.symbols.context_time} 0 (100%)`,bgColor:t.contextBg,fgColor:t.contextFg};let a=t.contextBg,c=t.contextFg;if(e.contextLeftPercentage<=20?(a=t.contextCriticalBg,c=t.contextCriticalFg):e.contextLeftPercentage<=40&&(a=t.contextWarningBg,c=t.contextWarningFg),i){let m=e.usablePercentage,f=Math.round(m/100*10),d=10-f,p=this.buildBar(i,f,d,10);return {text:n?.showPercentageOnly?`${p} ${m}%`:`${p} ${e.totalTokens.toLocaleString()} (${m}%)`,bgColor:a,fgColor:c}}let g=`${e.contextLeftPercentage}%`;return {text:n?.showPercentageOnly?`${this.symbols.context_time} ${g}`:`${this.symbols.context_time} ${e.totalTokens.toLocaleString()} (${g})`,bgColor:a,fgColor:c}}buildBar(e,t,n,r){if(e.marker){let o=Math.min(t,r-1);return e.filled.repeat(o)+e.marker+e.empty.repeat(r-o-1)}return e.cap?t===0?e.cap+e.empty.repeat(r-1):t>=r?e.filled.repeat(r):e.filled.repeat(t-1)+e.cap+e.empty.repeat(n):e.filled.repeat(t)+e.empty.repeat(n)}renderMetrics(e,t,n,r){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let o=[];if(r?.showLastResponseTime&&e.lastResponseTime!==null){let i=e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;o.push(`${this.symbols.metrics_last_response} ${i}`);}if(r?.showResponseTime!==false&&e.responseTime!==null){let i=e.responseTime<60?`${e.responseTime.toFixed(1)}s`:`${(e.responseTime/60).toFixed(1)}m`;o.push(`${this.symbols.metrics_response} ${i}`);}if(r?.showDuration!==false&&e.sessionDuration!==null){let i=je(e.sessionDuration);o.push(`${this.symbols.metrics_duration} ${i}`);}return r?.showMessageCount!==false&&e.messageCount!==null&&o.push(`${this.symbols.metrics_messages} ${e.messageCount}`),r?.showLinesAdded!==false&&e.linesAdded!==null&&e.linesAdded>0&&o.push(`${this.symbols.metrics_lines_added} ${e.linesAdded}`),r?.showLinesRemoved!==false&&e.linesRemoved!==null&&e.linesRemoved>0&&o.push(`${this.symbols.metrics_lines_removed} ${e.linesRemoved}`),o.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:o.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,n){let r;if(e.cost===null&&e.tokens===null)r="No active block";else {let o=n?.type||"cost",i=n?.burnType,a=this.config.budget?.block,c=e.timeRemaining!==null?(()=>{let m=Math.floor(e.timeRemaining/60),f=e.timeRemaining%60;return m>0?`${m}h ${f}m`:`${f}m`})():null,g;switch(o){case "cost":g=this.formatUsageWithBudget(e.cost,null,null,"cost",a?.amount,a?.warningThreshold,a?.type);break;case "tokens":g=this.formatUsageWithBudget(null,e.tokens,null,"tokens",a?.amount,a?.warningThreshold,a?.type);break;case "weighted":let m=a?.type==="tokens"?a.amount:void 0,f=P(e.weightedTokens);if(m&&e.weightedTokens!==null){let d=me(e.weightedTokens,m,a?.warningThreshold||80);g=`${f}${d.displayText}`;}else g=`${f} (weighted)`;break;case "both":g=this.formatUsageWithBudget(e.cost,e.tokens,null,"both",a?.amount,a?.warningThreshold,a?.type);break;case "time":g=c||"N/A";break;default:g=this.formatUsageWithBudget(e.cost,null,null,"cost",a?.amount,a?.warningThreshold,a?.type);}let u="";if(i&&i!=="none")switch(i){case "cost":u=` | ${e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A"}`;break;case "tokens":u=` | ${e.tokenBurnRate!==null?`${P(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let d=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",p=e.tokenBurnRate!==null?`${P(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${d} / ${p}`;break}o==="time"?r=g:r=c?`${g}${u} (${c} left)`:`${g}${u}`;}return {text:`${this.symbols.block_cost} ${r}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let r=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,r?.amount,r?.warningThreshold,r?.type)}`,bgColor:t.todayBg,fgColor:t.todayFg}}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||C.basename(t)||"project":C.basename(e)||"root":C.basename(e)||"root"}abbreviateFishStyle(e){let t=e.split(C.sep);return t.map((n,r)=>r===t.length-1||n==="~"||n===""?n:n.charAt(0)).join(C.sep)}formatUsageDisplay(e,t,n,r){switch(r){case "cost":return K(e);case "tokens":return P(t);case "both":return `${K(e)} (${P(t)})`;case "breakdown":return Oe(n);default:return K(e)}}formatUsageWithBudget(e,t,n,r,o,i=80,a){let c=this.formatUsageDisplay(e,t,n,r);if(o&&o>0){let g=null;if(a==="tokens"&&t!==null?g=t:(a==="cost"&&e!==null||!a&&e!==null)&&(g=e),g!==null){let u=me(g,o,i);return c+u.displayText}}return c}renderVersion(e,t,n){return e.version?{text:`${this.symbols.version} v${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}:null}};function St(s){return s.includes("opus")?5:(s.includes("sonnet")||s.includes("haiku"),1)}function Tt(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},costUSD:s.costUSD||0,model:s.message?.model||"unknown"}}var Z=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],r=[...e].sort((a,c)=>a.timestamp.getTime()-c.timestamp.getTime()),o=null,i=[];for(let a of r){let c=a.timestamp;if(o==null)o=this.floorToHour(c),i=[a];else {let g=c.getTime()-o.getTime(),u=i[i.length-1];if(u==null)continue;let m=u.timestamp,f=c.getTime()-m.getTime();g>t||f>t?(n.push(i),o=this.floorToHour(c),i=[a]):i.push(a);}}return o!=null&&i.length>0&&n.push(i),n}createBlockInfo(e,t){let n=new Date,r=this.sessionDurationHours*60*60*1e3,o=new Date(e.getTime()+r),i=t[t.length-1],a=i!=null?i.timestamp:e,c=n.getTime()-a.getTime()<r&&n<o;return {block:t,isActive:c}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let r=n[0];if(!r)continue;let o=this.floorToHour(r.timestamp),i=this.createBlockInfo(o,n);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{l("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await z(void 0,(c,g)=>g>=e,!0),r=[];for(let c of n)if(c.message?.usage){let g=Tt(c);!g.costUSD&&c.raw&&(g.costUSD=await E.calculateCostForEntry(c.raw)),r.push(g);}let o=this.identifySessionBlocks(r);l(`Block segment: Found ${o.length} session blocks`);let i=this.findActiveBlock(o),a=[];if(i&&i.length>0){l(`Block segment: Found active block with ${i.length} entries`);let c=i[0],g=i[i.length-1];c&&g&&l(`Block segment: Active block from ${c.timestamp.toISOString()} to ${g.timestamp.toISOString()}`),a=i;}else l("Block segment: No active block found"),a=[];return a}catch(e){return l("Error loading block entries:",e),[]}}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return l("Block segment: No entries in current block"),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((g,u)=>g+u.costUSD,0),n=e.reduce((g,u)=>g+u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,0),r=e.reduce((g,u)=>{let m=u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,f=St(u.model);return g+m*f},0),o=new Date,i=null;if(e.length>0){let g=e[0];if(g){let u=this.sessionDurationHours*60*60*1e3,m=this.floorToHour(g.timestamp),f=new Date(m.getTime()+u);i=Math.max(0,Math.round((f.getTime()-o.getTime())/(1e3*60)));}}let a=null,c=null;if(e.length>=1&&(t>0||n>0)){let g=e.map(f=>f.timestamp).sort((f,d)=>f.getTime()-d.getTime()),u=g[0],m=g[g.length-1];if(u&&m){let f=(m.getTime()-u.getTime())/6e4;f>0&&(t>0&&(a=t/f*60),n>0&&(c=n/f*60));}}return l(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${i}m remaining, burn rate: ${a?"$"+a.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,weightedTokens:r,timeRemaining:i,burnRate:a,tokenBurnRate:c}}catch(e){return l("Error getting active block info:",e),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function O(s){let e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function vt(s){return s.inputTokens+s.outputTokens+s.cacheCreationInputTokens+s.cacheReadInputTokens}function Pt(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},costUSD:s.costUSD||0,model:s.message?.model||"unknown"}}var Q=class{async loadTodayEntries(){let t=O(new Date);l(`Today segment: Loading entries for date ${t}`);let n=await v.getLatestTranscriptMtime(),r=await v.getUsageCache("today",n);if(r)return l("Using shared today usage cache"),r;let o=new Date;o.setDate(o.getDate()-1),o.setHours(0,0,0,0);let i=(f,d)=>d>=o,a=new Date;a.setHours(0,0,0,0);let g=await z(f=>f.timestamp>=a,i,true),u=[],m=0;for(let f of g)if(O(f.timestamp)===t&&f.message?.usage){let p=Pt(f);!p.costUSD&&f.raw&&(p.costUSD=await E.calculateCostForEntry(f.raw)),u.push(p),m++;}return l(`Today segment: Found ${m} entries for today (${t})`),await v.setUsageCache("today",u,n),u}async getTodayEntries(){try{return await this.loadTodayEntries()}catch(e){return l("Error loading today's entries:",e),[]}}async getTodayInfo(){try{let e=await this.getTodayEntries();if(e.length===0)return {cost:null,tokens:null,tokenBreakdown:null,date:O(new Date)};let t=e.reduce((o,i)=>o+i.costUSD,0),n=e.reduce((o,i)=>o+vt(i.usage),0),r=e.reduce((o,i)=>({input:o.input+i.usage.inputTokens,output:o.output+i.usage.outputTokens,cacheCreation:o.cacheCreation+i.usage.cacheCreationInputTokens,cacheRead:o.cacheRead+i.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return l(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:r,date:O(new Date)}}catch(e){return l("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:O(new Date)}}}};var We="\x1B[0m",Ge={right:"\uE0B0",left_rounded:"\uE0B6",right_rounded:"\uE0B4",branch:"\u2387",model:"\u2731",git_clean:"\u2713",git_dirty:"\u25CF",git_conflicts:"\u26A0",git_ahead:"\u2191",git_behind:"\u2193",git_worktree:"\u29C9",git_tag:"\u2302",git_sha:"\u266F",git_upstream:"\u2192",git_stash:"\u29C7",git_time:"\u25F7",session_cost:"\xA7",block_cost:"\u25F1",today_cost:"\u2609",context_time:"\u25D4",metrics_response:"\u29D6",metrics_last_response:"\u0394",metrics_duration:"\u29D7",metrics_messages:"\u27D0",metrics_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u27E2",version:"\u25C8",bar_filled:"\u25AA",bar_empty:"\u25AB"},Ve={right:"\uE0B0",left_rounded:"\uE0B6",right_rounded:"\uE0B4",branch:"~",model:"M",git_clean:"=",git_dirty:"*",git_conflicts:"!",git_ahead:"^",git_behind:"v",git_worktree:"W",git_tag:"T",git_sha:"#",git_upstream:">>",git_stash:"S",git_time:"@",session_cost:"S",block_cost:"B",today_cost:"D",context_time:"C",metrics_response:"R",metrics_last_response:"L",metrics_duration:"T",metrics_messages:"#",metrics_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"~/h",version:"V",bar_filled:"=",bar_empty:"-"};var Et="\x1B",$t=new RegExp(`${Et}\\[[0-9;]*m`,"g"),Rt=/^[a-zA-Z0-9/]+$/;function Bt(){if(process.platform==="win32")return null;let s=process.pid.toString();for(let e=0;e<10;e++)try{let n=execSync(`ps -o ppid=,tty= -p ${s}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(/\s+/),r=n[0],o=n[1];if(o&&o!=="?"&&o!=="??"&&Rt.test(o))return o;if(!r||r==="1"||r==="0")break;s=r;}catch{break}return null}function At(){try{let e=execSync("mode con",{encoding:"utf8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).match(/Columns:\s*(\d+)/i);if(e?.[1]){let t=parseInt(e[1],10);if(!isNaN(t)&&t>0)return t}}catch{}return null}function Dt(){let s=Bt();if(s)try{let t=execSync(`stty size < /dev/${s}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"],shell:"/bin/sh"}).trim().split(" ")[1];if(t){let n=parseInt(t,10);if(!isNaN(n)&&n>0)return n}}catch{}try{let e=execSync("tput cols 2>/dev/null",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim(),t=parseInt(e,10);if(!isNaN(t)&&t>0)return t}catch{}return null}function Ye(){let s=n=>Math.floor(n*.8),e=process.env.COLUMNS;if(e){let n=parseInt(e,10);if(!isNaN(n)&&n>0)return s(n)}if(process.stdout.columns&&process.stdout.columns>0)return s(process.stdout.columns);if(process.platform==="win32"){let n=At();if(n)return s(n)}let t=Dt();return t?s(t):null}function Ft(s){return s.replace($t,"")}function Je(s){return Ft(s).length}var te=class{constructor(e){this.config=e;this.symbols=this.initializeSymbols();}symbols;_usageProvider;_blockProvider;_todayProvider;_contextProvider;_gitService;_tmuxService;_metricsProvider;_segmentRenderer;get usageProvider(){return this._usageProvider||(this._usageProvider=new M),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new Z),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new Q),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new U(this.config)),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new D),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new F),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new L),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new I(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id,e):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,r=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,o=this.needsSegmentInfo("context")?await this.contextProvider.getContextInfo(e):null,i=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id,e):null;return this.config.display.autoWrap?this.generateAutoWrapStatusline(e,t,n,r,o,i):(await Promise.all(this.config.display.lines.map(c=>this.renderLine(c,e,t,n,r,o,i)))).filter(c=>c.length>0).join(`
8
+ `)}async generateAutoWrapStatusline(e,t,n,r,o,i){let a=this.getThemeColors(),c=e.workspace?.current_dir||e.cwd||"/",g=Ye(),u=[];for(let m of this.config.display.lines){let f=Object.entries(m.segments).filter(([y,b])=>b?.enabled).map(([y,b])=>({type:y,config:b})),d=[];for(let y of f){let b=await this.renderSegment(y,e,t,n,r,o,i,a,c);b&&d.push({type:y.type,text:b.text,bgColor:b.bgColor,fgColor:b.fgColor});}if(d.length===0)continue;if(!g||g<=0){u.push(this.buildLineFromSegments(d,a));continue}let p=[],h=0;for(let y of d){let b=this.calculateSegmentWidth(y,p.length===0);p.length>0&&h+b>g&&(u.push(this.buildLineFromSegments(p,a)),p=[],h=0),p.push(y),h+=b;}p.length>0&&u.push(this.buildLineFromSegments(p,a));}return u.join(`
9
+ `)}calculateSegmentWidth(e,t){let n=this.config.display.style==="capsule",r=Je(e.text),i=(this.config.display.padding??1)*2;if(n){let c=2+i+(t?0:1);return r+c}let a=1+i;return r+a}buildLineFromSegments(e,t){let n=this.config.display.style==="capsule",r=t.reset;for(let o=0;o<e.length;o++){let i=e[o];if(!i)continue;let a=o===0,g=o===e.length-1?null:e[o+1];n&&!a&&(r+=" "),r+=this.formatSegment(i.bgColor,i.fgColor,i.text,g?.bgColor,t);}return r}async renderLine(e,t,n,r,o,i,a){let c=this.getThemeColors(),g=t.workspace?.current_dir||t.cwd||"/",u=Object.entries(e.segments).filter(([f,d])=>d?.enabled).map(([f,d])=>({type:f,config:d})),m=[];for(let f of u){let d=await this.renderSegment(f,t,n,r,o,i,a,c,g);d&&m.push({type:f.type,text:d.text,bgColor:d.bgColor,fgColor:d.fgColor});}return this.buildLineFromSegments(m,c)}async renderSegment(e,t,n,r,o,i,a,c,g){return e.type==="directory"?this.segmentRenderer.renderDirectory(t,c,e.config):e.type==="model"?this.segmentRenderer.renderModel(t,c):e.type==="git"?await this.renderGitSegment(e.config,t,c,g):e.type==="session"?this.renderSessionSegment(e.config,n,c):e.type==="tmux"?await this.renderTmuxSegment(c):e.type==="context"?this.renderContextSegment(e.config,i,c):e.type==="metrics"?this.renderMetricsSegment(e.config,a,r,c):e.type==="block"?this.renderBlockSegment(e.config,r,c):e.type==="today"?this.renderTodaySegment(e.config,o,c):e.type==="version"?this.renderVersionSegment(e.config,t,c):null}async renderGitSegment(e,t,n,r){if(!this.needsSegmentInfo("git"))return null;let o=await this.gitService.getGitInfo(r,{showSha:e?.showSha,showWorkingTree:e?.showWorkingTree,showOperation:e?.showOperation,showTag:e?.showTag,showTimeSinceCommit:e?.showTimeSinceCommit,showStashCount:e?.showStashCount,showUpstream:e?.showUpstream,showRepoName:e?.showRepoName},t.workspace?.project_dir);return o?this.segmentRenderer.renderGit(o,n,e):null}renderSessionSegment(e,t,n){return t?this.segmentRenderer.renderSession(t,n,e):null}async renderTmuxSegment(e){if(!this.needsSegmentInfo("tmux"))return null;let t=await this.tmuxService.getSessionId();return this.segmentRenderer.renderTmux(t,e)}renderContextSegment(e,t,n){return this.needsSegmentInfo("context")?this.segmentRenderer.renderContext(t,n,e):null}renderMetricsSegment(e,t,n,r){return this.segmentRenderer.renderMetrics(t,r,n,e)}renderBlockSegment(e,t,n){return t?this.segmentRenderer.renderBlock(t,n,e):null}renderTodaySegment(e,t,n){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderToday(t,n,r)}renderVersionSegment(e,t,n){return this.segmentRenderer.renderVersion(t,n,e)}initializeSymbols(){let e=this.config.display.style,t=this.config.display.charset||"unicode",n=e==="minimal",r=e==="capsule",o=t==="text"?Ve:Ge;return {right:n?"":r?o.right_rounded:o.right,left:r?o.left_rounded:"",branch:o.branch,model:o.model,git_clean:o.git_clean,git_dirty:o.git_dirty,git_conflicts:o.git_conflicts,git_ahead:o.git_ahead,git_behind:o.git_behind,git_worktree:o.git_worktree,git_tag:o.git_tag,git_sha:o.git_sha,git_upstream:o.git_upstream,git_stash:o.git_stash,git_time:o.git_time,session_cost:o.session_cost,block_cost:o.block_cost,today_cost:o.today_cost,context_time:o.context_time,metrics_response:o.metrics_response,metrics_last_response:o.metrics_last_response,metrics_duration:o.metrics_duration,metrics_messages:o.metrics_messages,metrics_lines_added:o.metrics_lines_added,metrics_lines_removed:o.metrics_lines_removed,metrics_burn:o.metrics_burn,version:o.version,bar_filled:o.bar_filled,bar_empty:o.bar_empty}}getThemeColors(){let e=this.config.theme,t,n=this.config.display.colorCompatibility||"auto",r=n==="auto"?H():n;if(e==="custom"){if(t=this.config.colors?.custom,!t)throw new Error("Custom theme selected but no colors provided in configuration")}else t=W(e,r),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=W("dark",r));let o=W("dark",r),i=x=>{let k=t[x]||o[x];return r==="none"?{bg:"",fg:""}:r==="ansi"?{bg:ae(k.bg,true),fg:ae(k.fg,false)}:r==="ansi256"?{bg:ie(k.bg,true),fg:ie(k.fg,false)}:{bg:se(k.bg,true),fg:se(k.fg,false)}},a=i("directory"),c=i("git"),g=i("model"),u=i("session"),m=i("block"),f=i("today"),d=i("tmux"),p=i("context"),h=i("contextWarning"),y=i("contextCritical"),b=i("metrics"),A=i("version");return {reset:r==="none"?"":We,modeBg:a.bg,modeFg:a.fg,gitBg:c.bg,gitFg:c.fg,modelBg:g.bg,modelFg:g.fg,sessionBg:u.bg,sessionFg:u.fg,blockBg:m.bg,blockFg:m.fg,todayBg:f.bg,todayFg:f.fg,tmuxBg:d.bg,tmuxFg:d.fg,contextBg:p.bg,contextFg:p.fg,contextWarningBg:h.bg,contextWarningFg:h.fg,contextCriticalBg:y.bg,contextCriticalFg:y.fg,metricsBg:b.bg,metricsFg:b.fg,versionBg:A.bg,versionFg:A.fg}}getSegmentBgColor(e,t){switch(e){case "directory":return t.modeBg;case "git":return t.gitBg;case "model":return t.modelBg;case "session":return t.sessionBg;case "block":return t.blockBg;case "today":return t.todayBg;case "tmux":return t.tmuxBg;case "context":return t.contextBg;case "metrics":return t.metricsBg;case "version":return t.versionBg;default:return t.modeBg}}formatSegment(e,t,n,r,o){let i=this.config.display.style==="capsule",a=" ".repeat(this.config.display.padding??1);if(i){let f=this.config.display.colorCompatibility||"auto",p=(f==="auto"?H():f)==="ansi",h=j(e,p),y=`${h}${this.symbols.left}${o.reset}`,b=`${e}${t}${a}${n}${a}${o.reset}`,A=`${h}${this.symbols.right}${o.reset}`;return `${y}${b}${A}`}let c=`${e}${t}${a}${n}${a}`,g=this.config.display.colorCompatibility||"auto",m=(g==="auto"?H():g)==="ansi";if(r){let f=j(e,m);c+=`${o.reset}${r}${f}${this.symbols.right}`;}else c+=`${o.reset}${j(e,m)}${this.symbols.right}${o.reset}`;return c}};var ze={theme:"dark",display:{style:"minimal",charset:"unicode",colorCompatibility:"auto",autoWrap:true,padding:1,lines:[{segments:{directory:{enabled:true,style:"basename"},git:{enabled:true,showSha:false,showWorkingTree:false,showOperation:false,showTag:false,showTimeSinceCommit:false,showStashCount:false,showUpstream:false,showRepoName:false},model:{enabled:true},session:{enabled:true,type:"tokens",costSource:"calculated"},today:{enabled:true,type:"cost"},block:{enabled:false,type:"cost",burnType:"cost"},version:{enabled:false},tmux:{enabled:false},context:{enabled:true,showPercentageOnly:false,displayStyle:"text"},metrics:{enabled:false,showResponseTime:true,showLastResponseTime:true,showDuration:true,showMessageCount:true,showLinesAdded:true,showLinesRemoved:true}}}]},budget:{session:{warningThreshold:80},today:{warningThreshold:80,amount:50},block:{warningThreshold:80,amount:15}},modelContextLimits:{default:2e5,sonnet:2e5,opus:2e5}};function he(s){return ["light","dark","nord","tokyo-night","rose-pine","gruvbox","custom"].includes(s)}function be(s){return s==="minimal"||s==="powerline"||s==="capsule"}function qe(s){return s==="unicode"||s==="text"}function re(s,e){for(let t=0;t<s.length;t++){let n=s[t];if(n===e&&t+1<s.length)return s[t+1];if(n?.startsWith(`${e}=`))return n.split("=")[1]}}function oe(s,e){let t={...s};for(let n in e){let r=e[n];if(r!==void 0)if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=t[n]||{};t[n]=oe(o,r);}else t[n]=r;}return t}function Mt(s,e){return s?_.existsSync(s)?s:null:[...e?[C.join(e,".claude-powerline.json")]:[],C.join(process.cwd(),".claude-powerline.json"),C.join(pe.homedir(),".claude","claude-powerline.json"),C.join(pe.homedir(),".config","claude-powerline","config.json")].find(_.existsSync)||null}function Ut(s){try{let e=_.readFileSync(s,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${s}: ${e instanceof Error?e.message:String(e)}`)}}function Lt(){let s={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&he(t)&&(s.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(be(n)?e.style=n:(console.warn(`Invalid display style '${n}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(s.display=e),s}function It(){return process.env.CLAUDE_POWERLINE_CONFIG}function Ot(s){let e={},t={},n=re(s,"--theme");n&&he(n)&&(e.theme=n);let r=re(s,"--style");r&&(be(r)?t.style=r:(console.warn(`Invalid display style '${r}' from CLI argument, falling back to 'minimal'`),t.style="minimal"));let o=re(s,"--charset");return o&&(qe(o)?t.charset=o:(console.warn(`Invalid charset '${o}' from CLI argument, falling back to 'unicode'`),t.charset="unicode")),Object.keys(t).length>0&&(e.display=t),e}function Nt(s=process.argv,e){let t=JSON.parse(JSON.stringify(ze)),n=re(s,"--config")||It(),r=n?.startsWith("~")?n.replace("~",pe.homedir()):n,o=Mt(r,e);if(o)try{let c=Ut(o);t=oe(t,c);}catch(c){console.warn(`Warning: ${c instanceof Error?c.message:String(c)}`);}t.display?.style&&!be(t.display.style)&&(console.warn(`Invalid display style '${t.display.style}' in config file, falling back to 'minimal'`),t.display.style="minimal"),t.display?.charset&&!qe(t.display.charset)&&(console.warn(`Invalid charset '${t.display.charset}' in config file, falling back to 'unicode'`),t.display.charset="unicode"),t.theme&&!he(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let i=Lt();t=oe(t,i);let a=Ot(s);return t=oe(t,a),t}var Xe=Nt;function Ke(){console.log(`
10
10
  claude-powerline - Beautiful powerline statusline for Claude Code
11
11
 
12
12
  Usage: claude-powerline [options]
@@ -25,7 +25,7 @@ Claude Code Options (for settings.json):
25
25
 
26
26
  See example config at: https://github.com/Owloops/claude-powerline/blob/main/.claude-powerline.json
27
27
 
28
- `);}async function jt(){try{(x.argv.includes("--help")||x.argv.includes("-h"))&&(Ke(),x.exit(0)),x.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
28
+ `);}async function Ht(){try{(w.argv.includes("--help")||w.argv.includes("-h"))&&(Ke(),w.exit(0)),w.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
29
29
 
30
30
  claude-powerline is designed to be used as a Claude Code statusLine command.
31
31
  It reads hook data from stdin and outputs formatted statusline.
@@ -41,4 +41,4 @@ Add to ~/.claude/settings.json:
41
41
  Run with --help for more options.
42
42
 
43
43
  To test output manually:
44
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-3-5-sonnet","display_name":"Claude"}}' | claude-powerline --style=powerline`),x.exit(1)),l(`Working directory: ${x.cwd()}`),l("Process args:",x.argv);let e=await json(x.stdin);l("Received hook data:",JSON.stringify(e,null,2)),e||(console.error("Error: No input data received from stdin"),Ke(),x.exit(1));let t=e.workspace?.project_dir,n=Xe(x.argv,t),r=await new te(n).generateStatusline(e);console.log(r);}catch(s){let e=s instanceof Error?s.message:String(s);console.error("Error generating statusline:",e),x.exit(1);}}jt();
44
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-3-5-sonnet","display_name":"Claude"}}' | claude-powerline --style=powerline`),w.exit(1)),l(`Working directory: ${w.cwd()}`),l("Process args:",w.argv);let e=await json(w.stdin);l("Received hook data:",JSON.stringify(e,null,2)),e||(console.error("Error: No input data received from stdin"),Ke(),w.exit(1));let t=e.workspace?.project_dir,n=Xe(w.argv,t),o=await new te(n).generateStatusline(e);console.log(o);}catch(s){let e=s instanceof Error?s.message:String(s);console.error("Error generating statusline:",e),w.exit(1);}}Ht();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owloops/claude-powerline",
3
- "version": "1.16.0",
3
+ "version": "1.17.0",
4
4
  "description": "Beautiful vim-style powerline statusline for Claude Code with real-time usage tracking, git integration, and custom themes",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",