@owloops/claude-powerline 1.20.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +7 -7
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import v from'process';import {json}from'stream/consumers';import X from'tty';import {exec,execSync}from'child_process';import {promisify}from'util';import S,{existsSync,readFileSync,createReadStream}from'fs';import _,{join,posix,dirname}from'path';import {get}from'https';import {URL}from'url';import Ae,{homedir}from'os';import {createHash}from'crypto';import {setTimeout}from'timers/promises';import {readdir,stat,readFile}from'fs/promises';import {createInterface}from'readline';function _e(n,e){if(e&&(n.toLowerCase()==="transparent"||n.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${o};${r}m`}function J(n,e=false){if(!n||n==="")return "";let t=n.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(n.includes("\x1B[")&&n.includes("m")){let o=n.match(/\[(\d+)m/);if(o&&o[1]){let r=parseInt(o[1],10);if(r>=40&&r<=47)return `\x1B[${r-10}m`;if(r>=100&&r<=107)return `\x1B[${r-10}m`}}return n.replace("48","38")}function q(){let{env:n}=v,e=true;n.NO_COLOR&&n.NO_COLOR!==""&&(e=false);let t=n.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||n.TERM==="dumb")return "none";if(n.CI)return ["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(r=>r in n)?"truecolor":"ansi";if(n.COLORTERM==="truecolor"||["xterm-kitty","xterm-ghostty","wezterm","alacritty","foot","contour"].includes(n.TERM||""))return "truecolor";if(n.TERM_PROGRAM)switch(n.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(n.TERM||""))return "ansi256";if(/-truecolor$/i.test(n.TERM||""))return "truecolor";if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM||"")||n.COLORTERM)return "ansi";if(X?.WriteStream?.prototype?.hasColors)try{if(!X.WriteStream.prototype.hasColors())return "none";let s=X.WriteStream.prototype.hasColors(256);return X.WriteStream.prototype.hasColors(16777216)?"truecolor":s?"ansi256":"ansi"}catch{}return "ansi"}function xe(n,e){if(e&&(n.toLowerCase()==="transparent"||n.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16),i=((a,c,l)=>a===c&&c===l?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(l/255*5))(t,o,r);return `\x1B[${e?"48":"38"};5;${i}m`}function Se(n,e){if(e&&(n.toLowerCase()==="transparent"||n.toLowerCase()==="none"))return "\x1B[49m";if(e)return "";let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16);return o>t&&o>r&&o>120?"\x1B[32m":t>o&&t>r&&t>120?"\x1B[31m":r>t&&r>o&&r>120?"\x1B[34m":(t+o+r)/3>150?"\x1B[37m":"\x1B[90m"}function We(n,e){let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16),s=parseInt(e.slice(1,3),16),i=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return Math.sqrt((t-s)**2+(o-i)**2+(r-a)**2)}var je={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"},env:{bg:"#2d2d3d",fg:"#d0a0d0"}},He={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"},env:{bg:"#3a3a3a",fg:"#d787d7"}},Ge={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"},env:{bg:"#444444",fg:"#ff87ff"}};var ze={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"},env:{bg:"#d45dbf",fg:"#ffffff"}},Ve={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"},env:{bg:"#d787af",fg:"#ffffff"}},Ye={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"},env:{bg:"#d787af",fg:"#ffffff"}};var Xe={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"},env:{bg:"#3b4252",fg:"#b48ead"}},Je={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"},env:{bg:"#4e4e4e",fg:"#d787af"}},qe={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"},env:{bg:"#585858",fg:"#ff87af"}};var Ke={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"},env:{bg:"#24283b",fg:"#fca7ea"}},Ze={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"},env:{bg:"#303050",fg:"#ff87ff"}},Qe={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"},env:{bg:"#444470",fg:"#ff87ff"}};var et={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"},env:{bg:"#21202e",fg:"#eb6f92"}},tt={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"},env:{bg:"#303030",fg:"#ff5f87"}},nt={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"},env:{bg:"#444444",fg:"#ff5f87"}};var ot={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"},env:{bg:"#3c3836",fg:"#d3869b"}},rt={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"},env:{bg:"#444444",fg:"#d787af"}},st={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"},env:{bg:"#585858",fg:"#ff87af"}};var we={dark:je,"dark-ansi256":He,"dark-ansi":Ge,light:ze,"light-ansi256":Ve,"light-ansi":Ye,nord:Xe,"nord-ansi256":Je,"nord-ansi":qe,"tokyo-night":Ke,"tokyo-night-ansi256":Ze,"tokyo-night-ansi":Qe,"rose-pine":et,"rose-pine-ansi256":tt,"rose-pine-ansi":nt,gruvbox:ot,"gruvbox-ansi256":rt,"gruvbox-ansi":st};function K(n,e){let t=we[n];if(!t)return null;if(e==="none"||e==="ansi"){let o=we[`${n}-ansi`];if(o)return o}if(e==="ansi256"){let o=we[`${n}-ansi256`];if(o)return o}return t}var f=(n,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${n}`,...e);};var Lt=promisify(exec),O=class{isGitRepo(e){try{return S.existsSync(_.join(e,".git"))}catch{return false}}async execGitAsync(e,t){return Lt(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={},o){let r,s=this.isWorktree(e);if(s)r=e;else if(o&&this.isGitRepo(o))r=o;else if(this.isGitRepo(e))r=e;else {let i=await this.findGitRoot(e);if(!i)return null;r=i;}try{let i=await this.getStatusWithBranchAsync(r),a=await this.getAheadBehindAsync(r),c={branch:i.branch||"detached",status:i.status,ahead:a.ahead,behind:a.behind};t.showWorkingTree&&i.workingTree&&(c.staged=i.workingTree.staged,c.unstaged=i.workingTree.unstaged,c.untracked=i.workingTree.untracked,c.conflicts=i.workingTree.conflicts);let l={},g={};t.showSha&&(l.sha=this.getShaAsync(r)),t.showTag&&(l.tag=this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(l.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,d]of Object.entries(l))try{let p=await d;u.set(m,p);}catch{}return Object.keys(g).length>0&&(await Promise.allSettled(Object.entries(g).map(async([d,p])=>({key:d,value:await p})))).forEach(d=>{d.status==="fulfilled"&&u.set(d.value.key,d.value.value);}),t.showSha&&(c.sha=u.get("sha")||void 0),t.showOperation&&(c.operation=this.getOngoingOperation(r)||void 0),t.showTag&&(c.tag=u.get("tag")||void 0),t.showTimeSinceCommit&&(c.timeSinceCommit=u.get("timeSinceCommit")||void 0),t.showStashCount&&(c.stashCount=u.get("stashCount")||0),t.showUpstream&&(c.upstream=u.get("upstream")||void 0),t.showRepoName&&(c.repoName=u.get("repoName")||void 0,c.isWorktree=s),c}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}}resolveGitDir(e){let t=_.join(e,".git");if(S.existsSync(t)&&S.statSync(t).isFile()){let r=S.readFileSync(t,"utf-8").match(/^gitdir:\s*(.+)$/m);if(r?.[1])return _.resolve(e,r[1].trim())}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return S.existsSync(_.join(t,"MERGE_HEAD"))?"MERGE":S.existsSync(_.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":S.existsSync(_.join(t,"REVERT_HEAD"))?"REVERT":S.existsSync(_.join(t,"BISECT_LOG"))?"BISECT":S.existsSync(_.join(t,"rebase-merge"))||S.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 o=(await this.execGitAsync("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!o)return null;let r=parseInt(o)*1e3,s=Date.now();return Math.floor((s-r)/1e3)}catch{return null}}async getStashCountAsync(e){try{let o=(await this.execGitAsync("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return o?o.split(`
|
|
2
|
+
import v from'process';import {json}from'stream/consumers';import X from'tty';import {exec,execSync}from'child_process';import {promisify}from'util';import S,{existsSync,readFileSync,createReadStream}from'fs';import _,{join,posix,dirname}from'path';import {get}from'https';import {URL}from'url';import Ae,{homedir}from'os';import {createHash}from'crypto';import {setTimeout}from'timers/promises';import {readdir,stat,readFile}from'fs/promises';import {createInterface}from'readline';function _e(n,e){if(e&&(n.toLowerCase()==="transparent"||n.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${o};${r}m`}function J(n,e=false){if(!n||n==="")return "";let t=n.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(n.includes("\x1B[")&&n.includes("m")){let o=n.match(/\[(\d+)m/);if(o&&o[1]){let r=parseInt(o[1],10);if(r>=40&&r<=47)return `\x1B[${r-10}m`;if(r>=100&&r<=107)return `\x1B[${r-10}m`}}return n.replace("48","38")}function q(){let{env:n}=v,e=true;n.NO_COLOR&&n.NO_COLOR!==""&&(e=false);let t=n.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||n.TERM==="dumb")return "none";if(n.CI)return ["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(r=>r in n)?"truecolor":"ansi";if(n.COLORTERM==="truecolor"||["xterm-kitty","xterm-ghostty","wezterm","alacritty","foot","contour"].includes(n.TERM||""))return "truecolor";if(n.TERM_PROGRAM)switch(n.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(n.TERM||""))return "ansi256";if(/-truecolor$/i.test(n.TERM||""))return "truecolor";if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM||"")||n.COLORTERM)return "ansi";if(X?.WriteStream?.prototype?.hasColors)try{if(!X.WriteStream.prototype.hasColors())return "none";let s=X.WriteStream.prototype.hasColors(256);return X.WriteStream.prototype.hasColors(16777216)?"truecolor":s?"ansi256":"ansi"}catch{}return "ansi"}function xe(n,e){if(e&&(n.toLowerCase()==="transparent"||n.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16),i=((a,c,l)=>a===c&&c===l?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(l/255*5))(t,o,r);return `\x1B[${e?"48":"38"};5;${i}m`}function Se(n,e){if(e&&(n.toLowerCase()==="transparent"||n.toLowerCase()==="none"))return "\x1B[49m";if(e)return "";let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16);return o>t&&o>r&&o>120?"\x1B[32m":t>o&&t>r&&t>120?"\x1B[31m":r>t&&r>o&&r>120?"\x1B[34m":(t+o+r)/3>150?"\x1B[37m":"\x1B[90m"}function We(n,e){let t=parseInt(n.slice(1,3),16),o=parseInt(n.slice(3,5),16),r=parseInt(n.slice(5,7),16),s=parseInt(e.slice(1,3),16),i=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return Math.sqrt((t-s)**2+(o-i)**2+(r-a)**2)}var je={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"},env:{bg:"#2d2d3d",fg:"#d0a0d0"}},He={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"},env:{bg:"#3a3a3a",fg:"#d787d7"}},Ge={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"},env:{bg:"#444444",fg:"#ff87ff"}};var ze={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"},env:{bg:"#d45dbf",fg:"#ffffff"}},Ve={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"},env:{bg:"#d787af",fg:"#ffffff"}},Ye={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"},env:{bg:"#d787af",fg:"#ffffff"}};var Xe={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"},env:{bg:"#3b4252",fg:"#b48ead"}},Je={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"},env:{bg:"#4e4e4e",fg:"#d787af"}},qe={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"},env:{bg:"#585858",fg:"#ff87af"}};var Ke={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"},env:{bg:"#24283b",fg:"#fca7ea"}},Ze={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"},env:{bg:"#303050",fg:"#ff87ff"}},Qe={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"},env:{bg:"#444470",fg:"#ff87ff"}};var et={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"},env:{bg:"#21202e",fg:"#eb6f92"}},tt={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"},env:{bg:"#303030",fg:"#ff5f87"}},nt={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"},env:{bg:"#444444",fg:"#ff5f87"}};var ot={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"},env:{bg:"#3c3836",fg:"#d3869b"}},rt={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"},env:{bg:"#444444",fg:"#d787af"}},st={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"},env:{bg:"#585858",fg:"#ff87af"}};var we={dark:je,"dark-ansi256":He,"dark-ansi":Ge,light:ze,"light-ansi256":Ve,"light-ansi":Ye,nord:Xe,"nord-ansi256":Je,"nord-ansi":qe,"tokyo-night":Ke,"tokyo-night-ansi256":Ze,"tokyo-night-ansi":Qe,"rose-pine":et,"rose-pine-ansi256":tt,"rose-pine-ansi":nt,gruvbox:ot,"gruvbox-ansi256":rt,"gruvbox-ansi":st};function K(n,e){let t=we[n];if(!t)return null;if(e==="none"||e==="ansi"){let o=we[`${n}-ansi`];if(o)return o}if(e==="ansi256"){let o=we[`${n}-ansi256`];if(o)return o}return t}var f=(n,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${n}`,...e);};var Lt=promisify(exec),O=class{isGitRepo(e){try{return S.existsSync(_.join(e,".git"))}catch{return false}}async execGitAsync(e,t){return Lt(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={},o){let r,s=this.isWorktree(e);if(s)r=e;else if(o&&this.isGitRepo(o))r=o;else if(this.isGitRepo(e))r=e;else {let i=await this.findGitRoot(e);if(!i)return null;r=i;}try{let i=await this.getStatusWithBranchAsync(r),a=await this.getAheadBehindAsync(r),c={branch:i.branch||"detached",status:i.status,ahead:a.ahead,behind:a.behind};t.showWorkingTree&&i.workingTree&&(c.staged=i.workingTree.staged,c.unstaged=i.workingTree.unstaged,c.untracked=i.workingTree.untracked,c.conflicts=i.workingTree.conflicts);let l={},u={};t.showSha&&(l.sha=this.getShaAsync(r)),t.showTag&&(l.tag=this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(l.timeSinceCommit=this.getTimeSinceLastCommitAsync(r)),t.showStashCount&&(u.stashCount=this.getStashCountAsync(r)),t.showUpstream&&(u.upstream=this.getUpstreamAsync(r)),t.showRepoName&&(u.repoName=this.getRepoNameAsync(r));let g=new Map;for(let[m,d]of Object.entries(l))try{let p=await d;g.set(m,p);}catch{}return Object.keys(u).length>0&&(await Promise.allSettled(Object.entries(u).map(async([d,p])=>({key:d,value:await p})))).forEach(d=>{d.status==="fulfilled"&&g.set(d.value.key,d.value.value);}),t.showSha&&(c.sha=g.get("sha")||void 0),t.showOperation&&(c.operation=this.getOngoingOperation(r)||void 0),t.showTag&&(c.tag=g.get("tag")||void 0),t.showTimeSinceCommit&&(c.timeSinceCommit=g.get("timeSinceCommit")||void 0),t.showStashCount&&(c.stashCount=g.get("stashCount")||0),t.showUpstream&&(c.upstream=g.get("upstream")||void 0),t.showRepoName&&(c.repoName=g.get("repoName")||void 0,c.isWorktree=s),c}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}}resolveGitDir(e){let t=_.join(e,".git");if(S.existsSync(t)&&S.statSync(t).isFile()){let r=S.readFileSync(t,"utf-8").match(/^gitdir:\s*(.+)$/m);if(r?.[1])return _.resolve(e,r[1].trim())}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return S.existsSync(_.join(t,"MERGE_HEAD"))?"MERGE":S.existsSync(_.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":S.existsSync(_.join(t,"REVERT_HEAD"))?"REVERT":S.existsSync(_.join(t,"BISECT_LOG"))?"BISECT":S.existsSync(_.join(t,"rebase-merge"))||S.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 o=(await this.execGitAsync("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!o)return null;let r=parseInt(o)*1e3,s=Date.now();return Math.floor((s-r)/1e3)}catch{return null}}async getStashCountAsync(e){try{let o=(await this.execGitAsync("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return o?o.split(`
|
|
3
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 o=(await this.execGitAsync("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return o?o.match(/\/([^/]+?)(\.git)?$/)?.[1]||_.basename(e):_.basename(e)}catch{return _.basename(e)}}isWorktree(e){try{let t=_.join(e,".git");return !!(S.existsSync(t)&&S.statSync(t).isFile())}catch{return false}}async getStatusWithBranchAsync(e){try{f(`[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
|
-
`),s=null,i="clean",a=0,c=0,l=0,
|
|
4
|
+
`),s=null,i="clean",a=0,c=0,l=0,u=0;for(let g of r)if(g){if(g.startsWith("## ")){let d=g.substring(3).split("...")[0];d&&d!=="HEAD (no branch)"&&(s=d);continue}if(g.length>=2){let m=g.charAt(0),d=g.charAt(1);if(m==="?"&&d==="?"){l++,i==="clean"&&(i="dirty");continue}let p=m+d;if(["DD","AU","UD","UA","DU","AA","UU"].includes(p)){u++,i="conflicts";continue}m!==" "&&m!=="?"&&(a++,i==="clean"&&(i="dirty")),d!==" "&&d!=="?"&&(c++,i==="clean"&&(i="dirty"));}}return {branch:s||await this.getFallbackBranch(e),status:i,workingTree:{staged:a,unstaged:c,untracked:l,conflicts:u}}}catch(t){return f(`Git status with branch command failed in ${e}:`,t),{branch:await this.getFallbackBranch(e),status:"clean"}}}async getFallbackBranch(e){try{let o=(await this.execGitAsync("git branch --show-current",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(o)return o}catch{try{let o=(await this.execGitAsync("git symbolic-ref --short HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(o)return o}catch{return null}}return null}async getAheadBehindAsync(e){try{f(`[GIT-EXEC] Running git ahead/behind in ${e}`);let[t,o]=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(o.stdout.trim())||0}}catch(t){return f(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}};var Nt=promisify(exec),N=class{async getSessionId(){try{if(!process.env.TMUX_PANE)return f("TMUX_PANE not set, not in tmux session"),null;f(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let t=(await Nt("tmux display-message -p '#S'",{encoding:"utf8",timeout:1e3})).stdout.trim();return f(`Tmux session ID: ${t||"empty"}`),t||null}catch(e){return f("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};function Q(){let n=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let o=t.trim();existsSync(o)&&n.push(o);}),n.length===0){let t=homedir(),o=join(t,".config","claude"),r=join(t,".claude");existsSync(o)&&n.push(o),existsSync(r)&&n.push(r);}return n}async function ee(n){let e=[];for(let t of n){let o=join(t,"projects");if(existsSync(o))try{let r=await readdir(o,{withFileTypes:!0});for(let s of r)if(s.isDirectory()){let i=posix.join(o,s.name);e.push(i);}}catch(r){f(`Failed to read projects directory ${o}:`,r);}}return e}async function te(n){let e=Q(),t=await ee(e);for(let o of t){let r=posix.join(o,`${n}.jsonl`);if(existsSync(r))return r}return null}async function lt(n,e){let t=[],o=posix.join(e,n,"subagents");try{let s=(await readdir(o)).filter(i=>i.startsWith("agent-")&&i.endsWith(".jsonl"));for(let i of s){let a=posix.join(o,i);try{let l=(await readFile(a,"utf-8")).split(`
|
|
5
5
|
`)[0];l&&JSON.parse(l).sessionId===n&&t.push(a);}catch{f(`Failed to check agent file ${a}`);}}}catch(r){f(`Failed to read subagents directory ${o}:`,r);}return t}async function ke(n){try{return (await stat(n)).mtime}catch{return null}}function Gt(n){let e=n.message?.id||(typeof n.raw.message=="object"&&n.raw.message!==null&&"id"in n.raw.message?n.raw.message.id:void 0),t="requestId"in n.raw?n.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var zt=1024*1024;async function I(n){try{let t=(await stat(n)).size,o;return t>zt?(f(`Using streaming parser for large file ${n} (${Math.round(t/1024)}KB)`),o=await Yt(n)):o=await Vt(n),f(`Parsed ${o.length} entries from ${n}`),o}catch(e){return f(`Failed to read file ${n}:`,e),[]}}async function Vt(n){let t=(await readFile(n,"utf-8")).trim().split(`
|
|
6
|
-
`).filter(r=>r.trim()),o=[];for(let r of t)try{let s=JSON.parse(r);if(!s.timestamp)continue;let i={timestamp:new Date(s.timestamp),message:s.message,costUSD:typeof s.costUSD=="number"?s.costUSD:void 0,isSidechain:s.isSidechain===!0,raw:s};o.push(i);}catch(s){f(`Failed to parse JSONL line: ${s}`);continue}return o}async function Yt(n){return new Promise((e,t)=>{let o=[],r=createReadStream(n,{encoding:"utf8"}),s=createInterface({input:r,crlfDelay:1/0});s.on("line",i=>{let a=i.trim();if(a)try{let c=JSON.parse(a);if(!c.timestamp)return;let l={timestamp:new Date(c.timestamp),message:c.message,costUSD:typeof c.costUSD=="number"?c.costUSD:void 0,isSidechain:c.isSidechain===!0,raw:c};o.push(l);}catch(c){f(`Failed to parse JSONL line: ${c}`);}}),s.on("close",()=>{e(o);}),s.on("error",i=>{f(`Streaming parser error for ${n}:`,i),t(i);}),r.on("error",i=>{f(`File stream error for ${n}:`,i),t(i);});})}async function it(n){try{let e=await ke(n);return e?{filePath:n,mtime:e}:null}catch{return null}}async function Xt(n,e){try{let t=await readdir(n,{withFileTypes:!0}),o=t.filter(a=>!a.isDirectory()&&a.name.endsWith(".jsonl")).map(a=>it(posix.join(n,a.name))),r=t.filter(a=>a.isDirectory()).map(async a=>{let c=posix.join(n,a.name,"subagents");try{return (await readdir(c)).filter(g=>g.startsWith("agent-")&&g.endsWith(".jsonl")).map(g=>it(posix.join(c,g)))}catch{return []}}),[s,i]=await Promise.all([Promise.all(o),Promise.all(r).then(a=>Promise.all(a.flat()))]);return [...s,...i].filter(a=>a!==null&&(!e||e(a.filePath,a.mtime)))}catch(t){return f(`Failed to read project directory ${n}:`,t),[]}}async function ne(n,e,t=false){let o=Q(),r=await ee(o),s=new Set,i=r.map(p=>Xt(p,e)),c=(await Promise.all(i)).flat().filter(p=>p!==null);t&&c.sort((p,h)=>h.mtime.getTime()-p.mtime.getTime());let l=c.map(p=>p.filePath),g=[],u=l.map(async p=>(await I(p)).filter(b=>!n||n(b))),m=await Promise.all(u);for(let p of m)g.push(...p);g.sort((p,h)=>p.timestamp.getTime()-h.timestamp.getTime());let d=[];for(let p of g){let h=Gt(p);h&&s.has(h)||(h&&s.add(h),d.push(p));}return d}var E=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(!S.existsSync(t))return false;try{let o=S.readFileSync(t,"utf-8"),r=parseInt(o.trim(),10);if(isNaN(r))return f(`Invalid PID in lock file ${e}, removing stale lock`),S.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(s){return s.code==="ESRCH"?(f(`Removing stale lock file ${e} for dead process ${r}`),S.unlinkSync(t),!1):(f(`Error checking process ${r} for lock ${e}:`,s),!0)}}catch(o){return f(`Error reading lock file ${e}:`,o),true}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let s=_.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await S.promises.writeFile(s,a,{flag:"wx"}),f(`Lock acquired for ${e}`),!0}catch(c){if(c.code==="EEXIST")await setTimeout(50);else throw c}return f(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=_.join(this.LOCKS_DIR,e);try{await S.promises.unlink(t),f(`Lock released for ${e}`);}catch(o){o.code!=="ENOENT"&&f(`Error releasing lock for ${e}:`,o);}}static async ensureCacheDirectories(){try{await Promise.all([S.promises.mkdir(this.CACHE_DIR,{recursive:!0}),S.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),S.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){f("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 s="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)){f(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let g=await S.promises.readFile(i,s),u=JSON.parse(g);return !t||u.timestamp>=t?(f(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(u.data)):(f(`${e} cache outdated: cache=${u.timestamp}, latest=${t}`),null)}catch(g){if(g.code==="ENOENT")return f(`No shared ${e} usage cache found`),null;let u=c+1;f(`Attempt ${u} failed to read ${e} cache: ${g.message}. Retrying...`),await setTimeout(75);}}return f(`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,o){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){f(`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=o||Date.now(),l=JSON.stringify({data:t,timestamp:a});await S.promises.writeFile(i,l,"utf-8"),f(`[CACHE-SET] ${e} disk cache stored`);}catch(i){f(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(r);}}static async getLatestTranscriptMtime(){try{let e=Q(),t=await ee(e),o=0;for(let r of t)try{let i=(await S.promises.readdir(r)).filter(a=>a.endsWith(".jsonl"));for(let a of i){let c=_.join(r,a),l=await ke(c);l&&l.getTime()>o&&(o=l.getTime());}}catch(s){f(`Failed to read project directory ${r}:`,s);continue}return o}catch(e){return f("Failed to get latest transcript mtime:",e),Date.now()}}};var oe={"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}},R=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 E.getUsageCache("pricing",t)}static async saveDiskCache(e){await E.setUsageCache("pricing",e);}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),o=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},r=>{if(r.statusCode!==200){f(`HTTP ${r.statusCode}: ${r.statusMessage}`),e(null);return}let s="",i=0,a=1024*1024;r.on("data",c=>{if(i+=c.length,i>a){f("Response too large"),o.destroy(),e(null);return}s+=c;}),r.on("end",()=>{try{let l=JSON.parse(s),g=l._meta,u={};for(let[m,d]of Object.entries(l))m!=="_meta"&&(u[m]=d);this.validatePricingData(u)?(f(`Fetched fresh pricing from GitHub for ${Object.keys(u).length} models`),f(`Pricing last updated: ${g?.updated||"unknown"}`),e(u)):(f("Invalid pricing data structure"),e(null));}catch(c){f("Failed to parse JSON:",c),e(null);}}),r.on("error",c=>{f("Response error:",c),e(null);});});o.on("error",r=>{f("Request error:",r),e(null);}),o.on("timeout",()=>{f("Request timeout"),o.destroy(),e(null);}),o.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return f(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return f(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,f(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),f(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,f(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(f(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(oe).length} models`),this.executionCache=oe,f(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(oe).length} models`),oe)}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 o=t;if(typeof o.input!="number"||typeof o.output!="number"||typeof o.cache_read!="number")return false}return true}static async getModelPricing(e){if(this.modelPricingCache.has(e))return f(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),o;return t[e]?o=t[e]:o=this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,o),f(`[CACHE-SET] Model pricing cache: ${e}`),o}static fuzzyMatchModel(e,t){let o=e.toLowerCase();for(let[s,i]of Object.entries(t))if(s.toLowerCase()===o)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:s,fallback:i}of r)if(s.some(a=>o.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 o=e.message?.usage;if(!o)return 0;let r=this.extractModelId(e),s=await this.getModelPricing(r),i=o.input_tokens||0,a=o.output_tokens||0,c=o.cache_creation_input_tokens||0,l=o.cache_read_input_tokens||0,g=i/1e6*s.input,u=a/1e6*s.output,m=l/1e6*s.cache_read,d=c/1e6*s.cache_write_5m;return g+u+d+m}static extractModelId(e){if(e.model&&typeof e.model=="string")return e.model;let t=e.message;if(t?.model){let o=t.model;return typeof o=="string"?o:o?.id||"claude-3-5-sonnet-20241022"}return e.model_id&&typeof e.model_id=="string"?e.model_id:"claude-3-5-sonnet-20241022"}};function en(n){return {timestamp:n.timestamp.toISOString(),message:{usage:{input_tokens:n.message?.usage?.input_tokens||0,output_tokens:n.message?.usage?.output_tokens||0,cache_creation_input_tokens:n.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:n.message?.usage?.cache_read_input_tokens}},costUSD:n.costUSD}}var re=class{async getSessionUsage(e){try{let t=await te(e);if(!t)return f(`No transcript found for session: ${e}`),null;f(`Found transcript at: ${t}`);let o=await I(t),r=dirname(t),s=await lt(e,r);f(`Found ${s.length} agent transcripts for session`);for(let c of s){let l=await I(c);o.push(...l);}if(o.length===0)return {totalCost:0,entries:[]};let i=[],a=0;for(let c of o)if(c.message?.usage){let l=en(c);if(l.costUSD!==void 0)a+=l.costUSD;else {let g=await R.calculateCostForEntry(c.raw);l.costUSD=g,a+=g;}i.push(l);}return f(`Parsed ${i.length} usage entries, total cost: $${a.toFixed(4)}`),{totalCost:a,entries:i}}catch(t){return f(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,o)=>({input:t.input+(o.message.usage.input_tokens||0),output:t.output+(o.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(o.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(o.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e,t){let o=await this.getSessionUsage(e);if(!o||o.entries.length===0)return {cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};let r=this.calculateTokenBreakdown(o.entries),s=r.input+r.output+r.cacheCreation+r.cacheRead,i=o.totalCost,a=t?.cost?.total_cost_usd??null;return {cost:i??a,calculatedCost:i,officialCost:a,tokens:s,tokenBreakdown:r}}},j=class{sessionProvider=new re;async getUsageInfo(e,t){try{return f(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e,t)}}catch(o){return f(`Error getting usage info for session ${e}:`,o),{session:{cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null}}}}};var H=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},o=this.getModelType(e);return t[o]||t.default||2e5}getModelType(e){let t=e.toLowerCase();return t.includes("sonnet")?"sonnet":t.includes("opus")?"opus":"default"}calculatePercentages(e,t,o=33e3){let r=Math.min(100,Math.max(0,Math.round(e/t*100))),s=Math.max(1,t-o),i=Math.min(100,Math.max(0,Math.round(e/s*100))),a=Math.max(0,100-i);return {percentage:r,usablePercentage:i,contextLeftPercentage:a,usableTokens:s}}calculateContextFromHookData(e,t=33e3){let o=e.context_window?.current_usage;if(!o)return f("No current_usage in hook data, falling back to transcript parsing"),null;let r=e.context_window?.context_window_size||2e5,s=(o.input_tokens||0)+(o.cache_creation_input_tokens||0)+(o.cache_read_input_tokens||0);f(`Native current_usage: input=${o.input_tokens}, cache_create=${o.cache_creation_input_tokens}, cache_read=${o.cache_read_input_tokens}, total=${s} (limit: ${r})`);let i=this.calculatePercentages(s,r,t);return {totalTokens:s,maxTokens:r,...i}}async calculateContextTokensFromTranscript(e,t,o=33e3){try{f(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return f("Transcript file is empty"),null}catch{return f("Could not read transcript file"),null}let r=await I(e);if(r.length===0)return f("No entries in transcript"),null;let s=null;for(let i=r.length-1;i>=0;i--){let a=r[i];if(a&&a.message?.usage?.input_tokens&&a.isSidechain!==!0){s=a,f(`Context segment: Found most recent entry at ${a.timestamp.toISOString()}, stopping search`);break}}if(s?.message?.usage){let i=s.message.usage,a=(i.input_tokens||0)+(i.cache_read_input_tokens||0)+(i.cache_creation_input_tokens||0),c=t?this.getContextLimit(t):2e5;f(`Most recent main chain context: ${a} tokens (limit: ${c})`);let l=this.calculatePercentages(a,c,o);return {totalTokens:a,maxTokens:c,...l}}return f("No main chain entries with usage data found"),null}catch(r){return f(`Error reading transcript: ${r instanceof Error?r.message:String(r)}`),null}}async getContextInfo(e,t=33e3){let o=this.calculateContextFromHookData(e,t);return o||this.calculateContextTokensFromTranscript(e.transcript_path,e.model?.id,t)}};var G=class{async loadTranscriptEntries(e){try{let t=await te(e);if(!t)return f(`No transcript found for session: ${e}`),[];f(`Loading transcript from: ${t}`);let r=(await readFile(t,"utf-8")).trim().split(`
|
|
7
|
-
`).filter(i=>i.trim()),s=[];for(let i of r)try{let a=JSON.parse(i);if(a.isSidechain===!0)continue;s.push(a);}catch(a){f(`Failed to parse JSONL line: ${a}`);continue}return f(`Loaded ${s.length} transcript entries`),s}catch(t){return f(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let o=t.type||t.message?.role||t.message?.type,r=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return o==="user"&&!r}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),o=null,r=null;for(let s of t)if(s.timestamp)try{let i=new Date(s.timestamp),a=s.type||s.message?.role||s.message?.type,c=s.type==="user"&&s.message?.content?.[0]?.type==="tool_result";if(a==="user"&&!c)o=i;else if(a==="assistant"&&o){let g=(i.getTime()-o.getTime())/1e3;g>.1&&g<300&&(r=g);}}catch{continue}return r}async getMetricsInfo(e,t){try{if(f(`Getting metrics from hook data for session: ${e}`),!t.cost)return f("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let o=await this.loadTranscriptEntries(e),r=this.calculateMessageCount(o),s=this.calculateLastResponseTime(o);return {responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:s,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed}}catch(o){return f(`Error getting metrics from hook data for session ${e}:`,o),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function k(n){return n===null?"$0.00":n<.01?"<$0.01":`$${n.toFixed(2)}`}function T(n){return n===null||n===0?"0 tokens":n>=1e6?`${(n/1e6).toFixed(1)}M tokens`:n>=1e3?`${(n/1e3).toFixed(1)}K tokens`:`${n} tokens`}function gt(n){if(!n)return "0 tokens";let e=[];if(n.input>0&&e.push(`${T(n.input).replace(" tokens","")} in`),n.output>0&&e.push(`${T(n.output).replace(" tokens","")} out`),n.cacheCreation>0||n.cacheRead>0){let t=n.cacheCreation+n.cacheRead;e.push(`${T(t).replace(" tokens","")} cached`);}return e.length>0?e.join(" + "):"0 tokens"}function ft(n){return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:n<604800?`${Math.floor(n/86400)}d`:`${Math.floor(n/604800)}w`}function se(n){return n<60?`${n.toFixed(0)}s`:n<3600?`${(n/60).toFixed(0)}m`:n<86400?`${(n/3600).toFixed(1)}h`:`${(n/86400).toFixed(1)}d`}var on=/^(?:(?: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 ie(n){if(!n)return "Claude";let e=n.trim().match(on);if(!e?.groups)return n;let{family:t,newMajor:o,newMinor:r,oldMajor:s,oldMinor:i,oldFamily:a}=e.groups,c=t||a,l=o||s,g=r||i;if(c&&l){let u=c.charAt(0).toUpperCase()+c.slice(1).toLowerCase(),m=g?`${l}.${g}`:l;return `${u} ${m}`}return n}function ae(n){let e=n.includes("/")?"/":"\\",t=n.split(e);return t.map((o,r)=>r===t.length-1||o==="~"||o===""?o:o.charAt(0)).join(e)}function ut(n){return n<60?`${n.toFixed(1)}s`:`${(n/60).toFixed(1)}m`}function mt(n){let e=Math.floor(n/60),t=n%60;return e>0?`${e}h ${t}m left`:`${t}m left`}function rn(n,e){return !e||e<=0||n<0?null:Math.min(100,n/e*100)}function D(n,e,t=80){let o=rn(n,e);if(o===null)return {percentage:null,isWarning:false,displayText:""};let r=`${o.toFixed(0)}%`,s=o>=t,i="";return s?i=` !${r}`:o>=50?i=` +${r}`:i=` ${r}`,{percentage:o,isWarning:s,displayText:i}}var sn={ball:{filled:"\u2500",empty:"\u2500",marker:"\u25CF"},blocks:{filled:"\u2588",empty:"\u2591"},"blocks-line":{filled:"\u2588",empty:"\u2500"},capped:{filled:"\u2501",empty:"\u2504",cap:"\u2578"},dots:{filled:"\u25CF",empty:"\u25CB"},filled:{filled:"\u25A0",empty:"\u25A1"},geometric:{filled:"\u25B0",empty:"\u25B1"},line:{filled:"\u2501",empty:"\u2504"},squares:{filled:"\u25FC",empty:"\u25FB"}},z=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,o){let r=e.workspace?.current_dir||e.cwd||"/",s=e.workspace?.project_dir,i=o?.style??(o?.showBasename?"basename":"full");if(i==="basename")return {text:_.basename(r)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let a=process.env.HOME||process.env.USERPROFILE,c=r,l=s;a&&(r.startsWith(a)&&(c=r.replace(a,"~")),s&&s.startsWith(a)&&(l=s.replace(a,"~")));let g=this.getDisplayDirectoryName(c,l);return i==="fish"&&(g=ae(g)),{text:g,bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,o){if(!e)return null;let r=[];if(o?.showRepoName&&e.repoName&&(r.push(e.repoName),e.isWorktree&&r.push(this.symbols.git_worktree)),o?.showOperation&&e.operation&&r.push(`[${e.operation}]`),r.push(`${this.symbols.branch} ${e.branch}`),o?.showTag&&e.tag&&r.push(`${this.symbols.git_tag} ${e.tag}`),o?.showSha&&e.sha&&r.push(`${this.symbols.git_sha} ${e.sha}`),o?.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}`)),o?.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(o?.showUpstream&&e.upstream&&r.push(`${this.symbols.git_upstream}${e.upstream}`),o?.showStashCount&&e.stashCount&&e.stashCount>0&&r.push(`${this.symbols.git_stash} ${e.stashCount}`),o?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=ft(e.timeSinceCommit);r.push(`${this.symbols.git_time} ${i}`);}let s=this.symbols.git_clean;return e.status==="conflicts"?s=this.symbols.git_conflicts:e.status==="dirty"&&(s=this.symbols.git_dirty),r.push(s),{text:r.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}renderModel(e,t){let o=e.model?.display_name||"Claude",r=ie(o);return {text:`${this.symbols.model} ${r}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,o){let r=o?.type||"cost",s=o?.costSource,i=this.config.budget?.session,a=()=>s==="calculated"?e.session.calculatedCost:s==="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,o){let s=o?.displayStyle??"text",i=s==="text"?"remaining":"used",a=o?.percentageMode??i,c=s==="bar"?{filled:this.symbols.bar_filled,empty:this.symbols.bar_empty}:sn[s]??null,l=a==="remaining"?"100%":"0%";if(!e)return c?{text:`${c.empty.repeat(10)} ${l}`,bgColor:t.contextBg,fgColor:t.contextFg}:{text:`${this.symbols.context_time} 0 (${l})`,bgColor:t.contextBg,fgColor:t.contextFg};let g=t.contextBg,u=t.contextFg;e.contextLeftPercentage<=20?(g=t.contextCriticalBg,u=t.contextCriticalFg):e.contextLeftPercentage<=40&&(g=t.contextWarningBg,u=t.contextWarningFg);let m=a==="remaining"?e.contextLeftPercentage:e.usablePercentage,d=Math.round(e.usablePercentage/100*10),p=10-d;if(c){let b=this.buildBar(c,d,p,10);return {text:o?.showPercentageOnly?`${b} ${m}%`:`${b} ${e.totalTokens.toLocaleString()} (${m}%)`,bgColor:g,fgColor:u}}return {text:o?.showPercentageOnly?`${this.symbols.context_time} ${m}%`:`${this.symbols.context_time} ${e.totalTokens.toLocaleString()} (${m}%)`,bgColor:g,fgColor:u}}buildBar(e,t,o,r){if(e.marker){let s=Math.min(t,r-1);return e.filled.repeat(s)+e.marker+e.empty.repeat(r-s-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(o):e.filled.repeat(t)+e.empty.repeat(o)}renderMetrics(e,t,o,r){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let s=[];if(r?.showLastResponseTime&&e.lastResponseTime!==null){let i=e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;s.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`;s.push(`${this.symbols.metrics_response} ${i}`);}if(r?.showDuration!==false&&e.sessionDuration!==null){let i=se(e.sessionDuration);s.push(`${this.symbols.metrics_duration} ${i}`);}return r?.showMessageCount!==false&&e.messageCount!==null&&s.push(`${this.symbols.metrics_messages} ${e.messageCount}`),r?.showLinesAdded!==false&&e.linesAdded!==null&&e.linesAdded>0&&s.push(`${this.symbols.metrics_lines_added} ${e.linesAdded}`),r?.showLinesRemoved!==false&&e.linesRemoved!==null&&e.linesRemoved>0&&s.push(`${this.symbols.metrics_lines_removed} ${e.linesRemoved}`),s.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:s.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,o){let r;if(e.cost===null&&e.tokens===null)r="No active block";else {let s=o?.type||"cost",i=o?.burnType,a=this.config.budget?.block,c=e.timeRemaining!==null?(()=>{let u=Math.floor(e.timeRemaining/60),m=e.timeRemaining%60;return u>0?`${u}h ${m}m`:`${m}m`})():null,l;switch(s){case "cost":l=this.formatUsageWithBudget(e.cost,null,null,"cost",a?.amount,a?.warningThreshold,a?.type);break;case "tokens":l=this.formatUsageWithBudget(null,e.tokens,null,"tokens",a?.amount,a?.warningThreshold,a?.type);break;case "weighted":let u=a?.type==="tokens"?a.amount:void 0,m=T(e.weightedTokens);if(u&&e.weightedTokens!==null){let d=D(e.weightedTokens,u,a?.warningThreshold||80);l=`${m}${d.displayText}`;}else l=`${m} (weighted)`;break;case "both":l=this.formatUsageWithBudget(e.cost,e.tokens,null,"both",a?.amount,a?.warningThreshold,a?.type);break;case "time":l=c||"N/A";break;default:l=this.formatUsageWithBudget(e.cost,null,null,"cost",a?.amount,a?.warningThreshold,a?.type);}let g="";if(i&&i!=="none")switch(i){case "cost":g=` | ${e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A"}`;break;case "tokens":g=` | ${e.tokenBurnRate!==null?`${T(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?`${T(Math.round(e.tokenBurnRate))}/h`:"N/A";g=` | ${d} / ${p}`;break}s==="time"?r=l:r=c?`${l}${g} (${c} left)`:`${l}${g}`;}return {text:`${this.symbols.block_cost} ${r}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,o="cost"){let r=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,o,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)||_.basename(t)||"project":e}formatUsageDisplay(e,t,o,r){switch(r){case "cost":return k(e);case "tokens":return T(t);case "both":return `${k(e)} (${T(t)})`;case "breakdown":return gt(o);default:return k(e)}}formatUsageWithBudget(e,t,o,r,s,i=80,a){let c=this.formatUsageDisplay(e,t,o,r);if(s&&s>0){let l=null;if(a==="tokens"&&t!==null?l=t:(a==="cost"&&e!==null||!a&&e!==null)&&(l=e),l!==null){let g=D(l,s,i);return c+g.displayText}}return c}renderVersion(e,t,o){return e.version?{text:`${this.symbols.version} v${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}:null}renderEnv(e,t){let o=process.env[t.variable];if(!o)return null;let r=t.prefix??t.variable;return {text:r?`${this.symbols.env} ${r}: ${o}`:`${this.symbols.env} ${o}`,bgColor:e.envBg,fgColor:e.envFg}}};function an(n){return n.includes("opus")?5:(n.includes("sonnet")||n.includes("haiku"),1)}function cn(n){return {timestamp:n.timestamp,usage:{inputTokens:n.message?.usage?.input_tokens||0,outputTokens:n.message?.usage?.output_tokens||0,cacheCreationInputTokens:n.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:n.message?.usage?.cache_read_input_tokens||0},costUSD:n.costUSD||0,model:n.message?.model||"unknown"}}var ce=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,o=[],r=[...e].sort((a,c)=>a.timestamp.getTime()-c.timestamp.getTime()),s=null,i=[];for(let a of r){let c=a.timestamp;if(s==null)s=this.floorToHour(c),i=[a];else {let l=c.getTime()-s.getTime(),g=i[i.length-1];if(g==null)continue;let u=g.timestamp,m=c.getTime()-u.getTime();l>t||m>t?(o.push(i),s=this.floorToHour(c),i=[a]):i.push(a);}}return s!=null&&i.length>0&&o.push(i),o}createBlockInfo(e,t){let o=new Date,r=this.sessionDurationHours*60*60*1e3,s=new Date(e.getTime()+r),i=t[t.length-1],a=i!=null?i.timestamp:e,c=o.getTime()-a.getTime()<r&&o<s;return {block:t,isActive:c}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if(!o||o.length===0)continue;let r=o[0];if(!r)continue;let s=this.floorToHour(r.timestamp),i=this.createBlockInfo(s,o);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{f("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let o=await ne(void 0,(c,l)=>l>=e,!0),r=[];for(let c of o)if(c.message?.usage){let l=cn(c);!l.costUSD&&c.raw&&(l.costUSD=await R.calculateCostForEntry(c.raw)),r.push(l);}let s=this.identifySessionBlocks(r);f(`Block segment: Found ${s.length} session blocks`);let i=this.findActiveBlock(s),a=[];if(i&&i.length>0){f(`Block segment: Found active block with ${i.length} entries`);let c=i[0],l=i[i.length-1];c&&l&&f(`Block segment: Active block from ${c.timestamp.toISOString()} to ${l.timestamp.toISOString()}`),a=i;}else f("Block segment: No active block found"),a=[];return a}catch(e){return f("Error loading block entries:",e),[]}}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return f("Block segment: No entries in current block"),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((l,g)=>l+g.costUSD,0),o=e.reduce((l,g)=>l+g.usage.inputTokens+g.usage.outputTokens+g.usage.cacheCreationInputTokens+g.usage.cacheReadInputTokens,0),r=e.reduce((l,g)=>{let u=g.usage.inputTokens+g.usage.outputTokens+g.usage.cacheCreationInputTokens+g.usage.cacheReadInputTokens,m=an(g.model);return l+u*m},0),s=new Date,i=null;if(e.length>0){let l=e[0];if(l){let g=this.sessionDurationHours*60*60*1e3,u=this.floorToHour(l.timestamp),m=new Date(u.getTime()+g);i=Math.max(0,Math.round((m.getTime()-s.getTime())/(1e3*60)));}}let a=null,c=null;if(e.length>=1&&(t>0||o>0)){let l=e.map(m=>m.timestamp).sort((m,d)=>m.getTime()-d.getTime()),g=l[0],u=l[l.length-1];if(g&&u){let m=(u.getTime()-g.getTime())/6e4;m>0&&(t>0&&(a=t/m*60),o>0&&(c=o/m*60));}}return f(`Block segment: $${t.toFixed(2)}, ${o} tokens, ${i}m remaining, burn rate: ${a?"$"+a.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:o,weightedTokens:r,timeRemaining:i,burnRate:a,tokenBurnRate:c}}catch(e){return f("Error getting active block info:",e),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function V(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${o}`}function ln(n){return n.inputTokens+n.outputTokens+n.cacheCreationInputTokens+n.cacheReadInputTokens}function gn(n){return {timestamp:n.timestamp,usage:{inputTokens:n.message?.usage?.input_tokens||0,outputTokens:n.message?.usage?.output_tokens||0,cacheCreationInputTokens:n.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:n.message?.usage?.cache_read_input_tokens||0},costUSD:n.costUSD||0,model:n.message?.model||"unknown"}}var le=class{async loadTodayEntries(){let t=V(new Date);f(`Today segment: Loading entries for date ${t}`);let o=await E.getLatestTranscriptMtime(),r=await E.getUsageCache("today",o);if(r)return f("Using shared today usage cache"),r;let s=new Date;s.setDate(s.getDate()-1),s.setHours(0,0,0,0);let i=(m,d)=>d>=s,a=new Date;a.setHours(0,0,0,0);let l=await ne(m=>m.timestamp>=a,i,true),g=[],u=0;for(let m of l)if(V(m.timestamp)===t&&m.message?.usage){let p=gn(m);!p.costUSD&&m.raw&&(p.costUSD=await R.calculateCostForEntry(m.raw)),g.push(p),u++;}return f(`Today segment: Found ${u} entries for today (${t})`),await E.setUsageCache("today",g,o),g}async getTodayEntries(){try{return await this.loadTodayEntries()}catch(e){return f("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:V(new Date)};let t=e.reduce((s,i)=>s+i.costUSD,0),o=e.reduce((s,i)=>s+ln(i.usage),0),r=e.reduce((s,i)=>({input:s.input+i.usage.inputTokens,output:s.output+i.usage.outputTokens,cacheCreation:s.cacheCreation+i.usage.cacheCreationInputTokens,cacheRead:s.cacheRead+i.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return f(`Today segment: $${t.toFixed(2)}, ${o} tokens total`),{cost:t,tokens:o,tokenBreakdown:r,date:V(new Date)}}catch(e){return f("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:V(new Date)}}}};var pt="\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:"\u25C6",metrics_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u2197",version:"\u25C8",bar_filled:"\u25AA",bar_empty:"\u25AB",env:"\u2699"},ht={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",teeLeft:"\u251C",teeRight:"\u2524"},bt={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",teeLeft:"+",teeRight:"+"},fe={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:"-",env:"$"};var fn="\x1B",un=new RegExp(`${fn}\\[[0-9;]*m`,"g"),mn=/^[a-zA-Z0-9/]+$/;function dn(){if(process.platform==="win32")return null;let n=process.pid.toString();for(let e=0;e<10;e++)try{let o=execSync(`ps -o ppid=,tty= -p ${n}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(/\s+/),r=o[0],s=o[1];if(s&&s!=="?"&&s!=="??"&&mn.test(s))return s;if(!r||r==="1"||r==="0")break;n=r;}catch{break}return null}function pn(){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 hn(){let n=dn();if(n)try{let t=execSync(`stty size < /dev/${n}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"],shell:"/bin/sh"}).trim().split(" ")[1];if(t){let o=parseInt(t,10);if(!isNaN(o)&&o>0)return o}}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 $e(){let n=o=>Math.floor(o*.7),e=process.env.COLUMNS;if(e){let o=parseInt(e,10);if(!isNaN(o)&&o>0)return n(o)}if(process.stdout.columns&&process.stdout.columns>0)return n(process.stdout.columns);if(process.platform==="win32"){let o=pn();if(o)return n(o)}let t=hn();return t?n(t):null}function Pe(n){return n.replace(un,"")}function F(n){return Pe(n).length}function y(n,e,t){return e?`${e}${n}${t}`:n}function bn(n,e){let t=F(n);return t>=e?n:n+" ".repeat(e-t)}var yt="\x1B",yn=new RegExp(`(${yt}\\[[0-9;]*m)`);function Cn(n,e){if(Pe(n).length<=e)return n;let t=0,o="",r=n.split(yn);for(let s of r){if(s.startsWith(yt)){o+=s;continue}for(let i of s){if(t>=e-1)return o+="\u2026",o;o+=i,t++;}}return o}function x(n,e,t){let o=t-2,r=Cn(e,o),s=bn(r,o);return n.vertical+" "+s+" "+n.vertical}function Y(n,e){return n.teeLeft+n.horizontal.repeat(e)+n.teeRight}function Ct(n,e){return n.bottomLeft+n.horizontal.repeat(e)+n.bottomRight}function _t(n,e){if(n.length===0)return "";if(n.length===1)return n[0]??"";let t=n.map(l=>F(l)),o=t.reduce((l,g)=>l+g,0),r=e-o,s=Math.max(2,Math.floor(r/(n.length-1))),i=new Array(n.length);i[n.length-1]=t[n.length-1]??0;for(let l=n.length-2;l>=0;l--)i[l]=(i[l+1]??0)+(t[l]??0);let a=n[0]??"",c=t[0]??0;for(let l=1;l<n.length;l++){let g=e-c-(i[l]??0)-(n.length-1-l)*2,u=Math.max(2,Math.min(s,g));a+=" ".repeat(u)+(n[l]??""),c+=u+(t[l]??0);}return a}function A(n,e,t){if(!e)return n;if(!n)return e;let o=F(n),r=F(e),s=t-o-r;return s<2?`${n} ${e}`:n+" ".repeat(s)+e}function xt(n,e,t){let o=n.hookData.model?.display_name||"Claude",r=ie(o).toLowerCase(),s="claude-powerline",i=` ${r} `,a=` ${s} `,c=t-1-i.length-a.length;if(c<2){let l=t-1-i.length;return e.topLeft+e.horizontal+i+e.horizontal.repeat(Math.max(0,l))+e.topRight}return e.topLeft+e.horizontal+i+e.horizontal.repeat(c)+a+e.topRight}function St(n,e,t,o,r){let s=Math.min(Math.floor(e*.45),40);if(!n.contextInfo)return null;let i=n.contextInfo.usablePercentage,a=Math.round(i/100*s),c=s-a,l=t.bar_filled.repeat(a)+t.bar_empty.repeat(c),g=n.contextInfo.totalTokens>=1e3?`${(n.contextInfo.totalTokens/1e3).toFixed(0)}k`:`${n.contextInfo.totalTokens}`,u=n.contextInfo.maxTokens>=1e3?`${(n.contextInfo.maxTokens/1e3).toFixed(0)}k`:`${n.contextInfo.maxTokens}`,m=r.contextFg;return i>=80?m=r.contextCriticalFg:i>=60&&(m=r.contextWarningFg),y(`${l} ${i}% ${g}/${u}`,m,o)}function _n(n){let e=n.workspace?.current_dir||n.cwd||"/",t=process.env.HOME||process.env.USERPROFILE;return t&&e.startsWith(t)?e.replace(t,"~"):e}function wt(n,e,t,o,r){let s=[];n.blockInfo&&s.push(y(pe(n.blockInfo,e,t),r.blockFg,o)),n.usageInfo&&s.push(y(Re(n.usageInfo,e,t),r.sessionFg,o)),n.todayInfo&&s.push(y(Be(n.todayInfo,e,t),r.todayFg,o));let i=Ee(n,e);return i.length>0&&s.push(y(i.join(" \xB7 "),r.metricsFg,o)),s}function Ee(n,e){let t=[];return n.metricsInfo&&(n.metricsInfo.sessionDuration!==null&&n.metricsInfo.sessionDuration>0&&t.push(`${e.metrics_duration} ${se(n.metricsInfo.sessionDuration)}`),n.metricsInfo.messageCount!==null&&n.metricsInfo.messageCount>0&&t.push(`${e.metrics_messages} ${n.metricsInfo.messageCount}`)),t}function me(n,e,t,o){let r=[];if(n.gitInfo){let i=`${e.branch} ${n.gitInfo.branch}`;n.gitInfo.status==="conflicts"?i+=` ${e.git_conflicts}`:n.gitInfo.status==="dirty"?i+=` ${e.git_dirty}`:i+=` ${e.git_clean}`,n.gitInfo.ahead>0&&(i+=` ${e.git_ahead}${n.gitInfo.ahead}`),n.gitInfo.behind>0&&(i+=` ${e.git_behind}${n.gitInfo.behind}`);let a=[];n.gitInfo.staged&&n.gitInfo.staged>0&&a.push(`+${n.gitInfo.staged}`),n.gitInfo.unstaged&&n.gitInfo.unstaged>0&&a.push(`~${n.gitInfo.unstaged}`),n.gitInfo.untracked&&n.gitInfo.untracked>0&&a.push(`?${n.gitInfo.untracked}`),a.length>0&&(i+=` (${a.join(" ")})`),r.push(y(i,o.gitFg,t));}let s=ae(_n(n.hookData));return r.push(y(s,o.modeFg,t)),r}function de(n,e,t,o,r){let s=[];if(n.hookData.version&&s.push(y(`${e.version} v${n.hookData.version}`,r.versionFg,o)),n.tmuxSessionId&&s.push(y(`tmux:${n.tmuxSessionId}`,r.tmuxFg,o)),n.metricsInfo){let a=[];if(n.metricsInfo.responseTime!==null&&!isNaN(n.metricsInfo.responseTime)&&n.metricsInfo.responseTime>0&&a.push(`${e.metrics_response} ${ut(n.metricsInfo.responseTime)}`),n.metricsInfo.linesAdded!==null&&n.metricsInfo.linesAdded>0&&a.push(`${e.metrics_lines_added}${n.metricsInfo.linesAdded}`),n.metricsInfo.linesRemoved!==null&&n.metricsInfo.linesRemoved>0&&a.push(`${e.metrics_lines_removed}${n.metricsInfo.linesRemoved}`),n.blockInfo?.burnRate!==null&&n.blockInfo?.burnRate!==void 0&&n.blockInfo.burnRate>0){let c=n.blockInfo.burnRate<1?`${(n.blockInfo.burnRate*100).toFixed(0)}c/h`:`$${n.blockInfo.burnRate.toFixed(2)}/h`;a.push(`${e.metrics_burn} ${c}`);}a.length>0&&s.push(y(a.join(" \xB7 "),r.metricsFg,o));}let i=t.display.lines.map(a=>a.segments.env).find(a=>a?.enabled);if(i&&i.variable){let a=process.env[i.variable];if(a){let c=i.prefix??i.variable;s.push(y(c?`${c}:${a}`:a,r.envFg,o));}}return s}function pe(n,e,t){let o=k(n.cost),r=`${e.block_cost} ${o}`;n.timeRemaining!==null&&(r+=` \xB7 ${mt(n.timeRemaining)}`);let s=t.budget?.block;if(s?.amount&&n.cost!==null){let i=D(n.cost,s.amount,s.warningThreshold||80);r+=i.displayText;}return r}function Re(n,e,t){let o=k(n.session.cost),r=n.session.tokens,s=r!==null&&r>0?T(r).replace(" tokens",""):null,i=`${e.session_cost} ${o}`;s&&(i+=` \xB7 ${s}`);let a=t.budget?.session;if(a?.amount&&n.session.cost!==null){let c=D(n.session.cost,a.amount,a.warningThreshold||80);i+=c.displayText;}return i}function Be(n,e,t){let o=k(n.cost),r=`${e.today_cost} ${o} today`,s=t.budget?.today;if(s?.amount&&n.cost!==null){let i=D(n.cost,s.amount,s.warningThreshold||80);r+=i.displayText;}return r}function Tt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,g=wt(t,i,a,c,l);g.length>0&&e.push(x(o,_t(g,r),s));}function kt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,g=me(t,i,c,l),u=de(t,i,a,c,l),m=g.join(" "),d=u.join(" \xB7 ");(m||d)&&(e.push(Y(o,s)),e.push(x(o,A(m,d,r),s)));}function vt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,g=[],u=[];t.blockInfo&&g.push(y(pe(t.blockInfo,i,a),l.blockFg,c)),t.todayInfo&&g.push(y(Be(t.todayInfo,i,a),l.todayFg,c)),t.usageInfo&&u.push(y(Re(t.usageInfo,i,a),l.sessionFg,c));let m=Ee(t,i);m.length>0&&u.push(y(m.join(" \xB7 "),l.metricsFg,c)),g.length>0&&e.push(x(o,A(g[0]??"",g[1]??"",r),s)),u.length>0&&e.push(x(o,A(u[0]??"",u[1]??"",r),s));}function $t(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,g=me(t,i,c,l);g.length>0&&(e.push(Y(o,s)),e.push(x(o,A(g[0]??"",g[1]??"",r),s)));let u=de(t,i,a,c,l);u.length>0&&(e.push(Y(o,s)),e.push(x(o,u.join(" \xB7 "),s)));}function Pt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n;t.blockInfo&&e.push(x(o,y(pe(t.blockInfo,i,a),l.blockFg,c),s));let g=[];t.usageInfo&&g.push(y(`${i.session_cost} ${k(t.usageInfo.session.cost)}`,l.sessionFg,c)),t.todayInfo&&g.push(y(`${i.today_cost} ${k(t.todayInfo.cost)} today`,l.todayFg,c)),g.length>0&&e.push(x(o,A(g[0]??"",g[1]??"",r),s));}function Et(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,g=me(t,i,c,l);g.length>0&&(e.push(Y(o,s)),e.push(x(o,A(g[0]??"",g[1]??"",r),s)));let u=de(t,i,a,c,l);u.length>0&&e.push(x(o,u.join(" \xB7 "),s));}var xn="\x1B[?2026h",Sn="\x1B[?2026l",wn=32,Tn=80,kn=55;function vn(n){return n>=Tn?"wide":n>=kn?"medium":"narrow"}function $n(n){return n&&n>0?Math.max(wn,n):80}function De(n,e,t,o,r){let s=(r.display.charset||"unicode")==="text"?fe:ge,i=n.colors,a=$n(o),c=a-2,l=c-2,g=vn(a),u=[];u.push(xt(n,e,c));let m=St(n,l,s,t,i);m&&u.push(x(e,m,c));let d={lines:u,data:n,box:e,contentWidth:l,innerWidth:c,sym:s,config:r,reset:t,colors:i};return g==="wide"?(Tt(d),kt(d)):g==="medium"?(vt(d),$t(d)):(Pt(d),Et(d)),u.push(Ct(e,c)),xn+u.join(`
|
|
8
|
-
`)+Sn}var he=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 j),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new ce),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new le),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new H(this.config)),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new O),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new N),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new G),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new z(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){if(this.config.display.style==="tui")return this.generateTuiStatusline(e);let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id,e):null,o=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,r=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,i=this.config.display.lines.map(
|
|
9
|
-
`)}async generateAutoWrapStatusline(e,t,o,r,s,i){let a=this.getThemeColors(),c=e.workspace?.current_dir||e.cwd||"/",l=$e(),
|
|
10
|
-
`)}async generateTuiStatusline(e){let t=this.getThemeColors(),o=$e(),r=e.workspace?.current_dir||e.cwd||"/",i=(this.config.display.charset||"unicode")==="text"?bt:ht,c=this.config.display.lines.map($=>$.segments.context).find($=>$?.enabled)?.autocompactBuffer??33e3,l=await Promise.allSettled([this.usageProvider.getUsageInfo(e.session_id,e),this.blockProvider.getActiveBlockInfo(),this.todayProvider.getTodayInfo(),this.contextProvider.getContextInfo(e,c),this.metricsProvider.getMetricsInfo(e.session_id,e),this.gitService.getGitInfo(r,{showSha:false,showWorkingTree:true,showOperation:false,showTag:false,showTimeSinceCommit:false,showStashCount:false,showUpstream:false,showRepoName:false},e.workspace?.project_dir),this.tmuxService.getSessionId()]),g=$=>$.status==="fulfilled"?$.value:null,[u,m,d,p,h,b,C]=[g(l[0]),g(l[1]),g(l[2]),g(l[3]),g(l[4]),g(l[5]),g(l[6])];return De({hookData:e,usageInfo:u,blockInfo:m,todayInfo:d,contextInfo:p,metricsInfo:h,gitInfo:b,tmuxSessionId:C,colors:t},i,t.reset,o,this.config)}calculateSegmentWidth(e,t){let o=this.config.display.style==="capsule",r=F(e.text),i=(this.config.display.padding??1)*2;if(o){let c=2+i+(t?0:1);return r+c}let a=1+i;return r+a}buildLineFromSegments(e,t){let o=this.config.display.style==="capsule",r=t.reset;for(let s=0;s<e.length;s++){let i=e[s];if(!i)continue;let a=s===0,l=s===e.length-1?null:e[s+1];o&&!a&&(r+=" "),r+=this.formatSegment(i.bgColor,i.fgColor,i.text,l?.bgColor,t);}return r}async renderLine(e,t,o,r,s,i,a){let c=this.getThemeColors(),l=t.workspace?.current_dir||t.cwd||"/",g=Object.entries(e.segments).filter(([m,d])=>d?.enabled).map(([m,d])=>({type:m,config:d})),u=[];for(let m of g){let d=await this.renderSegment(m,t,o,r,s,i,a,c,l);d&&u.push({type:m.type,text:d.text,bgColor:d.bgColor,fgColor:d.fgColor});}return this.buildLineFromSegments(u,c)}async renderSegment(e,t,o,r,s,i,a,c,l){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,l):e.type==="session"?this.renderSessionSegment(e.config,o,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,s,c):e.type==="version"?this.renderVersionSegment(e.config,t,c):e.type==="env"?this.segmentRenderer.renderEnv(c,e.config):null}async renderGitSegment(e,t,o,r){if(!this.needsSegmentInfo("git"))return null;let s=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 s?this.segmentRenderer.renderGit(s,o,e):null}renderSessionSegment(e,t,o){return t?this.segmentRenderer.renderSession(t,o,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,o){return this.needsSegmentInfo("context")?this.segmentRenderer.renderContext(t,o,e):null}renderMetricsSegment(e,t,o,r){return this.segmentRenderer.renderMetrics(t,r,o,e)}renderBlockSegment(e,t,o){return t?this.segmentRenderer.renderBlock(t,o,e):null}renderTodaySegment(e,t,o){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderToday(t,o,r)}renderVersionSegment(e,t,o){return this.segmentRenderer.renderVersion(t,o,e)}initializeSymbols(){let e=this.config.display.style,t=this.config.display.charset||"unicode",o=e==="minimal",r=e==="capsule",s=t==="text"?fe:ge;return {right:o?"":r?s.right_rounded:s.right,left:r?s.left_rounded:"",branch:s.branch,model:s.model,git_clean:s.git_clean,git_dirty:s.git_dirty,git_conflicts:s.git_conflicts,git_ahead:s.git_ahead,git_behind:s.git_behind,git_worktree:s.git_worktree,git_tag:s.git_tag,git_sha:s.git_sha,git_upstream:s.git_upstream,git_stash:s.git_stash,git_time:s.git_time,session_cost:s.session_cost,block_cost:s.block_cost,today_cost:s.today_cost,context_time:s.context_time,metrics_response:s.metrics_response,metrics_last_response:s.metrics_last_response,metrics_duration:s.metrics_duration,metrics_messages:s.metrics_messages,metrics_lines_added:s.metrics_lines_added,metrics_lines_removed:s.metrics_lines_removed,metrics_burn:s.metrics_burn,version:s.version,bar_filled:s.bar_filled,bar_empty:s.bar_empty,env:s.env}}getThemeColors(){let e=this.config.theme,t,o=this.config.display.colorCompatibility||"auto",r=o==="auto"?q():o;if(e==="custom"){if(t=this.config.colors?.custom,!t)throw new Error("Custom theme selected but no colors provided in configuration")}else t=K(e,r),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=K("dark",r));let s=K("dark",r),i=this.config.display.style==="tui",c=e==="light"?"#f0f0f0":"#1e1e1e",l=Ne=>{let L=t[Ne]||s[Ne],U=L.fg;return i&&We(U,c)<60&&(U=L.bg),r==="none"?{bg:"",fg:""}:r==="ansi"?{bg:Se(L.bg,true),fg:Se(U,false)}:r==="ansi256"?{bg:xe(L.bg,true),fg:xe(U,false)}:{bg:_e(L.bg,true),fg:_e(U,false)}},g=l("directory"),u=l("git"),m=l("model"),d=l("session"),p=l("block"),h=l("today"),b=l("tmux"),C=l("context"),M=l("contextWarning"),$=l("contextCritical"),Le=l("metrics"),Ue=l("version"),Oe=l("env");return {reset:r==="none"?"":pt,modeBg:g.bg,modeFg:g.fg,gitBg:u.bg,gitFg:u.fg,modelBg:m.bg,modelFg:m.fg,sessionBg:d.bg,sessionFg:d.fg,blockBg:p.bg,blockFg:p.fg,todayBg:h.bg,todayFg:h.fg,tmuxBg:b.bg,tmuxFg:b.fg,contextBg:C.bg,contextFg:C.fg,contextWarningBg:M.bg,contextWarningFg:M.fg,contextCriticalBg:$.bg,contextCriticalFg:$.fg,metricsBg:Le.bg,metricsFg:Le.fg,versionBg:Ue.bg,versionFg:Ue.fg,envBg:Oe.bg,envFg:Oe.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;case "env":return t.envBg;default:return t.modeBg}}formatSegment(e,t,o,r,s){let i=this.config.display.style==="capsule",a=" ".repeat(this.config.display.padding??1);if(i){let m=this.config.display.colorCompatibility||"auto",p=(m==="auto"?q():m)==="ansi",h=J(e,p),b=`${h}${this.symbols.left}${s.reset}`,C=`${e}${t}${a}${o}${a}${s.reset}`,M=`${h}${this.symbols.right}${s.reset}`;return `${b}${C}${M}`}let c=`${e}${t}${a}${o}${a}`,l=this.config.display.colorCompatibility||"auto",u=(l==="auto"?q():l)==="ansi";if(r){let m=J(e,u);c+=`${s.reset}${r}${m}${this.symbols.right}`;}else c+=`${s.reset}${J(e,u)}${this.symbols.right}${s.reset}`;return c}};var Rt={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",autocompactBuffer:33e3},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 Ie(n){return ["light","dark","nord","tokyo-night","rose-pine","gruvbox","custom"].includes(n)}function Me(n){return n==="minimal"||n==="powerline"||n==="capsule"||n==="tui"}function Bt(n){return n==="unicode"||n==="text"}function ye(n,e){for(let t=0;t<n.length;t++){let o=n[t];if(o===e&&t+1<n.length)return n[t+1];if(o?.startsWith(`${e}=`))return o.split("=")[1]}}function Ce(n,e){let t={...n};for(let o in e){let r=e[o];if(r!==void 0)if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let s=t[o]||{};t[o]=Ce(s,r);}else t[o]=r;}return t}function Pn(n,e){return n?S.existsSync(n)?n:null:[...e?[_.join(e,".claude-powerline.json")]:[],_.join(process.cwd(),".claude-powerline.json"),_.join(Ae.homedir(),".claude","claude-powerline.json"),_.join(Ae.homedir(),".config","claude-powerline","config.json")].find(S.existsSync)||null}function En(n){try{let e=S.readFileSync(n,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Rn(){let n={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&Ie(t)&&(n.theme=t);let o=process.env.CLAUDE_POWERLINE_STYLE;return o&&(Me(o)?e.style=o:(console.warn(`Invalid display style '${o}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(n.display=e),n}function Bn(){return process.env.CLAUDE_POWERLINE_CONFIG}function Dn(n){let e={},t={},o=ye(n,"--theme");o&&Ie(o)&&(e.theme=o);let r=ye(n,"--style");r&&(Me(r)?t.style=r:(console.warn(`Invalid display style '${r}' from CLI argument, falling back to 'minimal'`),t.style="minimal"));let s=ye(n,"--charset");return s&&(Bt(s)?t.charset=s:(console.warn(`Invalid charset '${s}' from CLI argument, falling back to 'unicode'`),t.charset="unicode")),Object.keys(t).length>0&&(e.display=t),e}function Fn(n=process.argv,e){let t=JSON.parse(JSON.stringify(Rt)),o=ye(n,"--config")||Bn(),r=o?.startsWith("~")?o.replace("~",Ae.homedir()):o,s=Pn(r,e);if(s)try{let c=En(s);t=Ce(t,c);}catch(c){console.warn(`Warning: ${c instanceof Error?c.message:String(c)}`);}t.display?.style&&!Me(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&&!Bt(t.display.charset)&&(console.warn(`Invalid charset '${t.display.charset}' in config file, falling back to 'unicode'`),t.display.charset="unicode"),t.theme&&!Ie(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let i=Rn();t=Ce(t,i);let a=Dn(n);return t=Ce(t,a),t}var Dt=Fn;function Ft(){console.log(`
|
|
6
|
+
`).filter(r=>r.trim()),o=[];for(let r of t)try{let s=JSON.parse(r);if(!s.timestamp)continue;let i={timestamp:new Date(s.timestamp),message:s.message,costUSD:typeof s.costUSD=="number"?s.costUSD:void 0,isSidechain:s.isSidechain===!0,raw:s};o.push(i);}catch(s){f(`Failed to parse JSONL line: ${s}`);continue}return o}async function Yt(n){return new Promise((e,t)=>{let o=[],r=createReadStream(n,{encoding:"utf8"}),s=createInterface({input:r,crlfDelay:1/0});s.on("line",i=>{let a=i.trim();if(a)try{let c=JSON.parse(a);if(!c.timestamp)return;let l={timestamp:new Date(c.timestamp),message:c.message,costUSD:typeof c.costUSD=="number"?c.costUSD:void 0,isSidechain:c.isSidechain===!0,raw:c};o.push(l);}catch(c){f(`Failed to parse JSONL line: ${c}`);}}),s.on("close",()=>{e(o);}),s.on("error",i=>{f(`Streaming parser error for ${n}:`,i),t(i);}),r.on("error",i=>{f(`File stream error for ${n}:`,i),t(i);});})}async function it(n){try{let e=await ke(n);return e?{filePath:n,mtime:e}:null}catch{return null}}async function Xt(n,e){try{let t=await readdir(n,{withFileTypes:!0}),o=t.filter(a=>!a.isDirectory()&&a.name.endsWith(".jsonl")).map(a=>it(posix.join(n,a.name))),r=t.filter(a=>a.isDirectory()).map(async a=>{let c=posix.join(n,a.name,"subagents");try{return (await readdir(c)).filter(u=>u.startsWith("agent-")&&u.endsWith(".jsonl")).map(u=>it(posix.join(c,u)))}catch{return []}}),[s,i]=await Promise.all([Promise.all(o),Promise.all(r).then(a=>Promise.all(a.flat()))]);return [...s,...i].filter(a=>a!==null&&(!e||e(a.filePath,a.mtime)))}catch(t){return f(`Failed to read project directory ${n}:`,t),[]}}async function ne(n,e,t=false){let o=Q(),r=await ee(o),s=new Set,i=r.map(p=>Xt(p,e)),c=(await Promise.all(i)).flat().filter(p=>p!==null);t&&c.sort((p,h)=>h.mtime.getTime()-p.mtime.getTime());let l=c.map(p=>p.filePath),u=[],g=l.map(async p=>(await I(p)).filter(b=>!n||n(b))),m=await Promise.all(g);for(let p of m)u.push(...p);u.sort((p,h)=>p.timestamp.getTime()-h.timestamp.getTime());let d=[];for(let p of u){let h=Gt(p);h&&s.has(h)||(h&&s.add(h),d.push(p));}return d}var E=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(!S.existsSync(t))return false;try{let o=S.readFileSync(t,"utf-8"),r=parseInt(o.trim(),10);if(isNaN(r))return f(`Invalid PID in lock file ${e}, removing stale lock`),S.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(s){return s.code==="ESRCH"?(f(`Removing stale lock file ${e} for dead process ${r}`),S.unlinkSync(t),!1):(f(`Error checking process ${r} for lock ${e}:`,s),!0)}}catch(o){return f(`Error reading lock file ${e}:`,o),true}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let s=_.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await S.promises.writeFile(s,a,{flag:"wx"}),f(`Lock acquired for ${e}`),!0}catch(c){if(c.code==="EEXIST")await setTimeout(50);else throw c}return f(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=_.join(this.LOCKS_DIR,e);try{await S.promises.unlink(t),f(`Lock released for ${e}`);}catch(o){o.code!=="ENOENT"&&f(`Error releasing lock for ${e}:`,o);}}static async ensureCacheDirectories(){try{await Promise.all([S.promises.mkdir(this.CACHE_DIR,{recursive:!0}),S.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),S.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){f("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 s="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)){f(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let u=await S.promises.readFile(i,s),g=JSON.parse(u);return !t||g.timestamp>=t?(f(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(g.data)):(f(`${e} cache outdated: cache=${g.timestamp}, latest=${t}`),null)}catch(u){if(u.code==="ENOENT")return f(`No shared ${e} usage cache found`),null;let g=c+1;f(`Attempt ${g} failed to read ${e} cache: ${u.message}. Retrying...`),await setTimeout(75);}}return f(`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,o){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){f(`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=o||Date.now(),l=JSON.stringify({data:t,timestamp:a});await S.promises.writeFile(i,l,"utf-8"),f(`[CACHE-SET] ${e} disk cache stored`);}catch(i){f(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(r);}}static async getLatestTranscriptMtime(){try{let e=Q(),t=await ee(e),o=0;for(let r of t)try{let i=(await S.promises.readdir(r)).filter(a=>a.endsWith(".jsonl"));for(let a of i){let c=_.join(r,a),l=await ke(c);l&&l.getTime()>o&&(o=l.getTime());}}catch(s){f(`Failed to read project directory ${r}:`,s);continue}return o}catch(e){return f("Failed to get latest transcript mtime:",e),Date.now()}}};var oe={"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-opus-4-5":{name:"Claude Opus 4.5",input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:"Claude Opus 4.5",input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:"Claude Opus 4.6",input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:"Claude Opus 4.6",input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:"Claude Sonnet 4.6",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}},R=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 E.getUsageCache("pricing",t)}static async saveDiskCache(e){await E.setUsageCache("pricing",e);}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),o=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},r=>{if(r.statusCode!==200){f(`HTTP ${r.statusCode}: ${r.statusMessage}`),e(null);return}let s="",i=0,a=1024*1024;r.on("data",c=>{if(i+=c.length,i>a){f("Response too large"),o.destroy(),e(null);return}s+=c;}),r.on("end",()=>{try{let l=JSON.parse(s),u=l._meta,g={};for(let[m,d]of Object.entries(l))m!=="_meta"&&(g[m]=d);this.validatePricingData(g)?(f(`Fetched fresh pricing from GitHub for ${Object.keys(g).length} models`),f(`Pricing last updated: ${u?.updated||"unknown"}`),e(g)):(f("Invalid pricing data structure"),e(null));}catch(c){f("Failed to parse JSON:",c),e(null);}}),r.on("error",c=>{f("Response error:",c),e(null);});});o.on("error",r=>{f("Request error:",r),e(null);}),o.on("timeout",()=>{f("Request timeout"),o.destroy(),e(null);}),o.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return f(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return f(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,f(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),f(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,f(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(f(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(oe).length} models`),this.executionCache=oe,f(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(oe).length} models`),oe)}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 o=t;if(typeof o.input!="number"||typeof o.output!="number"||typeof o.cache_read!="number")return false}return true}static async getModelPricing(e){if(this.modelPricingCache.has(e))return f(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),o;return t[e]?o=t[e]:o=this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,o),f(`[CACHE-SET] Model pricing cache: ${e}`),o}static fuzzyMatchModel(e,t){let o=e.toLowerCase();for(let[s,i]of Object.entries(t))if(s.toLowerCase()===o)return i;let r=[{pattern:["opus-4-6","claude-opus-4-6"],fallback:"claude-opus-4-6-20260205"},{pattern:["opus-4-5","claude-opus-4-5"],fallback:"claude-opus-4-5-20251101"},{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-6","sonnet-4.6","claude-sonnet-4-6"],fallback:"claude-sonnet-4-6"},{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:s,fallback:i}of r)if(s.some(a=>o.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 o=e.message?.usage;if(!o)return 0;let r=this.extractModelId(e),s=await this.getModelPricing(r),i=o.input_tokens||0,a=o.output_tokens||0,c=o.cache_creation_input_tokens||0,l=o.cache_read_input_tokens||0,u=i/1e6*s.input,g=a/1e6*s.output,m=l/1e6*s.cache_read,d=c/1e6*s.cache_write_5m;return u+g+d+m}static extractModelId(e){if(e.model&&typeof e.model=="string")return e.model;let t=e.message;if(t?.model){let o=t.model;return typeof o=="string"?o:o?.id||"claude-3-5-sonnet-20241022"}return e.model_id&&typeof e.model_id=="string"?e.model_id:"claude-3-5-sonnet-20241022"}};function en(n){return {timestamp:n.timestamp.toISOString(),message:{usage:{input_tokens:n.message?.usage?.input_tokens||0,output_tokens:n.message?.usage?.output_tokens||0,cache_creation_input_tokens:n.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:n.message?.usage?.cache_read_input_tokens}},costUSD:n.costUSD}}var re=class{async getSessionUsage(e){try{let t=await te(e);if(!t)return f(`No transcript found for session: ${e}`),null;f(`Found transcript at: ${t}`);let o=await I(t),r=dirname(t),s=await lt(e,r);f(`Found ${s.length} agent transcripts for session`);for(let c of s){let l=await I(c);o.push(...l);}if(o.length===0)return {totalCost:0,entries:[]};let i=[],a=0;for(let c of o)if(c.message?.usage){let l=en(c);if(l.costUSD!==void 0)a+=l.costUSD;else {let u=await R.calculateCostForEntry(c.raw);l.costUSD=u,a+=u;}i.push(l);}return f(`Parsed ${i.length} usage entries, total cost: $${a.toFixed(4)}`),{totalCost:a,entries:i}}catch(t){return f(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,o)=>({input:t.input+(o.message.usage.input_tokens||0),output:t.output+(o.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(o.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(o.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e,t){let o=await this.getSessionUsage(e);if(!o||o.entries.length===0)return {cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};let r=this.calculateTokenBreakdown(o.entries),s=r.input+r.output+r.cacheCreation+r.cacheRead,i=o.totalCost,a=t?.cost?.total_cost_usd??null;return {cost:i??a,calculatedCost:i,officialCost:a,tokens:s,tokenBreakdown:r}}},j=class{sessionProvider=new re;async getUsageInfo(e,t){try{return f(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e,t)}}catch(o){return f(`Error getting usage info for session ${e}:`,o),{session:{cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null}}}}};var H=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},o=this.getModelType(e);return t[o]||t.default||2e5}getModelType(e){let t=e.toLowerCase();return t.includes("sonnet")?"sonnet":t.includes("opus")?"opus":"default"}calculatePercentages(e,t,o=33e3){let r=Math.min(100,Math.max(0,Math.round(e/t*100))),s=Math.max(1,t-o),i=Math.min(100,Math.max(0,Math.round(e/s*100))),a=Math.max(0,100-i);return {percentage:r,usablePercentage:i,contextLeftPercentage:a,usableTokens:s}}calculateContextFromHookData(e,t=33e3){let o=e.context_window?.current_usage;if(!o)return f("No current_usage in hook data, falling back to transcript parsing"),null;let r=e.context_window?.context_window_size||2e5,s=(o.input_tokens||0)+(o.cache_creation_input_tokens||0)+(o.cache_read_input_tokens||0);f(`Native current_usage: input=${o.input_tokens}, cache_create=${o.cache_creation_input_tokens}, cache_read=${o.cache_read_input_tokens}, total=${s} (limit: ${r})`);let i=this.calculatePercentages(s,r,t);return {totalTokens:s,maxTokens:r,...i}}async calculateContextTokensFromTranscript(e,t,o=33e3){try{f(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return f("Transcript file is empty"),null}catch{return f("Could not read transcript file"),null}let r=await I(e);if(r.length===0)return f("No entries in transcript"),null;let s=null;for(let i=r.length-1;i>=0;i--){let a=r[i];if(a&&a.message?.usage?.input_tokens&&a.isSidechain!==!0){s=a,f(`Context segment: Found most recent entry at ${a.timestamp.toISOString()}, stopping search`);break}}if(s?.message?.usage){let i=s.message.usage,a=(i.input_tokens||0)+(i.cache_read_input_tokens||0)+(i.cache_creation_input_tokens||0),c=t?this.getContextLimit(t):2e5;f(`Most recent main chain context: ${a} tokens (limit: ${c})`);let l=this.calculatePercentages(a,c,o);return {totalTokens:a,maxTokens:c,...l}}return f("No main chain entries with usage data found"),null}catch(r){return f(`Error reading transcript: ${r instanceof Error?r.message:String(r)}`),null}}async getContextInfo(e,t=33e3){let o=this.calculateContextFromHookData(e,t);return o||this.calculateContextTokensFromTranscript(e.transcript_path,e.model?.id,t)}};var G=class{async loadTranscriptEntries(e){try{let t=await te(e);if(!t)return f(`No transcript found for session: ${e}`),[];f(`Loading transcript from: ${t}`);let r=(await readFile(t,"utf-8")).trim().split(`
|
|
7
|
+
`).filter(i=>i.trim()),s=[];for(let i of r)try{let a=JSON.parse(i);if(a.isSidechain===!0)continue;s.push(a);}catch(a){f(`Failed to parse JSONL line: ${a}`);continue}return f(`Loaded ${s.length} transcript entries`),s}catch(t){return f(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let o=t.type||t.message?.role||t.message?.type,r=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return o==="user"&&!r}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),o=null,r=null;for(let s of t)if(s.timestamp)try{let i=new Date(s.timestamp),a=s.type||s.message?.role||s.message?.type,c=s.type==="user"&&s.message?.content?.[0]?.type==="tool_result";if(a==="user"&&!c)o=i;else if(a==="assistant"&&o){let u=(i.getTime()-o.getTime())/1e3;u>.1&&u<300&&(r=u);}}catch{continue}return r}async getMetricsInfo(e,t){try{if(f(`Getting metrics from hook data for session: ${e}`),!t.cost)return f("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let o=await this.loadTranscriptEntries(e),r=this.calculateMessageCount(o),s=this.calculateLastResponseTime(o);return {responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:s,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed}}catch(o){return f(`Error getting metrics from hook data for session ${e}:`,o),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function k(n){return n===null?"$0.00":n<.01?"<$0.01":`$${n.toFixed(2)}`}function T(n){return n===null||n===0?"0 tokens":n>=1e6?`${(n/1e6).toFixed(1)}M tokens`:n>=1e3?`${(n/1e3).toFixed(1)}K tokens`:`${n} tokens`}function ut(n){if(!n)return "0 tokens";let e=[];if(n.input>0&&e.push(`${T(n.input).replace(" tokens","")} in`),n.output>0&&e.push(`${T(n.output).replace(" tokens","")} out`),n.cacheCreation>0||n.cacheRead>0){let t=n.cacheCreation+n.cacheRead;e.push(`${T(t).replace(" tokens","")} cached`);}return e.length>0?e.join(" + "):"0 tokens"}function ft(n){return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:n<604800?`${Math.floor(n/86400)}d`:`${Math.floor(n/604800)}w`}function se(n){return n<60?`${n.toFixed(0)}s`:n<3600?`${(n/60).toFixed(0)}m`:n<86400?`${(n/3600).toFixed(1)}h`:`${(n/86400).toFixed(1)}d`}var on=/^(?:(?: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 ie(n){if(!n)return "Claude";let e=n.trim().match(on);if(!e?.groups)return n;let{family:t,newMajor:o,newMinor:r,oldMajor:s,oldMinor:i,oldFamily:a}=e.groups,c=t||a,l=o||s,u=r||i;if(c&&l){let g=c.charAt(0).toUpperCase()+c.slice(1).toLowerCase(),m=u?`${l}.${u}`:l;return `${g} ${m}`}return n}function ae(n){let e=n.includes("/")?"/":"\\",t=n.split(e);return t.map((o,r)=>r===t.length-1||o==="~"||o===""?o:o.charAt(0)).join(e)}function gt(n){return n<60?`${n.toFixed(1)}s`:`${(n/60).toFixed(1)}m`}function mt(n){let e=Math.floor(n/60),t=n%60;return e>0?`${e}h ${t}m left`:`${t}m left`}function rn(n,e){return !e||e<=0||n<0?null:Math.min(100,n/e*100)}function D(n,e,t=80){let o=rn(n,e);if(o===null)return {percentage:null,isWarning:false,displayText:""};let r=`${o.toFixed(0)}%`,s=o>=t,i="";return s?i=` !${r}`:o>=50?i=` +${r}`:i=` ${r}`,{percentage:o,isWarning:s,displayText:i}}var sn={ball:{filled:"\u2500",empty:"\u2500",marker:"\u25CF"},blocks:{filled:"\u2588",empty:"\u2591"},"blocks-line":{filled:"\u2588",empty:"\u2500"},capped:{filled:"\u2501",empty:"\u2504",cap:"\u2578"},dots:{filled:"\u25CF",empty:"\u25CB"},filled:{filled:"\u25A0",empty:"\u25A1"},geometric:{filled:"\u25B0",empty:"\u25B1"},line:{filled:"\u2501",empty:"\u2504"},squares:{filled:"\u25FC",empty:"\u25FB"}},z=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,o){let r=e.workspace?.current_dir||e.cwd||"/",s=e.workspace?.project_dir,i=o?.style??(o?.showBasename?"basename":"full");if(i==="basename")return {text:_.basename(r)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let a=process.env.HOME||process.env.USERPROFILE,c=r,l=s;a&&(r.startsWith(a)&&(c=r.replace(a,"~")),s&&s.startsWith(a)&&(l=s.replace(a,"~")));let u=this.getDisplayDirectoryName(c,l);return i==="fish"&&(u=ae(u)),{text:u,bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,o){if(!e)return null;let r=[];if(o?.showRepoName&&e.repoName&&(r.push(e.repoName),e.isWorktree&&r.push(this.symbols.git_worktree)),o?.showOperation&&e.operation&&r.push(`[${e.operation}]`),r.push(`${this.symbols.branch} ${e.branch}`),o?.showTag&&e.tag&&r.push(`${this.symbols.git_tag} ${e.tag}`),o?.showSha&&e.sha&&r.push(`${this.symbols.git_sha} ${e.sha}`),o?.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}`)),o?.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(o?.showUpstream&&e.upstream&&r.push(`${this.symbols.git_upstream}${e.upstream}`),o?.showStashCount&&e.stashCount&&e.stashCount>0&&r.push(`${this.symbols.git_stash} ${e.stashCount}`),o?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=ft(e.timeSinceCommit);r.push(`${this.symbols.git_time} ${i}`);}let s=this.symbols.git_clean;return e.status==="conflicts"?s=this.symbols.git_conflicts:e.status==="dirty"&&(s=this.symbols.git_dirty),r.push(s),{text:r.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}renderModel(e,t){let o=e.model?.display_name||"Claude",r=ie(o);return {text:`${this.symbols.model} ${r}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,o){let r=o?.type||"cost",s=o?.costSource,i=this.config.budget?.session,a=()=>s==="calculated"?e.session.calculatedCost:s==="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,o){let s=o?.displayStyle??"text",i=s==="text"?"remaining":"used",a=o?.percentageMode??i,c=s==="bar"?{filled:this.symbols.bar_filled,empty:this.symbols.bar_empty}:sn[s]??null,l=a==="remaining"?"100%":"0%";if(!e)return c?{text:`${c.empty.repeat(10)} ${l}`,bgColor:t.contextBg,fgColor:t.contextFg}:{text:`${this.symbols.context_time} 0 (${l})`,bgColor:t.contextBg,fgColor:t.contextFg};let u=t.contextBg,g=t.contextFg;e.contextLeftPercentage<=20?(u=t.contextCriticalBg,g=t.contextCriticalFg):e.contextLeftPercentage<=40&&(u=t.contextWarningBg,g=t.contextWarningFg);let m=a==="remaining"?e.contextLeftPercentage:e.usablePercentage,d=Math.round(e.usablePercentage/100*10),p=10-d;if(c){let b=this.buildBar(c,d,p,10);return {text:o?.showPercentageOnly?`${b} ${m}%`:`${b} ${e.totalTokens.toLocaleString()} (${m}%)`,bgColor:u,fgColor:g}}return {text:o?.showPercentageOnly?`${this.symbols.context_time} ${m}%`:`${this.symbols.context_time} ${e.totalTokens.toLocaleString()} (${m}%)`,bgColor:u,fgColor:g}}buildBar(e,t,o,r){if(e.marker){let s=Math.min(t,r-1);return e.filled.repeat(s)+e.marker+e.empty.repeat(r-s-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(o):e.filled.repeat(t)+e.empty.repeat(o)}renderMetrics(e,t,o,r){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let s=[];if(r?.showLastResponseTime&&e.lastResponseTime!==null){let i=e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;s.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`;s.push(`${this.symbols.metrics_response} ${i}`);}if(r?.showDuration!==false&&e.sessionDuration!==null){let i=se(e.sessionDuration);s.push(`${this.symbols.metrics_duration} ${i}`);}return r?.showMessageCount!==false&&e.messageCount!==null&&s.push(`${this.symbols.metrics_messages} ${e.messageCount}`),r?.showLinesAdded!==false&&e.linesAdded!==null&&e.linesAdded>0&&s.push(`${this.symbols.metrics_lines_added} ${e.linesAdded}`),r?.showLinesRemoved!==false&&e.linesRemoved!==null&&e.linesRemoved>0&&s.push(`${this.symbols.metrics_lines_removed} ${e.linesRemoved}`),s.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:s.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,o){let r;if(e.cost===null&&e.tokens===null)r="No active block";else {let s=o?.type||"cost",i=o?.burnType,a=this.config.budget?.block,c=e.timeRemaining!==null?(()=>{let g=Math.floor(e.timeRemaining/60),m=e.timeRemaining%60;return g>0?`${g}h ${m}m`:`${m}m`})():null,l;switch(s){case "cost":l=this.formatUsageWithBudget(e.cost,null,null,"cost",a?.amount,a?.warningThreshold,a?.type);break;case "tokens":l=this.formatUsageWithBudget(null,e.tokens,null,"tokens",a?.amount,a?.warningThreshold,a?.type);break;case "weighted":let g=a?.type==="tokens"?a.amount:void 0,m=T(e.weightedTokens);if(g&&e.weightedTokens!==null){let d=D(e.weightedTokens,g,a?.warningThreshold||80);l=`${m}${d.displayText}`;}else l=`${m} (weighted)`;break;case "both":l=this.formatUsageWithBudget(e.cost,e.tokens,null,"both",a?.amount,a?.warningThreshold,a?.type);break;case "time":l=c||"N/A";break;default:l=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?`${T(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?`${T(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${d} / ${p}`;break}s==="time"?r=l:r=c?`${l}${u} (${c} left)`:`${l}${u}`;}return {text:`${this.symbols.block_cost} ${r}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,o="cost"){let r=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,o,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)||_.basename(t)||"project":e}formatUsageDisplay(e,t,o,r){switch(r){case "cost":return k(e);case "tokens":return T(t);case "both":return `${k(e)} (${T(t)})`;case "breakdown":return ut(o);default:return k(e)}}formatUsageWithBudget(e,t,o,r,s,i=80,a){let c=this.formatUsageDisplay(e,t,o,r);if(s&&s>0){let l=null;if(a==="tokens"&&t!==null?l=t:(a==="cost"&&e!==null||!a&&e!==null)&&(l=e),l!==null){let u=D(l,s,i);return c+u.displayText}}return c}renderVersion(e,t,o){return e.version?{text:`${this.symbols.version} v${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}:null}renderEnv(e,t){let o=process.env[t.variable];if(!o)return null;let r=t.prefix??t.variable;return {text:r?`${this.symbols.env} ${r}: ${o}`:`${this.symbols.env} ${o}`,bgColor:e.envBg,fgColor:e.envFg}}};function an(n){return n.includes("opus")?5:(n.includes("sonnet")||n.includes("haiku"),1)}function cn(n){return {timestamp:n.timestamp,usage:{inputTokens:n.message?.usage?.input_tokens||0,outputTokens:n.message?.usage?.output_tokens||0,cacheCreationInputTokens:n.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:n.message?.usage?.cache_read_input_tokens||0},costUSD:n.costUSD||0,model:n.message?.model||"unknown"}}var ce=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,o=[],r=[...e].sort((a,c)=>a.timestamp.getTime()-c.timestamp.getTime()),s=null,i=[];for(let a of r){let c=a.timestamp;if(s==null)s=this.floorToHour(c),i=[a];else {let l=c.getTime()-s.getTime(),u=i[i.length-1];if(u==null)continue;let g=u.timestamp,m=c.getTime()-g.getTime();l>t||m>t?(o.push(i),s=this.floorToHour(c),i=[a]):i.push(a);}}return s!=null&&i.length>0&&o.push(i),o}createBlockInfo(e,t){let o=new Date,r=this.sessionDurationHours*60*60*1e3,s=new Date(e.getTime()+r),i=t[t.length-1],a=i!=null?i.timestamp:e,c=o.getTime()-a.getTime()<r&&o<s;return {block:t,isActive:c}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if(!o||o.length===0)continue;let r=o[0];if(!r)continue;let s=this.floorToHour(r.timestamp),i=this.createBlockInfo(s,o);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{f("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let o=await ne(void 0,(c,l)=>l>=e,!0),r=[];for(let c of o)if(c.message?.usage){let l=cn(c);!l.costUSD&&c.raw&&(l.costUSD=await R.calculateCostForEntry(c.raw)),r.push(l);}let s=this.identifySessionBlocks(r);f(`Block segment: Found ${s.length} session blocks`);let i=this.findActiveBlock(s),a=[];if(i&&i.length>0){f(`Block segment: Found active block with ${i.length} entries`);let c=i[0],l=i[i.length-1];c&&l&&f(`Block segment: Active block from ${c.timestamp.toISOString()} to ${l.timestamp.toISOString()}`),a=i;}else f("Block segment: No active block found"),a=[];return a}catch(e){return f("Error loading block entries:",e),[]}}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return f("Block segment: No entries in current block"),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((l,u)=>l+u.costUSD,0),o=e.reduce((l,u)=>l+u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,0),r=e.reduce((l,u)=>{let g=u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,m=an(u.model);return l+g*m},0),s=new Date,i=null;if(e.length>0){let l=e[0];if(l){let u=this.sessionDurationHours*60*60*1e3,g=this.floorToHour(l.timestamp),m=new Date(g.getTime()+u);i=Math.max(0,Math.round((m.getTime()-s.getTime())/(1e3*60)));}}let a=null,c=null;if(e.length>=1&&(t>0||o>0)){let l=e.map(m=>m.timestamp).sort((m,d)=>m.getTime()-d.getTime()),u=l[0],g=l[l.length-1];if(u&&g){let m=(g.getTime()-u.getTime())/6e4;m>0&&(t>0&&(a=t/m*60),o>0&&(c=o/m*60));}}return f(`Block segment: $${t.toFixed(2)}, ${o} tokens, ${i}m remaining, burn rate: ${a?"$"+a.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:o,weightedTokens:r,timeRemaining:i,burnRate:a,tokenBurnRate:c}}catch(e){return f("Error getting active block info:",e),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function V(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),o=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${o}`}function ln(n){return n.inputTokens+n.outputTokens+n.cacheCreationInputTokens+n.cacheReadInputTokens}function un(n){return {timestamp:n.timestamp,usage:{inputTokens:n.message?.usage?.input_tokens||0,outputTokens:n.message?.usage?.output_tokens||0,cacheCreationInputTokens:n.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:n.message?.usage?.cache_read_input_tokens||0},costUSD:n.costUSD||0,model:n.message?.model||"unknown"}}var le=class{async loadTodayEntries(){let t=V(new Date);f(`Today segment: Loading entries for date ${t}`);let o=await E.getLatestTranscriptMtime(),r=await E.getUsageCache("today",o);if(r)return f("Using shared today usage cache"),r;let s=new Date;s.setDate(s.getDate()-1),s.setHours(0,0,0,0);let i=(m,d)=>d>=s,a=new Date;a.setHours(0,0,0,0);let l=await ne(m=>m.timestamp>=a,i,true),u=[],g=0;for(let m of l)if(V(m.timestamp)===t&&m.message?.usage){let p=un(m);!p.costUSD&&m.raw&&(p.costUSD=await R.calculateCostForEntry(m.raw)),u.push(p),g++;}return f(`Today segment: Found ${g} entries for today (${t})`),await E.setUsageCache("today",u,o),u}async getTodayEntries(){try{return await this.loadTodayEntries()}catch(e){return f("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:V(new Date)};let t=e.reduce((s,i)=>s+i.costUSD,0),o=e.reduce((s,i)=>s+ln(i.usage),0),r=e.reduce((s,i)=>({input:s.input+i.usage.inputTokens,output:s.output+i.usage.outputTokens,cacheCreation:s.cacheCreation+i.usage.cacheCreationInputTokens,cacheRead:s.cacheRead+i.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return f(`Today segment: $${t.toFixed(2)}, ${o} tokens total`),{cost:t,tokens:o,tokenBreakdown:r,date:V(new Date)}}catch(e){return f("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:V(new Date)}}}};var pt="\x1B[0m",ue={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:"\u25C6",metrics_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u2197",version:"\u25C8",bar_filled:"\u25AA",bar_empty:"\u25AB",env:"\u2699"},ht={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",teeLeft:"\u251C",teeRight:"\u2524"},bt={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",teeLeft:"+",teeRight:"+"},fe={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:"-",env:"$"};var fn="\x1B",gn=new RegExp(`${fn}\\[[0-9;]*m`,"g"),mn=/^[a-zA-Z0-9/]+$/;function dn(){if(process.platform==="win32")return null;let n=process.pid.toString();for(let e=0;e<10;e++)try{let o=execSync(`ps -o ppid=,tty= -p ${n}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(/\s+/),r=o[0],s=o[1];if(s&&s!=="?"&&s!=="??"&&mn.test(s))return s;if(!r||r==="1"||r==="0")break;n=r;}catch{break}return null}function pn(){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 hn(){let n=dn();if(n)try{let t=execSync(`stty size < /dev/${n}`,{encoding:"utf8",stdio:["pipe","pipe","ignore"],shell:"/bin/sh"}).trim().split(" ")[1];if(t){let o=parseInt(t,10);if(!isNaN(o)&&o>0)return o}}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 $e(){let n=o=>Math.floor(o*.7),e=process.env.COLUMNS;if(e){let o=parseInt(e,10);if(!isNaN(o)&&o>0)return n(o)}if(process.stdout.columns&&process.stdout.columns>0)return n(process.stdout.columns);if(process.platform==="win32"){let o=pn();if(o)return n(o)}let t=hn();return t?n(t):null}function Pe(n){return n.replace(gn,"")}function F(n){return Pe(n).length}function y(n,e,t){return e?`${e}${n}${t}`:n}function bn(n,e){let t=F(n);return t>=e?n:n+" ".repeat(e-t)}var yt="\x1B",yn=new RegExp(`(${yt}\\[[0-9;]*m)`);function Cn(n,e){if(Pe(n).length<=e)return n;let t=0,o="",r=n.split(yn);for(let s of r){if(s.startsWith(yt)){o+=s;continue}for(let i of s){if(t>=e-1)return o+="\u2026",o;o+=i,t++;}}return o}function x(n,e,t){let o=t-2,r=Cn(e,o),s=bn(r,o);return n.vertical+" "+s+" "+n.vertical}function Y(n,e){return n.teeLeft+n.horizontal.repeat(e)+n.teeRight}function Ct(n,e){return n.bottomLeft+n.horizontal.repeat(e)+n.bottomRight}function _t(n,e){if(n.length===0)return "";if(n.length===1)return n[0]??"";let t=n.map(l=>F(l)),o=t.reduce((l,u)=>l+u,0),r=e-o,s=Math.max(2,Math.floor(r/(n.length-1))),i=new Array(n.length);i[n.length-1]=t[n.length-1]??0;for(let l=n.length-2;l>=0;l--)i[l]=(i[l+1]??0)+(t[l]??0);let a=n[0]??"",c=t[0]??0;for(let l=1;l<n.length;l++){let u=e-c-(i[l]??0)-(n.length-1-l)*2,g=Math.max(2,Math.min(s,u));a+=" ".repeat(g)+(n[l]??""),c+=g+(t[l]??0);}return a}function A(n,e,t){if(!e)return n;if(!n)return e;let o=F(n),r=F(e),s=t-o-r;return s<2?`${n} ${e}`:n+" ".repeat(s)+e}function xt(n,e,t){let o=n.hookData.model?.display_name||"Claude",r=ie(o).toLowerCase(),s="claude-powerline",i=` ${r} `,a=` ${s} `,c=t-1-i.length-a.length;if(c<2){let l=t-1-i.length;return e.topLeft+e.horizontal+i+e.horizontal.repeat(Math.max(0,l))+e.topRight}return e.topLeft+e.horizontal+i+e.horizontal.repeat(c)+a+e.topRight}function St(n,e,t,o,r){let s=Math.min(Math.floor(e*.45),40);if(!n.contextInfo)return null;let i=n.contextInfo.usablePercentage,a=Math.round(i/100*s),c=s-a,l=t.bar_filled.repeat(a)+t.bar_empty.repeat(c),u=n.contextInfo.totalTokens>=1e3?`${(n.contextInfo.totalTokens/1e3).toFixed(0)}k`:`${n.contextInfo.totalTokens}`,g=n.contextInfo.maxTokens>=1e3?`${(n.contextInfo.maxTokens/1e3).toFixed(0)}k`:`${n.contextInfo.maxTokens}`,m=r.contextFg;return i>=80?m=r.contextCriticalFg:i>=60&&(m=r.contextWarningFg),y(`${l} ${i}% ${u}/${g}`,m,o)}function _n(n){let e=n.workspace?.current_dir||n.cwd||"/",t=process.env.HOME||process.env.USERPROFILE;return t&&e.startsWith(t)?e.replace(t,"~"):e}function wt(n,e,t,o,r){let s=[];n.blockInfo&&s.push(y(pe(n.blockInfo,e,t),r.blockFg,o)),n.usageInfo&&s.push(y(Re(n.usageInfo,e,t),r.sessionFg,o)),n.todayInfo&&s.push(y(Be(n.todayInfo,e,t),r.todayFg,o));let i=Ee(n,e);return i.length>0&&s.push(y(i.join(" \xB7 "),r.metricsFg,o)),s}function Ee(n,e){let t=[];return n.metricsInfo&&(n.metricsInfo.sessionDuration!==null&&n.metricsInfo.sessionDuration>0&&t.push(`${e.metrics_duration} ${se(n.metricsInfo.sessionDuration)}`),n.metricsInfo.messageCount!==null&&n.metricsInfo.messageCount>0&&t.push(`${e.metrics_messages} ${n.metricsInfo.messageCount}`)),t}function me(n,e,t,o){let r=[];if(n.gitInfo){let i=`${e.branch} ${n.gitInfo.branch}`;n.gitInfo.status==="conflicts"?i+=` ${e.git_conflicts}`:n.gitInfo.status==="dirty"?i+=` ${e.git_dirty}`:i+=` ${e.git_clean}`,n.gitInfo.ahead>0&&(i+=` ${e.git_ahead}${n.gitInfo.ahead}`),n.gitInfo.behind>0&&(i+=` ${e.git_behind}${n.gitInfo.behind}`);let a=[];n.gitInfo.staged&&n.gitInfo.staged>0&&a.push(`+${n.gitInfo.staged}`),n.gitInfo.unstaged&&n.gitInfo.unstaged>0&&a.push(`~${n.gitInfo.unstaged}`),n.gitInfo.untracked&&n.gitInfo.untracked>0&&a.push(`?${n.gitInfo.untracked}`),a.length>0&&(i+=` (${a.join(" ")})`),r.push(y(i,o.gitFg,t));}let s=ae(_n(n.hookData));return r.push(y(s,o.modeFg,t)),r}function de(n,e,t,o,r){let s=[];if(n.hookData.version&&s.push(y(`${e.version} v${n.hookData.version}`,r.versionFg,o)),n.tmuxSessionId&&s.push(y(`tmux:${n.tmuxSessionId}`,r.tmuxFg,o)),n.metricsInfo){let a=[];if(n.metricsInfo.responseTime!==null&&!isNaN(n.metricsInfo.responseTime)&&n.metricsInfo.responseTime>0&&a.push(`${e.metrics_response} ${gt(n.metricsInfo.responseTime)}`),n.metricsInfo.linesAdded!==null&&n.metricsInfo.linesAdded>0&&a.push(`${e.metrics_lines_added}${n.metricsInfo.linesAdded}`),n.metricsInfo.linesRemoved!==null&&n.metricsInfo.linesRemoved>0&&a.push(`${e.metrics_lines_removed}${n.metricsInfo.linesRemoved}`),n.blockInfo?.burnRate!==null&&n.blockInfo?.burnRate!==void 0&&n.blockInfo.burnRate>0){let c=n.blockInfo.burnRate<1?`${(n.blockInfo.burnRate*100).toFixed(0)}c/h`:`$${n.blockInfo.burnRate.toFixed(2)}/h`;a.push(`${e.metrics_burn} ${c}`);}a.length>0&&s.push(y(a.join(" \xB7 "),r.metricsFg,o));}let i=t.display.lines.map(a=>a.segments.env).find(a=>a?.enabled);if(i&&i.variable){let a=process.env[i.variable];if(a){let c=i.prefix??i.variable;s.push(y(c?`${c}:${a}`:a,r.envFg,o));}}return s}function pe(n,e,t){let o=k(n.cost),r=`${e.block_cost} ${o}`;n.timeRemaining!==null&&(r+=` \xB7 ${mt(n.timeRemaining)}`);let s=t.budget?.block;if(s?.amount&&n.cost!==null){let i=D(n.cost,s.amount,s.warningThreshold||80);r+=i.displayText;}return r}function Re(n,e,t){let o=k(n.session.cost),r=n.session.tokens,s=r!==null&&r>0?T(r).replace(" tokens",""):null,i=`${e.session_cost} ${o}`;s&&(i+=` \xB7 ${s}`);let a=t.budget?.session;if(a?.amount&&n.session.cost!==null){let c=D(n.session.cost,a.amount,a.warningThreshold||80);i+=c.displayText;}return i}function Be(n,e,t){let o=k(n.cost),r=`${e.today_cost} ${o} today`,s=t.budget?.today;if(s?.amount&&n.cost!==null){let i=D(n.cost,s.amount,s.warningThreshold||80);r+=i.displayText;}return r}function Tt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,u=wt(t,i,a,c,l);u.length>0&&e.push(x(o,_t(u,r),s));}function kt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,u=me(t,i,c,l),g=de(t,i,a,c,l),m=u.join(" "),d=g.join(" \xB7 ");(m||d)&&(e.push(Y(o,s)),e.push(x(o,A(m,d,r),s)));}function vt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,u=[],g=[];t.blockInfo&&u.push(y(pe(t.blockInfo,i,a),l.blockFg,c)),t.todayInfo&&u.push(y(Be(t.todayInfo,i,a),l.todayFg,c)),t.usageInfo&&g.push(y(Re(t.usageInfo,i,a),l.sessionFg,c));let m=Ee(t,i);m.length>0&&g.push(y(m.join(" \xB7 "),l.metricsFg,c)),u.length>0&&e.push(x(o,A(u[0]??"",u[1]??"",r),s)),g.length>0&&e.push(x(o,A(g[0]??"",g[1]??"",r),s));}function $t(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,u=me(t,i,c,l);u.length>0&&(e.push(Y(o,s)),e.push(x(o,A(u[0]??"",u[1]??"",r),s)));let g=de(t,i,a,c,l);g.length>0&&(e.push(Y(o,s)),e.push(x(o,g.join(" \xB7 "),s)));}function Pt(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n;t.blockInfo&&e.push(x(o,y(pe(t.blockInfo,i,a),l.blockFg,c),s));let u=[];t.usageInfo&&u.push(y(`${i.session_cost} ${k(t.usageInfo.session.cost)}`,l.sessionFg,c)),t.todayInfo&&u.push(y(`${i.today_cost} ${k(t.todayInfo.cost)} today`,l.todayFg,c)),u.length>0&&e.push(x(o,A(u[0]??"",u[1]??"",r),s));}function Et(n){let{lines:e,data:t,box:o,contentWidth:r,innerWidth:s,sym:i,config:a,reset:c,colors:l}=n,u=me(t,i,c,l);u.length>0&&(e.push(Y(o,s)),e.push(x(o,A(u[0]??"",u[1]??"",r),s)));let g=de(t,i,a,c,l);g.length>0&&e.push(x(o,g.join(" \xB7 "),s));}var xn="\x1B[?2026h",Sn="\x1B[?2026l",wn=32,Tn=80,kn=55;function vn(n){return n>=Tn?"wide":n>=kn?"medium":"narrow"}function $n(n){return n&&n>0?Math.max(wn,n):80}function De(n,e,t,o,r){let s=(r.display.charset||"unicode")==="text"?fe:ue,i=n.colors,a=$n(o),c=a-2,l=c-2,u=vn(a),g=[];g.push(xt(n,e,c));let m=St(n,l,s,t,i);m&&g.push(x(e,m,c));let d={lines:g,data:n,box:e,contentWidth:l,innerWidth:c,sym:s,config:r,reset:t,colors:i};return u==="wide"?(Tt(d),kt(d)):u==="medium"?(vt(d),$t(d)):(Pt(d),Et(d)),g.push(Ct(e,c)),xn+g.join(`
|
|
8
|
+
`)+Sn}var he=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 j),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new ce),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new le),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new H(this.config)),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new O),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new N),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new G),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new z(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){if(this.config.display.style==="tui")return this.generateTuiStatusline(e);let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id,e):null,o=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,r=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,i=this.config.display.lines.map(u=>u.segments.context).find(u=>u?.enabled)?.autocompactBuffer??33e3,a=this.needsSegmentInfo("context")?await this.contextProvider.getContextInfo(e,i):null,c=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id,e):null;return this.config.display.autoWrap?this.generateAutoWrapStatusline(e,t,o,r,a,c):(await Promise.all(this.config.display.lines.map(u=>this.renderLine(u,e,t,o,r,a,c)))).filter(u=>u.length>0).join(`
|
|
9
|
+
`)}async generateAutoWrapStatusline(e,t,o,r,s,i){let a=this.getThemeColors(),c=e.workspace?.current_dir||e.cwd||"/",l=$e(),u=[];for(let g of this.config.display.lines){let m=Object.entries(g.segments).filter(([b,C])=>C?.enabled).map(([b,C])=>({type:b,config:C})),d=[];for(let b of m){let C=await this.renderSegment(b,e,t,o,r,s,i,a,c);C&&d.push({type:b.type,text:C.text,bgColor:C.bgColor,fgColor:C.fgColor});}if(d.length===0)continue;if(!l||l<=0){u.push(this.buildLineFromSegments(d,a));continue}let p=[],h=0;for(let b of d){let C=this.calculateSegmentWidth(b,p.length===0);p.length>0&&h+C>l&&(u.push(this.buildLineFromSegments(p,a)),p=[],h=0),p.push(b),h+=C;}p.length>0&&u.push(this.buildLineFromSegments(p,a));}return u.join(`
|
|
10
|
+
`)}async generateTuiStatusline(e){let t=this.getThemeColors(),o=$e(),r=e.workspace?.current_dir||e.cwd||"/",i=(this.config.display.charset||"unicode")==="text"?bt:ht,c=this.config.display.lines.map($=>$.segments.context).find($=>$?.enabled)?.autocompactBuffer??33e3,l=await Promise.allSettled([this.usageProvider.getUsageInfo(e.session_id,e),this.blockProvider.getActiveBlockInfo(),this.todayProvider.getTodayInfo(),this.contextProvider.getContextInfo(e,c),this.metricsProvider.getMetricsInfo(e.session_id,e),this.gitService.getGitInfo(r,{showSha:false,showWorkingTree:true,showOperation:false,showTag:false,showTimeSinceCommit:false,showStashCount:false,showUpstream:false,showRepoName:false},e.workspace?.project_dir),this.tmuxService.getSessionId()]),u=$=>$.status==="fulfilled"?$.value:null,[g,m,d,p,h,b,C]=[u(l[0]),u(l[1]),u(l[2]),u(l[3]),u(l[4]),u(l[5]),u(l[6])];return De({hookData:e,usageInfo:g,blockInfo:m,todayInfo:d,contextInfo:p,metricsInfo:h,gitInfo:b,tmuxSessionId:C,colors:t},i,t.reset,o,this.config)}calculateSegmentWidth(e,t){let o=this.config.display.style==="capsule",r=F(e.text),i=(this.config.display.padding??1)*2;if(o){let c=2+i+(t?0:1);return r+c}let a=1+i;return r+a}buildLineFromSegments(e,t){let o=this.config.display.style==="capsule",r=t.reset;for(let s=0;s<e.length;s++){let i=e[s];if(!i)continue;let a=s===0,l=s===e.length-1?null:e[s+1];o&&!a&&(r+=" "),r+=this.formatSegment(i.bgColor,i.fgColor,i.text,l?.bgColor,t);}return r}async renderLine(e,t,o,r,s,i,a){let c=this.getThemeColors(),l=t.workspace?.current_dir||t.cwd||"/",u=Object.entries(e.segments).filter(([m,d])=>d?.enabled).map(([m,d])=>({type:m,config:d})),g=[];for(let m of u){let d=await this.renderSegment(m,t,o,r,s,i,a,c,l);d&&g.push({type:m.type,text:d.text,bgColor:d.bgColor,fgColor:d.fgColor});}return this.buildLineFromSegments(g,c)}async renderSegment(e,t,o,r,s,i,a,c,l){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,l):e.type==="session"?this.renderSessionSegment(e.config,o,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,s,c):e.type==="version"?this.renderVersionSegment(e.config,t,c):e.type==="env"?this.segmentRenderer.renderEnv(c,e.config):null}async renderGitSegment(e,t,o,r){if(!this.needsSegmentInfo("git"))return null;let s=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 s?this.segmentRenderer.renderGit(s,o,e):null}renderSessionSegment(e,t,o){return t?this.segmentRenderer.renderSession(t,o,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,o){return this.needsSegmentInfo("context")?this.segmentRenderer.renderContext(t,o,e):null}renderMetricsSegment(e,t,o,r){return this.segmentRenderer.renderMetrics(t,r,o,e)}renderBlockSegment(e,t,o){return t?this.segmentRenderer.renderBlock(t,o,e):null}renderTodaySegment(e,t,o){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderToday(t,o,r)}renderVersionSegment(e,t,o){return this.segmentRenderer.renderVersion(t,o,e)}initializeSymbols(){let e=this.config.display.style,t=this.config.display.charset||"unicode",o=e==="minimal",r=e==="capsule",s=t==="text"?fe:ue;return {right:o?"":r?s.right_rounded:s.right,left:r?s.left_rounded:"",branch:s.branch,model:s.model,git_clean:s.git_clean,git_dirty:s.git_dirty,git_conflicts:s.git_conflicts,git_ahead:s.git_ahead,git_behind:s.git_behind,git_worktree:s.git_worktree,git_tag:s.git_tag,git_sha:s.git_sha,git_upstream:s.git_upstream,git_stash:s.git_stash,git_time:s.git_time,session_cost:s.session_cost,block_cost:s.block_cost,today_cost:s.today_cost,context_time:s.context_time,metrics_response:s.metrics_response,metrics_last_response:s.metrics_last_response,metrics_duration:s.metrics_duration,metrics_messages:s.metrics_messages,metrics_lines_added:s.metrics_lines_added,metrics_lines_removed:s.metrics_lines_removed,metrics_burn:s.metrics_burn,version:s.version,bar_filled:s.bar_filled,bar_empty:s.bar_empty,env:s.env}}getThemeColors(){let e=this.config.theme,t,o=this.config.display.colorCompatibility||"auto",r=o==="auto"?q():o;if(e==="custom"){if(t=this.config.colors?.custom,!t)throw new Error("Custom theme selected but no colors provided in configuration")}else t=K(e,r),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=K("dark",r));let s=K("dark",r),i=this.config.display.style==="tui",c=e==="light"?"#f0f0f0":"#1e1e1e",l=Ne=>{let L=t[Ne]||s[Ne],U=L.fg;return i&&We(U,c)<60&&(U=L.bg),r==="none"?{bg:"",fg:""}:r==="ansi"?{bg:Se(L.bg,true),fg:Se(U,false)}:r==="ansi256"?{bg:xe(L.bg,true),fg:xe(U,false)}:{bg:_e(L.bg,true),fg:_e(U,false)}},u=l("directory"),g=l("git"),m=l("model"),d=l("session"),p=l("block"),h=l("today"),b=l("tmux"),C=l("context"),M=l("contextWarning"),$=l("contextCritical"),Le=l("metrics"),Ue=l("version"),Oe=l("env");return {reset:r==="none"?"":pt,modeBg:u.bg,modeFg:u.fg,gitBg:g.bg,gitFg:g.fg,modelBg:m.bg,modelFg:m.fg,sessionBg:d.bg,sessionFg:d.fg,blockBg:p.bg,blockFg:p.fg,todayBg:h.bg,todayFg:h.fg,tmuxBg:b.bg,tmuxFg:b.fg,contextBg:C.bg,contextFg:C.fg,contextWarningBg:M.bg,contextWarningFg:M.fg,contextCriticalBg:$.bg,contextCriticalFg:$.fg,metricsBg:Le.bg,metricsFg:Le.fg,versionBg:Ue.bg,versionFg:Ue.fg,envBg:Oe.bg,envFg:Oe.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;case "env":return t.envBg;default:return t.modeBg}}formatSegment(e,t,o,r,s){let i=this.config.display.style==="capsule",a=" ".repeat(this.config.display.padding??1);if(i){let m=this.config.display.colorCompatibility||"auto",p=(m==="auto"?q():m)==="ansi",h=J(e,p),b=`${h}${this.symbols.left}${s.reset}`,C=`${e}${t}${a}${o}${a}${s.reset}`,M=`${h}${this.symbols.right}${s.reset}`;return `${b}${C}${M}`}let c=`${e}${t}${a}${o}${a}`,l=this.config.display.colorCompatibility||"auto",g=(l==="auto"?q():l)==="ansi";if(r){let m=J(e,g);c+=`${s.reset}${r}${m}${this.symbols.right}`;}else c+=`${s.reset}${J(e,g)}${this.symbols.right}${s.reset}`;return c}};var Rt={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",autocompactBuffer:33e3},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 Ie(n){return ["light","dark","nord","tokyo-night","rose-pine","gruvbox","custom"].includes(n)}function Me(n){return n==="minimal"||n==="powerline"||n==="capsule"||n==="tui"}function Bt(n){return n==="unicode"||n==="text"}function ye(n,e){for(let t=0;t<n.length;t++){let o=n[t];if(o===e&&t+1<n.length)return n[t+1];if(o?.startsWith(`${e}=`))return o.split("=")[1]}}function Ce(n,e){let t={...n};for(let o in e){let r=e[o];if(r!==void 0)if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let s=t[o]||{};t[o]=Ce(s,r);}else t[o]=r;}return t}function Pn(n,e){return n?S.existsSync(n)?n:null:[...e?[_.join(e,".claude-powerline.json")]:[],_.join(process.cwd(),".claude-powerline.json"),_.join(Ae.homedir(),".claude","claude-powerline.json"),_.join(Ae.homedir(),".config","claude-powerline","config.json")].find(S.existsSync)||null}function En(n){try{let e=S.readFileSync(n,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${n}: ${e instanceof Error?e.message:String(e)}`)}}function Rn(){let n={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&Ie(t)&&(n.theme=t);let o=process.env.CLAUDE_POWERLINE_STYLE;return o&&(Me(o)?e.style=o:(console.warn(`Invalid display style '${o}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(n.display=e),n}function Bn(){return process.env.CLAUDE_POWERLINE_CONFIG}function Dn(n){let e={},t={},o=ye(n,"--theme");o&&Ie(o)&&(e.theme=o);let r=ye(n,"--style");r&&(Me(r)?t.style=r:(console.warn(`Invalid display style '${r}' from CLI argument, falling back to 'minimal'`),t.style="minimal"));let s=ye(n,"--charset");return s&&(Bt(s)?t.charset=s:(console.warn(`Invalid charset '${s}' from CLI argument, falling back to 'unicode'`),t.charset="unicode")),Object.keys(t).length>0&&(e.display=t),e}function Fn(n=process.argv,e){let t=JSON.parse(JSON.stringify(Rt)),o=ye(n,"--config")||Bn(),r=o?.startsWith("~")?o.replace("~",Ae.homedir()):o,s=Pn(r,e);if(s)try{let c=En(s);t=Ce(t,c);}catch(c){console.warn(`Warning: ${c instanceof Error?c.message:String(c)}`);}t.display?.style&&!Me(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&&!Bt(t.display.charset)&&(console.warn(`Invalid charset '${t.display.charset}' in config file, falling back to 'unicode'`),t.display.charset="unicode"),t.theme&&!Ie(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let i=Rn();t=Ce(t,i);let a=Dn(n);return t=Ce(t,a),t}var Dt=Fn;function Ft(){console.log(`
|
|
11
11
|
claude-powerline - Beautiful powerline statusline for Claude Code
|
|
12
12
|
|
|
13
13
|
Usage: claude-powerline [options]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owloops/claude-powerline",
|
|
3
|
-
"version": "1.20.
|
|
3
|
+
"version": "1.20.1",
|
|
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",
|