@owloops/claude-powerline 1.7.7 → 1.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +4 -4
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import b from'process';import C,{join,posix}from'path';import y,{existsSync,readFileSync,createReadStream}from'fs';import {exec,execSync}from'child_process';import D,{homedir}from'os';import {json}from'stream/consumers';import {promisify}from'util';import {createHash}from'crypto';import {setTimeout}from'timers/promises';import {readdir,stat,readFile}from'fs/promises';import {createInterface}from'readline';import {get}from'https';import {URL}from'url';function se(o,e){if(e&&(o.toLowerCase()==="transparent"||o.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(o.slice(1,3),16),n=parseInt(o.slice(3,5),16),r=parseInt(o.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${n};${r}m`}function oe(o){let e=o.match(/48;2;(\d+);(\d+);(\d+)/);return e?`\x1B[38;2;${e[1]};${e[2]};${e[3]}m`:o.replace("48","38")}var ge={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 de={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 fe={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 he={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 pe={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 Re={dark:ge,light:de,nord:fe,"tokyo-night":he,"rose-pine":pe};function W(o){return Re[o]||null}var c=(o,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${o}`,...e);};function Y(){let o=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let n=t.trim();existsSync(n)&&o.push(n);}),o.length===0){let t=homedir(),n=join(t,".config","claude"),r=join(t,".claude");existsSync(n)?o.push(n):existsSync(r)&&o.push(r);}return o}async function J(o){let e=[];for(let t of o){let n=join(t,"projects");if(existsSync(n))try{let r=await readdir(n,{withFileTypes:!0});for(let s of r)if(s.isDirectory()){let i=posix.join(n,s.name);e.push(i);}}catch(r){c(`Failed to read projects directory ${n}:`,r);}}return e}async function V(o){let e=Y(),t=await J(e);for(let n of t){let r=posix.join(n,`${o}.jsonl`);if(existsSync(r))return r}return null}async function Ue(o){try{let t=(await readFile(o,"utf-8")).trim().split(`
3
- `),n=null;for(let r of t)if(r.trim())try{let s=JSON.parse(r);if(s.timestamp&&typeof s.timestamp=="string"){let i=new Date(s.timestamp);isNaN(i.getTime())||(n===null||i<n)&&(n=i);}}catch{continue}return n}catch(e){return c(`Failed to get earliest timestamp for ${o}:`,e),null}}async function Ae(o,e=true){return (await Promise.all(o.map(async n=>({file:n,timestamp:await Ue(n)})))).sort((n,r)=>n.timestamp===null&&r.timestamp===null?0:n.timestamp===null?1:r.timestamp===null?-1:(e?1:-1)*(n.timestamp.getTime()-r.timestamp.getTime())).map(n=>n.file)}async function ce(o){try{return (await stat(o)).mtime}catch{return null}}function Me(o){let e=o.message?.id||(typeof o.raw.message=="object"&&o.raw.message!==null&&"id"in o.raw.message?o.raw.message.id:void 0),t="requestId"in o.raw?o.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var Ie=1024*1024;async function F(o){try{let t=(await stat(o)).size,n;return t>Ie?(c(`Using streaming parser for large file ${o} (${Math.round(t/1024)}KB)`),n=await je(o)):n=await Le(o),c(`Parsed ${n.length} entries from ${o}`),n}catch(e){return c(`Failed to read file ${o}:`,e),[]}}async function Le(o){let t=(await readFile(o,"utf-8")).trim().split(`
4
- `).filter(r=>r.trim()),n=[];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};n.push(i);}catch(s){c(`Failed to parse JSONL line: ${s}`);continue}return n}async function je(o){return new Promise((e,t)=>{let n=[],r=createReadStream(o,{encoding:"utf8"}),s=createInterface({input:r,crlfDelay:1/0});s.on("line",i=>{let l=i.trim();if(l)try{let a=JSON.parse(l);if(!a.timestamp)return;let u={timestamp:new Date(a.timestamp),message:a.message,costUSD:typeof a.costUSD=="number"?a.costUSD:void 0,isSidechain:a.isSidechain===!0,raw:a};n.push(u);}catch(a){c(`Failed to parse JSONL line: ${a}`);}}),s.on("close",()=>{e(n);}),s.on("error",i=>{c(`Streaming parser error for ${o}:`,i),t(i);}),r.on("error",i=>{c(`File stream error for ${o}:`,i),t(i);});})}async function q(o,e,t=false){let n=Y(),r=await J(n),s=new Set,i=r.map(async g=>{try{let w=(await readdir(g)).filter(S=>S.endsWith(".jsonl")).map(async S=>{let re=posix.join(g,S);if(existsSync(re)){let $e=await ce(re);return {filePath:re,mtime:$e}}return null});return (await Promise.all(w)).filter(S=>S?.mtime&&(!e||e(S.filePath,S.mtime)))}catch(f){return c(`Failed to read project directory ${g}:`,f),[]}}),a=(await Promise.all(i)).flat().filter(g=>g!==null).map(g=>g.filePath);if(t){let g=await Ae(a,false);a.length=0,a.push(...g);}let u=[],d=a.map(async g=>(await F(g)).filter(p=>{let w=Me(p);return w&&s.has(w)?false:(w&&s.add(w),!o||o(p))})),m=await Promise.all(d);for(let g of m)u.push(...g);return u}var _=class{static CACHE_DIR=C.join(homedir(),".claude","powerline");static GIT_CACHE_DIR=C.join(this.CACHE_DIR,"git");static USAGE_CACHE_DIR=C.join(this.CACHE_DIR,"usage");static LOCKS_DIR=C.join(this.CACHE_DIR,"locks");static isLocked(e){let t=C.join(this.LOCKS_DIR,e);return y.existsSync(t)}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let s=C.join(this.LOCKS_DIR,e),i=Date.now(),l=String(process.pid);for(;Date.now()-i<t;)try{return await y.promises.writeFile(s,l,{flag:"wx"}),c(`Lock acquired for ${e}`),!0}catch(a){if(a.code==="EEXIST")await setTimeout(50);else throw a}return c(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=C.join(this.LOCKS_DIR,e);try{await y.promises.unlink(t),c(`Lock released for ${e}`);}catch(n){n.code!=="ENOENT"&&c(`Error releasing lock for ${e}:`,n);}}static async ensureCacheDirectories(){try{await Promise.all([y.promises.mkdir(this.CACHE_DIR,{recursive:!0}),y.promises.mkdir(this.GIT_CACHE_DIR,{recursive:!0}),y.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),y.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){c("Failed to create cache directories:",e);}}static createProjectHash(e){return createHash("md5").update(e).digest("hex").substring(0,8)}static async getGitRepoModTime(e){try{let t=C.join(e,".git"),n=C.join(t,"index"),r=C.join(t,"HEAD"),s=0;try{let i=await y.promises.stat(n);s=Math.max(s,i.mtime.getTime());}catch{}try{let i=await y.promises.stat(r);s=Math.max(s,i.mtime.getTime());}catch{}try{let i=await y.promises.stat(e);s=Math.max(s,i.mtime.getTime());}catch{}return s}catch(t){return c(`Failed to get git repo mod time for ${e}:`,t),Date.now()}}static async getGitCache(e){let r="utf-8";await this.ensureCacheDirectories();let s=this.createProjectHash(e),i=C.join(this.GIT_CACHE_DIR,`${s}.json`),l=`${s}.git.lock`;for(let a=0;a<3;a++){if(this.isLocked(l)){c(`Cache for git project ${s} is locked, waiting...`),await setTimeout(75);continue}try{let d=await y.promises.readFile(i,r),m=JSON.parse(d),g=await this.getGitRepoModTime(e),f=m.gitModTime||0;return g<=f?(c(`[CACHE-HIT] Git disk cache: ${e}`),m.data):(c(`[CACHE-MISS] Git repo changed: ${e}`),null)}catch(d){if(d.code==="ENOENT")return c(`No shared git cache found for ${e}`),null;let m=a+1;c(`Attempt ${m} failed to read git cache for ${e}: ${d.message}. Retrying...`),await setTimeout(75);}}return c(`Failed to read git cache for ${e} after 3 attempts.`),null}static async setGitCache(e,t){let n=this.createProjectHash(e),r=`${n}.git.lock`;if(!await this.acquireLock(r)){c(`Could not acquire lock to set git cache for ${e}`);return}try{await this.ensureCacheDirectories();let s=C.join(this.GIT_CACHE_DIR,`${n}.json`),i=await this.getGitRepoModTime(e),l={data:t,timestamp:Date.now(),gitModTime:i};await y.promises.writeFile(s,JSON.stringify(l),"utf-8"),c(`[CACHE-SET] Git disk cache stored: ${e}`);}catch(s){c(`Failed to save git cache for ${e}:`,s);}finally{await this.releaseLock(r);}}static async getUsageCache(e,t){let s="utf-8";await this.ensureCacheDirectories();let i=C.join(this.USAGE_CACHE_DIR,`${e}.json`),l=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(l)){c(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let d=await y.promises.readFile(i,s),m=JSON.parse(d);return !t||m.timestamp>=t?(c(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(m.data)):(c(`${e} cache outdated: cache=${m.timestamp}, latest=${t}`),null)}catch(d){if(d.code==="ENOENT")return c(`No shared ${e} usage cache found`),null;let m=a+1;c(`Attempt ${m} failed to read ${e} cache: ${d.message}. Retrying...`),await setTimeout(75);}}return c(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(t=>({...t,timestamp:new Date(t.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){c(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=C.join(this.USAGE_CACHE_DIR,`${e}.json`),l=n||Date.now(),u=JSON.stringify({data:t,timestamp:l});await y.promises.writeFile(i,u,"utf-8"),c(`[CACHE-SET] ${e} disk cache stored`);}catch(i){c(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(r);}}static async getLatestTranscriptMtime(){try{let e=Y(),t=await J(e),n=0;for(let r of t)try{let i=(await y.promises.readdir(r)).filter(l=>l.endsWith(".jsonl"));for(let l of i){let a=C.join(r,l),u=await ce(a);u&&u.getTime()>n&&(n=u.getTime());}}catch(s){c(`Failed to read project directory ${r}:`,s);continue}return n}catch(e){return c("Failed to get latest transcript mtime:",e),Date.now()}}static async cleanupOldCache(e=1440*60*1e3){await this.ensureCacheDirectories();let t=Date.now(),n=C.join(this.CACHE_DIR,".cleanup");try{let r=await y.promises.readFile(n,"utf-8");if(t-parseInt(r)<3600*1e3)return}catch{}try{let r=[this.GIT_CACHE_DIR,this.USAGE_CACHE_DIR];for(let s of r)try{let i=await y.promises.readdir(s);for(let l of i){let a=C.join(s,l),u=await y.promises.stat(a);t-u.mtime.getTime()>e&&(await y.promises.unlink(a),c(`Cleaned up old cache file: ${l}`));}}catch(i){c(`Error cleaning directory ${s}:`,i);}await y.promises.writeFile(n,t.toString()),c("Cache cleanup completed");}catch(r){c("Error during cache cleanup:",r);}}};var T=promisify(exec),A=class{isGitRepo(e){try{return y.existsSync(C.join(e,".git"))}catch{return false}}async getGitInfo(e,t={},n){let r=n&&this.isGitRepo(n)?n:e;if(!this.isGitRepo(r))return null;let s=await _.getGitCache(r);if(s)return c(`[CACHE-HIT] Git disk cache: ${r}`),s;try{let i=await this.getStatusWithBranchAsync(r),l=await this.getAheadBehindAsync(r),a={branch:i.branch||"detached",status:i.status,ahead:l.ahead,behind:l.behind};t.showWorkingTree&&i.workingTree&&(a.staged=i.workingTree.staged,a.unstaged=i.workingTree.unstaged,a.untracked=i.workingTree.untracked,a.conflicts=i.workingTree.conflicts);let u={},d={};t.showSha&&(u.sha=this.getShaAsync(r)),t.showTag&&(u.tag=this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(u.timeSinceCommit=this.getTimeSinceLastCommitAsync(r)),t.showStashCount&&(d.stashCount=this.getStashCountAsync(r)),t.showUpstream&&(d.upstream=this.getUpstreamAsync(r)),t.showRepoName&&(d.repoName=this.getRepoNameAsync(r));let m=new Map;for(let[g,f]of Object.entries(u))try{let p=await f;m.set(g,p);}catch{}return Object.keys(d).length>0&&(await Promise.allSettled(Object.entries(d).map(async([f,p])=>({key:f,value:await p})))).forEach(f=>{f.status==="fulfilled"&&m.set(f.value.key,f.value.value);}),t.showSha&&(a.sha=m.get("sha")||void 0),t.showOperation&&(a.operation=this.getOngoingOperation(r)||void 0),t.showTag&&(a.tag=m.get("tag")||void 0),t.showTimeSinceCommit&&(a.timeSinceCommit=m.get("timeSinceCommit")||void 0),t.showStashCount&&(a.stashCount=m.get("stashCount")||0),t.showUpstream&&(a.upstream=m.get("upstream")||void 0),t.showRepoName&&(a.repoName=m.get("repoName")||void 0,a.isWorktree=this.isWorktree(r)),await _.setGitCache(r,a),c(`[CACHE-SET] Git disk cache stored: ${r}`),_.cleanupOldCache().catch(()=>{}),a}catch{return null}}async getShaAsync(e){try{return (await T("git rev-parse --short=7 HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}getOngoingOperation(e){try{let t=C.join(e,".git");return y.existsSync(C.join(t,"MERGE_HEAD"))?"MERGE":y.existsSync(C.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":y.existsSync(C.join(t,"REVERT_HEAD"))?"REVERT":y.existsSync(C.join(t,"BISECT_LOG"))?"BISECT":y.existsSync(C.join(t,"rebase-merge"))||y.existsSync(C.join(t,"rebase-apply"))?"REBASE":null}catch{return null}}async getNearestTagAsync(e){try{return (await T("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getTimeSinceLastCommitAsync(e){try{let n=(await T("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!n)return null;let r=parseInt(n)*1e3,s=Date.now();return Math.floor((s-r)/1e3)}catch{return null}}async getStashCountAsync(e){try{let n=(await T("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.split(`
3
+ `),n=null;for(let r of t)if(r.trim())try{let s=JSON.parse(r);if(s.timestamp&&typeof s.timestamp=="string"){let i=new Date(s.timestamp);isNaN(i.getTime())||(n===null||i<n)&&(n=i);}}catch{continue}return n}catch(e){return c(`Failed to get earliest timestamp for ${o}:`,e),null}}async function Ae(o,e=true){return (await Promise.all(o.map(async n=>({file:n,timestamp:await Ue(n)})))).sort((n,r)=>n.timestamp===null&&r.timestamp===null?0:n.timestamp===null?1:r.timestamp===null?-1:(e?1:-1)*(n.timestamp.getTime()-r.timestamp.getTime())).map(n=>n.file)}async function ce(o){try{return (await stat(o)).mtime}catch{return null}}function Me(o){let e=o.message?.id||(typeof o.raw.message=="object"&&o.raw.message!==null&&"id"in o.raw.message?o.raw.message.id:void 0),t="requestId"in o.raw?o.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var Ie=1024*1024;async function F(o){try{let t=(await stat(o)).size,n;return t>Ie?(c(`Using streaming parser for large file ${o} (${Math.round(t/1024)}KB)`),n=await He(o)):n=await Le(o),c(`Parsed ${n.length} entries from ${o}`),n}catch(e){return c(`Failed to read file ${o}:`,e),[]}}async function Le(o){let t=(await readFile(o,"utf-8")).trim().split(`
4
+ `).filter(r=>r.trim()),n=[];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};n.push(i);}catch(s){c(`Failed to parse JSONL line: ${s}`);continue}return n}async function He(o){return new Promise((e,t)=>{let n=[],r=createReadStream(o,{encoding:"utf8"}),s=createInterface({input:r,crlfDelay:1/0});s.on("line",i=>{let l=i.trim();if(l)try{let a=JSON.parse(l);if(!a.timestamp)return;let u={timestamp:new Date(a.timestamp),message:a.message,costUSD:typeof a.costUSD=="number"?a.costUSD:void 0,isSidechain:a.isSidechain===!0,raw:a};n.push(u);}catch(a){c(`Failed to parse JSONL line: ${a}`);}}),s.on("close",()=>{e(n);}),s.on("error",i=>{c(`Streaming parser error for ${o}:`,i),t(i);}),r.on("error",i=>{c(`File stream error for ${o}:`,i),t(i);});})}async function q(o,e,t=false){let n=Y(),r=await J(n),s=new Set,i=r.map(async g=>{try{let w=(await readdir(g)).filter(S=>S.endsWith(".jsonl")).map(async S=>{let re=posix.join(g,S);if(existsSync(re)){let $e=await ce(re);return {filePath:re,mtime:$e}}return null});return (await Promise.all(w)).filter(S=>S?.mtime&&(!e||e(S.filePath,S.mtime)))}catch(f){return c(`Failed to read project directory ${g}:`,f),[]}}),a=(await Promise.all(i)).flat().filter(g=>g!==null).map(g=>g.filePath);if(t){let g=await Ae(a,false);a.length=0,a.push(...g);}let u=[],d=a.map(async g=>(await F(g)).filter(p=>{let w=Me(p);return w&&s.has(w)?false:(w&&s.add(w),!o||o(p))})),m=await Promise.all(d);for(let g of m)u.push(...g);return u}var _=class{static CACHE_DIR=C.join(homedir(),".claude","powerline");static GIT_CACHE_DIR=C.join(this.CACHE_DIR,"git");static USAGE_CACHE_DIR=C.join(this.CACHE_DIR,"usage");static LOCKS_DIR=C.join(this.CACHE_DIR,"locks");static isLocked(e){let t=C.join(this.LOCKS_DIR,e);return y.existsSync(t)}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let s=C.join(this.LOCKS_DIR,e),i=Date.now(),l=String(process.pid);for(;Date.now()-i<t;)try{return await y.promises.writeFile(s,l,{flag:"wx"}),c(`Lock acquired for ${e}`),!0}catch(a){if(a.code==="EEXIST")await setTimeout(50);else throw a}return c(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=C.join(this.LOCKS_DIR,e);try{await y.promises.unlink(t),c(`Lock released for ${e}`);}catch(n){n.code!=="ENOENT"&&c(`Error releasing lock for ${e}:`,n);}}static async ensureCacheDirectories(){try{await Promise.all([y.promises.mkdir(this.CACHE_DIR,{recursive:!0}),y.promises.mkdir(this.GIT_CACHE_DIR,{recursive:!0}),y.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),y.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){c("Failed to create cache directories:",e);}}static createProjectHash(e){return createHash("md5").update(e).digest("hex").substring(0,8)}static async getGitRepoModTime(e){try{let t=C.join(e,".git"),n=C.join(t,"index"),r=C.join(t,"HEAD"),s=0;try{let i=await y.promises.stat(n);s=Math.max(s,i.mtime.getTime());}catch{}try{let i=await y.promises.stat(r);s=Math.max(s,i.mtime.getTime());}catch{}try{let i=await y.promises.stat(e);s=Math.max(s,i.mtime.getTime());}catch{}return s}catch(t){return c(`Failed to get git repo mod time for ${e}:`,t),Date.now()}}static async getGitCache(e){let r="utf-8";await this.ensureCacheDirectories();let s=this.createProjectHash(e),i=C.join(this.GIT_CACHE_DIR,`${s}.json`),l=`${s}.git.lock`;for(let a=0;a<3;a++){if(this.isLocked(l)){c(`Cache for git project ${s} is locked, waiting...`),await setTimeout(75);continue}try{let d=await y.promises.readFile(i,r),m=JSON.parse(d),g=await this.getGitRepoModTime(e),f=m.gitModTime||0;return g<=f?(c(`[CACHE-HIT] Git disk cache: ${e}`),m.data):(c(`[CACHE-MISS] Git repo changed: ${e}`),null)}catch(d){if(d.code==="ENOENT")return c(`No shared git cache found for ${e}`),null;let m=a+1;c(`Attempt ${m} failed to read git cache for ${e}: ${d.message}. Retrying...`),await setTimeout(75);}}return c(`Failed to read git cache for ${e} after 3 attempts.`),null}static async setGitCache(e,t){let n=this.createProjectHash(e),r=`${n}.git.lock`;if(!await this.acquireLock(r)){c(`Could not acquire lock to set git cache for ${e}`);return}try{await this.ensureCacheDirectories();let s=C.join(this.GIT_CACHE_DIR,`${n}.json`),i=await this.getGitRepoModTime(e),l={data:t,timestamp:Date.now(),gitModTime:i};await y.promises.writeFile(s,JSON.stringify(l),"utf-8"),c(`[CACHE-SET] Git disk cache stored: ${e}`);}catch(s){c(`Failed to save git cache for ${e}:`,s);}finally{await this.releaseLock(r);}}static async getUsageCache(e,t){let s="utf-8";await this.ensureCacheDirectories();let i=C.join(this.USAGE_CACHE_DIR,`${e}.json`),l=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(l)){c(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let d=await y.promises.readFile(i,s),m=JSON.parse(d);return !t||m.timestamp>=t?(c(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(m.data)):(c(`${e} cache outdated: cache=${m.timestamp}, latest=${t}`),null)}catch(d){if(d.code==="ENOENT")return c(`No shared ${e} usage cache found`),null;let m=a+1;c(`Attempt ${m} failed to read ${e} cache: ${d.message}. Retrying...`),await setTimeout(75);}}return c(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(t=>({...t,timestamp:new Date(t.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){c(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=C.join(this.USAGE_CACHE_DIR,`${e}.json`),l=n||Date.now(),u=JSON.stringify({data:t,timestamp:l});await y.promises.writeFile(i,u,"utf-8"),c(`[CACHE-SET] ${e} disk cache stored`);}catch(i){c(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(r);}}static async getLatestTranscriptMtime(){try{let e=Y(),t=await J(e),n=0;for(let r of t)try{let i=(await y.promises.readdir(r)).filter(l=>l.endsWith(".jsonl"));for(let l of i){let a=C.join(r,l),u=await ce(a);u&&u.getTime()>n&&(n=u.getTime());}}catch(s){c(`Failed to read project directory ${r}:`,s);continue}return n}catch(e){return c("Failed to get latest transcript mtime:",e),Date.now()}}static async cleanupOldCache(e=1440*60*1e3){await this.ensureCacheDirectories();let t=Date.now(),n=C.join(this.CACHE_DIR,".cleanup");try{let r=await y.promises.readFile(n,"utf-8");if(t-parseInt(r)<3600*1e3)return}catch{}try{let r=[this.GIT_CACHE_DIR,this.USAGE_CACHE_DIR];for(let s of r)try{let i=await y.promises.readdir(s);for(let l of i){let a=C.join(s,l),u=await y.promises.stat(a);t-u.mtime.getTime()>e&&(await y.promises.unlink(a),c(`Cleaned up old cache file: ${l}`));}}catch(i){c(`Error cleaning directory ${s}:`,i);}await y.promises.writeFile(n,t.toString()),c("Cache cleanup completed");}catch(r){c("Error during cache cleanup:",r);}}};var T=promisify(exec),A=class{isGitRepo(e){try{return y.existsSync(C.join(e,".git"))}catch{return false}}async getGitInfo(e,t={},n){let r=n&&this.isGitRepo(n)?n:e;if(!this.isGitRepo(r))return null;let s=await _.getGitCache(r);if(s)return c(`[CACHE-HIT] Git disk cache: ${r}`),s;try{let i=await this.getStatusWithBranchAsync(r),l=await this.getAheadBehindAsync(r),a={branch:i.branch||"detached",status:i.status,ahead:l.ahead,behind:l.behind};t.showWorkingTree&&i.workingTree&&(a.staged=i.workingTree.staged,a.unstaged=i.workingTree.unstaged,a.untracked=i.workingTree.untracked,a.conflicts=i.workingTree.conflicts);let u={},d={};t.showSha&&(u.sha=this.getShaAsync(r)),t.showTag&&(u.tag=this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(u.timeSinceCommit=this.getTimeSinceLastCommitAsync(r)),t.showStashCount&&(d.stashCount=this.getStashCountAsync(r)),t.showUpstream&&(d.upstream=this.getUpstreamAsync(r)),t.showRepoName&&(d.repoName=this.getRepoNameAsync(r));let m=new Map;for(let[g,f]of Object.entries(u))try{let p=await f;m.set(g,p);}catch{}return Object.keys(d).length>0&&(await Promise.allSettled(Object.entries(d).map(async([f,p])=>({key:f,value:await p})))).forEach(f=>{f.status==="fulfilled"&&m.set(f.value.key,f.value.value);}),t.showSha&&(a.sha=m.get("sha")||void 0),t.showOperation&&(a.operation=this.getOngoingOperation(r)||void 0),t.showTag&&(a.tag=m.get("tag")||void 0),t.showTimeSinceCommit&&(a.timeSinceCommit=m.get("timeSinceCommit")||void 0),t.showStashCount&&(a.stashCount=m.get("stashCount")||0),t.showUpstream&&(a.upstream=m.get("upstream")||void 0),t.showRepoName&&(a.repoName=m.get("repoName")||void 0,a.isWorktree=this.isWorktree(r)),await _.setGitCache(r,a),c(`[CACHE-SET] Git disk cache stored: ${r}`),_.cleanupOldCache().catch(()=>{}),a}catch{return null}}async getShaAsync(e){try{return (await T("git rev-parse --short=7 HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}getOngoingOperation(e){try{let t=C.join(e,".git");return y.existsSync(C.join(t,"MERGE_HEAD"))?"MERGE":y.existsSync(C.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":y.existsSync(C.join(t,"REVERT_HEAD"))?"REVERT":y.existsSync(C.join(t,"BISECT_LOG"))?"BISECT":y.existsSync(C.join(t,"rebase-merge"))||y.existsSync(C.join(t,"rebase-apply"))?"REBASE":null}catch{return null}}async getNearestTagAsync(e){try{return (await T("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getTimeSinceLastCommitAsync(e){try{let n=(await T("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!n)return null;let r=parseInt(n)*1e3,s=Date.now();return Math.floor((s-r)/1e3)}catch{return null}}async getStashCountAsync(e){try{let n=(await T("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.split(`
5
5
  `).length:0}catch{return 0}}async getUpstreamAsync(e){try{return (await T("git rev-parse --abbrev-ref @{u}",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getRepoNameAsync(e){try{let n=(await T("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.match(/\/([^/]+?)(\.git)?$/)?.[1]||C.basename(e):C.basename(e)}catch{return C.basename(e)}}isWorktree(e){try{let t=C.join(e,".git");return !!(y.existsSync(t)&&y.statSync(t).isFile())}catch{return false}}async getStatusWithBranchAsync(e){try{c(`[GIT-EXEC] Running git status in ${e}`);let r=(await T("git status --porcelain -b",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.split(`
6
- `),s=null,i="clean",l=0,a=0,u=0,d=0;for(let m of r)if(m){if(m.startsWith("## ")){let f=m.substring(3).split("...")[0];f&&f!=="HEAD (no branch)"&&(s=f);continue}if(m.length>=2){let g=m.charAt(0),f=m.charAt(1);if(g==="?"&&f==="?"){u++,i==="clean"&&(i="dirty");continue}let p=g+f;if(["DD","AU","UD","UA","DU","AA","UU"].includes(p)){d++,i="conflicts";continue}g!==" "&&g!=="?"&&(l++,i==="clean"&&(i="dirty")),f!==" "&&f!=="?"&&(a++,i==="clean"&&(i="dirty"));}}return {branch:s||await this.getFallbackBranch(e),status:i,workingTree:{staged:l,unstaged:a,untracked:u,conflicts:d}}}catch(t){return c(`Git status with branch command failed in ${e}:`,t),{branch:await this.getFallbackBranch(e),status:"clean"}}}async getFallbackBranch(e){try{let n=(await T("git branch --show-current",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{try{let n=(await T("git symbolic-ref --short HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{return null}}return null}async getAheadBehindAsync(e){try{c(`[GIT-EXEC] Running git ahead/behind in ${e}`);let[t,n]=await Promise.all([T("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:2e3}),T("git rev-list --count HEAD..@{u}",{cwd:e,encoding:"utf8",timeout:2e3})]);return {ahead:parseInt(t.stdout.trim())||0,behind:parseInt(n.stdout.trim())||0}}catch(t){return c(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}};var Je=promisify(exec),M=class{async getSessionId(){try{if(!process.env.TMUX_PANE)return c("TMUX_PANE not set, not in tmux session"),null;c(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let t=(await Je("tmux display-message -p '#S'",{encoding:"utf8",timeout:1e3})).stdout.trim();return c(`Tmux session ID: ${t||"empty"}`),t||null}catch(e){return c("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};var X={"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}},v=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(){return await _.getUsageCache("pricing")}static async saveDiskCache(e){await _.setUsageCache("pricing",e);}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},r=>{if(r.statusCode!==200){c(`HTTP ${r.statusCode}: ${r.statusMessage}`),e(null);return}let s="",i=0,l=1024*1024;r.on("data",a=>{if(i+=a.length,i>l){c("Response too large"),n.destroy(),e(null);return}s+=a;}),r.on("end",()=>{try{let u=JSON.parse(s),d=u._meta,m={};for(let[g,f]of Object.entries(u))g!=="_meta"&&(m[g]=f);this.validatePricingData(m)?(c(`Fetched fresh pricing from GitHub for ${Object.keys(m).length} models`),c(`Pricing last updated: ${d?.updated||"unknown"}`),e(m)):(c("Invalid pricing data structure"),e(null));}catch(a){c("Failed to parse JSON:",a),e(null);}}),r.on("error",a=>{c("Response error:",a),e(null);});});n.on("error",r=>{c("Request error:",r),e(null);}),n.on("timeout",()=>{c("Request timeout"),n.destroy(),e(null);}),n.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return c(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return c(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),c(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(c(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(X).length} models`),this.executionCache=X,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(X).length} models`),X)}static validatePricingData(e){if(!e||typeof e!="object")return false;for(let[,t]of Object.entries(e)){if(!t||typeof t!="object")return false;let n=t;if(typeof n.input!="number"||typeof n.output!="number"||typeof n.cache_read!="number")return false}return true}static async getModelPricing(e){if(this.modelPricingCache.has(e))return c(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return t[e]?n=t[e]:n=this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),c(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[s,i]of Object.entries(t))if(s.toLowerCase()===n)return i;let r=[{pattern:["opus-4-1","claude-opus-4-1"],fallback:"claude-opus-4-1-20250805"},{pattern:["opus-4","claude-opus-4"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet-4","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:s,fallback:i}of r)if(s.some(l=>n.includes(l))&&t[i])return t[i];return t["claude-3-5-sonnet-20241022"]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let n=e.message?.usage;if(!n)return 0;let r=this.extractModelId(e),s=await this.getModelPricing(r),i=n.input_tokens||0,l=n.output_tokens||0,a=n.cache_creation_input_tokens||0,u=n.cache_read_input_tokens||0,d=i/1e6*s.input,m=l/1e6*s.output,g=u/1e6*s.cache_read,f=a/1e6*s.cache_write_5m;return d+m+f+g}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 Xe(o){return {timestamp:o.timestamp.toISOString(),message:{usage:{input_tokens:o.message?.usage?.input_tokens||0,output_tokens:o.message?.usage?.output_tokens||0,cache_creation_input_tokens:o.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:o.message?.usage?.cache_read_input_tokens}},costUSD:o.costUSD}}var z=class{async getSessionUsage(e){try{let t=await V(e);if(!t)return c(`No transcript found for session: ${e}`),null;c(`Found transcript at: ${t}`);let n=await F(t);if(n.length===0)return {totalCost:0,entries:[]};let r=[],s=0;for(let i of n)if(i.message?.usage){let l=Xe(i);if(l.costUSD!==void 0)s+=l.costUSD;else {let a=await v.calculateCostForEntry(i.raw);l.costUSD=a,s+=a;}r.push(l);}return c(`Parsed ${r.length} usage entries, total cost: $${s.toFixed(4)}`),{totalCost:s,entries:r}}catch(t){return c(`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),r=n.input+n.output+n.cacheCreation+n.cacheRead;return {cost:t.totalCost,tokens:r,tokenBreakdown:n}}},I=class{sessionProvider=new z;async getUsageInfo(e){try{return c(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e)}}catch(t){return c(`Error getting usage info for session ${e}:`,t),{session:{cost:null,tokens:null,tokenBreakdown:null}}}}};var L=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}getContextLimit(e){return 2e5}async calculateContextTokens(e,t){try{c(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return c("Transcript file is empty"),null}catch{return c("Could not read transcript file"),null}let n=await F(e);if(n.length===0)return c("No entries in transcript"),null;let r=null;for(let s=n.length-1;s>=0;s--){let i=n[s];if(i&&i.message?.usage?.input_tokens&&i.isSidechain!==!0){r=i,c(`Context segment: Found most recent entry at ${i.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let s=r.message.usage,i=(s.input_tokens||0)+(s.cache_read_input_tokens||0)+(s.cache_creation_input_tokens||0),l=t?this.getContextLimit(t):2e5;c(`Most recent main chain context: ${i} tokens (limit: ${l})`);let a=Math.min(100,Math.max(0,Math.round(i/l*100))),u=Math.round(l*.75),d=Math.min(100,Math.max(0,Math.round(i/u*100))),m=Math.max(0,100-d);return {inputTokens:i,percentage:a,usablePercentage:d,contextLeftPercentage:m,maxTokens:l,usableTokens:u}}return c("No main chain entries with usage data found"),null}catch(n){return c(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}};var j=class{async loadTranscriptEntries(e){try{let t=await V(e);if(!t)return c(`No transcript found for session: ${e}`),[];c(`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 l=JSON.parse(i);if(l.isSidechain===!0)continue;s.push(l);}catch(l){c(`Failed to parse JSONL line: ${l}`);continue}return c(`Loaded ${s.length} transcript entries`),s}catch(t){return c(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,r=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!r}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let s of t)if(s.timestamp)try{let i=new Date(s.timestamp),l=s.type||s.message?.role||s.message?.type,a=s.type==="user"&&s.message?.content?.[0]?.type==="tool_result";if(l==="user"&&!a)n=i;else if(l==="assistant"&&n){let d=(i.getTime()-n.getTime())/1e3;d>.1&&d<300&&(r=d);}}catch{continue}return r}async getMetricsInfo(e,t){try{if(c(`Getting metrics from hook data for session: ${e}`),!t.cost)return c("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let n=await this.loadTranscriptEntries(e),r=this.calculateMessageCount(n),s=this.calculateLastResponseTime(n);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(n){return c(`Error getting metrics from hook data for session ${e}:`,n),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function $(o){return o===null?"$0.00":o<.01?"<$0.01":`$${o.toFixed(2)}`}function x(o){return o===null||o===0?"0 tokens":o>=1e6?`${(o/1e6).toFixed(1)}M tokens`:o>=1e3?`${(o/1e3).toFixed(1)}K tokens`:`${o} tokens`}function _e(o){if(!o)return "0 tokens";let e=[];if(o.input>0&&e.push(`${x(o.input).replace(" tokens","")}in`),o.output>0&&e.push(`${x(o.output).replace(" tokens","")}out`),o.cacheCreation>0||o.cacheRead>0){let t=o.cacheCreation+o.cacheRead;e.push(`${x(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function we(o){return o<60?`${o}s`:o<3600?`${Math.floor(o/60)}m`:o<86400?`${Math.floor(o/3600)}h`:o<604800?`${Math.floor(o/86400)}d`:`${Math.floor(o/604800)}w`}function Se(o){return o<60?`${o.toFixed(0)}s`:o<3600?`${(o/60).toFixed(0)}m`:o<86400?`${(o/3600).toFixed(1)}h`:`${(o/86400).toFixed(1)}d`}function Ze(o,e){return !e||e<=0||o<0?null:Math.min(100,o/e*100)}function ke(o,e,t=80){let n=Ze(o,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let r=`${n.toFixed(0)}%`,s=n>=t,i="";return s?i=` !${r}`:n>=50?i=` +${r}`:i=` ${r}`,{percentage:n,isWarning:s,displayText:i}}var N=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let r=e.workspace?.current_dir||e.cwd||"/",s=e.workspace?.project_dir;if(n?.showBasename)return {text:C.basename(r)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let i=process.env.HOME||process.env.USERPROFILE,l=r,a=s;return i&&(r.startsWith(i)&&(l=r.replace(i,"~")),s&&s.startsWith(i)&&(a=s.replace(i,"~"))),{text:this.getDisplayDirectoryName(l,a),bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let r=[];if(n?.showRepoName&&e.repoName&&(r.push(e.repoName),e.isWorktree&&r.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&r.push(`[${e.operation}]`),r.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&r.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&r.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?r.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?r.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&r.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let i=[];e.staged&&e.staged>0&&i.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&i.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&i.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&i.push(`!${e.conflicts}`),i.length>0&&r.push(`(${i.join(" ")})`);}if(n?.showUpstream&&e.upstream&&r.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&r.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=we(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 n=e.model?.display_name||"Claude";return {text:`${this.symbols.model} ${n}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n="cost"){let r=this.config.budget?.session;return {text:`${this.symbols.session_cost} ${this.formatUsageWithBudget(e.session.cost,e.session.tokens,e.session.tokenBreakdown,n,r?.amount,r?.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(),r=`${e.contextLeftPercentage}%`;return {text:`${this.symbols.context_time} ${n} (${r})`,bgColor:t.contextBg,fgColor:t.contextFg}}renderMetrics(e,t,n,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,n){let r;if(e.cost===null&&e.tokens===null)r="No active block";else {let s=n?.type||"cost",i=n?.burnType,l=e.timeRemaining!==null?(()=>{let d=Math.floor(e.timeRemaining/60),m=e.timeRemaining%60;return d>0?`${d}h ${m}m`:`${m}m`})():null,a;switch(s){case "cost":a=$(e.cost);break;case "tokens":a=x(e.tokens);break;case "both":a=`${$(e.cost)} / ${x(e.tokens)}`;break;case "time":a=l||"N/A";break;default:a=$(e.cost);}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?`${x(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let g=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",f=e.tokenBurnRate!==null?`${x(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${g} / ${f}`;break}s==="time"?r=a:r=l?`${a}${u} (${l} left)`:`${a}${u}`;}return {text:`${this.symbols.block_cost} ${r}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let r=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,r?.amount,r?.warningThreshold)}`,bgColor:t.todayBg,fgColor:t.todayFg}}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||C.basename(t)||"project":C.basename(e)||"root":C.basename(e)||"root"}formatUsageDisplay(e,t,n,r){switch(r){case "cost":return $(e);case "tokens":return x(t);case "both":return `${$(e)} (${x(t)})`;case "breakdown":return _e(n);default:return $(e)}}formatUsageWithBudget(e,t,n,r,s,i=80){let l=this.formatUsageDisplay(e,t,n,r);if(s&&s>0&&e!==null){let a=ke(e,s,i);return l+a.displayText}return l}renderVersion(e,t,n){return e.version?{text:`${this.symbols.version} v${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}:null}};function Qe(o){return {timestamp:o.timestamp,usage:{inputTokens:o.message?.usage?.input_tokens||0,outputTokens:o.message?.usage?.output_tokens||0,cacheCreationInputTokens:o.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:o.message?.usage?.cache_read_input_tokens||0},costUSD:o.costUSD||0,model:o.message?.model||"unknown"}}var Z=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],r=[...e].sort((l,a)=>l.timestamp.getTime()-a.timestamp.getTime()),s=null,i=[];for(let l of r){let a=l.timestamp;if(s==null)s=this.floorToHour(a),i=[l];else {let u=a.getTime()-s.getTime(),d=i[i.length-1];if(d==null)continue;let m=d.timestamp,g=a.getTime()-m.getTime();u>t||g>t?(n.push(i),s=this.floorToHour(a),i=[l]):i.push(l);}}return s!=null&&i.length>0&&n.push(i),n}createBlockInfo(e,t){let n=new Date,r=this.sessionDurationHours*60*60*1e3,s=new Date(e.getTime()+r),i=t[t.length-1],l=i!=null?i.timestamp:e,a=n.getTime()-l.getTime()<r&&n<s;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 r=n[0];if(!r)continue;let s=this.floorToHour(r.timestamp),i=this.createBlockInfo(s,n);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{c("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await q(void 0,(a,u)=>u>=e,!0),r=[];for(let a of n)if(a.message?.usage){let u=Qe(a);!u.costUSD&&a.raw&&(u.costUSD=await v.calculateCostForEntry(a.raw)),r.push(u);}let s=this.identifySessionBlocks(r);c(`Block segment: Found ${s.length} session blocks`);let i=this.findActiveBlock(s),l=[];if(i&&i.length>0){c(`Block segment: Found active block with ${i.length} entries`);let a=i[0],u=i[i.length-1];a&&u&&c(`Block segment: Active block from ${a.timestamp.toISOString()} to ${u.timestamp.toISOString()}`),l=i;}else c("Block segment: No active block found"),l=[];return l}catch(e){return c("Error loading block entries:",e),[]}}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),r=new Date,s=null;if(e.length>0){let a=e[0];if(a){let u=this.sessionDurationHours*60*60*1e3,d=this.floorToHour(a.timestamp),m=new Date(d.getTime()+u);s=Math.max(0,Math.round((m.getTime()-r.getTime())/(1e3*60)));}}let i=null,l=null;if(e.length>=1&&(t>0||n>0)){let a=e.map(m=>m.timestamp).sort((m,g)=>m.getTime()-g.getTime()),u=a[0],d=a[a.length-1];if(u&&d){let m=(d.getTime()-u.getTime())/6e4;m>0&&(t>0&&(i=t/m*60),n>0&&(l=n/m*60));}}return c(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${s}m remaining, burn rate: ${i?"$"+i.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,timeRemaining:s,burnRate:i,tokenBurnRate:l}}catch(e){return c("Error getting active block info:",e),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function H(o){let e=o.getFullYear(),t=String(o.getMonth()+1).padStart(2,"0"),n=String(o.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function et(o){return o.inputTokens+o.outputTokens+o.cacheCreationInputTokens+o.cacheReadInputTokens}function tt(o){return {timestamp:o.timestamp,usage:{inputTokens:o.message?.usage?.input_tokens||0,outputTokens:o.message?.usage?.output_tokens||0,cacheCreationInputTokens:o.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:o.message?.usage?.cache_read_input_tokens||0},costUSD:o.costUSD||0,model:o.message?.model||"unknown"}}var Q=class{async loadTodayEntries(){let t=H(new Date);c(`Today segment: Loading entries for date ${t}`);let n=await _.getLatestTranscriptMtime(),r=await _.getUsageCache("today",n);if(r)return c("Using shared today usage cache"),r;let s=new Date;s.setDate(s.getDate()-1),s.setHours(0,0,0,0);let i=(g,f)=>f>=s,l=new Date;l.setHours(0,0,0,0);let u=await q(g=>g.timestamp>=l,i,true),d=[],m=0;for(let g of u)if(H(g.timestamp)===t&&g.message?.usage){let p=tt(g);!p.costUSD&&g.raw&&(p.costUSD=await v.calculateCostForEntry(g.raw)),d.push(p),m++;}return c(`Today segment: Found ${m} entries for today (${t})`),await _.setUsageCache("today",d,n),d}async getTodayEntries(){try{return await this.loadTodayEntries()}catch(e){return c("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:H(new Date)};let t=e.reduce((s,i)=>s+i.costUSD,0),n=e.reduce((s,i)=>s+et(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 c(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:r,date:H(new Date)}}catch(e){return c("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:H(new Date)}}}};var O="\x1B[0m",h={right:"\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_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u27E2",version:"\u25C8"};var ee=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 I),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new Z),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new Q),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new L),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new A),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new M),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new j),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new N(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,r=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,s=this.needsSegmentInfo("context")?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,i=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id,e):null;return (await Promise.all(this.config.display.lines.map(a=>this.renderLine(a,e,t,n,r,s,i)))).filter(a=>a.length>0).join(`
6
+ `),s=null,i="clean",l=0,a=0,u=0,d=0;for(let m of r)if(m){if(m.startsWith("## ")){let f=m.substring(3).split("...")[0];f&&f!=="HEAD (no branch)"&&(s=f);continue}if(m.length>=2){let g=m.charAt(0),f=m.charAt(1);if(g==="?"&&f==="?"){u++,i==="clean"&&(i="dirty");continue}let p=g+f;if(["DD","AU","UD","UA","DU","AA","UU"].includes(p)){d++,i="conflicts";continue}g!==" "&&g!=="?"&&(l++,i==="clean"&&(i="dirty")),f!==" "&&f!=="?"&&(a++,i==="clean"&&(i="dirty"));}}return {branch:s||await this.getFallbackBranch(e),status:i,workingTree:{staged:l,unstaged:a,untracked:u,conflicts:d}}}catch(t){return c(`Git status with branch command failed in ${e}:`,t),{branch:await this.getFallbackBranch(e),status:"clean"}}}async getFallbackBranch(e){try{let n=(await T("git branch --show-current",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{try{let n=(await T("git symbolic-ref --short HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{return null}}return null}async getAheadBehindAsync(e){try{c(`[GIT-EXEC] Running git ahead/behind in ${e}`);let[t,n]=await Promise.all([T("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:2e3}),T("git rev-list --count HEAD..@{u}",{cwd:e,encoding:"utf8",timeout:2e3})]);return {ahead:parseInt(t.stdout.trim())||0,behind:parseInt(n.stdout.trim())||0}}catch(t){return c(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}};var Je=promisify(exec),M=class{async getSessionId(){try{if(!process.env.TMUX_PANE)return c("TMUX_PANE not set, not in tmux session"),null;c(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let t=(await Je("tmux display-message -p '#S'",{encoding:"utf8",timeout:1e3})).stdout.trim();return c(`Tmux session ID: ${t||"empty"}`),t||null}catch(e){return c("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};var X={"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}},v=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(){return await _.getUsageCache("pricing")}static async saveDiskCache(e){await _.setUsageCache("pricing",e);}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},r=>{if(r.statusCode!==200){c(`HTTP ${r.statusCode}: ${r.statusMessage}`),e(null);return}let s="",i=0,l=1024*1024;r.on("data",a=>{if(i+=a.length,i>l){c("Response too large"),n.destroy(),e(null);return}s+=a;}),r.on("end",()=>{try{let u=JSON.parse(s),d=u._meta,m={};for(let[g,f]of Object.entries(u))g!=="_meta"&&(m[g]=f);this.validatePricingData(m)?(c(`Fetched fresh pricing from GitHub for ${Object.keys(m).length} models`),c(`Pricing last updated: ${d?.updated||"unknown"}`),e(m)):(c("Invalid pricing data structure"),e(null));}catch(a){c("Failed to parse JSON:",a),e(null);}}),r.on("error",a=>{c("Response error:",a),e(null);});});n.on("error",r=>{c("Request error:",r),e(null);}),n.on("timeout",()=>{c("Request timeout"),n.destroy(),e(null);}),n.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return c(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return c(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),c(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(c(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(X).length} models`),this.executionCache=X,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(X).length} models`),X)}static validatePricingData(e){if(!e||typeof e!="object")return false;for(let[,t]of Object.entries(e)){if(!t||typeof t!="object")return false;let n=t;if(typeof n.input!="number"||typeof n.output!="number"||typeof n.cache_read!="number")return false}return true}static async getModelPricing(e){if(this.modelPricingCache.has(e))return c(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return t[e]?n=t[e]:n=this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),c(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[s,i]of Object.entries(t))if(s.toLowerCase()===n)return i;let r=[{pattern:["opus-4-1","claude-opus-4-1"],fallback:"claude-opus-4-1-20250805"},{pattern:["opus-4","claude-opus-4"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet-4","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:s,fallback:i}of r)if(s.some(l=>n.includes(l))&&t[i])return t[i];return t["claude-3-5-sonnet-20241022"]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let n=e.message?.usage;if(!n)return 0;let r=this.extractModelId(e),s=await this.getModelPricing(r),i=n.input_tokens||0,l=n.output_tokens||0,a=n.cache_creation_input_tokens||0,u=n.cache_read_input_tokens||0,d=i/1e6*s.input,m=l/1e6*s.output,g=u/1e6*s.cache_read,f=a/1e6*s.cache_write_5m;return d+m+f+g}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 Xe(o){return {timestamp:o.timestamp.toISOString(),message:{usage:{input_tokens:o.message?.usage?.input_tokens||0,output_tokens:o.message?.usage?.output_tokens||0,cache_creation_input_tokens:o.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:o.message?.usage?.cache_read_input_tokens}},costUSD:o.costUSD}}var z=class{async getSessionUsage(e){try{let t=await V(e);if(!t)return c(`No transcript found for session: ${e}`),null;c(`Found transcript at: ${t}`);let n=await F(t);if(n.length===0)return {totalCost:0,entries:[]};let r=[],s=0;for(let i of n)if(i.message?.usage){let l=Xe(i);if(l.costUSD!==void 0)s+=l.costUSD;else {let a=await v.calculateCostForEntry(i.raw);l.costUSD=a,s+=a;}r.push(l);}return c(`Parsed ${r.length} usage entries, total cost: $${s.toFixed(4)}`),{totalCost:s,entries:r}}catch(t){return c(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,n)=>({input:t.input+(n.message.usage.input_tokens||0),output:t.output+(n.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(n.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(n.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e,t){let n=await this.getSessionUsage(e);if(!n||n.entries.length===0)return {cost:null,tokens:null,tokenBreakdown:null};let r=this.calculateTokenBreakdown(n.entries),s=r.input+r.output+r.cacheCreation+r.cacheRead,i=n.totalCost,l=t?.cost?.total_cost_usd??null;return {cost:i??l,tokens:s,tokenBreakdown:r}}},I=class{sessionProvider=new z;async getUsageInfo(e,t){try{return c(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e,t)}}catch(n){return c(`Error getting usage info for session ${e}:`,n),{session:{cost:null,tokens:null,tokenBreakdown:null}}}}};var L=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}getContextLimit(e){return 2e5}async calculateContextTokens(e,t){try{c(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return c("Transcript file is empty"),null}catch{return c("Could not read transcript file"),null}let n=await F(e);if(n.length===0)return c("No entries in transcript"),null;let r=null;for(let s=n.length-1;s>=0;s--){let i=n[s];if(i&&i.message?.usage?.input_tokens&&i.isSidechain!==!0){r=i,c(`Context segment: Found most recent entry at ${i.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let s=r.message.usage,i=(s.input_tokens||0)+(s.cache_read_input_tokens||0)+(s.cache_creation_input_tokens||0),l=t?this.getContextLimit(t):2e5;c(`Most recent main chain context: ${i} tokens (limit: ${l})`);let a=Math.min(100,Math.max(0,Math.round(i/l*100))),u=Math.round(l*.75),d=Math.min(100,Math.max(0,Math.round(i/u*100))),m=Math.max(0,100-d);return {inputTokens:i,percentage:a,usablePercentage:d,contextLeftPercentage:m,maxTokens:l,usableTokens:u}}return c("No main chain entries with usage data found"),null}catch(n){return c(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}};var H=class{async loadTranscriptEntries(e){try{let t=await V(e);if(!t)return c(`No transcript found for session: ${e}`),[];c(`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 l=JSON.parse(i);if(l.isSidechain===!0)continue;s.push(l);}catch(l){c(`Failed to parse JSONL line: ${l}`);continue}return c(`Loaded ${s.length} transcript entries`),s}catch(t){return c(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,r=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!r}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let s of t)if(s.timestamp)try{let i=new Date(s.timestamp),l=s.type||s.message?.role||s.message?.type,a=s.type==="user"&&s.message?.content?.[0]?.type==="tool_result";if(l==="user"&&!a)n=i;else if(l==="assistant"&&n){let d=(i.getTime()-n.getTime())/1e3;d>.1&&d<300&&(r=d);}}catch{continue}return r}async getMetricsInfo(e,t){try{if(c(`Getting metrics from hook data for session: ${e}`),!t.cost)return c("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let n=await this.loadTranscriptEntries(e),r=this.calculateMessageCount(n),s=this.calculateLastResponseTime(n);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(n){return c(`Error getting metrics from hook data for session ${e}:`,n),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function $(o){return o===null?"$0.00":o<.01?"<$0.01":`$${o.toFixed(2)}`}function x(o){return o===null||o===0?"0 tokens":o>=1e6?`${(o/1e6).toFixed(1)}M tokens`:o>=1e3?`${(o/1e3).toFixed(1)}K tokens`:`${o} tokens`}function _e(o){if(!o)return "0 tokens";let e=[];if(o.input>0&&e.push(`${x(o.input).replace(" tokens","")}in`),o.output>0&&e.push(`${x(o.output).replace(" tokens","")}out`),o.cacheCreation>0||o.cacheRead>0){let t=o.cacheCreation+o.cacheRead;e.push(`${x(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function we(o){return o<60?`${o}s`:o<3600?`${Math.floor(o/60)}m`:o<86400?`${Math.floor(o/3600)}h`:o<604800?`${Math.floor(o/86400)}d`:`${Math.floor(o/604800)}w`}function Se(o){return o<60?`${o.toFixed(0)}s`:o<3600?`${(o/60).toFixed(0)}m`:o<86400?`${(o/3600).toFixed(1)}h`:`${(o/86400).toFixed(1)}d`}function Ze(o,e){return !e||e<=0||o<0?null:Math.min(100,o/e*100)}function ke(o,e,t=80){let n=Ze(o,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let r=`${n.toFixed(0)}%`,s=n>=t,i="";return s?i=` !${r}`:n>=50?i=` +${r}`:i=` ${r}`,{percentage:n,isWarning:s,displayText:i}}var j=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let r=e.workspace?.current_dir||e.cwd||"/",s=e.workspace?.project_dir;if(n?.showBasename)return {text:C.basename(r)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let i=process.env.HOME||process.env.USERPROFILE,l=r,a=s;return i&&(r.startsWith(i)&&(l=r.replace(i,"~")),s&&s.startsWith(i)&&(a=s.replace(i,"~"))),{text:this.getDisplayDirectoryName(l,a),bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let r=[];if(n?.showRepoName&&e.repoName&&(r.push(e.repoName),e.isWorktree&&r.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&r.push(`[${e.operation}]`),r.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&r.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&r.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?r.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?r.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&r.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let i=[];e.staged&&e.staged>0&&i.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&i.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&i.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&i.push(`!${e.conflicts}`),i.length>0&&r.push(`(${i.join(" ")})`);}if(n?.showUpstream&&e.upstream&&r.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&r.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=we(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 n=e.model?.display_name||"Claude";return {text:`${this.symbols.model} ${n}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n="cost"){let r=this.config.budget?.session;return {text:`${this.symbols.session_cost} ${this.formatUsageWithBudget(e.session.cost,e.session.tokens,e.session.tokenBreakdown,n,r?.amount,r?.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(),r=`${e.contextLeftPercentage}%`;return {text:`${this.symbols.context_time} ${n} (${r})`,bgColor:t.contextBg,fgColor:t.contextFg}}renderMetrics(e,t,n,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,n){let r;if(e.cost===null&&e.tokens===null)r="No active block";else {let s=n?.type||"cost",i=n?.burnType,l=e.timeRemaining!==null?(()=>{let d=Math.floor(e.timeRemaining/60),m=e.timeRemaining%60;return d>0?`${d}h ${m}m`:`${m}m`})():null,a;switch(s){case "cost":a=$(e.cost);break;case "tokens":a=x(e.tokens);break;case "both":a=`${$(e.cost)} / ${x(e.tokens)}`;break;case "time":a=l||"N/A";break;default:a=$(e.cost);}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?`${x(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let g=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",f=e.tokenBurnRate!==null?`${x(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${g} / ${f}`;break}s==="time"?r=a:r=l?`${a}${u} (${l} left)`:`${a}${u}`;}return {text:`${this.symbols.block_cost} ${r}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let r=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,r?.amount,r?.warningThreshold)}`,bgColor:t.todayBg,fgColor:t.todayFg}}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||C.basename(t)||"project":C.basename(e)||"root":C.basename(e)||"root"}formatUsageDisplay(e,t,n,r){switch(r){case "cost":return $(e);case "tokens":return x(t);case "both":return `${$(e)} (${x(t)})`;case "breakdown":return _e(n);default:return $(e)}}formatUsageWithBudget(e,t,n,r,s,i=80){let l=this.formatUsageDisplay(e,t,n,r);if(s&&s>0&&e!==null){let a=ke(e,s,i);return l+a.displayText}return l}renderVersion(e,t,n){return e.version?{text:`${this.symbols.version} v${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}:null}};function Qe(o){return {timestamp:o.timestamp,usage:{inputTokens:o.message?.usage?.input_tokens||0,outputTokens:o.message?.usage?.output_tokens||0,cacheCreationInputTokens:o.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:o.message?.usage?.cache_read_input_tokens||0},costUSD:o.costUSD||0,model:o.message?.model||"unknown"}}var Z=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],r=[...e].sort((l,a)=>l.timestamp.getTime()-a.timestamp.getTime()),s=null,i=[];for(let l of r){let a=l.timestamp;if(s==null)s=this.floorToHour(a),i=[l];else {let u=a.getTime()-s.getTime(),d=i[i.length-1];if(d==null)continue;let m=d.timestamp,g=a.getTime()-m.getTime();u>t||g>t?(n.push(i),s=this.floorToHour(a),i=[l]):i.push(l);}}return s!=null&&i.length>0&&n.push(i),n}createBlockInfo(e,t){let n=new Date,r=this.sessionDurationHours*60*60*1e3,s=new Date(e.getTime()+r),i=t[t.length-1],l=i!=null?i.timestamp:e,a=n.getTime()-l.getTime()<r&&n<s;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 r=n[0];if(!r)continue;let s=this.floorToHour(r.timestamp),i=this.createBlockInfo(s,n);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{c("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await q(void 0,(a,u)=>u>=e,!0),r=[];for(let a of n)if(a.message?.usage){let u=Qe(a);!u.costUSD&&a.raw&&(u.costUSD=await v.calculateCostForEntry(a.raw)),r.push(u);}let s=this.identifySessionBlocks(r);c(`Block segment: Found ${s.length} session blocks`);let i=this.findActiveBlock(s),l=[];if(i&&i.length>0){c(`Block segment: Found active block with ${i.length} entries`);let a=i[0],u=i[i.length-1];a&&u&&c(`Block segment: Active block from ${a.timestamp.toISOString()} to ${u.timestamp.toISOString()}`),l=i;}else c("Block segment: No active block found"),l=[];return l}catch(e){return c("Error loading block entries:",e),[]}}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),r=new Date,s=null;if(e.length>0){let a=e[0];if(a){let u=this.sessionDurationHours*60*60*1e3,d=this.floorToHour(a.timestamp),m=new Date(d.getTime()+u);s=Math.max(0,Math.round((m.getTime()-r.getTime())/(1e3*60)));}}let i=null,l=null;if(e.length>=1&&(t>0||n>0)){let a=e.map(m=>m.timestamp).sort((m,g)=>m.getTime()-g.getTime()),u=a[0],d=a[a.length-1];if(u&&d){let m=(d.getTime()-u.getTime())/6e4;m>0&&(t>0&&(i=t/m*60),n>0&&(l=n/m*60));}}return c(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${s}m remaining, burn rate: ${i?"$"+i.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,timeRemaining:s,burnRate:i,tokenBurnRate:l}}catch(e){return c("Error getting active block info:",e),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function N(o){let e=o.getFullYear(),t=String(o.getMonth()+1).padStart(2,"0"),n=String(o.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function et(o){return o.inputTokens+o.outputTokens+o.cacheCreationInputTokens+o.cacheReadInputTokens}function tt(o){return {timestamp:o.timestamp,usage:{inputTokens:o.message?.usage?.input_tokens||0,outputTokens:o.message?.usage?.output_tokens||0,cacheCreationInputTokens:o.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:o.message?.usage?.cache_read_input_tokens||0},costUSD:o.costUSD||0,model:o.message?.model||"unknown"}}var Q=class{async loadTodayEntries(){let t=N(new Date);c(`Today segment: Loading entries for date ${t}`);let n=await _.getLatestTranscriptMtime(),r=await _.getUsageCache("today",n);if(r)return c("Using shared today usage cache"),r;let s=new Date;s.setDate(s.getDate()-1),s.setHours(0,0,0,0);let i=(g,f)=>f>=s,l=new Date;l.setHours(0,0,0,0);let u=await q(g=>g.timestamp>=l,i,true),d=[],m=0;for(let g of u)if(N(g.timestamp)===t&&g.message?.usage){let p=tt(g);!p.costUSD&&g.raw&&(p.costUSD=await v.calculateCostForEntry(g.raw)),d.push(p),m++;}return c(`Today segment: Found ${m} entries for today (${t})`),await _.setUsageCache("today",d,n),d}async getTodayEntries(){try{return await this.loadTodayEntries()}catch(e){return c("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:N(new Date)};let t=e.reduce((s,i)=>s+i.costUSD,0),n=e.reduce((s,i)=>s+et(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 c(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:r,date:N(new Date)}}catch(e){return c("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:N(new Date)}}}};var O="\x1B[0m",h={right:"\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_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u27E2",version:"\u25C8"};var ee=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 I),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new Z),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new Q),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new L),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new A),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new M),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new H),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new j(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id,e):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,r=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,s=this.needsSegmentInfo("context")?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,i=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id,e):null;return (await Promise.all(this.config.display.lines.map(a=>this.renderLine(a,e,t,n,r,s,i)))).filter(a=>a.length>0).join(`
8
8
  `)}async renderLine(e,t,n,r,s,i,l){let a=this.getThemeColors(),u=t.workspace?.current_dir||t.cwd||"/",d=Object.entries(e.segments).filter(([g,f])=>f?.enabled).map(([g,f])=>({type:g,config:f})),m=a.reset;for(let g=0;g<d.length;g++){let f=d[g];if(!f)continue;let p=g===d.length-1,w=p?null:d[g+1],B=w?this.getSegmentBgColor(w.type,a):"",S=await this.renderSegment(f,t,n,r,s,i,l,a,u);S&&(m+=this.formatSegment(S.bgColor,S.fgColor,S.text,p?void 0:B));}return m}async renderSegment(e,t,n,r,s,i,l,a,u){return e.type==="directory"?this.segmentRenderer.renderDirectory(t,a,e.config):e.type==="model"?this.segmentRenderer.renderModel(t,a):e.type==="git"?await this.renderGitSegment(e.config,t,a,u):e.type==="session"?this.renderSessionSegment(e.config,n,a):e.type==="tmux"?await this.renderTmuxSegment(a):e.type==="context"?this.renderContextSegment(i,a):e.type==="metrics"?this.renderMetricsSegment(e.config,l,r,a):e.type==="block"?this.renderBlockSegment(e.config,r,a):e.type==="today"?this.renderTodaySegment(e.config,s,a):e.type==="version"?this.renderVersionSegment(e.config,t,a):null}async renderGitSegment(e,t,n,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,n,e):null}renderSessionSegment(e,t,n){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderSession(t,n,r)}async renderTmuxSegment(e){if(!this.needsSegmentInfo("tmux"))return null;let t=await 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,r){return this.segmentRenderer.renderMetrics(t,r,n,e)}renderBlockSegment(e,t,n){return t?this.segmentRenderer.renderBlock(t,n,e):null}renderTodaySegment(e,t,n){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderToday(t,n,r)}renderVersionSegment(e,t,n){return this.segmentRenderer.renderVersion(t,n,e)}initializeSymbols(){return {right:this.config.display.style==="minimal"?"":h.right,branch:h.branch,model:h.model,git_clean:h.git_clean,git_dirty:h.git_dirty,git_conflicts:h.git_conflicts,git_ahead:h.git_ahead,git_behind:h.git_behind,git_worktree:h.git_worktree,git_tag:h.git_tag,git_sha:h.git_sha,git_upstream:h.git_upstream,git_stash:h.git_stash,git_time:h.git_time,session_cost:h.session_cost,block_cost:h.block_cost,today_cost:h.today_cost,context_time:h.context_time,metrics_response:h.metrics_response,metrics_last_response:h.metrics_last_response,metrics_duration:h.metrics_duration,metrics_messages:h.metrics_messages,metrics_lines_added:h.metrics_lines_added,metrics_lines_removed:h.metrics_lines_removed,metrics_burn:h.metrics_burn,version:h.version}}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=W(e),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=W("dark"));let n=W("dark"),r=w=>{let B=t[w]||n[w];return {bg:se(B.bg,true),fg:se(B.fg,false)}},s=r("directory"),i=r("git"),l=r("model"),a=r("session"),u=r("block"),d=r("today"),m=r("tmux"),g=r("context"),f=r("metrics"),p=r("version");return {reset:O,modeBg:s.bg,modeFg:s.fg,gitBg:i.bg,gitFg:i.fg,modelBg:l.bg,modelFg:l.fg,sessionBg:a.bg,sessionFg:a.fg,blockBg:u.bg,blockFg:u.fg,todayBg:d.bg,todayFg:d.fg,tmuxBg:m.bg,tmuxFg:m.fg,contextBg:g.bg,contextFg:g.fg,metricsBg:f.bg,metricsFg:f.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,r){let s=`${e}${t} ${n} `;if(r){let i=oe(e);s+=`${O}${r}${i}${this.symbols.right}`;}else s+=`${O}${oe(e)}${this.symbols.right}${O}`;return s}};var Te={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:true,type:"cost"},block:{enabled:false,type:"cost",burnType:"cost"},version:{enabled:false},tmux:{enabled:false},context:{enabled:true},metrics:{enabled:false,showResponseTime:true,showLastResponseTime:true,showDuration:true,showMessageCount:true,showLinesAdded:true,showLinesRemoved:true}}}]},budget:{session:{warningThreshold:80},today:{warningThreshold:80,amount:50}}};function ue(o){return ["light","dark","nord","tokyo-night","rose-pine","custom"].includes(o)}function me(o){return o==="minimal"||o==="powerline"}function ne(o,e){let t={...o};for(let n in e){let r=e[n];if(r!==void 0)if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let s=t[n]||{};t[n]=ne(s,r);}else t[n]=r;}return t}function nt(o,e){return o?y.existsSync(o)?o:null:[...e?[C.join(e,".claude-powerline.json")]:[],C.join(process.cwd(),".claude-powerline.json"),C.join(D.homedir(),".claude","claude-powerline.json"),C.join(D.homedir(),".config","claude-powerline","config.json")].find(y.existsSync)||null}function rt(o){try{let e=y.readFileSync(o,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${o}: ${e instanceof Error?e.message:String(e)}`)}}function st(){let o={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&ue(t)&&(o.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(me(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&&(o.display=e),o}function ot(){return process.env.CLAUDE_POWERLINE_CONFIG}function it(o){let e={},t={},n=o.find(s=>s.startsWith("--theme="))?.split("=")[1];n&&ue(n)&&(e.theme=n);let r=o.find(s=>s.startsWith("--style="))?.split("=")[1];return r&&(me(r)?t.style=r:(console.warn(`Invalid display style '${r}' from CLI argument, falling back to 'minimal'`),t.style="minimal")),Object.keys(t).length>0&&(e.display=t),e}function at(o=process.argv,e){let t=JSON.parse(JSON.stringify(Te)),n=o.find(l=>l.startsWith("--config="))?.split("=")[1]||ot(),r=nt(n,e);if(r)try{let l=rt(r);t=ne(t,l);}catch(l){console.warn(`Warning: ${l instanceof Error?l.message:String(l)}`);}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.theme&&!ue(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let s=st();t=ne(t,s);let i=it(o);return t=ne(t,i),t}var Ee=at;async function lt(){try{let o=D.platform(),e;if(o==="darwin")e=C.join(D.homedir(),"Library","Fonts");else if(o==="linux")e=C.join(D.homedir(),".local","share","fonts");else if(o==="win32")e=C.join(D.homedir(),"AppData","Local","Microsoft","Windows","Fonts");else {console.log("Unsupported platform for font installation");return}y.existsSync(e)||y.mkdirSync(e,{recursive:!0}),console.log("Installing Powerline Fonts..."),console.log("Downloading from https://github.com/powerline/fonts");let t=C.join(D.tmpdir(),"powerline-fonts"),n=()=>{y.existsSync(t)&&y.rmSync(t,{recursive:!0,force:!0});};b.on("SIGINT",n),b.on("SIGTERM",n);try{y.existsSync(t)&&y.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:D.tmpdir()}),console.log("Installing fonts...");let r=C.join(t,"install.sh");if(y.existsSync(r))y.chmodSync(r,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(),b.removeListener("SIGINT",n),b.removeListener("SIGTERM",n);}}catch(o){console.error("Error installing fonts:",o instanceof Error?o.message:String(o)),console.log("You can manually install fonts from: https://github.com/powerline/fonts");}}function Pe(){console.log(`
9
9
  claude-powerline - Beautiful powerline statusline for Claude Code
10
10
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owloops/claude-powerline",
3
- "version": "1.7.7",
3
+ "version": "1.7.8",
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",