@owloops/claude-powerline 1.7.5 → 1.7.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 +2 -2
- package/dist/index.js +9 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -451,10 +451,10 @@ Create custom themes by defining segment colors.
|
|
|
451
451
|
| `context` | ~40ms | ✗ | Hook data calculation |
|
|
452
452
|
| `metrics` | ~40ms | ✗ | Transcript analysis |
|
|
453
453
|
| `git` | ~70ms | ~40ms | Smart repo change detection |
|
|
454
|
-
| `tmux` | ~90ms |
|
|
454
|
+
| `tmux` | ~90ms | ✗ | Environment check + command |
|
|
455
455
|
| `block` | ~165ms | ✗ | 5-hour window transcript load |
|
|
456
456
|
| `today` | ~460ms | ~55ms | Full daily transcript load |
|
|
457
|
-
| `version` | ~
|
|
457
|
+
| `version` | ~40ms | ✗ | Uses hook data |
|
|
458
458
|
|
|
459
459
|
• **Tips:** Install globally (`npm install -g`) to avoid npx overhead
|
|
460
460
|
• Disable unused segments
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import w from'process';import
|
|
3
|
-
`),n=null;for(let s of t)if(s.trim())try{let r=JSON.parse(s);if(r.timestamp&&typeof r.timestamp=="string"){let o=new Date(r.timestamp);isNaN(o.getTime())||(n===null||o<n)&&(n=o);}}catch{continue}return n}catch(e){return
|
|
4
|
-
`).filter(s=>s.trim()),n=[];for(let s of t)try{let r=JSON.parse(s);if(!r.timestamp)continue;let o={timestamp:new Date(r.timestamp),message:r.message,costUSD:typeof r.costUSD=="number"?r.costUSD:void 0,isSidechain:r.isSidechain===!0,raw:r};n.push(o);}catch(r){a(`Failed to parse JSONL line: ${r}`);continue}return n}async function Ne(i){return new Promise((e,t)=>{let n=[],s=createReadStream(i,{encoding:"utf8"}),r=createInterface({input:s,crlfDelay:1/0});r.on("line",o=>{let l=o.trim();if(l)try{let c=JSON.parse(l);if(!c.timestamp)return;let u={timestamp:new Date(c.timestamp),message:c.message,costUSD:typeof c.costUSD=="number"?c.costUSD:void 0,isSidechain:c.isSidechain===!0,raw:c};n.push(u);}catch(c){a(`Failed to parse JSONL line: ${c}`);}}),r.on("close",()=>{e(n);}),r.on("error",o=>{a(`Streaming parser error for ${i}:`,o),t(o);}),s.on("error",o=>{a(`File stream error for ${i}:`,o),t(o);});})}async function z(i,e,t=false){let n=J(),s=await q(n),r=new Set,o=s.map(async g=>{try{let b=(await readdir(g)).filter(T=>T.endsWith(".jsonl")).map(async T=>{let v=posix.join(g,T);if(existsSync(v)){let Re=await le(v);return {filePath:v,mtime:Re}}return null});return (await Promise.all(b)).filter(T=>T?.mtime&&(!e||e(T.filePath,T.mtime)))}catch(f){return a(`Failed to read project directory ${g}:`,f),[]}}),c=(await Promise.all(o)).flat().filter(g=>g!==null).map(g=>g.filePath);if(t){let g=await Ae(c,false);c.length=0,c.push(...g);}let u=[],d=c.map(async g=>(await I(g)).filter(h=>{let b=Ue(h);return b&&r.has(b)?false:(b&&r.add(b),!i||i(h))})),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 VERSION_CACHE_DIR=C.join(this.CACHE_DIR,"version");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 r=C.join(this.LOCKS_DIR,e),o=Date.now(),l=String(process.pid);for(;Date.now()-o<t;)try{return await y.promises.writeFile(r,l,{flag:"wx"}),a(`Lock acquired for ${e}`),!0}catch(c){if(c.code==="EEXIST")await setTimeout(50);else throw c}return a(`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),a(`Lock released for ${e}`);}catch(n){n.code!=="ENOENT"&&a(`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}),y.promises.mkdir(this.VERSION_CACHE_DIR,{recursive:!0})]);}catch(e){a("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"),s=C.join(t,"HEAD"),r=0;try{let o=await y.promises.stat(n);r=Math.max(r,o.mtime.getTime());}catch{}try{let o=await y.promises.stat(s);r=Math.max(r,o.mtime.getTime());}catch{}try{let o=await y.promises.stat(e);r=Math.max(r,o.mtime.getTime());}catch{}return r}catch(t){return a(`Failed to get git repo mod time for ${e}:`,t),Date.now()}}static async getGitCache(e){let s="utf-8";await this.ensureCacheDirectories();let r=this.createProjectHash(e),o=C.join(this.GIT_CACHE_DIR,`${r}.json`),l=`${r}.git.lock`;for(let c=0;c<3;c++){if(this.isLocked(l)){a(`Cache for git project ${r} is locked, waiting...`),await setTimeout(75);continue}try{let d=await y.promises.readFile(o,s),m=JSON.parse(d),g=await this.getGitRepoModTime(e),f=m.gitModTime||0;return g<=f?(a(`[CACHE-HIT] Git disk cache: ${e}`),m.data):(a(`[CACHE-MISS] Git repo changed: ${e}`),null)}catch(d){if(d.code==="ENOENT")return a(`No shared git cache found for ${e}`),null;let m=c+1;a(`Attempt ${m} failed to read git cache for ${e}: ${d.message}. Retrying...`),await setTimeout(75);}}return a(`Failed to read git cache for ${e} after 3 attempts.`),null}static async setGitCache(e,t){let n=this.createProjectHash(e),s=`${n}.git.lock`;if(!await this.acquireLock(s)){a(`Could not acquire lock to set git cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=C.join(this.GIT_CACHE_DIR,`${n}.json`),o=await this.getGitRepoModTime(e),l={data:t,timestamp:Date.now(),gitModTime:o};await y.promises.writeFile(r,JSON.stringify(l),"utf-8"),a(`[CACHE-SET] Git disk cache stored: ${e}`);}catch(r){a(`Failed to save git cache for ${e}:`,r);}finally{await this.releaseLock(s);}}static async getUsageCache(e,t){let r="utf-8";await this.ensureCacheDirectories();let o=C.join(this.USAGE_CACHE_DIR,`${e}.json`),l=`${e}.usage.lock`;for(let c=0;c<3;c++){if(this.isLocked(l)){a(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let d=await y.promises.readFile(o,r),m=JSON.parse(d);return !t||m.timestamp>=t?(a(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(m.data)):(a(`${e} cache outdated: cache=${m.timestamp}, latest=${t}`),null)}catch(d){if(d.code==="ENOENT")return a(`No shared ${e} usage cache found`),null;let m=c+1;a(`Attempt ${m} failed to read ${e} cache: ${d.message}. Retrying...`),await setTimeout(75);}}return a(`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 s=`${e}.usage.lock`;if(!await this.acquireLock(s)){a(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let o=C.join(this.USAGE_CACHE_DIR,`${e}.json`),l=n||Date.now(),u=JSON.stringify({data:t,timestamp:l});await y.promises.writeFile(o,u,"utf-8"),a(`[CACHE-SET] ${e} disk cache stored`);}catch(o){a(`Failed to save ${e} usage cache:`,o);}finally{await this.releaseLock(s);}}static async getLatestTranscriptMtime(){try{let e=J(),t=await q(e),n=0;for(let s of t)try{let o=(await y.promises.readdir(s)).filter(l=>l.endsWith(".jsonl"));for(let l of o){let c=C.join(s,l),u=await le(c);u&&u.getTime()>n&&(n=u.getTime());}}catch(r){a(`Failed to read project directory ${s}:`,r);continue}return n}catch(e){return a("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 s=await y.promises.readFile(n,"utf-8");if(t-parseInt(s)<3600*1e3)return}catch{}try{let s=[this.GIT_CACHE_DIR,this.USAGE_CACHE_DIR,this.VERSION_CACHE_DIR];for(let r of s)try{let o=await y.promises.readdir(r);for(let l of o){let c=C.join(r,l),u=await y.promises.stat(c);t-u.mtime.getTime()>e&&(await y.promises.unlink(c),a(`Cleaned up old cache file: ${l}`));}}catch(o){a(`Error cleaning directory ${r}:`,o);}await y.promises.writeFile(n,t.toString()),a("Cache cleanup completed");}catch(s){a("Error during cache cleanup:",s);}}static async getVersionCache(e=1440*60*1e3){let s="utf-8";await this.ensureCacheDirectories();let r=C.join(this.VERSION_CACHE_DIR,"claude-version.json"),o="claude-version.lock";for(let l=0;l<3;l++){if(this.isLocked(o)){a("Version cache is locked, waiting..."),await setTimeout(75);continue}try{let u=await y.promises.readFile(r,s),d=JSON.parse(u),m=Date.now()-d.timestamp;return m<=e?(a(`[CACHE-HIT] Version cache: ${d.data}`),d.data):(a(`Version cache expired: age=${Math.round(m/1e3/60)}min`),null)}catch(u){if(u.code==="ENOENT")return a("No version cache found"),null;let d=l+1;a(`Attempt ${d} failed to read version cache: ${u.message}. Retrying...`),await setTimeout(75);}}return a("Failed to read version cache after 3 attempts."),null}static async setVersionCache(e){let t="claude-version.lock";if(!await this.acquireLock(t)){a("Could not acquire lock to set version cache");return}try{await this.ensureCacheDirectories();let s=C.join(this.VERSION_CACHE_DIR,"claude-version.json"),r={data:e,timestamp:Date.now()},o=JSON.stringify(r);await y.promises.writeFile(s,o,"utf-8"),a(`[CACHE-SET] Version cache stored: ${e}`);}catch(s){a("Failed to save version cache:",s);}finally{await this.releaseLock(t);}}};var k=promisify(exec),A=class{isGitRepo(e){try{return y.existsSync(C.join(e,".git"))}catch{return false}}async getGitInfo(e,t={},n){let s=n&&this.isGitRepo(n)?n:e;if(!this.isGitRepo(s))return null;let r=await _.getGitCache(s);if(r)return a(`[CACHE-HIT] Git disk cache: ${s}`),r;try{let o=await this.getStatusWithBranchAsync(s),l=await this.getAheadBehindAsync(s),c={branch:o.branch||"detached",status:o.status,ahead:l.ahead,behind:l.behind};t.showWorkingTree&&o.workingTree&&(c.staged=o.workingTree.staged,c.unstaged=o.workingTree.unstaged,c.untracked=o.workingTree.untracked,c.conflicts=o.workingTree.conflicts);let u={},d={};t.showSha&&(u.sha=this.getShaAsync(s)),t.showTag&&(u.tag=this.getNearestTagAsync(s)),t.showTimeSinceCommit&&(u.timeSinceCommit=this.getTimeSinceLastCommitAsync(s)),t.showStashCount&&(d.stashCount=this.getStashCountAsync(s)),t.showUpstream&&(d.upstream=this.getUpstreamAsync(s)),t.showRepoName&&(d.repoName=this.getRepoNameAsync(s));let m=new Map;for(let[g,f]of Object.entries(u))try{let h=await f;m.set(g,h);}catch{}return Object.keys(d).length>0&&(await Promise.allSettled(Object.entries(d).map(async([f,h])=>({key:f,value:await h})))).forEach(f=>{f.status==="fulfilled"&&m.set(f.value.key,f.value.value);}),t.showSha&&(c.sha=m.get("sha")||void 0),t.showOperation&&(c.operation=this.getOngoingOperation(s)||void 0),t.showTag&&(c.tag=m.get("tag")||void 0),t.showTimeSinceCommit&&(c.timeSinceCommit=m.get("timeSinceCommit")||void 0),t.showStashCount&&(c.stashCount=m.get("stashCount")||0),t.showUpstream&&(c.upstream=m.get("upstream")||void 0),t.showRepoName&&(c.repoName=m.get("repoName")||void 0,c.isWorktree=this.isWorktree(s)),await _.setGitCache(s,c),a(`[CACHE-SET] Git disk cache stored: ${s}`),_.cleanupOldCache().catch(()=>{}),c}catch{return null}}async getShaAsync(e){try{return (await k("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 k("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getTimeSinceLastCommitAsync(e){try{let n=(await k("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!n)return null;let s=parseInt(n)*1e3,r=Date.now();return Math.floor((r-s)/1e3)}catch{return null}}async getStashCountAsync(e){try{let n=(await k("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.split(`
|
|
5
|
-
`).length:0}catch{return 0}}async getUpstreamAsync(e){try{return (await
|
|
6
|
-
`),r=null,o="clean",l=0,c=0,u=0,d=0;for(let m of s)if(m){if(m.startsWith("## ")){let f=m.substring(3).split("...")[0];f&&f!=="HEAD (no branch)"&&(r=f);continue}if(m.length>=2){let g=m.charAt(0),f=m.charAt(1);if(g==="?"&&f==="?"){u++,o==="clean"&&(o="dirty");continue}let h=g+f;if(["DD","AU","UD","UA","DU","AA","UU"].includes(h)){d++,o="conflicts";continue}g!==" "&&g!=="?"&&(l++,o==="clean"&&(o="dirty")),f!==" "&&f!=="?"&&(c++,o==="clean"&&(o="dirty"));}}return {branch:r||await this.getFallbackBranch(e),status:o,workingTree:{staged:l,unstaged:c,untracked:u,conflicts:d}}}catch(t){return a(`Git status with branch command failed in ${e}:`,t),{branch:await this.getFallbackBranch(e),status:"clean"}}}async getFallbackBranch(e){try{let n=(await k("git branch --show-current",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{try{let n=(await k("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{a(`[GIT-EXEC] Running git ahead/behind in ${e}`);let[t,n]=await Promise.all([k("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:2e3}),k("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 a(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}};var Je=promisify(exec),U=class{async getSessionId(){try{if(!process.env.TMUX_PANE)return a("TMUX_PANE not set, not in tmux session"),null;a(`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 a(`Tmux session ID: ${t||"empty"}`),t||null}catch(e){return a("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};var K={"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}},P=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},s=>{if(s.statusCode!==200){a(`HTTP ${s.statusCode}: ${s.statusMessage}`),e(null);return}let r="",o=0,l=1024*1024;s.on("data",c=>{if(o+=c.length,o>l){a("Response too large"),n.destroy(),e(null);return}r+=c;}),s.on("end",()=>{try{let u=JSON.parse(r),d=u._meta,m={};for(let[g,f]of Object.entries(u))g!=="_meta"&&(m[g]=f);this.validatePricingData(m)?(a(`Fetched fresh pricing from GitHub for ${Object.keys(m).length} models`),a(`Pricing last updated: ${d?.updated||"unknown"}`),e(m)):(a("Invalid pricing data structure"),e(null));}catch(c){a("Failed to parse JSON:",c),e(null);}}),s.on("error",c=>{a("Response error:",c),e(null);});});n.on("error",s=>{a("Request error:",s),e(null);}),n.on("timeout",()=>{a("Request timeout"),n.destroy(),e(null);}),n.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return a(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return a(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,a(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),a(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,a(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(a(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(K).length} models`),this.executionCache=K,a(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(K).length} models`),K)}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 a(`[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),a(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[r,o]of Object.entries(t))if(r.toLowerCase()===n)return o;let s=[{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:r,fallback:o}of s)if(r.some(l=>n.includes(l))&&t[o])return t[o];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 s=this.extractModelId(e),r=await this.getModelPricing(s),o=n.input_tokens||0,l=n.output_tokens||0,c=n.cache_creation_input_tokens||0,u=n.cache_read_input_tokens||0,d=o/1e6*r.input,m=l/1e6*r.output,g=u/1e6*r.cache_read,f=c/1e6*r.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 ze(i){return {timestamp:i.timestamp.toISOString(),message:{usage:{input_tokens:i.message?.usage?.input_tokens||0,output_tokens:i.message?.usage?.output_tokens||0,cache_creation_input_tokens:i.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:i.message?.usage?.cache_read_input_tokens}},costUSD:i.costUSD}}var Z=class{async getSessionUsage(e){try{let t=await X(e);if(!t)return a(`No transcript found for session: ${e}`),null;a(`Found transcript at: ${t}`);let n=await I(t);if(n.length===0)return {totalCost:0,entries:[]};let s=[],r=0;for(let o of n)if(o.message?.usage){let l=ze(o);if(l.costUSD!==void 0)r+=l.costUSD;else {let c=await P.calculateCostForEntry(o.raw);l.costUSD=c,r+=c;}s.push(l);}return a(`Parsed ${s.length} usage entries, total cost: $${r.toFixed(4)}`),{totalCost:r,entries:s}}catch(t){return a(`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),s=n.input+n.output+n.cacheCreation+n.cacheRead;return {cost:t.totalCost,tokens:s,tokenBreakdown:n}}},L=class{sessionProvider=new Z;async getUsageInfo(e){try{return a(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e)}}catch(t){return a(`Error getting usage info for session ${e}:`,t),{session:{cost:null,tokens:null,tokenBreakdown:null}}}}};var O=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}getContextLimit(e){return 2e5}async calculateContextTokens(e,t){try{a(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return a("Transcript file is empty"),null}catch{return a("Could not read transcript file"),null}let n=await I(e);if(n.length===0)return a("No entries in transcript"),null;let s=null;for(let r=n.length-1;r>=0;r--){let o=n[r];if(o&&o.message?.usage?.input_tokens&&o.isSidechain!==!0){s=o,a(`Context segment: Found most recent entry at ${o.timestamp.toISOString()}, stopping search`);break}}if(s?.message?.usage){let r=s.message.usage,o=(r.input_tokens||0)+(r.cache_read_input_tokens||0)+(r.cache_creation_input_tokens||0),l=t?this.getContextLimit(t):2e5;a(`Most recent main chain context: ${o} tokens (limit: ${l})`);let c=Math.min(100,Math.max(0,Math.round(o/l*100))),u=Math.round(l*.75),d=Math.min(100,Math.max(0,Math.round(o/u*100))),m=Math.max(0,100-d);return {inputTokens:o,percentage:c,usablePercentage:d,contextLeftPercentage:m,maxTokens:l,usableTokens:u}}return a("No main chain entries with usage data found"),null}catch(n){return a(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}};var N=class{async loadTranscriptEntries(e){try{let t=await X(e);if(!t)return a(`No transcript found for session: ${e}`),[];a(`Loading transcript from: ${t}`);let s=(await readFile(t,"utf-8")).trim().split(`
|
|
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){a(`Failed to parse JSONL line: ${l}`);continue}return a(`Loaded ${r.length} transcript entries`),r}catch(t){return a(`Error loading transcript for ${e}:`,t),[]}}calculateResponseTimes(e){let t=[],n=[],s=-1,r=null,o=null,l=-1;for(let m=0;m<e.length;m++){let g=e[m];if(!(!g||!g.timestamp))try{let f=new Date(g.timestamp),h=g.type||g.message?.role||g.message?.type,b=g.type==="user"&&g.message?.content?.[0]?.type==="tool_result";h==="user"&&!b?(t.push(f),r=f,s=m,o=null,l=-1,a(`Found user message at index ${m}, timestamp ${f.toISOString()}`)):s>=0&&(h==="assistant"||b||h==="system"||g.message?.usage)&&(o=f,l=m,h==="assistant"||g.message?.usage?(n.push(f),a(`Found assistant message at index ${m}, timestamp ${f.toISOString()}`)):b?a(`Found tool result at index ${m}, timestamp ${f.toISOString()}`):a(`Found ${h} message at index ${m}, timestamp ${f.toISOString()}`));}catch{continue}}if(t.length===0||n.length===0)return {average:null,last:null};let c=[];for(let m of n){let g=t.filter(f=>f<m);if(g.length>0){let f=new Date(Math.max(...g.map(b=>b.getTime()))),h=(m.getTime()-f.getTime())/1e3;h>.1&&h<300?(c.push(h),a(`Valid response time: ${h.toFixed(1)}s`)):a(`Rejected response time: ${h.toFixed(1)}s (outside 0.1s-5m range)`);}}let u=null;if(r&&o&&l>s){let m=o.getTime()-r.getTime(),g=l-s;m===0&&g>0?(u=g*.1,a(`Estimated last response time from position difference: ${u.toFixed(2)}s (${g} messages)`)):m>0&&(u=m/1e3,a(`Last response time from timestamps: ${u.toFixed(2)}s`)),a(`Last user message at index ${s}, timestamp ${r.toISOString()}`),a(`Last response end at index ${l}, timestamp ${o.toISOString()}`);}if(c.length===0&&u===null)return {average:null,last:null};let d=c.length>0?c.reduce((m,g)=>m+g,0)/c.length:null;return a(`Calculated average response time: ${d?.toFixed(2)||"null"}s from ${c.length} measurements`),a(`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}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 getMetricsInfo(e){try{a(`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};let n=this.calculateResponseTimes(t),s=this.calculateSessionDuration(t),r=this.calculateMessageCount(t);return a(`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}}catch(t){return a(`Error calculating metrics for session ${e}:`,t),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null}}}};var tt=promisify(exec),j=class{async getClaudeVersion(){let t=await _.getVersionCache(18e5);if(t)return t;try{let s=(await tt("claude --version",{encoding:"utf8",timeout:1e3})).stdout.trim(),r=s.match(/^([\d.]+)/);if(r){let o=`v${r[1]}`;return a(`Claude Code version: ${o}`),await _.setVersionCache(o),o}return a(`Could not parse version from: ${s}`),null}catch(n){return a("Error getting Claude Code version:",n),null}}async getVersionInfo(){return {version:await this.getClaudeVersion()}}};function B(i){return i===null?"$0.00":i<.01?"<$0.01":`$${i.toFixed(2)}`}function x(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 _e(i){if(!i)return "0 tokens";let e=[];if(i.input>0&&e.push(`${x(i.input).replace(" tokens","")}in`),i.output>0&&e.push(`${x(i.output).replace(" tokens","")}out`),i.cacheCreation>0||i.cacheRead>0){let t=i.cacheCreation+i.cacheRead;e.push(`${x(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function Se(i){return i<60?`${i}s`:i<3600?`${Math.floor(i/60)}m`:i<86400?`${Math.floor(i/3600)}h`:i<604800?`${Math.floor(i/86400)}d`:`${Math.floor(i/604800)}w`}function ke(i){return i<60?`${i.toFixed(0)}s`:i<3600?`${(i/60).toFixed(0)}m`:i<86400?`${(i/3600).toFixed(1)}h`:`${(i/86400).toFixed(1)}d`}function nt(i,e){return !e||e<=0||i<0?null:Math.min(100,i/e*100)}function Te(i,e,t=80){let n=nt(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 H=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,c=r;return o&&(s.startsWith(o)&&(l=s.replace(o,"~")),r&&r.startsWith(o)&&(c=r.replace(o,"~"))),{text:this.getDisplayDirectoryName(l,c),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=Se(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}}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=ke(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),m=e.timeRemaining%60;return d>0?`${d}h ${m}m`:`${m}m`})():null,c;switch(r){case "cost":c=B(e.cost);break;case "tokens":c=x(e.tokens);break;case "both":c=`${B(e.cost)} / ${x(e.tokens)}`;break;case "time":c=l||"N/A";break;default:c=B(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?`${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}r==="time"?s=c:s=l?`${c}${u} (${l} left)`:`${c}${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}}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 B(e);case "tokens":return x(t);case "both":return `${B(e)} (${x(t)})`;case "breakdown":return _e(n);default:return B(e)}}formatUsageWithBudget(e,t,n,s,r,o=80){let l=this.formatUsageDisplay(e,t,n,s);if(r&&r>0&&e!==null){let c=Te(e,r,o);return l+c.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 st(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 ee=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,c)=>l.timestamp.getTime()-c.timestamp.getTime()),r=null,o=[];for(let l of s){let c=l.timestamp;if(r==null)r=this.floorToHour(c),o=[l];else {let u=c.getTime()-r.getTime(),d=o[o.length-1];if(d==null)continue;let m=d.timestamp,g=c.getTime()-m.getTime();u>t||g>t?(n.push(o),r=this.floorToHour(c),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,c=n.getTime()-l.getTime()<s&&n<r;return {block:t,isActive:c}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let 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(){try{a("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await z(void 0,(c,u)=>u>=e,!0),s=[];for(let c of n)if(c.message?.usage){let u=st(c);!u.costUSD&&c.raw&&(u.costUSD=await P.calculateCostForEntry(c.raw)),s.push(u);}let r=this.identifySessionBlocks(s);a(`Block segment: Found ${r.length} session blocks`);let o=this.findActiveBlock(r),l=[];if(o&&o.length>0){a(`Block segment: Found active block with ${o.length} entries`);let c=o[0],u=o[o.length-1];c&&u&&a(`Block segment: Active block from ${c.timestamp.toISOString()} to ${u.timestamp.toISOString()}`),l=o;}else a("Block segment: No active block found"),l=[];return l}catch(e){return a("Error loading block entries:",e),[]}}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return a("Block segment: No entries in current block"),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((c,u)=>c+u.costUSD,0),n=e.reduce((c,u)=>c+u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,0),s=new Date,r=null;if(e.length>0){let c=e[0];if(c){let u=this.sessionDurationHours*60*60*1e3,d=this.floorToHour(c.timestamp),m=new Date(d.getTime()+u);r=Math.max(0,Math.round((m.getTime()-s.getTime())/(1e3*60)));}}let o=null,l=null;if(e.length>=1&&(t>0||n>0)){let c=e.map(m=>m.timestamp).sort((m,g)=>m.getTime()-g.getTime()),u=c[0],d=c[c.length-1];if(u&&d){let m=(d.getTime()-u.getTime())/6e4;m>0&&(t>0&&(o=t/m*60),n>0&&(l=n/m*60));}}return a(`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 a("Error getting active block info:",e),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function G(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 rt(i){return i.inputTokens+i.outputTokens+i.cacheCreationInputTokens+i.cacheReadInputTokens}function ot(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 te=class{async loadTodayEntries(){let t=G(new Date);a(`Today segment: Loading entries for date ${t}`);let n=await _.getLatestTranscriptMtime(),s=await _.getUsageCache("today",n);if(s)return a("Using shared today usage cache"),s;let r=new Date;r.setDate(r.getDate()-1),r.setHours(0,0,0,0);let o=(g,f)=>f>=r,l=new Date;l.setHours(0,0,0,0);let u=await z(g=>g.timestamp>=l,o,true),d=[],m=0;for(let g of u)if(G(g.timestamp)===t&&g.message?.usage){let h=ot(g);!h.costUSD&&g.raw&&(h.costUSD=await P.calculateCostForEntry(g.raw)),d.push(h),m++;}return a(`Today segment: Found ${m} entries for today (${t})`),await _.setUsageCache("today",d,n),d}async getTodayEntries(){try{return await this.loadTodayEntries()}catch(e){return a("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:G(new Date)};let t=e.reduce((r,o)=>r+o.costUSD,0),n=e.reduce((r,o)=>r+rt(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 a(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:s,date:G(new Date)}}catch(e){return a("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:G(new Date)}}}};var V="\x1B[0m",p={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_burn:"\u27E2",version:"\u25C8"};var ne=class{constructor(e){this.config=e;this.symbols=this.initializeSymbols();}symbols;_usageProvider;_blockProvider;_todayProvider;_contextProvider;_gitService;_tmuxService;_metricsProvider;_versionProvider;_segmentRenderer;get usageProvider(){return this._usageProvider||(this._usageProvider=new L),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new ee),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new te),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new O),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new A),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new U),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new N),this._metricsProvider}get versionProvider(){return this._versionProvider||(this._versionProvider=new j),this._versionProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new H(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,s=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,r=this.needsSegmentInfo("context")?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,o=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id):null,l=this.needsSegmentInfo("version")?await this.versionProvider.getVersionInfo():null;return (await Promise.all(this.config.display.lines.map(u=>this.renderLine(u,e,t,n,s,r,o,l)))).filter(u=>u.length>0).join(`
|
|
8
|
-
`)}async renderLine(e,t,n,s,r,o,l
|
|
2
|
+
import w from'process';import b,{join,posix}from'path';import y,{existsSync,readFileSync,createReadStream}from'fs';import {exec,execSync}from'child_process';import B,{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 re(i,e){if(e&&(i.toLowerCase()==="transparent"||i.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(i.slice(1,3),16),n=parseInt(i.slice(3,5),16),s=parseInt(i.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${n};${s}m`}function oe(i){let e=i.match(/48;2;(\d+);(\d+);(\d+)/);return e?`\x1B[38;2;${e[1]};${e[2]};${e[3]}m`:i.replace("48","38")}var me={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:me,light:de,nord:fe,"tokyo-night":he,"rose-pine":pe};function W(i){return Re[i]||null}var c=(i,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${i}`,...e);};function Y(){let i=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let n=t.trim();existsSync(n)&&i.push(n);}),i.length===0){let t=homedir(),n=join(t,".config","claude"),s=join(t,".claude");existsSync(n)?i.push(n):existsSync(s)&&i.push(s);}return i}async function V(i){let e=[];for(let t of i){let n=join(t,"projects");if(existsSync(n))try{let s=await readdir(n,{withFileTypes:!0});for(let r of s)if(r.isDirectory()){let o=posix.join(n,r.name);e.push(o);}}catch(s){c(`Failed to read projects directory ${n}:`,s);}}return e}async function J(i){let e=Y(),t=await V(e);for(let n of t){let s=posix.join(n,`${i}.jsonl`);if(existsSync(s))return s}return null}async function Me(i){try{let t=(await readFile(i,"utf-8")).trim().split(`
|
|
3
|
+
`),n=null;for(let s of t)if(s.trim())try{let r=JSON.parse(s);if(r.timestamp&&typeof r.timestamp=="string"){let o=new Date(r.timestamp);isNaN(o.getTime())||(n===null||o<n)&&(n=o);}}catch{continue}return n}catch(e){return c(`Failed to get earliest timestamp for ${i}:`,e),null}}async function Ue(i,e=true){return (await Promise.all(i.map(async n=>({file:n,timestamp:await Me(n)})))).sort((n,s)=>n.timestamp===null&&s.timestamp===null?0:n.timestamp===null?1:s.timestamp===null?-1:(e?1:-1)*(n.timestamp.getTime()-s.timestamp.getTime())).map(n=>n.file)}async function ce(i){try{return (await stat(i)).mtime}catch{return null}}function Ae(i){let e=i.message?.id||(typeof i.raw.message=="object"&&i.raw.message!==null&&"id"in i.raw.message?i.raw.message.id:void 0),t="requestId"in i.raw?i.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var Ie=1024*1024;async function F(i){try{let t=(await stat(i)).size,n;return t>Ie?(c(`Using streaming parser for large file ${i} (${Math.round(t/1024)}KB)`),n=await Oe(i)):n=await Le(i),c(`Parsed ${n.length} entries from ${i}`),n}catch(e){return c(`Failed to read file ${i}:`,e),[]}}async function Le(i){let t=(await readFile(i,"utf-8")).trim().split(`
|
|
4
|
+
`).filter(s=>s.trim()),n=[];for(let s of t)try{let r=JSON.parse(s);if(!r.timestamp)continue;let o={timestamp:new Date(r.timestamp),message:r.message,costUSD:typeof r.costUSD=="number"?r.costUSD:void 0,isSidechain:r.isSidechain===!0,raw:r};n.push(o);}catch(r){c(`Failed to parse JSONL line: ${r}`);continue}return n}async function Oe(i){return new Promise((e,t)=>{let n=[],s=createReadStream(i,{encoding:"utf8"}),r=createInterface({input:s,crlfDelay:1/0});r.on("line",o=>{let l=o.trim();if(l)try{let a=JSON.parse(l);if(!a.timestamp)return;let g={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(g);}catch(a){c(`Failed to parse JSONL line: ${a}`);}}),r.on("close",()=>{e(n);}),r.on("error",o=>{c(`Streaming parser error for ${i}:`,o),t(o);}),s.on("error",o=>{c(`File stream error for ${i}:`,o),t(o);});})}async function q(i,e,t=false){let n=Y(),s=await V(n),r=new Set,o=s.map(async m=>{try{let C=(await readdir(m)).filter(S=>S.endsWith(".jsonl")).map(async S=>{let se=posix.join(m,S);if(existsSync(se)){let ve=await ce(se);return {filePath:se,mtime:ve}}return null});return (await Promise.all(C)).filter(S=>S?.mtime&&(!e||e(S.filePath,S.mtime)))}catch(f){return c(`Failed to read project directory ${m}:`,f),[]}}),a=(await Promise.all(o)).flat().filter(m=>m!==null).map(m=>m.filePath);if(t){let m=await Ue(a,false);a.length=0,a.push(...m);}let g=[],d=a.map(async m=>(await F(m)).filter(h=>{let C=Ae(h);return C&&r.has(C)?false:(C&&r.add(C),!i||i(h))})),u=await Promise.all(d);for(let m of u)g.push(...m);return g}var _=class{static CACHE_DIR=b.join(homedir(),".claude","powerline");static GIT_CACHE_DIR=b.join(this.CACHE_DIR,"git");static USAGE_CACHE_DIR=b.join(this.CACHE_DIR,"usage");static LOCKS_DIR=b.join(this.CACHE_DIR,"locks");static isLocked(e){let t=b.join(this.LOCKS_DIR,e);return y.existsSync(t)}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let r=b.join(this.LOCKS_DIR,e),o=Date.now(),l=String(process.pid);for(;Date.now()-o<t;)try{return await y.promises.writeFile(r,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=b.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=b.join(e,".git"),n=b.join(t,"index"),s=b.join(t,"HEAD"),r=0;try{let o=await y.promises.stat(n);r=Math.max(r,o.mtime.getTime());}catch{}try{let o=await y.promises.stat(s);r=Math.max(r,o.mtime.getTime());}catch{}try{let o=await y.promises.stat(e);r=Math.max(r,o.mtime.getTime());}catch{}return r}catch(t){return c(`Failed to get git repo mod time for ${e}:`,t),Date.now()}}static async getGitCache(e){let s="utf-8";await this.ensureCacheDirectories();let r=this.createProjectHash(e),o=b.join(this.GIT_CACHE_DIR,`${r}.json`),l=`${r}.git.lock`;for(let a=0;a<3;a++){if(this.isLocked(l)){c(`Cache for git project ${r} is locked, waiting...`),await setTimeout(75);continue}try{let d=await y.promises.readFile(o,s),u=JSON.parse(d),m=await this.getGitRepoModTime(e),f=u.gitModTime||0;return m<=f?(c(`[CACHE-HIT] Git disk cache: ${e}`),u.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 u=a+1;c(`Attempt ${u} 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),s=`${n}.git.lock`;if(!await this.acquireLock(s)){c(`Could not acquire lock to set git cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=b.join(this.GIT_CACHE_DIR,`${n}.json`),o=await this.getGitRepoModTime(e),l={data:t,timestamp:Date.now(),gitModTime:o};await y.promises.writeFile(r,JSON.stringify(l),"utf-8"),c(`[CACHE-SET] Git disk cache stored: ${e}`);}catch(r){c(`Failed to save git cache for ${e}:`,r);}finally{await this.releaseLock(s);}}static async getUsageCache(e,t){let r="utf-8";await this.ensureCacheDirectories();let o=b.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(o,r),u=JSON.parse(d);return !t||u.timestamp>=t?(c(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(u.data)):(c(`${e} cache outdated: cache=${u.timestamp}, latest=${t}`),null)}catch(d){if(d.code==="ENOENT")return c(`No shared ${e} usage cache found`),null;let u=a+1;c(`Attempt ${u} 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 s=`${e}.usage.lock`;if(!await this.acquireLock(s)){c(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let o=b.join(this.USAGE_CACHE_DIR,`${e}.json`),l=n||Date.now(),g=JSON.stringify({data:t,timestamp:l});await y.promises.writeFile(o,g,"utf-8"),c(`[CACHE-SET] ${e} disk cache stored`);}catch(o){c(`Failed to save ${e} usage cache:`,o);}finally{await this.releaseLock(s);}}static async getLatestTranscriptMtime(){try{let e=Y(),t=await V(e),n=0;for(let s of t)try{let o=(await y.promises.readdir(s)).filter(l=>l.endsWith(".jsonl"));for(let l of o){let a=b.join(s,l),g=await ce(a);g&&g.getTime()>n&&(n=g.getTime());}}catch(r){c(`Failed to read project directory ${s}:`,r);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=b.join(this.CACHE_DIR,".cleanup");try{let s=await y.promises.readFile(n,"utf-8");if(t-parseInt(s)<3600*1e3)return}catch{}try{let s=[this.GIT_CACHE_DIR,this.USAGE_CACHE_DIR];for(let r of s)try{let o=await y.promises.readdir(r);for(let l of o){let a=b.join(r,l),g=await y.promises.stat(a);t-g.mtime.getTime()>e&&(await y.promises.unlink(a),c(`Cleaned up old cache file: ${l}`));}}catch(o){c(`Error cleaning directory ${r}:`,o);}await y.promises.writeFile(n,t.toString()),c("Cache cleanup completed");}catch(s){c("Error during cache cleanup:",s);}}};var T=promisify(exec),U=class{isGitRepo(e){try{return y.existsSync(b.join(e,".git"))}catch{return false}}async getGitInfo(e,t={},n){let s=n&&this.isGitRepo(n)?n:e;if(!this.isGitRepo(s))return null;let r=await _.getGitCache(s);if(r)return c(`[CACHE-HIT] Git disk cache: ${s}`),r;try{let o=await this.getStatusWithBranchAsync(s),l=await this.getAheadBehindAsync(s),a={branch:o.branch||"detached",status:o.status,ahead:l.ahead,behind:l.behind};t.showWorkingTree&&o.workingTree&&(a.staged=o.workingTree.staged,a.unstaged=o.workingTree.unstaged,a.untracked=o.workingTree.untracked,a.conflicts=o.workingTree.conflicts);let g={},d={};t.showSha&&(g.sha=this.getShaAsync(s)),t.showTag&&(g.tag=this.getNearestTagAsync(s)),t.showTimeSinceCommit&&(g.timeSinceCommit=this.getTimeSinceLastCommitAsync(s)),t.showStashCount&&(d.stashCount=this.getStashCountAsync(s)),t.showUpstream&&(d.upstream=this.getUpstreamAsync(s)),t.showRepoName&&(d.repoName=this.getRepoNameAsync(s));let u=new Map;for(let[m,f]of Object.entries(g))try{let h=await f;u.set(m,h);}catch{}return Object.keys(d).length>0&&(await Promise.allSettled(Object.entries(d).map(async([f,h])=>({key:f,value:await h})))).forEach(f=>{f.status==="fulfilled"&&u.set(f.value.key,f.value.value);}),t.showSha&&(a.sha=u.get("sha")||void 0),t.showOperation&&(a.operation=this.getOngoingOperation(s)||void 0),t.showTag&&(a.tag=u.get("tag")||void 0),t.showTimeSinceCommit&&(a.timeSinceCommit=u.get("timeSinceCommit")||void 0),t.showStashCount&&(a.stashCount=u.get("stashCount")||0),t.showUpstream&&(a.upstream=u.get("upstream")||void 0),t.showRepoName&&(a.repoName=u.get("repoName")||void 0,a.isWorktree=this.isWorktree(s)),await _.setGitCache(s,a),c(`[CACHE-SET] Git disk cache stored: ${s}`),_.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=b.join(e,".git");return y.existsSync(b.join(t,"MERGE_HEAD"))?"MERGE":y.existsSync(b.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":y.existsSync(b.join(t,"REVERT_HEAD"))?"REVERT":y.existsSync(b.join(t,"BISECT_LOG"))?"BISECT":y.existsSync(b.join(t,"rebase-merge"))||y.existsSync(b.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 s=parseInt(n)*1e3,r=Date.now();return Math.floor((r-s)/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
|
+
`).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]||b.basename(e):b.basename(e)}catch{return b.basename(e)}}isWorktree(e){try{let t=b.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 s=(await T("git status --porcelain -b",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.split(`
|
|
6
|
+
`),r=null,o="clean",l=0,a=0,g=0,d=0;for(let u of s)if(u){if(u.startsWith("## ")){let f=u.substring(3).split("...")[0];f&&f!=="HEAD (no branch)"&&(r=f);continue}if(u.length>=2){let m=u.charAt(0),f=u.charAt(1);if(m==="?"&&f==="?"){g++,o==="clean"&&(o="dirty");continue}let h=m+f;if(["DD","AU","UD","UA","DU","AA","UU"].includes(h)){d++,o="conflicts";continue}m!==" "&&m!=="?"&&(l++,o==="clean"&&(o="dirty")),f!==" "&&f!=="?"&&(a++,o==="clean"&&(o="dirty"));}}return {branch:r||await this.getFallbackBranch(e),status:o,workingTree:{staged:l,unstaged:a,untracked:g,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 Ve=promisify(exec),A=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 Ve("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}},P=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},s=>{if(s.statusCode!==200){c(`HTTP ${s.statusCode}: ${s.statusMessage}`),e(null);return}let r="",o=0,l=1024*1024;s.on("data",a=>{if(o+=a.length,o>l){c("Response too large"),n.destroy(),e(null);return}r+=a;}),s.on("end",()=>{try{let g=JSON.parse(r),d=g._meta,u={};for(let[m,f]of Object.entries(g))m!=="_meta"&&(u[m]=f);this.validatePricingData(u)?(c(`Fetched fresh pricing from GitHub for ${Object.keys(u).length} models`),c(`Pricing last updated: ${d?.updated||"unknown"}`),e(u)):(c("Invalid pricing data structure"),e(null));}catch(a){c("Failed to parse JSON:",a),e(null);}}),s.on("error",a=>{c("Response error:",a),e(null);});});n.on("error",s=>{c("Request error:",s),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[r,o]of Object.entries(t))if(r.toLowerCase()===n)return o;let s=[{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:r,fallback:o}of s)if(r.some(l=>n.includes(l))&&t[o])return t[o];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 s=this.extractModelId(e),r=await this.getModelPricing(s),o=n.input_tokens||0,l=n.output_tokens||0,a=n.cache_creation_input_tokens||0,g=n.cache_read_input_tokens||0,d=o/1e6*r.input,u=l/1e6*r.output,m=g/1e6*r.cache_read,f=a/1e6*r.cache_write_5m;return d+u+f+m}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(i){return {timestamp:i.timestamp.toISOString(),message:{usage:{input_tokens:i.message?.usage?.input_tokens||0,output_tokens:i.message?.usage?.output_tokens||0,cache_creation_input_tokens:i.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:i.message?.usage?.cache_read_input_tokens}},costUSD:i.costUSD}}var z=class{async getSessionUsage(e){try{let t=await J(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 s=[],r=0;for(let o of n)if(o.message?.usage){let l=Xe(o);if(l.costUSD!==void 0)r+=l.costUSD;else {let a=await P.calculateCostForEntry(o.raw);l.costUSD=a,r+=a;}s.push(l);}return c(`Parsed ${s.length} usage entries, total cost: $${r.toFixed(4)}`),{totalCost:r,entries:s}}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),s=n.input+n.output+n.cacheCreation+n.cacheRead;return {cost:t.totalCost,tokens:s,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 s=null;for(let r=n.length-1;r>=0;r--){let o=n[r];if(o&&o.message?.usage?.input_tokens&&o.isSidechain!==!0){s=o,c(`Context segment: Found most recent entry at ${o.timestamp.toISOString()}, stopping search`);break}}if(s?.message?.usage){let r=s.message.usage,o=(r.input_tokens||0)+(r.cache_read_input_tokens||0)+(r.cache_creation_input_tokens||0),l=t?this.getContextLimit(t):2e5;c(`Most recent main chain context: ${o} tokens (limit: ${l})`);let a=Math.min(100,Math.max(0,Math.round(o/l*100))),g=Math.round(l*.75),d=Math.min(100,Math.max(0,Math.round(o/g*100))),u=Math.max(0,100-d);return {inputTokens:o,percentage:a,usablePercentage:d,contextLeftPercentage:u,maxTokens:l,usableTokens:g}}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 O=class{async loadTranscriptEntries(e){try{let t=await J(e);if(!t)return c(`No transcript found for session: ${e}`),[];c(`Loading transcript from: ${t}`);let s=(await readFile(t,"utf-8")).trim().split(`
|
|
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 u=0;u<e.length;u++){let m=e[u];if(!(!m||!m.timestamp))try{let f=new Date(m.timestamp),h=m.type||m.message?.role||m.message?.type,C=m.type==="user"&&m.message?.content?.[0]?.type==="tool_result";h==="user"&&!C?(t.push(f),r=f,s=u,o=null,l=-1,c(`Found user message at index ${u}, timestamp ${f.toISOString()}`)):s>=0&&(h==="assistant"||C||h==="system"||m.message?.usage)&&(o=f,l=u,h==="assistant"||m.message?.usage?(n.push(f),c(`Found assistant message at index ${u}, timestamp ${f.toISOString()}`)):C?c(`Found tool result at index ${u}, timestamp ${f.toISOString()}`):c(`Found ${h} message at index ${u}, timestamp ${f.toISOString()}`));}catch{continue}}if(t.length===0||n.length===0)return {average:null,last:null};let a=[];for(let u of n){let m=t.filter(f=>f<u);if(m.length>0){let f=new Date(Math.max(...m.map(C=>C.getTime()))),h=(u.getTime()-f.getTime())/1e3;h>.1&&h<300?(a.push(h),c(`Valid response time: ${h.toFixed(1)}s`)):c(`Rejected response time: ${h.toFixed(1)}s (outside 0.1s-5m range)`);}}let g=null;if(r&&o&&l>s){let u=o.getTime()-r.getTime(),m=l-s;u===0&&m>0?(g=m*.1,c(`Estimated last response time from position difference: ${g.toFixed(2)}s (${m} messages)`)):u>0&&(g=u/1e3,c(`Last response time from timestamps: ${g.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&&g===null)return {average:null,last:null};let d=a.length>0?a.reduce((u,m)=>u+m,0)/a.length:null;return c(`Calculated average response time: ${d?.toFixed(2)||"null"}s from ${a.length} measurements`),c(`Last response time: ${g?.toFixed(2)||"null"}s`),{average:d,last:g}}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}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 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};let n=this.calculateResponseTimes(t),s=this.calculateSessionDuration(t),r=this.calculateMessageCount(t);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}}catch(t){return c(`Error calculating metrics for session ${e}:`,t),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null}}}};function v(i){return i===null?"$0.00":i<.01?"<$0.01":`$${i.toFixed(2)}`}function x(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 we(i){if(!i)return "0 tokens";let e=[];if(i.input>0&&e.push(`${x(i.input).replace(" tokens","")}in`),i.output>0&&e.push(`${x(i.output).replace(" tokens","")}out`),i.cacheCreation>0||i.cacheRead>0){let t=i.cacheCreation+i.cacheRead;e.push(`${x(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function Se(i){return i<60?`${i}s`:i<3600?`${Math.floor(i/60)}m`:i<86400?`${Math.floor(i/3600)}h`:i<604800?`${Math.floor(i/86400)}d`:`${Math.floor(i/604800)}w`}function _e(i){return i<60?`${i.toFixed(0)}s`:i<3600?`${(i/60).toFixed(0)}m`:i<86400?`${(i/3600).toFixed(1)}h`:`${(i/86400).toFixed(1)}d`}function Ze(i,e){return !e||e<=0||i<0?null:Math.min(100,i/e*100)}function ke(i,e,t=80){let n=Ze(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 j=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:b.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=Se(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}}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=_e(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),u=e.timeRemaining%60;return d>0?`${d}h ${u}m`:`${u}m`})():null,a;switch(r){case "cost":a=v(e.cost);break;case "tokens":a=x(e.tokens);break;case "both":a=`${v(e.cost)} / ${x(e.tokens)}`;break;case "time":a=l||"N/A";break;default:a=v(e.cost);}let g="";if(o&&o!=="none")switch(o){case "cost":g=` | ${e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A"}`;break;case "tokens":g=` | ${e.tokenBurnRate!==null?`${x(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let m=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";g=` | ${m} / ${f}`;break}r==="time"?s=a:s=l?`${a}${g} (${l} left)`:`${a}${g}`;}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}}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,s){switch(s){case "cost":return v(e);case "tokens":return x(t);case "both":return `${v(e)} (${x(t)})`;case "breakdown":return we(n);default:return v(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=ke(e,r,o);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(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 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=[],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 g=a.getTime()-r.getTime(),d=o[o.length-1];if(d==null)continue;let u=d.timestamp,m=a.getTime()-u.getTime();g>t||m>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(){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,g)=>g>=e,!0),s=[];for(let a of n)if(a.message?.usage){let g=Qe(a);!g.costUSD&&a.raw&&(g.costUSD=await P.calculateCostForEntry(a.raw)),s.push(g);}let r=this.identifySessionBlocks(s);c(`Block segment: Found ${r.length} session blocks`);let o=this.findActiveBlock(r),l=[];if(o&&o.length>0){c(`Block segment: Found active block with ${o.length} entries`);let a=o[0],g=o[o.length-1];a&&g&&c(`Block segment: Active block from ${a.timestamp.toISOString()} to ${g.timestamp.toISOString()}`),l=o;}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,g)=>a+g.costUSD,0),n=e.reduce((a,g)=>a+g.usage.inputTokens+g.usage.outputTokens+g.usage.cacheCreationInputTokens+g.usage.cacheReadInputTokens,0),s=new Date,r=null;if(e.length>0){let a=e[0];if(a){let g=this.sessionDurationHours*60*60*1e3,d=this.floorToHour(a.timestamp),u=new Date(d.getTime()+g);r=Math.max(0,Math.round((u.getTime()-s.getTime())/(1e3*60)));}}let o=null,l=null;if(e.length>=1&&(t>0||n>0)){let a=e.map(u=>u.timestamp).sort((u,m)=>u.getTime()-m.getTime()),g=a[0],d=a[a.length-1];if(g&&d){let u=(d.getTime()-g.getTime())/6e4;u>0&&(t>0&&(o=t/u*60),n>0&&(l=n/u*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 N(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 et(i){return i.inputTokens+i.outputTokens+i.cacheCreationInputTokens+i.cacheReadInputTokens}function tt(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{async loadTodayEntries(){let t=N(new Date);c(`Today segment: Loading entries for date ${t}`);let n=await _.getLatestTranscriptMtime(),s=await _.getUsageCache("today",n);if(s)return c("Using shared today usage cache"),s;let r=new Date;r.setDate(r.getDate()-1),r.setHours(0,0,0,0);let o=(m,f)=>f>=r,l=new Date;l.setHours(0,0,0,0);let g=await q(m=>m.timestamp>=l,o,true),d=[],u=0;for(let m of g)if(N(m.timestamp)===t&&m.message?.usage){let h=tt(m);!h.costUSD&&m.raw&&(h.costUSD=await P.calculateCostForEntry(m.raw)),d.push(h),u++;}return c(`Today segment: Found ${u} 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((r,o)=>r+o.costUSD,0),n=e.reduce((r,o)=>r+et(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:N(new Date)}}catch(e){return c("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:N(new Date)}}}};var H="\x1B[0m",p={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_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 U),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new A),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new O),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):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,s=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,r=this.needsSegmentInfo("context")?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,o=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id):null;return (await Promise.all(this.config.display.lines.map(a=>this.renderLine(a,e,t,n,s,r,o)))).filter(a=>a.length>0).join(`
|
|
8
|
+
`)}async renderLine(e,t,n,s,r,o,l){let a=this.getThemeColors(),g=t.workspace?.current_dir||t.cwd||"/",d=Object.entries(e.segments).filter(([m,f])=>f?.enabled).map(([m,f])=>({type:m,config:f})),u=a.reset;for(let m=0;m<d.length;m++){let f=d[m];if(!f)continue;let h=m===d.length-1,C=h?null:d[m+1],R=C?this.getSegmentBgColor(C.type,a):"",S=await this.renderSegment(f,t,n,s,r,o,l,a,g);S&&(u+=this.formatSegment(S.bgColor,S.fgColor,S.text,h?void 0:R));}return u}async renderSegment(e,t,n,s,r,o,l,a,g){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,g):e.type==="session"?this.renderSessionSegment(e.config,n,a):e.type==="tmux"?await this.renderTmuxSegment(a):e.type==="context"?this.renderContextSegment(o,a):e.type==="metrics"?this.renderMetricsSegment(e.config,l,s,a):e.type==="block"?this.renderBlockSegment(e.config,s,a):e.type==="today"?this.renderTodaySegment(e.config,r,a):e.type==="version"?this.renderVersionSegment(e.config,t,a):null}async renderGitSegment(e,t,n,s){if(!this.needsSegmentInfo("git"))return null;let r=await this.gitService.getGitInfo(s,{showSha:e?.showSha,showWorkingTree:e?.showWorkingTree,showOperation:e?.showOperation,showTag:e?.showTag,showTimeSinceCommit:e?.showTimeSinceCommit,showStashCount:e?.showStashCount,showUpstream:e?.showUpstream,showRepoName:e?.showRepoName},t.workspace?.project_dir);return r?this.segmentRenderer.renderGit(r,n,e):null}renderSessionSegment(e,t,n){if(!t)return null;let s=e?.type||"cost";return this.segmentRenderer.renderSession(t,n,s)}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,s){return this.segmentRenderer.renderMetrics(t,s,n,e)}renderBlockSegment(e,t,n){return t?this.segmentRenderer.renderBlock(t,n,e):null}renderTodaySegment(e,t,n){if(!t)return null;let s=e?.type||"cost";return this.segmentRenderer.renderToday(t,n,s)}renderVersionSegment(e,t,n){return this.segmentRenderer.renderVersion(t,n,e)}initializeSymbols(){return {right:this.config.display.style==="minimal"?"":p.right,branch:p.branch,model:p.model,git_clean:p.git_clean,git_dirty:p.git_dirty,git_conflicts:p.git_conflicts,git_ahead:p.git_ahead,git_behind:p.git_behind,git_worktree:p.git_worktree,git_tag:p.git_tag,git_sha:p.git_sha,git_upstream:p.git_upstream,git_stash:p.git_stash,git_time:p.git_time,session_cost:p.session_cost,block_cost:p.block_cost,today_cost:p.today_cost,context_time:p.context_time,metrics_response:p.metrics_response,metrics_last_response:p.metrics_last_response,metrics_duration:p.metrics_duration,metrics_messages:p.metrics_messages,metrics_burn:p.metrics_burn,version:p.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"),s=C=>{let R=t[C]||n[C];return {bg:re(R.bg,true),fg:re(R.fg,false)}},r=s("directory"),o=s("git"),l=s("model"),a=s("session"),g=s("block"),d=s("today"),u=s("tmux"),m=s("context"),f=s("metrics"),h=s("version");return {reset:H,modeBg:r.bg,modeFg:r.fg,gitBg:o.bg,gitFg:o.fg,modelBg:l.bg,modelFg:l.fg,sessionBg:a.bg,sessionFg:a.fg,blockBg:g.bg,blockFg:g.fg,todayBg:d.bg,todayFg:d.fg,tmuxBg:u.bg,tmuxFg:u.fg,contextBg:m.bg,contextFg:m.fg,metricsBg:f.bg,metricsFg:f.fg,versionBg:h.bg,versionFg:h.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,s){let r=`${e}${t} ${n} `;if(s){let o=oe(e);r+=`${H}${s}${o}${this.symbols.right}`;}else r+=`${H}${oe(e)}${this.symbols.right}${H}`;return r}};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:false,showDuration:true,showMessageCount:true}}}]},budget:{session:{warningThreshold:80},today:{warningThreshold:80,amount:50}}};function ue(i){return ["light","dark","nord","tokyo-night","rose-pine","custom"].includes(i)}function ge(i){return i==="minimal"||i==="powerline"}function ne(i,e){let t={...i};for(let n in e){let s=e[n];if(s!==void 0)if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let r=t[n]||{};t[n]=ne(r,s);}else t[n]=s;}return t}function nt(i,e){return i?y.existsSync(i)?i:null:[...e?[b.join(e,".claude-powerline.json")]:[],b.join(process.cwd(),".claude-powerline.json"),b.join(B.homedir(),".claude","claude-powerline.json"),b.join(B.homedir(),".config","claude-powerline","config.json")].find(y.existsSync)||null}function st(i){try{let e=y.readFileSync(i,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${i}: ${e instanceof Error?e.message:String(e)}`)}}function rt(){let i={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&ue(t)&&(i.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(ge(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&&(i.display=e),i}function ot(){return process.env.CLAUDE_POWERLINE_CONFIG}function it(i){let e={},t={},n=i.find(r=>r.startsWith("--theme="))?.split("=")[1];n&&ue(n)&&(e.theme=n);let s=i.find(r=>r.startsWith("--style="))?.split("=")[1];return s&&(ge(s)?t.style=s:(console.warn(`Invalid display style '${s}' from CLI argument, falling back to 'minimal'`),t.style="minimal")),Object.keys(t).length>0&&(e.display=t),e}function at(i=process.argv,e){let t=JSON.parse(JSON.stringify(Te)),n=i.find(l=>l.startsWith("--config="))?.split("=")[1]||ot(),s=nt(n,e);if(s)try{let l=st(s);t=ne(t,l);}catch(l){console.warn(`Warning: ${l instanceof Error?l.message:String(l)}`);}t.display?.style&&!ge(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 r=rt();t=ne(t,r);let o=it(i);return t=ne(t,o),t}var Ee=at;async function lt(){try{let i=B.platform(),e;if(i==="darwin")e=b.join(B.homedir(),"Library","Fonts");else if(i==="linux")e=b.join(B.homedir(),".local","share","fonts");else if(i==="win32")e=b.join(B.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=b.join(B.tmpdir(),"powerline-fonts"),n=()=>{y.existsSync(t)&&y.rmSync(t,{recursive:!0,force:!0});};w.on("SIGINT",n),w.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:B.tmpdir()}),console.log("Installing fonts...");let s=b.join(t,"install.sh");if(y.existsSync(s))y.chmodSync(s,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(),w.removeListener("SIGINT",n),w.removeListener("SIGTERM",n);}}catch(i){console.error("Error installing fonts:",i instanceof Error?i.message:String(i)),console.log("You can manually install fonts from: https://github.com/powerline/fonts");}}function $e(){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 ut(){try{let i=w.argv.includes("--help")||w.argv.includes("-h");w.argv.includes("--install-fonts")&&(await lt(),w.exit(0)),i&&($e(),w.exit(0)),w.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`),w.exit(1)),
|
|
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`),w.exit(1)),c(`Working directory: ${w.cwd()}`),c("Process args:",w.argv);let t=await json(w.stdin);c("Received hook data:",JSON.stringify(t,null,2)),t||(console.error("Error: No input data received from stdin"),$e(),w.exit(1));let n=t.workspace?.project_dir,s=Ee(w.argv,n),o=await new ee(s).generateStatusline(t);console.log(o);}catch(i){let e=i instanceof Error?i.message:String(i);console.error("Error generating statusline:",e),w.exit(1);}}ut();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owloops/claude-powerline",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.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",
|