@owloops/claude-powerline 1.6.4 → 1.6.6
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/README.md +1 -0
- package/dist/index.js +9 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
[](https://www.npmjs.com/package/@owloops/claude-powerline)
|
|
9
9
|
[](https://www.npmjs.com/package/@owloops/claude-powerline)
|
|
10
10
|
[](https://packagephobia.com/result?p=@owloops/claude-powerline)
|
|
11
|
+
[](https://www.npmjs.com/package/@owloops/claude-powerline)
|
|
11
12
|
|
|
12
13
|
[](https://github.com/hesreallyhim/awesome-claude-code)
|
|
13
14
|
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`);for(let a of
|
|
4
|
-
`).length:0}catch{return 0}}getUpstream(e){try{return execSync("git rev-parse --abbrev-ref @{u}",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}getRepoName(e){try{let t=execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return t?t.match(/\/([^/]+?)(\.git)?$/)?.[1]||
|
|
5
|
-
`),n=null;for(let
|
|
6
|
-
`).filter(
|
|
7
|
-
`).filter(o=>o.trim()),r=[];for(let o of s)try{let l=JSON.parse(o);if(l.isSidechain===!0)continue;r.push(l);}catch(l){c(`Failed to parse JSONL line: ${l}`);continue}return c(`Loaded ${r.length} transcript entries`),r}catch(t){return c(`Error loading transcript for ${e}:`,t),[]}}calculateResponseTimes(e){let t=[],n=[],s=-1,r=null,o=null,l=-1;for(let g=0;g<e.length;g++){let f=e[g];if(!(!f||!f.timestamp))try{let m=new Date(f.timestamp),p=f.type||f.message?.role||f.message?.type,b=f.type==="user"&&f.message?.content?.[0]?.type==="tool_result";p==="user"&&!b?(t.push(m),r=m,s=g,o=null,l=-1,c(`Found user message at index ${g}, timestamp ${m.toISOString()}`)):s>=0&&(p==="assistant"||b||p==="system"||f.message?.usage)&&(o=m,l=g,p==="assistant"||f.message?.usage?(n.push(m),c(`Found assistant message at index ${g}, timestamp ${m.toISOString()}`)):b?c(`Found tool result at index ${g}, timestamp ${m.toISOString()}`):c(`Found ${p} message at index ${g}, timestamp ${m.toISOString()}`));}catch{continue}}if(t.length===0||n.length===0)return {average:null,last:null};let a=[];for(let g of n){let f=t.filter(m=>m<g);if(f.length>0){let m=new Date(Math.max(...f.map(b=>b.getTime()))),p=(g.getTime()-m.getTime())/1e3;p>.1&&p<300?(a.push(p),c(`Valid response time: ${p.toFixed(1)}s`)):c(`Rejected response time: ${p.toFixed(1)}s (outside 0.1s-5m range)`);}}let u=null;if(r&&o&&l>s){let g=o.getTime()-r.getTime(),f=l-s;g===0&&f>0?(u=f*.1,c(`Estimated last response time from position difference: ${u.toFixed(2)}s (${f} messages)`)):g>0&&(u=g/1e3,c(`Last response time from timestamps: ${u.toFixed(2)}s`)),c(`Last user message at index ${s}, timestamp ${r.toISOString()}`),c(`Last response end at index ${l}, timestamp ${o.toISOString()}`);}if(a.length===0&&u===null)return {average:null,last:null};let d=a.length>0?a.reduce((g,f)=>g+f,0)/a.length:null;return c(`Calculated average response time: ${d?.toFixed(2)||"null"}s from ${a.length} measurements`),c(`Last response time: ${u?.toFixed(2)||"null"}s`),{average:d,last:u}}calculateSessionDuration(e){let t=[];for(let o of e)if(o.timestamp)try{t.push(new Date(o.timestamp));}catch{continue}if(t.length<2)return null;t.sort((o,l)=>o.getTime()-l.getTime());let n=t[t.length-1],s=t[0];if(!n||!s)return null;let r=(n.getTime()-s.getTime())/1e3;return r>0?r:null}calculateBurnRateDuration(e){if(e.length===0)return null;let t=new Date,n=e.map(o=>o.timestamp).filter(Boolean).map(o=>new Date(o)).filter(o=>t.getTime()-o.getTime()<7200*1e3).sort((o,l)=>o.getTime()-l.getTime());if(n.length===0)return null;let s=n[0];return s?Math.max((t.getTime()-s.getTime())/1e3,1800):null}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,s=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!s}).length}async calculateTotalCost(e){let t=0,n=new Set;for(let s of e){let r=`${s.timestamp}-${JSON.stringify(s.message?.usage||{})}`;if(n.has(r)){c(`Skipping duplicate entry at ${s.timestamp}`);continue}if(n.add(r),typeof s.costUSD=="number")t+=s.costUSD;else if(s.message?.usage){let o=await T.calculateCostForEntry(s);t+=o;}}return Math.round(t*1e4)/1e4}calculateTotalTokens(e){let t=new Set;return e.reduce((n,s)=>{let r=s.message?.usage;if(!r)return n;let o=`${s.timestamp}-${JSON.stringify(r)}`;return t.has(o)?(c(`Skipping duplicate token entry at ${s.timestamp}`),n):(t.add(o),n+(r.input_tokens||0)+(r.output_tokens||0)+(r.cache_creation_input_tokens||0)+(r.cache_read_input_tokens||0))},0)}async getMetricsInfo(e){try{c(`Starting metrics calculation for session: ${e}`);let t=await this.loadTranscriptEntries(e);if(t.length===0)return {responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,costBurnRate:null,tokenBurnRate:null};let n=this.calculateResponseTimes(t),s=this.calculateSessionDuration(t),r=this.calculateMessageCount(t),o=null,l=null,a=this.calculateBurnRateDuration(t);if(a&&a>60){let u=a/3600;if(u<=0)c(`Invalid hours elapsed: ${u}`);else {let d=await this.calculateTotalCost(t),g=this.calculateTotalTokens(t);d>0&&(o=Math.round(d/u*100)/100,c(`Cost burn rate: $${o}/h (total: $${d}, duration: ${u}h)`)),g>0&&(l=Math.round(g/u),c(`Token burn rate: ${l}/h (total: ${g}, duration: ${u}h)`));}}return c(`Metrics calculated: avgResponseTime=${n.average?.toFixed(2)||"null"}s, lastResponseTime=${n.last?.toFixed(2)||"null"}s, sessionDuration=${s?.toFixed(0)||"null"}s, messageCount=${r}`),{responseTime:n.average,lastResponseTime:n.last,sessionDuration:s,messageCount:r,costBurnRate:o,tokenBurnRate:l}}catch(t){return c(`Error calculating metrics for session ${e}:`,t),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,costBurnRate:null,tokenBurnRate:null}}}};var I=class{cachedVersion=null;cacheTimestamp=0;CACHE_TTL=3e4;getClaudeVersion(){let e=Date.now();if(this.cachedVersion!==null&&e-this.cacheTimestamp<this.CACHE_TTL)return this.cachedVersion;try{let t=execSync("claude --version",{encoding:"utf8",timeout:1e3}).trim(),n=t.match(/^([\d.]+)/);return n?(this.cachedVersion=`v${n[1]}`,this.cacheTimestamp=e,c(`Claude Code version: ${this.cachedVersion}`),this.cachedVersion):(c(`Could not parse version from: ${t}`),null)}catch(t){return c("Error getting Claude Code version:",t),null}}async getVersionInfo(){return {version:this.getClaudeVersion()}}};function x(i){return i===null?"$0.00":i<.01?"<$0.01":`$${i.toFixed(2)}`}function k(i){return i===null||i===0?"0 tokens":i>=1e6?`${(i/1e6).toFixed(1)}M tokens`:i>=1e3?`${(i/1e3).toFixed(1)}K tokens`:`${i} tokens`}function fe(i){if(!i)return "0 tokens";let e=[];if(i.input>0&&e.push(`${k(i.input).replace(" tokens","")}in`),i.output>0&&e.push(`${k(i.output).replace(" tokens","")}out`),i.cacheCreation>0||i.cacheRead>0){let t=i.cacheCreation+i.cacheRead;e.push(`${k(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function Oe(i,e){return !e||e<=0||i<0?null:Math.min(100,i/e*100)}function pe(i,e,t=80){let n=Oe(i,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let s=`${n.toFixed(0)}%`,r=n>=t,o="";return r?o=` !${s}`:n>=50?o=` +${s}`:o=` ${s}`,{percentage:n,isWarning:r,displayText:o}}var L=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let s=e.workspace?.current_dir||e.cwd||"/",r=e.workspace?.project_dir;if(n?.showBasename)return {text:C.basename(s)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let o=process.env.HOME||process.env.USERPROFILE,l=s,a=r;return o&&(s.startsWith(o)&&(l=s.replace(o,"~")),r&&r.startsWith(o)&&(a=r.replace(o,"~"))),{text:this.getDisplayDirectoryName(l,a),bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let s=[];if(n?.showRepoName&&e.repoName&&(s.push(e.repoName),e.isWorktree&&s.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&s.push(`[${e.operation}]`),s.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&s.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&s.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?s.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?s.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&s.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let o=[];e.staged&&e.staged>0&&o.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&o.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&o.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&o.push(`!${e.conflicts}`),o.length>0&&s.push(`(${o.join(" ")})`);}if(n?.showUpstream&&e.upstream&&s.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&s.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let o=this.formatTimeSince(e.timeSinceCommit);s.push(`${this.symbols.git_time} ${o}`);}let r=this.symbols.git_clean;return e.status==="conflicts"?r=this.symbols.git_conflicts:e.status==="dirty"&&(r=this.symbols.git_dirty),s.push(r),{text:s.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}formatTimeSince(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:e<604800?`${Math.floor(e/86400)}d`:`${Math.floor(e/604800)}w`}renderModel(e,t){let n=e.model?.display_name||"Claude";return {text:`${this.symbols.model} ${n}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n="cost"){let s=this.config.budget?.session;return {text:`${this.symbols.session_cost} ${this.formatUsageWithBudget(e.session.cost,e.session.tokens,e.session.tokenBreakdown,n,s?.amount,s?.warningThreshold||80)}`,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){if(!e)return {text:`${this.symbols.context_time} 0 (100%)`,bgColor:t.contextBg,fgColor:t.contextFg};let n=e.inputTokens.toLocaleString(),s=`${e.contextLeftPercentage}%`;return {text:`${this.symbols.context_time} ${n} (${s})`,bgColor:t.contextBg,fgColor:t.contextFg}}renderMetrics(e,t,n,s){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let r=[];if(s?.showLastResponseTime){let o=e.lastResponseTime===null?"0.0s":e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;r.push(`${this.symbols.metrics_last_response} ${o}`);}if(s?.showResponseTime!==false&&e.responseTime!==null){let o=e.responseTime<60?`${e.responseTime.toFixed(1)}s`:`${(e.responseTime/60).toFixed(1)}m`;r.push(`${this.symbols.metrics_response} ${o}`);}if(s?.showDuration!==false&&e.sessionDuration!==null){let o=this.formatDuration(e.sessionDuration);r.push(`${this.symbols.metrics_duration} ${o}`);}return s?.showMessageCount!==false&&e.messageCount!==null&&r.push(`${this.symbols.metrics_messages} ${e.messageCount}`),r.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:r.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,n){let s;if(e.cost===null&&e.tokens===null)s="No active block";else {let r=n?.type||"cost",o=n?.burnType,l=e.timeRemaining!==null?(()=>{let d=Math.floor(e.timeRemaining/60),g=e.timeRemaining%60;return d>0?`${d}h ${g}m`:`${g}m`})():null,a;switch(r){case "cost":a=x(e.cost);break;case "tokens":a=k(e.tokens);break;case "both":a=`${x(e.cost)} / ${k(e.tokens)}`;break;case "time":a=l||"N/A";break;default:a=x(e.cost);}let u="";if(o&&o!=="none")switch(o){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?`${k(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let f=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",m=e.tokenBurnRate!==null?`${k(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${f} / ${m}`;break}r==="time"?s=a:s=l?`${a}${u} (${l} left)`:`${a}${u}`;}return {text:`${this.symbols.block_cost} ${s}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let s=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,s?.amount,s?.warningThreshold)}`,bgColor:t.todayBg,fgColor:t.todayFg}}formatDuration(e){return e<60?`${e.toFixed(0)}s`:e<3600?`${(e/60).toFixed(0)}m`:e<86400?`${(e/3600).toFixed(1)}h`:`${(e/86400).toFixed(1)}d`}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||C.basename(t)||"project":C.basename(e)||"root":C.basename(e)||"root"}formatUsageDisplay(e,t,n,s){switch(s){case "cost":return x(e);case "tokens":return k(t);case "both":return `${x(e)} (${k(t)})`;case "breakdown":return fe(n);default:return x(e)}}formatUsageWithBudget(e,t,n,s,r,o=80){let l=this.formatUsageDisplay(e,t,n,s);if(r&&r>0&&e!==null){let a=pe(e,r,o);return l+a.displayText}return l}renderVersion(e,t,n){return !e||!e.version?null:{text:`${this.symbols.version} ${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}}};function Ae(i){return {timestamp:i.timestamp,usage:{inputTokens:i.message?.usage?.input_tokens||0,outputTokens:i.message?.usage?.output_tokens||0,cacheCreationInputTokens:i.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:i.message?.usage?.cache_read_input_tokens||0},costUSD:i.costUSD||0,model:i.message?.model||"unknown"}}var J=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],s=[...e].sort((l,a)=>l.timestamp.getTime()-a.timestamp.getTime()),r=null,o=[];for(let l of s){let a=l.timestamp;if(r==null)r=this.floorToHour(a),o=[l];else {let u=a.getTime()-r.getTime(),d=o[o.length-1];if(d==null)continue;let g=d.timestamp,f=a.getTime()-g.getTime();u>t||f>t?(n.push(o),r=this.floorToHour(a),o=[l]):o.push(l);}}return r!=null&&o.length>0&&n.push(o),n}createBlockInfo(e,t){let n=new Date,s=this.sessionDurationHours*60*60*1e3,r=new Date(e.getTime()+s),o=t[t.length-1],l=o!=null?o.timestamp:e,a=n.getTime()-l.getTime()<s&&n<r;return {block:t,isActive:a}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let s=n[0];if(!s)continue;let r=this.floorToHour(s.timestamp),o=this.createBlockInfo(r,n);if(o.isActive)return o.block}return null}async loadUsageEntries(){c("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await G(void 0,(l,a)=>a>=e,true),s=[];for(let l of n)if(l.message?.usage){let a=Ae(l);!a.costUSD&&l.raw&&(a.costUSD=await T.calculateCostForEntry(l.raw)),s.push(a);}let r=this.identifySessionBlocks(s);c(`Block segment: Found ${r.length} session blocks`);let o=this.findActiveBlock(r);if(o&&o.length>0){c(`Block segment: Found active block with ${o.length} entries`);let l=o[0],a=o[o.length-1];return l&&a&&c(`Block segment: Active block from ${l.timestamp.toISOString()} to ${a.timestamp.toISOString()}`),o}else return c("Block segment: No active block found"),[]}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return c("Block segment: No entries in current block"),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((a,u)=>a+u.costUSD,0),n=e.reduce((a,u)=>a+u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,0),s=new Date,r=null;if(e.length>0){let a=e[0];if(a){let u=this.sessionDurationHours*60*60*1e3,d=this.floorToHour(a.timestamp),g=new Date(d.getTime()+u);r=Math.max(0,Math.round((g.getTime()-s.getTime())/(1e3*60)));}}let o=null,l=null;if(e.length>=1&&(t>0||n>0)){let a=e.map(g=>g.timestamp).sort((g,f)=>g.getTime()-f.getTime()),u=a[0],d=a[a.length-1];if(u&&d){let g=(d.getTime()-u.getTime())/6e4;g>0&&(t>0&&(o=t/g*60),n>0&&(l=n/g*60));}}return c(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${r}m remaining, burn rate: ${o?"$"+o.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,timeRemaining:r,burnRate:o,tokenBurnRate:l}}catch(e){return c("Error getting active block info:",e),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function j(i){let e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),n=String(i.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function Ne(i){return i.inputTokens+i.outputTokens+i.cacheCreationInputTokens+i.cacheReadInputTokens}function He(i){return {timestamp:i.timestamp,usage:{inputTokens:i.message?.usage?.input_tokens||0,outputTokens:i.message?.usage?.output_tokens||0,cacheCreationInputTokens:i.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:i.message?.usage?.cache_read_input_tokens||0},costUSD:i.costUSD||0,model:i.message?.model||"unknown"}}var q=class{cache=new Map;CACHE_TTL=3e5;async loadTodayEntries(){let t=j(new Date);c(`Today segment: Loading entries for date ${t}`);let n=new Date;n.setDate(n.getDate()-7);let r=await G(void 0,(a,u)=>u>=n,true),o=[],l=0;for(let a of r)if(j(a.timestamp)===t&&a.message?.usage){let d=He(a);!d.costUSD&&a.raw&&(d.costUSD=await T.calculateCostForEntry(a.raw)),o.push(d),l++;}return c(`Today segment: Found ${l} entries for today (${t})`),o}async getTodayEntries(){let e="today",t=this.cache.get(e),n=Date.now();if(t&&n-t.timestamp<this.CACHE_TTL)return t.data;this.cache.clear();try{let s=await this.loadTodayEntries();return this.cache.set(e,{data:s,timestamp:n}),s}catch(s){return c("Error loading today's entries:",s),[]}}async getTodayInfo(){try{let e=await this.getTodayEntries();if(e.length===0)return {cost:null,tokens:null,tokenBreakdown:null,date:j(new Date)};let t=e.reduce((r,o)=>r+o.costUSD,0),n=e.reduce((r,o)=>r+Ne(o.usage),0),s=e.reduce((r,o)=>({input:r.input+o.usage.inputTokens,output:r.output+o.usage.outputTokens,cacheCreation:r.cacheCreation+o.usage.cacheCreationInputTokens,cacheRead:r.cacheRead+o.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return c(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:s,date:j(new Date)}}catch(e){return c("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:j(new Date)}}}};var K=class{constructor(e){this.config=e;this.symbols=this.initializeSymbols(),this.usageProvider=new U,this.blockProvider=new J,this.todayProvider=new q,this.contextProvider=new F,this.gitService=new D,this.tmuxService=new B,this.metricsProvider=new M,this.versionProvider=new I,this.segmentRenderer=new L(e,this.symbols);}symbols;usageProvider;blockProvider;todayProvider;contextProvider;gitService;tmuxService;metricsProvider;versionProvider;segmentRenderer;needsUsageInfo(){return this.config.display.lines.some(e=>e.segments.session?.enabled)}needsGitInfo(){return this.config.display.lines.some(e=>e.segments.git?.enabled)}needsTmuxInfo(){return this.config.display.lines.some(e=>e.segments.tmux?.enabled)}needsContextInfo(){return this.config.display.lines.some(e=>e.segments.context?.enabled)}needsMetricsInfo(){return this.config.display.lines.some(e=>e.segments.metrics?.enabled)}needsBlockInfo(){return this.config.display.lines.some(e=>e.segments.block?.enabled)}needsTodayInfo(){return this.config.display.lines.some(e=>e.segments.today?.enabled)}needsVersionInfo(){return this.config.display.lines.some(e=>e.segments.version?.enabled)}async generateStatusline(e){let t=this.needsUsageInfo()?await this.usageProvider.getUsageInfo(e.session_id):null,n=this.needsBlockInfo()?await this.blockProvider.getActiveBlockInfo():null,s=this.needsTodayInfo()?await this.todayProvider.getTodayInfo():null,r=this.needsContextInfo()?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,o=this.needsMetricsInfo()?await this.metricsProvider.getMetricsInfo(e.session_id):null,l=this.needsVersionInfo()?await this.versionProvider.getVersionInfo():null;return this.config.display.lines.map(u=>this.renderLine(u,e,t,n,s,r,o,l)).filter(u=>u.length>0).join(`
|
|
8
|
-
`)}renderLine(e,t,n,
|
|
2
|
+
import h from'process';import b,{posix,join}from'path';import T,{readFileSync,existsSync,mkdirSync,writeFileSync}from'fs';import {execSync}from'child_process';import v,{homedir}from'os';import {json}from'stream/consumers';import {get}from'https';import {URL}from'url';import {readFile,readdir,stat}from'fs/promises';function z(r,e){if(e&&(r.toLowerCase()==="transparent"||r.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(r.slice(1,3),16),n=parseInt(r.slice(3,5),16),o=parseInt(r.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${n};${o}m`}function Y(r){let e=r.match(/48;2;(\d+);(\d+);(\d+)/);return e?`\x1B[38;2;${e[1]};${e[2]};${e[3]}m`:r.replace("48","38")}var oe={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"},metrics:{bg:"#374151",fg:"#d1d5db"},version:{bg:"#3a3a4a",fg:"#b8b8d0"}};var re={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"},metrics:{bg:"#6b7280",fg:"#ffffff"},version:{bg:"#8b7dd8",fg:"#ffffff"}};var se={directory:{bg:"#434c5e",fg:"#d8dee9"},git:{bg:"#3b4252",fg:"#a3be8c"},model:{bg:"#4c566a",fg:"#81a1c1"},session:{bg:"#2e3440",fg:"#88c0d0"},block:{bg:"#3b4252",fg:"#81a1c1"},today:{bg:"#2e3440",fg:"#8fbcbb"},tmux:{bg:"#2e3440",fg:"#8fbcbb"},context:{bg:"#5e81ac",fg:"#eceff4"},metrics:{bg:"#b48ead",fg:"#2e3440"},version:{bg:"#434c5e",fg:"#88c0d0"}};var ie={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"},metrics:{bg:"#3d59a1",fg:"#c0caf5"},version:{bg:"#292e42",fg:"#bb9af7"}};var ae={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"},metrics:{bg:"#524f67",fg:"#e0def4"},version:{bg:"#2a273f",fg:"#c4a7e7"}};var ke={dark:oe,light:re,nord:se,"tokyo-night":ie,"rose-pine":ae};function O(r){return ke[r]||null}var l=(r,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${r}`,...e);};var P=class{cache=new Map;CACHE_TTL=1e3;isGitRepo(e){try{return T.existsSync(b.join(e,".git"))}catch{return false}}getGitInfo(e,t={},n){let o=n&&this.isGitRepo(n)?n:e,i=JSON.stringify(t),s=`${o}:${i}`,c=this.cache.get(s),a=Date.now();if(c&&a-c.timestamp<this.CACHE_TTL)return c.data;if(!this.isGitRepo(o))return this.cache.set(s,{data:null,timestamp:a}),null;try{let u=this.getBranch(o),d=this.getStatus(o),{ahead:g,behind:f}=this.getAheadBehind(o),m={branch:u||"detached",status:d,ahead:g,behind:f};if(t.showSha&&(m.sha=this.getSha(o)||void 0),t.showWorkingTree){let p=this.getWorkingTreeCounts(o);m.staged=p.staged,m.unstaged=p.unstaged,m.untracked=p.untracked,m.conflicts=p.conflicts;}return t.showOperation&&(m.operation=this.getOngoingOperation(o)||void 0),t.showTag&&(m.tag=this.getNearestTag(o)||void 0),t.showTimeSinceCommit&&(m.timeSinceCommit=this.getTimeSinceLastCommit(o)||void 0),t.showStashCount&&(m.stashCount=this.getStashCount(o)),t.showUpstream&&(m.upstream=this.getUpstream(o)||void 0),t.showRepoName&&(m.repoName=this.getRepoName(o)||void 0,m.isWorktree=this.isWorktree(o)),this.cache.set(s,{data:m,timestamp:a}),m}catch{return this.cache.set(s,{data:null,timestamp:a}),null}}getBranch(e){try{return execSync("git branch --show-current",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch(t){return l(`Git branch command failed in ${e}:`,t),null}}getStatus(e){try{let t=execSync("git status --porcelain",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return t?t.includes("UU")||t.includes("AA")||t.includes("DD")?"conflicts":"dirty":"clean"}catch(t){return l(`Git status command failed in ${e}:`,t),"clean"}}getWorkingTreeCounts(e){try{let t=execSync("git status --porcelain=v1",{cwd:e,encoding:"utf8",timeout:5e3}),n=0,o=0,i=0,s=0;if(!t.trim())return {staged:n,unstaged:o,untracked:i,conflicts:s};let c=t.split(`
|
|
3
|
+
`);for(let a of c){if(!a||a.length<2)continue;let u=a.charAt(0),d=a.charAt(1);if(u==="?"&&d==="?"){i++;continue}let g=u+d;if(["DD","AU","UD","UA","DU","AA","UU"].includes(g)){s++;continue}u!==" "&&u!=="?"&&n++,d!==" "&&d!=="?"&&o++;}return {staged:n,unstaged:o,untracked:i,conflicts:s}}catch(t){return l(`Git working tree counts failed in ${e}:`,t),{staged:0,unstaged:0,untracked:0,conflicts:0}}}getAheadBehind(e){try{let t=execSync("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:5e3}).trim(),n=execSync("git rev-list --count HEAD..@{u}",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return {ahead:parseInt(t)||0,behind:parseInt(n)||0}}catch(t){return l(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}getSha(e){try{return execSync("git rev-parse --short=7 HEAD",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}getOngoingOperation(e){try{let t=b.join(e,".git");return T.existsSync(b.join(t,"MERGE_HEAD"))?"MERGE":T.existsSync(b.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":T.existsSync(b.join(t,"REVERT_HEAD"))?"REVERT":T.existsSync(b.join(t,"BISECT_LOG"))?"BISECT":T.existsSync(b.join(t,"rebase-merge"))||T.existsSync(b.join(t,"rebase-apply"))?"REBASE":null}catch{return null}}getNearestTag(e){try{return execSync("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}getTimeSinceLastCommit(e){try{let t=execSync("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:5e3}).trim();if(!t)return null;let n=parseInt(t)*1e3,o=Date.now();return Math.floor((o-n)/1e3)}catch{return null}}getStashCount(e){try{let t=execSync("git stash list",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return t?t.split(`
|
|
4
|
+
`).length:0}catch{return 0}}getUpstream(e){try{return execSync("git rev-parse --abbrev-ref @{u}",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}getRepoName(e){try{let t=execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return t?t.match(/\/([^/]+?)(\.git)?$/)?.[1]||b.basename(e):b.basename(e)}catch{return b.basename(e)}}isWorktree(e){try{let t=b.join(e,".git");return !!(T.existsSync(t)&&T.statSync(t).isFile())}catch{return false}}};var E=class{getSessionId(){try{if(!process.env.TMUX_PANE)return l("TMUX_PANE not set, not in tmux session"),null;l(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let e=execSync("tmux display-message -p '#S'",{encoding:"utf8",timeout:1e3}).trim();return l(`Tmux session ID: ${e||"empty"}`),e||null}catch(e){return l("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};var le={"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-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-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}},S=class{static memoryCache=new Map;static CACHE_TTL=1440*60*1e3;static GITHUB_PRICING_URL="https://raw.githubusercontent.com/Owloops/claude-powerline/main/pricing.json";static getCacheFilePath(){let e=join(homedir(),".claude","cache");try{mkdirSync(e,{recursive:!0});}catch{}return join(e,"pricing.json")}static loadDiskCache(){try{let e=this.getCacheFilePath(),t=readFileSync(e,"utf-8"),n=JSON.parse(t);if(n&&n.data&&n.timestamp)return n}catch{}return null}static saveDiskCache(e){try{let t=this.getCacheFilePath(),n={data:e,timestamp:Date.now()};writeFileSync(t,JSON.stringify(n));}catch(t){l("Failed to save pricing cache to disk:",t);}}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},o=>{if(o.statusCode!==200){l(`HTTP ${o.statusCode}: ${o.statusMessage}`),e(null);return}let i="",s=0,c=1024*1024;o.on("data",a=>{if(s+=a.length,s>c){l("Response too large"),n.destroy(),e(null);return}i+=a;}),o.on("end",()=>{try{let u=JSON.parse(i),d=u._meta,g={};for(let[f,m]of Object.entries(u))f!=="_meta"&&(g[f]=m);this.validatePricingData(g)?(l(`Fetched fresh pricing from GitHub for ${Object.keys(g).length} models`),l(`Pricing last updated: ${d?.updated||"unknown"}`),e(g)):(l("Invalid pricing data structure"),e(null));}catch(a){l("Failed to parse JSON:",a),e(null);}}),o.on("error",a=>{l("Response error:",a),e(null);});});n.on("error",o=>{l("Request error:",o),e(null);}),n.on("timeout",()=>{l("Request timeout"),n.destroy(),e(null);}),n.end();})}static async getCurrentPricing(){let e=Date.now(),t=this.memoryCache.get("pricing");if(t&&e-t.timestamp<this.CACHE_TTL)return l(`Using memory cached pricing data for ${Object.keys(t.data).length} models`),t.data;let n=this.loadDiskCache();if(n&&e-n.timestamp<this.CACHE_TTL)return this.memoryCache.clear(),this.memoryCache.set("pricing",n),l(`Using disk cached pricing data for ${Object.keys(n.data).length} models`),n.data;let o=await this.fetchPricingData();return o?(this.memoryCache.clear(),this.memoryCache.set("pricing",{data:o,timestamp:e}),this.saveDiskCache(o),o):n?(this.memoryCache.set("pricing",n),l(`Using stale cached pricing data for ${Object.keys(n.data).length} models`),n.data):(l(`Using offline pricing data for ${Object.keys(le).length} models`),le)}static validatePricingData(e){if(!e||typeof e!="object")return false;for(let[,t]of Object.entries(e)){if(!t||typeof t!="object")return false;let n=t;if(typeof n.input!="number"||typeof n.output!="number"||typeof n.cache_read!="number")return false}return true}static async getModelPricing(e){let t=await this.getCurrentPricing();return t[e]?t[e]:this.fuzzyMatchModel(e,t)}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[i,s]of Object.entries(t))if(i.toLowerCase()===n)return s;let o=[{pattern:["opus-4-1","claude-opus-4-1"],fallback:"claude-opus-4-1-20250805"},{pattern:["opus-4","claude-opus-4"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet-4","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:["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:i,fallback:s}of o)if(i.some(c=>n.includes(c))&&t[s])return t[s];return t["claude-3-5-sonnet-20241022"]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let n=e.message?.usage;if(!n)return 0;let o=this.extractModelId(e),i=await this.getModelPricing(o),s=n.input_tokens||0,c=n.output_tokens||0,a=n.cache_creation_input_tokens||0,u=n.cache_read_input_tokens||0,d=s/1e6*i.input,g=c/1e6*i.output,f=u/1e6*i.cache_read,m=a/1e6*i.cache_write_5m;return d+g+m+f}static extractModelId(e){if(e.model&&typeof e.model=="string")return e.model;let t=e.message;if(t?.model){let n=t.model;return typeof n=="string"?n:n?.id||"claude-3-5-sonnet-20241022"}return e.model_id&&typeof e.model_id=="string"?e.model_id:"claude-3-5-sonnet-20241022"}};function me(){let r=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let n=t.trim();existsSync(n)&&r.push(n);}),r.length===0){let t=homedir(),n=join(t,".config","claude"),o=join(t,".claude");existsSync(n)?r.push(n):existsSync(o)&&r.push(o);}return r}async function de(r){let e=[];for(let t of r){let n=join(t,"projects");if(existsSync(n))try{let o=await readdir(n,{withFileTypes:!0});for(let i of o)if(i.isDirectory()){let s=posix.join(n,i.name);e.push(s);}}catch(o){l(`Failed to read projects directory ${n}:`,o);}}return e}async function A(r){let e=me(),t=await de(e);for(let n of t){let o=posix.join(n,`${r}.jsonl`);if(existsSync(o))return o}return null}async function Ue(r){try{let t=(await readFile(r,"utf-8")).trim().split(`
|
|
5
|
+
`),n=null;for(let o of t)if(o.trim())try{let i=JSON.parse(o);if(i.timestamp&&typeof i.timestamp=="string"){let s=new Date(i.timestamp);isNaN(s.getTime())||(n===null||s<n)&&(n=s);}}catch{continue}return n}catch(e){return l(`Failed to get earliest timestamp for ${r}:`,e),null}}async function Fe(r,e=true){return (await Promise.all(r.map(async n=>({file:n,timestamp:await Ue(n)})))).sort((n,o)=>n.timestamp===null&&o.timestamp===null?0:n.timestamp===null?1:o.timestamp===null?-1:(e?1:-1)*(n.timestamp.getTime()-o.timestamp.getTime())).map(n=>n.file)}async function Me(r){try{return (await stat(r)).mtime}catch{return null}}function Ie(r){let e=r.message?.id||(typeof r.raw.message=="object"&&r.raw.message!==null&&"id"in r.raw.message?r.raw.message.id:void 0),t="requestId"in r.raw?r.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}async function D(r){try{let t=(await readFile(r,"utf-8")).trim().split(`
|
|
6
|
+
`).filter(o=>o.trim()),n=[];for(let o of t)try{let i=JSON.parse(o);if(!i.timestamp)continue;let s={timestamp:new Date(i.timestamp),message:i.message,costUSD:typeof i.costUSD=="number"?i.costUSD:void 0,isSidechain:i.isSidechain===!0,raw:i};n.push(s);}catch(i){l(`Failed to parse JSONL line: ${i}`);continue}return n}catch(e){return l(`Failed to read file ${r}:`,e),[]}}async function N(r,e,t=false){let n=[],o=me(),i=await de(o),s=new Set,c=[];for(let a of i)try{let g=(await readdir(a)).filter(m=>m.endsWith(".jsonl")).map(async m=>{let p=posix.join(a,m);if(existsSync(p)){let y=await Me(p);return {filePath:p,mtime:y}}return null}),f=await Promise.all(g);for(let m of f)m?.mtime&&(!e||e(m.filePath,m.mtime))&&c.push(m.filePath);}catch(u){l(`Failed to read project directory ${a}:`,u);continue}if(t){let a=await Fe(c,false);c.length=0,c.push(...a);}for(let a of c){let u=await D(a);for(let d of u){let g=Ie(d);if(g&&s.has(g)){l(`Skipping duplicate entry: ${g}`);continue}g&&s.add(g),n.push(d);}}return n}function Le(r){return {timestamp:r.timestamp.toISOString(),message:{usage:{input_tokens:r.message?.usage?.input_tokens||0,output_tokens:r.message?.usage?.output_tokens||0,cache_creation_input_tokens:r.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:r.message?.usage?.cache_read_input_tokens}},costUSD:r.costUSD}}var H=class{async getSessionUsage(e){try{let t=await A(e);if(!t)return l(`No transcript found for session: ${e}`),null;l(`Found transcript at: ${t}`);let n=await D(t);if(n.length===0)return {totalCost:0,entries:[]};let o=[],i=0;for(let s of n)if(s.message?.usage){let c=Le(s);if(c.costUSD!==void 0)i+=c.costUSD;else {let a=await S.calculateCostForEntry(s.raw);c.costUSD=a,i+=a;}o.push(c);}return l(`Parsed ${o.length} usage entries, total cost: $${i.toFixed(4)}`),{totalCost:i,entries:o}}catch(t){return l(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,n)=>({input:t.input+(n.message.usage.input_tokens||0),output:t.output+(n.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(n.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(n.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e){let t=await this.getSessionUsage(e);if(!t||t.entries.length===0)return {cost:null,tokens:null,tokenBreakdown:null};let n=this.calculateTokenBreakdown(t.entries),o=n.input+n.output+n.cacheCreation+n.cacheRead;return {cost:t.totalCost,tokens:o,tokenBreakdown:n}}},B=class{sessionProvider=new H;async getUsageInfo(e){try{return l(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e)}}catch(t){return l(`Error getting usage info for session ${e}:`,t),{session:{cost:null,tokens:null,tokenBreakdown:null}}}}};var R=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}getContextLimit(e){return 2e5}async calculateContextTokens(e,t){try{l(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return l("Transcript file is empty"),null}catch{return l("Could not read transcript file"),null}let n=await D(e);if(n.length===0)return l("No entries in transcript"),null;let o=null;for(let i=n.length-1;i>=0;i--){let s=n[i];if(s&&s.message?.usage?.input_tokens&&s.isSidechain!==!0){o=s,l(`Context segment: Found most recent entry at ${s.timestamp.toISOString()}, stopping search`);break}}if(o?.message?.usage){let i=o.message.usage,s=(i.input_tokens||0)+(i.cache_read_input_tokens||0)+(i.cache_creation_input_tokens||0),c=t?this.getContextLimit(t):2e5;l(`Most recent main chain context: ${s} tokens (limit: ${c})`);let a=Math.min(100,Math.max(0,Math.round(s/c*100))),u=Math.round(c*.75),d=Math.min(100,Math.max(0,Math.round(s/u*100))),g=Math.max(0,100-d);return {inputTokens:s,percentage:a,usablePercentage:d,contextLeftPercentage:g,maxTokens:c,usableTokens:u}}return l("No main chain entries with usage data found"),null}catch(n){return l(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}};var U=class{async loadTranscriptEntries(e){try{let t=await A(e);if(!t)return l(`No transcript found for session: ${e}`),[];l(`Loading transcript from: ${t}`);let o=(await readFile(t,"utf-8")).trim().split(`
|
|
7
|
+
`).filter(s=>s.trim()),i=[];for(let s of o)try{let c=JSON.parse(s);if(c.isSidechain===!0)continue;i.push(c);}catch(c){l(`Failed to parse JSONL line: ${c}`);continue}return l(`Loaded ${i.length} transcript entries`),i}catch(t){return l(`Error loading transcript for ${e}:`,t),[]}}calculateResponseTimes(e){let t=[],n=[],o=-1,i=null,s=null,c=-1;for(let g=0;g<e.length;g++){let f=e[g];if(!(!f||!f.timestamp))try{let m=new Date(f.timestamp),p=f.type||f.message?.role||f.message?.type,y=f.type==="user"&&f.message?.content?.[0]?.type==="tool_result";p==="user"&&!y?(t.push(m),i=m,o=g,s=null,c=-1,l(`Found user message at index ${g}, timestamp ${m.toISOString()}`)):o>=0&&(p==="assistant"||y||p==="system"||f.message?.usage)&&(s=m,c=g,p==="assistant"||f.message?.usage?(n.push(m),l(`Found assistant message at index ${g}, timestamp ${m.toISOString()}`)):y?l(`Found tool result at index ${g}, timestamp ${m.toISOString()}`):l(`Found ${p} message at index ${g}, timestamp ${m.toISOString()}`));}catch{continue}}if(t.length===0||n.length===0)return {average:null,last:null};let a=[];for(let g of n){let f=t.filter(m=>m<g);if(f.length>0){let m=new Date(Math.max(...f.map(y=>y.getTime()))),p=(g.getTime()-m.getTime())/1e3;p>.1&&p<300?(a.push(p),l(`Valid response time: ${p.toFixed(1)}s`)):l(`Rejected response time: ${p.toFixed(1)}s (outside 0.1s-5m range)`);}}let u=null;if(i&&s&&c>o){let g=s.getTime()-i.getTime(),f=c-o;g===0&&f>0?(u=f*.1,l(`Estimated last response time from position difference: ${u.toFixed(2)}s (${f} messages)`)):g>0&&(u=g/1e3,l(`Last response time from timestamps: ${u.toFixed(2)}s`)),l(`Last user message at index ${o}, timestamp ${i.toISOString()}`),l(`Last response end at index ${c}, timestamp ${s.toISOString()}`);}if(a.length===0&&u===null)return {average:null,last:null};let d=a.length>0?a.reduce((g,f)=>g+f,0)/a.length:null;return l(`Calculated average response time: ${d?.toFixed(2)||"null"}s from ${a.length} measurements`),l(`Last response time: ${u?.toFixed(2)||"null"}s`),{average:d,last:u}}calculateSessionDuration(e){let t=[];for(let s of e)if(s.timestamp)try{t.push(new Date(s.timestamp));}catch{continue}if(t.length<2)return null;t.sort((s,c)=>s.getTime()-c.getTime());let n=t[t.length-1],o=t[0];if(!n||!o)return null;let i=(n.getTime()-o.getTime())/1e3;return i>0?i:null}calculateBurnRateDuration(e){if(e.length===0)return null;let t=new Date,n=e.map(s=>s.timestamp).filter(Boolean).map(s=>new Date(s)).filter(s=>t.getTime()-s.getTime()<7200*1e3).sort((s,c)=>s.getTime()-c.getTime());if(n.length===0)return null;let o=n[0];return o?Math.max((t.getTime()-o.getTime())/1e3,1800):null}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,o=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!o}).length}async calculateTotalCost(e){let t=0,n=new Set;for(let o of e){let i=`${o.timestamp}-${JSON.stringify(o.message?.usage||{})}`;if(n.has(i)){l(`Skipping duplicate entry at ${o.timestamp}`);continue}if(n.add(i),typeof o.costUSD=="number")t+=o.costUSD;else if(o.message?.usage){let s=await S.calculateCostForEntry(o);t+=s;}}return Math.round(t*1e4)/1e4}calculateTotalTokens(e){let t=new Set;return e.reduce((n,o)=>{let i=o.message?.usage;if(!i)return n;let s=`${o.timestamp}-${JSON.stringify(i)}`;return t.has(s)?(l(`Skipping duplicate token entry at ${o.timestamp}`),n):(t.add(s),n+(i.input_tokens||0)+(i.output_tokens||0)+(i.cache_creation_input_tokens||0)+(i.cache_read_input_tokens||0))},0)}async getMetricsInfo(e){try{l(`Starting metrics calculation for session: ${e}`);let t=await this.loadTranscriptEntries(e);if(t.length===0)return {responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,costBurnRate:null,tokenBurnRate:null};let n=this.calculateResponseTimes(t),o=this.calculateSessionDuration(t),i=this.calculateMessageCount(t),s=null,c=null,a=this.calculateBurnRateDuration(t);if(a&&a>60){let u=a/3600;if(u<=0)l(`Invalid hours elapsed: ${u}`);else {let d=await this.calculateTotalCost(t),g=this.calculateTotalTokens(t);d>0&&(s=Math.round(d/u*100)/100,l(`Cost burn rate: $${s}/h (total: $${d}, duration: ${u}h)`)),g>0&&(c=Math.round(g/u),l(`Token burn rate: ${c}/h (total: ${g}, duration: ${u}h)`));}}return l(`Metrics calculated: avgResponseTime=${n.average?.toFixed(2)||"null"}s, lastResponseTime=${n.last?.toFixed(2)||"null"}s, sessionDuration=${o?.toFixed(0)||"null"}s, messageCount=${i}`),{responseTime:n.average,lastResponseTime:n.last,sessionDuration:o,messageCount:i,costBurnRate:s,tokenBurnRate:c}}catch(t){return l(`Error calculating metrics for session ${e}:`,t),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,costBurnRate:null,tokenBurnRate:null}}}};var F=class{cachedVersion=null;cacheTimestamp=0;CACHE_TTL=3e4;getClaudeVersion(){let e=Date.now();if(this.cachedVersion!==null&&e-this.cacheTimestamp<this.CACHE_TTL)return this.cachedVersion;try{let t=execSync("claude --version",{encoding:"utf8",timeout:1e3}).trim(),n=t.match(/^([\d.]+)/);return n?(this.cachedVersion=`v${n[1]}`,this.cacheTimestamp=e,l(`Claude Code version: ${this.cachedVersion}`),this.cachedVersion):(l(`Could not parse version from: ${t}`),null)}catch(t){return l("Error getting Claude Code version:",t),null}}async getVersionInfo(){return {version:this.getClaudeVersion()}}};function _(r){return r===null?"$0.00":r<.01?"<$0.01":`$${r.toFixed(2)}`}function w(r){return r===null||r===0?"0 tokens":r>=1e6?`${(r/1e6).toFixed(1)}M tokens`:r>=1e3?`${(r/1e3).toFixed(1)}K tokens`:`${r} tokens`}function fe(r){if(!r)return "0 tokens";let e=[];if(r.input>0&&e.push(`${w(r.input).replace(" tokens","")}in`),r.output>0&&e.push(`${w(r.output).replace(" tokens","")}out`),r.cacheCreation>0||r.cacheRead>0){let t=r.cacheCreation+r.cacheRead;e.push(`${w(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function pe(r){return r<60?`${r}s`:r<3600?`${Math.floor(r/60)}m`:r<86400?`${Math.floor(r/3600)}h`:r<604800?`${Math.floor(r/86400)}d`:`${Math.floor(r/604800)}w`}function he(r){return r<60?`${r.toFixed(0)}s`:r<3600?`${(r/60).toFixed(0)}m`:r<86400?`${(r/3600).toFixed(1)}h`:`${(r/86400).toFixed(1)}d`}function Ne(r,e){return !e||e<=0||r<0?null:Math.min(100,r/e*100)}function ye(r,e,t=80){let n=Ne(r,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let o=`${n.toFixed(0)}%`,i=n>=t,s="";return i?s=` !${o}`:n>=50?s=` +${o}`:s=` ${o}`,{percentage:n,isWarning:i,displayText:s}}var M=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let o=e.workspace?.current_dir||e.cwd||"/",i=e.workspace?.project_dir;if(n?.showBasename)return {text:b.basename(o)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let s=process.env.HOME||process.env.USERPROFILE,c=o,a=i;return s&&(o.startsWith(s)&&(c=o.replace(s,"~")),i&&i.startsWith(s)&&(a=i.replace(s,"~"))),{text:this.getDisplayDirectoryName(c,a),bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let o=[];if(n?.showRepoName&&e.repoName&&(o.push(e.repoName),e.isWorktree&&o.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&o.push(`[${e.operation}]`),o.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&o.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&o.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?o.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?o.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&o.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let s=[];e.staged&&e.staged>0&&s.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&s.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&s.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&s.push(`!${e.conflicts}`),s.length>0&&o.push(`(${s.join(" ")})`);}if(n?.showUpstream&&e.upstream&&o.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&o.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let s=pe(e.timeSinceCommit);o.push(`${this.symbols.git_time} ${s}`);}let i=this.symbols.git_clean;return e.status==="conflicts"?i=this.symbols.git_conflicts:e.status==="dirty"&&(i=this.symbols.git_dirty),o.push(i),{text:o.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}renderModel(e,t){let n=e.model?.display_name||"Claude";return {text:`${this.symbols.model} ${n}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n="cost"){let o=this.config.budget?.session;return {text:`${this.symbols.session_cost} ${this.formatUsageWithBudget(e.session.cost,e.session.tokens,e.session.tokenBreakdown,n,o?.amount,o?.warningThreshold||80)}`,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){if(!e)return {text:`${this.symbols.context_time} 0 (100%)`,bgColor:t.contextBg,fgColor:t.contextFg};let n=e.inputTokens.toLocaleString(),o=`${e.contextLeftPercentage}%`;return {text:`${this.symbols.context_time} ${n} (${o})`,bgColor:t.contextBg,fgColor:t.contextFg}}renderMetrics(e,t,n,o){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let i=[];if(o?.showLastResponseTime){let s=e.lastResponseTime===null?"0.0s":e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;i.push(`${this.symbols.metrics_last_response} ${s}`);}if(o?.showResponseTime!==false&&e.responseTime!==null){let s=e.responseTime<60?`${e.responseTime.toFixed(1)}s`:`${(e.responseTime/60).toFixed(1)}m`;i.push(`${this.symbols.metrics_response} ${s}`);}if(o?.showDuration!==false&&e.sessionDuration!==null){let s=he(e.sessionDuration);i.push(`${this.symbols.metrics_duration} ${s}`);}return o?.showMessageCount!==false&&e.messageCount!==null&&i.push(`${this.symbols.metrics_messages} ${e.messageCount}`),i.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:i.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,n){let o;if(e.cost===null&&e.tokens===null)o="No active block";else {let i=n?.type||"cost",s=n?.burnType,c=e.timeRemaining!==null?(()=>{let d=Math.floor(e.timeRemaining/60),g=e.timeRemaining%60;return d>0?`${d}h ${g}m`:`${g}m`})():null,a;switch(i){case "cost":a=_(e.cost);break;case "tokens":a=w(e.tokens);break;case "both":a=`${_(e.cost)} / ${w(e.tokens)}`;break;case "time":a=c||"N/A";break;default:a=_(e.cost);}let u="";if(s&&s!=="none")switch(s){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?`${w(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let f=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",m=e.tokenBurnRate!==null?`${w(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${f} / ${m}`;break}i==="time"?o=a:o=c?`${a}${u} (${c} left)`:`${a}${u}`;}return {text:`${this.symbols.block_cost} ${o}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let o=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,o?.amount,o?.warningThreshold)}`,bgColor:t.todayBg,fgColor:t.todayFg}}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||b.basename(t)||"project":b.basename(e)||"root":b.basename(e)||"root"}formatUsageDisplay(e,t,n,o){switch(o){case "cost":return _(e);case "tokens":return w(t);case "both":return `${_(e)} (${w(t)})`;case "breakdown":return fe(n);default:return _(e)}}formatUsageWithBudget(e,t,n,o,i,s=80){let c=this.formatUsageDisplay(e,t,n,o);if(i&&i>0&&e!==null){let a=ye(e,i,s);return c+a.displayText}return c}renderVersion(e,t,n){return !e||!e.version?null:{text:`${this.symbols.version} ${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}}};function He(r){return {timestamp:r.timestamp,usage:{inputTokens:r.message?.usage?.input_tokens||0,outputTokens:r.message?.usage?.output_tokens||0,cacheCreationInputTokens:r.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:r.message?.usage?.cache_read_input_tokens||0},costUSD:r.costUSD||0,model:r.message?.model||"unknown"}}var V=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],o=[...e].sort((c,a)=>c.timestamp.getTime()-a.timestamp.getTime()),i=null,s=[];for(let c of o){let a=c.timestamp;if(i==null)i=this.floorToHour(a),s=[c];else {let u=a.getTime()-i.getTime(),d=s[s.length-1];if(d==null)continue;let g=d.timestamp,f=a.getTime()-g.getTime();u>t||f>t?(n.push(s),i=this.floorToHour(a),s=[c]):s.push(c);}}return i!=null&&s.length>0&&n.push(s),n}createBlockInfo(e,t){let n=new Date,o=this.sessionDurationHours*60*60*1e3,i=new Date(e.getTime()+o),s=t[t.length-1],c=s!=null?s.timestamp:e,a=n.getTime()-c.getTime()<o&&n<i;return {block:t,isActive:a}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let o=n[0];if(!o)continue;let i=this.floorToHour(o.timestamp),s=this.createBlockInfo(i,n);if(s.isActive)return s.block}return null}async loadUsageEntries(){l("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await N(void 0,(c,a)=>a>=e,true),o=[];for(let c of n)if(c.message?.usage){let a=He(c);!a.costUSD&&c.raw&&(a.costUSD=await S.calculateCostForEntry(c.raw)),o.push(a);}let i=this.identifySessionBlocks(o);l(`Block segment: Found ${i.length} session blocks`);let s=this.findActiveBlock(i);if(s&&s.length>0){l(`Block segment: Found active block with ${s.length} entries`);let c=s[0],a=s[s.length-1];return c&&a&&l(`Block segment: Active block from ${c.timestamp.toISOString()} to ${a.timestamp.toISOString()}`),s}else return l("Block segment: No active block found"),[]}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return l("Block segment: No entries in current block"),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((a,u)=>a+u.costUSD,0),n=e.reduce((a,u)=>a+u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,0),o=new Date,i=null;if(e.length>0){let a=e[0];if(a){let u=this.sessionDurationHours*60*60*1e3,d=this.floorToHour(a.timestamp),g=new Date(d.getTime()+u);i=Math.max(0,Math.round((g.getTime()-o.getTime())/(1e3*60)));}}let s=null,c=null;if(e.length>=1&&(t>0||n>0)){let a=e.map(g=>g.timestamp).sort((g,f)=>g.getTime()-f.getTime()),u=a[0],d=a[a.length-1];if(u&&d){let g=(d.getTime()-u.getTime())/6e4;g>0&&(t>0&&(s=t/g*60),n>0&&(c=n/g*60));}}return l(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${i}m remaining, burn rate: ${s?"$"+s.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,timeRemaining:i,burnRate:s,tokenBurnRate:c}}catch(e){return l("Error getting active block info:",e),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function I(r){let e=r.getFullYear(),t=String(r.getMonth()+1).padStart(2,"0"),n=String(r.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function Ge(r){return r.inputTokens+r.outputTokens+r.cacheCreationInputTokens+r.cacheReadInputTokens}function Ve(r){return {timestamp:r.timestamp,usage:{inputTokens:r.message?.usage?.input_tokens||0,outputTokens:r.message?.usage?.output_tokens||0,cacheCreationInputTokens:r.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:r.message?.usage?.cache_read_input_tokens||0},costUSD:r.costUSD||0,model:r.message?.model||"unknown"}}var W=class{cache=new Map;CACHE_TTL=3e5;async loadTodayEntries(){let t=I(new Date);l(`Today segment: Loading entries for date ${t}`);let n=new Date;n.setDate(n.getDate()-7);let i=await N(void 0,(a,u)=>u>=n,true),s=[],c=0;for(let a of i)if(I(a.timestamp)===t&&a.message?.usage){let d=Ve(a);!d.costUSD&&a.raw&&(d.costUSD=await S.calculateCostForEntry(a.raw)),s.push(d),c++;}return l(`Today segment: Found ${c} entries for today (${t})`),s}async getTodayEntries(){let e="today",t=this.cache.get(e),n=Date.now();if(t&&n-t.timestamp<this.CACHE_TTL)return t.data;this.cache.clear();try{let o=await this.loadTodayEntries();return this.cache.set(e,{data:o,timestamp:n}),o}catch(o){return l("Error loading today's entries:",o),[]}}async getTodayInfo(){try{let e=await this.getTodayEntries();if(e.length===0)return {cost:null,tokens:null,tokenBreakdown:null,date:I(new Date)};let t=e.reduce((i,s)=>i+s.costUSD,0),n=e.reduce((i,s)=>i+Ge(s.usage),0),o=e.reduce((i,s)=>({input:i.input+s.usage.inputTokens,output:i.output+s.usage.outputTokens,cacheCreation:i.cacheCreation+s.usage.cacheCreationInputTokens,cacheRead:i.cacheRead+s.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return l(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:o,date:I(new Date)}}catch(e){return l("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:I(new Date)}}}};var J=class{constructor(e){this.config=e;this.symbols=this.initializeSymbols(),this.usageProvider=new B,this.blockProvider=new V,this.todayProvider=new W,this.contextProvider=new R,this.gitService=new P,this.tmuxService=new E,this.metricsProvider=new U,this.versionProvider=new F,this.segmentRenderer=new M(e,this.symbols);}symbols;usageProvider;blockProvider;todayProvider;contextProvider;gitService;tmuxService;metricsProvider;versionProvider;segmentRenderer;needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,o=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,i=this.needsSegmentInfo("context")?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,s=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id):null,c=this.needsSegmentInfo("version")?await this.versionProvider.getVersionInfo():null;return this.config.display.lines.map(u=>this.renderLine(u,e,t,n,o,i,s,c)).filter(u=>u.length>0).join(`
|
|
8
|
+
`)}renderLine(e,t,n,o,i,s,c,a){let u=this.getThemeColors(),d=t.workspace?.current_dir||t.cwd||"/",g=Object.entries(e.segments).filter(([m,p])=>p?.enabled).map(([m,p])=>({type:m,config:p})),f=u.reset;for(let m=0;m<g.length;m++){let p=g[m];if(!p)continue;let y=m===g.length-1,x=y?null:g[m+1],ne=x?this.getSegmentBgColor(x.type,u):"",j=this.renderSegment(p,t,n,o,i,s,c,a,u,d);j&&(f+=this.formatSegment(j.bgColor,j.fgColor,j.text,y?void 0:ne));}return f}renderSegment(e,t,n,o,i,s,c,a,u,d){return e.type==="directory"?this.segmentRenderer.renderDirectory(t,u,e.config):e.type==="model"?this.segmentRenderer.renderModel(t,u):e.type==="git"?this.renderGitSegment(e.config,t,u,d):e.type==="session"?this.renderSessionSegment(e.config,n,u):e.type==="tmux"?this.renderTmuxSegment(u):e.type==="context"?this.renderContextSegment(s,u):e.type==="metrics"?this.renderMetricsSegment(e.config,c,o,u):e.type==="block"?this.renderBlockSegment(e.config,o,u):e.type==="today"?this.renderTodaySegment(e.config,i,u):e.type==="version"?this.renderVersionSegment(e.config,a,u):null}renderGitSegment(e,t,n,o){if(!this.needsSegmentInfo("git"))return null;let i=this.gitService.getGitInfo(o,{showSha:e?.showSha,showWorkingTree:e?.showWorkingTree,showOperation:e?.showOperation,showTag:e?.showTag,showTimeSinceCommit:e?.showTimeSinceCommit,showStashCount:e?.showStashCount,showUpstream:e?.showUpstream,showRepoName:e?.showRepoName},t.workspace?.project_dir);return i?this.segmentRenderer.renderGit(i,n,e):null}renderSessionSegment(e,t,n){if(!t)return null;let o=e?.type||"cost";return this.segmentRenderer.renderSession(t,n,o)}renderTmuxSegment(e){if(!this.needsSegmentInfo("tmux"))return null;let t=this.tmuxService.getSessionId();return this.segmentRenderer.renderTmux(t,e)}renderContextSegment(e,t){return this.needsSegmentInfo("context")?this.segmentRenderer.renderContext(e,t):null}renderMetricsSegment(e,t,n,o){return this.segmentRenderer.renderMetrics(t,o,n,e)}renderBlockSegment(e,t,n){return t?this.segmentRenderer.renderBlock(t,n,e):null}renderTodaySegment(e,t,n){if(!t)return null;let o=e?.type||"cost";return this.segmentRenderer.renderToday(t,n,o)}renderVersionSegment(e,t,n){return t?this.segmentRenderer.renderVersion(t,n,e):null}initializeSymbols(){return {right:this.config.display.style==="minimal"?"":"\uE0B0",branch:"\u2387",model:"\u26A1",git_clean:"\u2713",git_dirty:"\u25CF",git_conflicts:"\u26A0",git_ahead:"\u2191",git_behind:"\u2193",git_worktree:"\u29C9",git_tag:"\u2302",git_sha:"\u266F",git_upstream:"\u2192",git_stash:"\u29C7",git_time:"\u25F7",session_cost:"\xA7",block_cost:"\u25F1",today_cost:"\u2609",context_time:"\u25D4",metrics_response:"\u29D6",metrics_last_response:"\u0394",metrics_duration:"\u29D7",metrics_messages:"\u27D0",metrics_burn:"\u27E2",version:"\u25C8"}}getThemeColors(){let e=this.config.theme,t;if(e==="custom"){if(t=this.config.colors?.custom,!t)throw new Error("Custom theme selected but no colors provided in configuration")}else t=O(e),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=O("dark"));let n=O("dark"),o=y=>{let x=t[y]||n[y];return {bg:z(x.bg,true),fg:z(x.fg,false)}},i=o("directory"),s=o("git"),c=o("model"),a=o("session"),u=o("block"),d=o("today"),g=o("tmux"),f=o("context"),m=o("metrics"),p=o("version");return {reset:"\x1B[0m",modeBg:i.bg,modeFg:i.fg,gitBg:s.bg,gitFg:s.fg,modelBg:c.bg,modelFg:c.fg,sessionBg:a.bg,sessionFg:a.fg,blockBg:u.bg,blockFg:u.fg,todayBg:d.bg,todayFg:d.fg,tmuxBg:g.bg,tmuxFg:g.fg,contextBg:f.bg,contextFg:f.fg,metricsBg:m.bg,metricsFg:m.fg,versionBg:p.bg,versionFg:p.fg}}getSegmentBgColor(e,t){switch(e){case "directory":return t.modeBg;case "git":return t.gitBg;case "model":return t.modelBg;case "session":return t.sessionBg;case "block":return t.blockBg;case "today":return t.todayBg;case "tmux":return t.tmuxBg;case "context":return t.contextBg;case "metrics":return t.metricsBg;case "version":return t.versionBg;default:return t.modeBg}}formatSegment(e,t,n,o){let i=`${e}${t} ${n} `,s="\x1B[0m";if(o){let c=Y(e);i+=`${s}${o}${c}${this.symbols.right}`;}else i+=`${s}${Y(e)}${this.symbols.right}${s}`;return i}};var be={theme:"dark",display:{style:"minimal",lines:[{segments:{directory:{enabled:true,showBasename:true},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"},today:{enabled:false,type:"cost"},block:{enabled:true,type:"cost",burnType:"cost"},version:{enabled:false},tmux:{enabled:false},context:{enabled:true},metrics:{enabled:false,showResponseTime:true,showLastResponseTime:false,showDuration:true,showMessageCount:true}}}]},budget:{session:{warningThreshold:80},today:{warningThreshold:80,amount:50}}};function ee(r){return ["light","dark","nord","tokyo-night","rose-pine","custom"].includes(r)}function te(r){return r==="minimal"||r==="powerline"}function K(r,e){let t={...r};for(let n in e){let o=e[n];if(o!==void 0)if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=t[n]||{};t[n]=K(i,o);}else t[n]=o;}return t}function We(r,e){return r?T.existsSync(r)?r:null:[...e?[b.join(e,".claude-powerline.json")]:[],b.join(process.cwd(),".claude-powerline.json"),b.join(v.homedir(),".claude","claude-powerline.json"),b.join(v.homedir(),".config","claude-powerline","config.json")].find(T.existsSync)||null}function Je(r){try{let e=T.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${r}: ${e instanceof Error?e.message:String(e)}`)}}function qe(){let r={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&ee(t)&&(r.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(te(n)?e.style=n:(console.warn(`Invalid display style '${n}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(r.display=e),r}function Ke(){return process.env.CLAUDE_POWERLINE_CONFIG}function ze(r){let e={},t={},n=r.find(i=>i.startsWith("--theme="))?.split("=")[1];n&&ee(n)&&(e.theme=n);let o=r.find(i=>i.startsWith("--style="))?.split("=")[1];return o&&(te(o)?t.style=o:(console.warn(`Invalid display style '${o}' from CLI argument, falling back to 'minimal'`),t.style="minimal")),Object.keys(t).length>0&&(e.display=t),e}function Ye(r=process.argv,e){let t=JSON.parse(JSON.stringify(be)),n=r.find(c=>c.startsWith("--config="))?.split("=")[1]||Ke(),o=We(n,e);if(o)try{let c=Je(o);t=K(t,c);}catch(c){console.warn(`Warning: ${c instanceof Error?c.message:String(c)}`);}t.display?.style&&!te(t.display.style)&&(console.warn(`Invalid display style '${t.display.style}' in config file, falling back to 'minimal'`),t.display.style="minimal"),t.theme&&!ee(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let i=qe();t=K(t,i);let s=ze(r);return t=K(t,s),t}var Se=Ye;async function Ze(){try{let r=v.platform(),e;if(r==="darwin")e=b.join(v.homedir(),"Library","Fonts");else if(r==="linux")e=b.join(v.homedir(),".local","share","fonts");else if(r==="win32")e=b.join(v.homedir(),"AppData","Local","Microsoft","Windows","Fonts");else {console.log("Unsupported platform for font installation");return}T.existsSync(e)||T.mkdirSync(e,{recursive:!0}),console.log("Installing Powerline Fonts..."),console.log("Downloading from https://github.com/powerline/fonts");let t=b.join(v.tmpdir(),"powerline-fonts"),n=()=>{T.existsSync(t)&&T.rmSync(t,{recursive:!0,force:!0});};h.on("SIGINT",n),h.on("SIGTERM",n);try{T.existsSync(t)&&T.rmSync(t,{recursive:!0,force:!0}),console.log("Cloning powerline fonts repository..."),execSync("git clone --depth=1 https://github.com/powerline/fonts.git powerline-fonts",{stdio:"inherit",cwd:v.tmpdir()}),console.log("Installing fonts...");let o=b.join(t,"install.sh");if(T.existsSync(o))T.chmodSync(o,493),execSync("./install.sh",{stdio:"inherit",cwd:t});else throw new Error("Install script not found in powerline fonts repository");console.log("Powerline fonts installation complete!"),console.log("Please restart your terminal and set your terminal font to a powerline font."),console.log("Popular choices: Source Code Pro Powerline, DejaVu Sans Mono Powerline, Ubuntu Mono Powerline");}finally{n(),h.removeListener("SIGINT",n),h.removeListener("SIGTERM",n);}}catch(r){console.error("Error installing fonts:",r instanceof Error?r.message:String(r)),console.log("You can manually install fonts from: https://github.com/powerline/fonts");}}function Te(){console.log(`
|
|
9
9
|
claude-powerline - Beautiful powerline statusline for Claude Code
|
|
10
10
|
|
|
11
11
|
Usage: claude-powerline [options]
|
|
@@ -24,7 +24,7 @@ Claude Code Options (for settings.json):
|
|
|
24
24
|
|
|
25
25
|
See example config at: https://github.com/Owloops/claude-powerline/blob/main/.claude-powerline.json
|
|
26
26
|
|
|
27
|
-
`);}async function
|
|
27
|
+
`);}async function Qe(){try{let r=h.argv.includes("--help")||h.argv.includes("-h");h.argv.includes("--install-fonts")&&(await Ze(),h.exit(0)),r&&(Te(),h.exit(0)),h.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
28
28
|
|
|
29
29
|
claude-powerline is designed to be used as a Claude Code statusLine command.
|
|
30
30
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -40,4 +40,4 @@ Add to ~/.claude/settings.json:
|
|
|
40
40
|
Run with --help for more options.
|
|
41
41
|
|
|
42
42
|
To test output manually:
|
|
43
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-3-5-sonnet","display_name":"Claude"}}' | claude-powerline --style=powerline`),
|
|
43
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-3-5-sonnet","display_name":"Claude"}}' | claude-powerline --style=powerline`),h.exit(1)),l(`Working directory: ${h.cwd()}`),l("Process args:",h.argv);let t=await json(h.stdin);l("Received hook data:",JSON.stringify(t,null,2)),t||(console.error("Error: No input data received from stdin"),Te(),h.exit(1));let n=t.workspace?.project_dir,o=Se(h.argv,n),s=await new J(o).generateStatusline(t);console.log(s);}catch(r){let e=r instanceof Error?r.message:String(r);console.error("Error generating statusline:",e),h.exit(1);}}Qe();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owloops/claude-powerline",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.6",
|
|
4
4
|
"description": "Beautiful vim-style powerline statusline for Claude Code with real-time cost tracking, git integration, and custom themes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|