@owloops/claude-powerline 1.9.0 → 1.9.2
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 +48 -28
- package/dist/index.js +8 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
|
|
55
55
|
### Usage Tracking
|
|
56
56
|
|
|
57
|
-
- Real-time session costs
|
|
58
|
-
- 5-hour billing window
|
|
59
|
-
-
|
|
57
|
+
- Real-time session costs
|
|
58
|
+
- 5-hour billing window monitoring
|
|
59
|
+
- Daily budget alerts with percentages
|
|
60
60
|
- Token breakdown (input/output/cached)
|
|
61
61
|
|
|
62
62
|
### Git Integration
|
|
@@ -171,8 +171,8 @@ Config files reload automatically and no restart needed.
|
|
|
171
171
|
| `git` | Branch, status, repository info | `showSha`, `showWorkingTree`, `showTag`, `showStashCount`, `showOperation`, `showTimeSinceCommit`, `showUpstream`, `showRepoName` |
|
|
172
172
|
| `model` | Current Claude model | - |
|
|
173
173
|
| `session` | Real-time usage for conversation | `type`: `cost`|`tokens`|`both`|`breakdown` |
|
|
174
|
-
| `block` | 5-hour billing window
|
|
175
|
-
| `today` | Daily
|
|
174
|
+
| `block` | 5-hour billing window usage | `type`, `burnType`: `cost`|`tokens`|`both`|`none` |
|
|
175
|
+
| `today` | Daily usage with budget monitoring | `type` |
|
|
176
176
|
| `context` | Context window usage | - |
|
|
177
177
|
| `tmux` | Tmux session info | - |
|
|
178
178
|
| `metrics` | Performance analytics | `showResponseTime`, `showLastResponseTime`, `showDuration`, `showMessageCount`, `showLinesAdded`, `showLinesRemoved` |
|
|
@@ -281,11 +281,16 @@ Shows context window usage and auto-compact threshold.
|
|
|
281
281
|
|
|
282
282
|
```json
|
|
283
283
|
"context": {
|
|
284
|
-
"enabled": true
|
|
284
|
+
"enabled": true,
|
|
285
|
+
"showPercentageOnly": false
|
|
285
286
|
}
|
|
286
287
|
```
|
|
287
288
|
|
|
288
|
-
**
|
|
289
|
+
**Options:**
|
|
290
|
+
|
|
291
|
+
- `showPercentageOnly`: Show only percentage remaining (default: false)
|
|
292
|
+
|
|
293
|
+
**Display:** `◔ 34,040 (79%)` or `◔ 79%` (percentage only)
|
|
289
294
|
|
|
290
295
|
---
|
|
291
296
|
|
|
@@ -322,13 +327,15 @@ Shows real-time usage for current Claude conversation.
|
|
|
322
327
|
```json
|
|
323
328
|
"session": {
|
|
324
329
|
"enabled": true,
|
|
325
|
-
"type": "tokens"
|
|
330
|
+
"type": "tokens",
|
|
331
|
+
"costSource": "calculated"
|
|
326
332
|
}
|
|
327
333
|
```
|
|
328
334
|
|
|
329
335
|
**Options:**
|
|
330
336
|
|
|
331
337
|
- `type`: Display format - `cost` | `tokens` | `both` | `breakdown`
|
|
338
|
+
- `costSource`: Cost calculation method - `calculated` (ccusage-style) | `official` (hook data)
|
|
332
339
|
|
|
333
340
|
**Symbols:** `§` Session
|
|
334
341
|
|
|
@@ -336,52 +343,65 @@ Shows real-time usage for current Claude conversation.
|
|
|
336
343
|
|
|
337
344
|
#### Block
|
|
338
345
|
|
|
339
|
-
Shows
|
|
346
|
+
Shows usage within current 5-hour billing window (Claude\'s rate limit period).
|
|
340
347
|
|
|
341
348
|
```json
|
|
342
349
|
"block": {
|
|
343
350
|
"enabled": true,
|
|
344
|
-
"type": "
|
|
345
|
-
"burnType": "
|
|
351
|
+
"type": "weighted",
|
|
352
|
+
"burnType": "cost"
|
|
346
353
|
}
|
|
347
354
|
```
|
|
348
355
|
|
|
349
356
|
**Options:**
|
|
350
357
|
|
|
351
|
-
- `type`: Display format - `tokens` | `time`
|
|
352
|
-
- `burnType`: Burn rate display - `tokens` | `none`
|
|
358
|
+
- `type`: Display format - `cost` | `tokens` | `both` | `time` | `weighted`
|
|
359
|
+
- `burnType`: Burn rate display - `cost` | `tokens` | `both` | `none`
|
|
360
|
+
|
|
361
|
+
**Weighted Tokens:** Opus tokens count 5x toward rate limits compared to Sonnet/Haiku tokens
|
|
362
|
+
|
|
363
|
+
**Rate Limit Indicators:** `25%` Normal • `+75%` Moderate (50-79%) • `!85%` Warning (80%+)
|
|
353
364
|
|
|
354
365
|
**Symbols:** `◱` Block
|
|
355
366
|
|
|
367
|
+
> [!TIP]
|
|
368
|
+
> Claude's rate limits consider multiple factors beyond tokens (message count, length, attachments, model). See [Anthropic's usage documentation](https://support.anthropic.com/en/articles/11014257-about-claude-s-max-plan-usage) for details.
|
|
369
|
+
|
|
356
370
|
---
|
|
357
371
|
|
|
358
372
|
#### Today
|
|
359
373
|
|
|
360
|
-
Shows total daily
|
|
374
|
+
Shows total daily usage with budget monitoring.
|
|
361
375
|
|
|
362
376
|
```json
|
|
363
377
|
"today": {
|
|
364
378
|
"enabled": true,
|
|
365
|
-
"type": "
|
|
379
|
+
"type": "cost"
|
|
366
380
|
}
|
|
367
381
|
```
|
|
368
382
|
|
|
369
383
|
**Options:**
|
|
370
384
|
|
|
371
|
-
- `type`: Display format - `tokens` | `breakdown`
|
|
385
|
+
- `type`: Display format - `cost` | `tokens` | `both` | `breakdown`
|
|
372
386
|
|
|
373
387
|
**Symbols:** `☉` Today
|
|
374
388
|
|
|
375
389
|
### Budget Configuration
|
|
376
390
|
|
|
377
|
-
Session cost budget monitoring with percentage indicators.
|
|
378
|
-
|
|
379
391
|
```json
|
|
380
392
|
"budget": {
|
|
381
|
-
"session": { "amount": 10.0, "warningThreshold": 80 }
|
|
393
|
+
"session": { "amount": 10.0, "warningThreshold": 80 },
|
|
394
|
+
"today": { "amount": 25.0, "warningThreshold": 80 },
|
|
395
|
+
"block": { "amount": 15.0, "type": "cost", "warningThreshold": 80 }
|
|
382
396
|
}
|
|
383
397
|
```
|
|
384
398
|
|
|
399
|
+
**Options:**
|
|
400
|
+
|
|
401
|
+
- `amount`: Budget limit (required for percentage display)
|
|
402
|
+
- `type`: Budget type - `cost` (USD) | `tokens` (for token-based limits)
|
|
403
|
+
- `warningThreshold`: Warning threshold percentage (default: 80)
|
|
404
|
+
|
|
385
405
|
**Indicators:** `25%` Normal • `+75%` Moderate (50-79%) • `!85%` Warning (80%+)
|
|
386
406
|
|
|
387
407
|
### Multi-line Layout
|
|
@@ -441,8 +461,8 @@ Create custom themes by defining segment colors.
|
|
|
441
461
|
|
|
442
462
|
## Performance
|
|
443
463
|
|
|
444
|
-
• **~
|
|
445
|
-
• **~
|
|
464
|
+
• **~50ms** default config (`directory`, `git`, `model`, `session`, `today`, `context`)
|
|
465
|
+
• **~190ms** full-featured
|
|
446
466
|
|
|
447
467
|
**Benchmark Tool:**
|
|
448
468
|
|
|
@@ -452,14 +472,14 @@ Create custom themes by defining segment colors.
|
|
|
452
472
|
|-------------|-----------|----------|--------------------------------|
|
|
453
473
|
| `directory` | ~40ms | ✗ | No external commands |
|
|
454
474
|
| `model` | ~40ms | ✗ | Uses hook data |
|
|
455
|
-
| `session` | ~
|
|
475
|
+
| `session` | ~41ms | ✗ | Minimal transcript parsing |
|
|
456
476
|
| `context` | ~40ms | ✗ | Hook data calculation |
|
|
457
477
|
| `metrics` | ~40ms | ✗ | Transcript analysis |
|
|
458
|
-
| `git` | ~
|
|
459
|
-
| `tmux` | ~
|
|
460
|
-
| `block` | ~
|
|
461
|
-
| `today` | ~
|
|
462
|
-
| `version` | ~40ms | ✗ | Uses hook data
|
|
478
|
+
| `git` | ~70ms | ✗ | No caching for fresh data |
|
|
479
|
+
| `tmux` | ~90ms | ✗ | Environment check + command |
|
|
480
|
+
| `block` | ~165ms | ✗ | 5-hour window transcript load |
|
|
481
|
+
| `today` | ~460ms | ~55ms | Full daily transcript load |
|
|
482
|
+
| `version` | ~40ms | ✗ | Uses hook data |
|
|
463
483
|
|
|
464
484
|
• **Tips:** Install globally (`npm install -g`) to avoid npx overhead
|
|
465
485
|
• Disable unused segments
|
|
@@ -513,7 +533,7 @@ See [CONTRIBUTORS.md](CONTRIBUTORS.md) for people who have contributed outside o
|
|
|
513
533
|
|
|
514
534
|
### Library Usage
|
|
515
535
|
|
|
516
|
-
Claude-powerline is designed as a CLI tool for Claude Code statuslines. While the codebase contains reusable components like `PowerlineRenderer`, we currently focus on the CLI use case to keep the project simple and maintainable.
|
|
536
|
+
Claude-powerline is designed as a CLI tool for Claude Code statuslines. While the codebase contains reusable components like `PricingService` and `PowerlineRenderer`, we currently focus on the CLI use case to keep the project simple and maintainable.
|
|
517
537
|
|
|
518
538
|
## License
|
|
519
539
|
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`).length:0}catch{return 0}}async getUpstreamAsync(e){try{return (await
|
|
4
|
-
`),o=null,i="clean",a=0,l=0,
|
|
5
|
-
`),n=null;for(let r of t)if(r.trim())try{let o=JSON.parse(r);if(o.timestamp&&typeof o.timestamp=="string"){let i=new Date(o.timestamp);isNaN(i.getTime())||(n===null||i<n)&&(n=i);}}catch{continue}return n}catch(e){return c(`Failed to get earliest timestamp for ${s}:`,e),null}}async function Ie(s,e=true){return (await Promise.all(s.map(async n=>({file:n,timestamp:await Ae(n)})))).sort((n,r)=>n.timestamp===null&&r.timestamp===null?0:n.timestamp===null?1:r.timestamp===null?-1:(e?1:-1)*(n.timestamp.getTime()-r.timestamp.getTime())).map(n=>n.file)}async function se(s){try{return (await stat(s)).mtime}catch{return null}}function Me(s){let e=s.message?.id||(typeof s.raw.message=="object"&&s.raw.message!==null&&"id"in s.raw.message?s.raw.message.id:void 0),t="requestId"in s.raw?s.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var Le=1024*1024;async function F(s){try{let t=(await stat(s)).size,n;return t>Le?(c(`Using streaming parser for large file ${s} (${Math.round(t/1024)}KB)`),n=await je(s)):n=await Ne(s),c(`Parsed ${n.length} entries from ${s}`),n}catch(e){return c(`Failed to read file ${s}:`,e),[]}}async function Ne(s){let t=(await readFile(s,"utf-8")).trim().split(`
|
|
6
|
-
`).filter(r=>r.trim()),n=[];for(let r of t)try{let o=JSON.parse(r);if(!o.timestamp)continue;let i={timestamp:new Date(o.timestamp),message:o.message,costUSD:typeof o.costUSD=="number"?o.costUSD:void 0,isSidechain:o.isSidechain===!0,raw:o};n.push(i);}catch(o){c(`Failed to parse JSONL line: ${o}`);continue}return n}async function je(s){return new Promise((e,t)=>{let n=[],r=createReadStream(s,{encoding:"utf8"}),o=createInterface({input:r,crlfDelay:1/0});o.on("line",i=>{let a=i.trim();if(a)try{let l=JSON.parse(a);if(!l.timestamp)return;let g={timestamp:new Date(l.timestamp),message:l.message,costUSD:typeof l.costUSD=="number"?l.costUSD:void 0,isSidechain:l.isSidechain===!0,raw:l};n.push(g);}catch(l){c(`Failed to parse JSONL line: ${l}`);}}),o.on("close",()=>{e(n);}),o.on("error",i=>{c(`Streaming parser error for ${s}:`,i),t(i);}),r.on("error",i=>{c(`File stream error for ${s}:`,i),t(i);});})}async function V(s,e,t=false){let n=H(),r=await G(n),o=new Set,i=r.map(async u=>{try{let b=(await readdir(u)).filter(C=>C.endsWith(".jsonl")).map(async C=>{let Z=posix.join(u,C);if(existsSync(Z)){let xe=await se(Z);return {filePath:Z,mtime:xe}}return null});return (await Promise.all(b)).filter(C=>C?.mtime&&(!e||e(C.filePath,C.mtime)))}catch(d){return c(`Failed to read project directory ${u}:`,d),[]}}),l=(await Promise.all(i)).flat().filter(u=>u!==null).map(u=>u.filePath);if(t){let u=await Ie(l,false);l.length=0,l.push(...u);}let g=[],m=l.map(async u=>(await F(u)).filter(y=>{let b=Me(y);return b&&o.has(b)?false:(b&&o.add(b),!s||s(y))})),f=await Promise.all(m);for(let u of f)g.push(...u);return g}function Oe(s){return {timestamp:s.timestamp.toISOString(),message:{usage:{input_tokens:s.message?.usage?.input_tokens||0,output_tokens:s.message?.usage?.output_tokens||0,cache_creation_input_tokens:s.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:s.message?.usage?.cache_read_input_tokens}}}}var Y=class{async getSessionUsage(e){try{let t=await W(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 {entries:[]};let r=[];for(let o of n)if(o.message?.usage){let i=Oe(o);r.push(i);}return c(`Parsed ${r.length} usage entries`),{entries:r}}catch(t){return c(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,n)=>({input:t.input+(n.message.usage.input_tokens||0),output:t.output+(n.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(n.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(n.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e,t){let n=await this.getSessionUsage(e);if(!n||n.entries.length===0)return {cost:null,tokens:null,tokenBreakdown:null};let r=this.calculateTokenBreakdown(n.entries),o=r.input+r.output+r.cacheCreation+r.cacheRead;return {cost:t?.cost?.total_cost_usd??null,tokens:o,tokenBreakdown:r}}},U=class{sessionProvider=new Y;async getUsageInfo(e,t){try{return c(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e,t)}}catch(n){return c(`Error getting usage info for session ${e}:`,n),{session:{cost:null,tokens:null,tokenBreakdown:null}}}}};var A=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}getContextLimit(e){return 2e5}async calculateContextTokens(e,t){try{c(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return c("Transcript file is empty"),null}catch{return c("Could not read transcript file"),null}let n=await F(e);if(n.length===0)return c("No entries in transcript"),null;let r=null;for(let o=n.length-1;o>=0;o--){let i=n[o];if(i&&i.message?.usage?.input_tokens&&i.isSidechain!==!0){r=i,c(`Context segment: Found most recent entry at ${i.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let o=r.message.usage,i=(o.input_tokens||0)+(o.cache_read_input_tokens||0)+(o.cache_creation_input_tokens||0),a=t?this.getContextLimit(t):2e5;c(`Most recent main chain context: ${i} tokens (limit: ${a})`);let l=Math.min(100,Math.max(0,Math.round(i/a*100))),g=Math.round(a*.75),m=Math.min(100,Math.max(0,Math.round(i/g*100))),f=Math.max(0,100-m);return {inputTokens:i,percentage:l,usablePercentage:m,contextLeftPercentage:f,maxTokens:a,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 I=class{async loadTranscriptEntries(e){try{let t=await W(e);if(!t)return c(`No transcript found for session: ${e}`),[];c(`Loading transcript from: ${t}`);let r=(await readFile(t,"utf-8")).trim().split(`
|
|
7
|
-
`).filter(i=>i.trim()),o=[];for(let i of r)try{let a=JSON.parse(i);if(a.isSidechain===!0)continue;o.push(a);}catch(a){c(`Failed to parse JSONL line: ${a}`);continue}return c(`Loaded ${o.length} transcript entries`),o}catch(t){return c(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,r=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!r}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let o of t)if(o.timestamp)try{let i=new Date(o.timestamp),a=o.type||o.message?.role||o.message?.type,l=o.type==="user"&&o.message?.content?.[0]?.type==="tool_result";if(a==="user"&&!l)n=i;else if(a==="assistant"&&n){let m=(i.getTime()-n.getTime())/1e3;m>.1&&m<300&&(r=m);}}catch{continue}return r}async getMetricsInfo(e,t){try{if(c(`Getting metrics from hook data for session: ${e}`),!t.cost)return c("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let n=await this.loadTranscriptEntries(e),r=this.calculateMessageCount(n),o=this.calculateLastResponseTime(n);return {responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:o,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed}}catch(n){return c(`Error getting metrics from hook data for session ${e}:`,n),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function _(s){return s===null||s===0?"0 tokens":s>=1e6?`${(s/1e6).toFixed(1)}M tokens`:s>=1e3?`${(s/1e3).toFixed(1)}K tokens`:`${s} tokens`}function ye(s){if(!s)return "0 tokens";let e=[];if(s.input>0&&e.push(`${_(s.input).replace(" tokens","")}in`),s.output>0&&e.push(`${_(s.output).replace(" tokens","")}out`),s.cacheCreation>0||s.cacheRead>0){let t=s.cacheCreation+s.cacheRead;e.push(`${_(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function be(s){return s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:s<86400?`${Math.floor(s/3600)}h`:s<604800?`${Math.floor(s/86400)}d`:`${Math.floor(s/604800)}w`}function Ce(s){return s<60?`${s.toFixed(0)}s`:s<3600?`${(s/60).toFixed(0)}m`:s<86400?`${(s/3600).toFixed(1)}h`:`${(s/86400).toFixed(1)}d`}var M=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let r=e.workspace?.current_dir||e.cwd||"/",o=e.workspace?.project_dir;if(n?.showBasename)return {text:S.basename(r)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let i=process.env.HOME||process.env.USERPROFILE,a=r,l=o;return i&&(r.startsWith(i)&&(a=r.replace(i,"~")),o&&o.startsWith(i)&&(l=o.replace(i,"~"))),{text:this.getDisplayDirectoryName(a,l),bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let r=[];if(n?.showRepoName&&e.repoName&&(r.push(e.repoName),e.isWorktree&&r.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&r.push(`[${e.operation}]`),r.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&r.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&r.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?r.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?r.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&r.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let i=[];e.staged&&e.staged>0&&i.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&i.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&i.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&i.push(`!${e.conflicts}`),i.length>0&&r.push(`(${i.join(" ")})`);}if(n?.showUpstream&&e.upstream&&r.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&r.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=be(e.timeSinceCommit);r.push(`${this.symbols.git_time} ${i}`);}let o=this.symbols.git_clean;return e.status==="conflicts"?o=this.symbols.git_conflicts:e.status==="dirty"&&(o=this.symbols.git_dirty),r.push(o),{text:r.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}renderModel(e,t){let n=e.model?.display_name||"Claude";return {text:`${this.symbols.model} ${n}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n="cost"){let r=this.config.budget?.session;return {text:`${this.symbols.session_cost} ${this.formatUsageWithBudget(e.session.cost,e.session.tokens,e.session.tokenBreakdown,n,r?.amount,r?.warningThreshold||80)}`,bgColor:t.sessionBg,fgColor:t.sessionFg}}renderTmux(e,t){return e?{text:`tmux:${e}`,bgColor:t.tmuxBg,fgColor:t.tmuxFg}:{text:"tmux:none",bgColor:t.tmuxBg,fgColor:t.tmuxFg}}renderContext(e,t){if(!e)return {text:`${this.symbols.context_time} 0 (100%)`,bgColor:t.contextBg,fgColor:t.contextFg};let n=e.inputTokens.toLocaleString(),r=`${e.contextLeftPercentage}%`;return {text:`${this.symbols.context_time} ${n} (${r})`,bgColor:t.contextBg,fgColor:t.contextFg}}renderMetrics(e,t,n,r){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let o=[];if(r?.showLastResponseTime&&e.lastResponseTime!==null){let i=e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;o.push(`${this.symbols.metrics_last_response} ${i}`);}if(r?.showResponseTime!==false&&e.responseTime!==null){let i=e.responseTime<60?`${e.responseTime.toFixed(1)}s`:`${(e.responseTime/60).toFixed(1)}m`;o.push(`${this.symbols.metrics_response} ${i}`);}if(r?.showDuration!==false&&e.sessionDuration!==null){let i=Ce(e.sessionDuration);o.push(`${this.symbols.metrics_duration} ${i}`);}return r?.showMessageCount!==false&&e.messageCount!==null&&o.push(`${this.symbols.metrics_messages} ${e.messageCount}`),r?.showLinesAdded!==false&&e.linesAdded!==null&&e.linesAdded>0&&o.push(`${this.symbols.metrics_lines_added} ${e.linesAdded}`),r?.showLinesRemoved!==false&&e.linesRemoved!==null&&e.linesRemoved>0&&o.push(`${this.symbols.metrics_lines_removed} ${e.linesRemoved}`),o.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:o.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,n){let r;if(e.tokens===null)r="No active block";else {let o=n?.type||"tokens",i=n?.burnType,a=e.timeRemaining!==null?(()=>{let m=Math.floor(e.timeRemaining/60),f=e.timeRemaining%60;return m>0?`${m}h ${f}m`:`${f}m`})():null,l;switch(o){case "tokens":l=_(e.tokens);break;case "time":l=a||"N/A";break;default:l=_(e.tokens);}let g="";if(i&&i!=="none")switch(i){case "tokens":g=` | ${e.tokenBurnRate!==null?`${_(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break}o==="time"?r=l:r=a?`${l}${g} (${a} left)`:`${l}${g}`;}return {text:`${this.symbols.block_cost} ${r}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="tokens"){return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(null,e.tokens,e.tokenBreakdown,n,void 0,void 0)}`,bgColor:t.todayBg,fgColor:t.todayFg}}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||S.basename(t)||"project":S.basename(e)||"root":S.basename(e)||"root"}formatUsageDisplay(e,t,n,r){switch(r){case "cost":return e!==null?`$${e.toFixed(2)}`:"No cost data";case "tokens":return _(t);case "both":return e!==null?`$${e.toFixed(2)} (${_(t)})`:_(t);case "breakdown":return ye(n);default:return _(t)}}formatUsageWithBudget(e,t,n,r,o,i=80){let a=this.formatUsageDisplay(e,t,n,r);if(o&&o>0&&e!==null&&(r==="cost"||r==="both")){let l=Math.min(100,e/o*100),g=l>=i,m=`${l.toFixed(0)}%`,f="";return g?f=` !${m}`:l>=50?f=` +${m}`:f=` ${m}`,a+f}return a}renderVersion(e,t,n){return e.version?{text:`${this.symbols.version} v${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}:null}};function We(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},model:s.message?.model||"unknown"}}var q=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],r=[...e].sort((a,l)=>a.timestamp.getTime()-l.timestamp.getTime()),o=null,i=[];for(let a of r){let l=a.timestamp;if(o==null)o=this.floorToHour(l),i=[a];else {let g=l.getTime()-o.getTime(),m=i[i.length-1];if(m==null)continue;let f=m.timestamp,u=l.getTime()-f.getTime();g>t||u>t?(n.push(i),o=this.floorToHour(l),i=[a]):i.push(a);}}return o!=null&&i.length>0&&n.push(i),n}createBlockInfo(e,t){let n=new Date,r=this.sessionDurationHours*60*60*1e3,o=new Date(e.getTime()+r),i=t[t.length-1],a=i!=null?i.timestamp:e,l=n.getTime()-a.getTime()<r&&n<o;return {block:t,isActive:l}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let r=n[0];if(!r)continue;let o=this.floorToHour(r.timestamp),i=this.createBlockInfo(o,n);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{c("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await V(void 0,(l,g)=>g>=e,!0),r=[];for(let l of n)if(l.message?.usage){let g=We(l);r.push(g);}let o=this.identifySessionBlocks(r);c(`Block segment: Found ${o.length} session blocks`);let i=this.findActiveBlock(o),a=[];if(i&&i.length>0){c(`Block segment: Found active block with ${i.length} entries`);let l=i[0],g=i[i.length-1];l&&g&&c(`Block segment: Active block from ${l.timestamp.toISOString()} to ${g.timestamp.toISOString()}`),a=i;}else c("Block segment: No active block found"),a=[];return a}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"),{tokens:null,timeRemaining:null,tokenBurnRate:null};let t=e.reduce((i,a)=>i+a.usage.inputTokens+a.usage.outputTokens+a.usage.cacheCreationInputTokens+a.usage.cacheReadInputTokens,0),n=new Date,r=null;if(e.length>0){let i=e[0];if(i){let a=this.sessionDurationHours*60*60*1e3,l=this.floorToHour(i.timestamp),g=new Date(l.getTime()+a);r=Math.max(0,Math.round((g.getTime()-n.getTime())/(1e3*60)));}}let o=null;if(e.length>=1&&t>0){let i=e.map(g=>g.timestamp).sort((g,m)=>g.getTime()-m.getTime()),a=i[0],l=i[i.length-1];if(a&&l){let g=(l.getTime()-a.getTime())/6e4;g>0&&t>0&&(o=t/g*60);}}return c(`Block segment: ${t} tokens, ${r}m remaining, token burn rate: ${o?o.toFixed(0)+" tokens/hr":"N/A"}`),{tokens:t,timeRemaining:r,tokenBurnRate:o}}catch(e){return c("Error getting active block info:",e),{tokens:null,timeRemaining:null,tokenBurnRate:null}}}};var P=class{static CACHE_DIR=S.join(homedir(),".claude","powerline");static USAGE_CACHE_DIR=S.join(this.CACHE_DIR,"usage");static LOCKS_DIR=S.join(this.CACHE_DIR,"locks");static isLocked(e){let t=S.join(this.LOCKS_DIR,e);if(!w.existsSync(t))return false;try{let n=w.readFileSync(t,"utf-8"),r=parseInt(n.trim(),10);if(isNaN(r))return c(`Invalid PID in lock file ${e}, removing stale lock`),w.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(o){return o.code==="ESRCH"?(c(`Removing stale lock file ${e} for dead process ${r}`),w.unlinkSync(t),!1):(c(`Error checking process ${r} for lock ${e}:`,o),!0)}}catch(n){return c(`Error reading lock file ${e}:`,n),true}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let o=S.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await w.promises.writeFile(o,a,{flag:"wx"}),c(`Lock acquired for ${e}`),!0}catch(l){if(l.code==="EEXIST")await setTimeout(50);else throw l}return c(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=S.join(this.LOCKS_DIR,e);try{await w.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([w.promises.mkdir(this.CACHE_DIR,{recursive:!0}),w.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),w.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){c("Failed to create cache directories:",e);}}static createProjectHash(e){return createHash("md5").update(e).digest("hex").substring(0,8)}static async getUsageCache(e,t){let o="utf-8";await this.ensureCacheDirectories();let i=S.join(this.USAGE_CACHE_DIR,`${e}.json`),a=`${e}.usage.lock`;for(let l=0;l<3;l++){if(this.isLocked(a)){c(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let m=await w.promises.readFile(i,o),f=JSON.parse(m);return !t||f.timestamp>=t?(c(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(f.data)):(c(`${e} cache outdated: cache=${f.timestamp}, latest=${t}`),null)}catch(m){if(m.code==="ENOENT")return c(`No shared ${e} usage cache found`),null;let f=l+1;c(`Attempt ${f} failed to read ${e} cache: ${m.message}. Retrying...`),await setTimeout(75);}}return c(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(t=>({...t,timestamp:new Date(t.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){c(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=S.join(this.USAGE_CACHE_DIR,`${e}.json`),a=n||Date.now(),g=JSON.stringify({data:t,timestamp:a});await w.promises.writeFile(i,g,"utf-8"),c(`[CACHE-SET] ${e} disk cache stored`);}catch(i){c(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(r);}}static async getLatestTranscriptMtime(){try{let e=H(),t=await G(e),n=0;for(let r of t)try{let i=(await w.promises.readdir(r)).filter(a=>a.endsWith(".jsonl"));for(let a of i){let l=S.join(r,a),g=await se(l);g&&g.getTime()>n&&(n=g.getTime());}}catch(o){c(`Failed to read project directory ${r}:`,o);continue}return n}catch(e){return c("Failed to get latest transcript mtime:",e),Date.now()}}};function L(s){let e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function Je(s){return s.inputTokens+s.outputTokens+s.cacheCreationInputTokens+s.cacheReadInputTokens}function qe(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},model:s.message?.model||"unknown"}}var X=class{async loadTodayEntries(){let t=L(new Date);c(`Today segment: Loading entries for date ${t}`);let n=await P.getLatestTranscriptMtime(),r=await P.getUsageCache("today",n);if(r)return c("Using shared today usage cache"),r;let o=new Date;o.setDate(o.getDate()-1),o.setHours(0,0,0,0);let i=(u,d)=>d>=o,a=new Date;a.setHours(0,0,0,0);let g=await V(u=>u.timestamp>=a,i,true),m=[],f=0;for(let u of g)if(L(u.timestamp)===t&&u.message?.usage){let y=qe(u);m.push(y),f++;}return c(`Today segment: Found ${f} entries for today (${t})`),await P.setUsageCache("today",m,n),m}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 {tokens:null,tokenBreakdown:null,date:L(new Date)};let t=e.reduce((r,o)=>r+Je(o.usage),0),n=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} tokens total`),{tokens:t,tokenBreakdown:n,date:L(new Date)}}catch(e){return c("Error getting today's info:",e),{tokens:null,tokenBreakdown:null,date:L(new Date)}}}};var N="\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_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u27E2",version:"\u25C8"};var K=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 U),this._usageProvider}get blockProvider(){return this._blockProvider||(this._blockProvider=new q),this._blockProvider}get todayProvider(){return this._todayProvider||(this._todayProvider=new X),this._todayProvider}get contextProvider(){return this._contextProvider||(this._contextProvider=new A),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new D),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new B),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new I),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new M(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id,e):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,r=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,o=this.needsSegmentInfo("context")?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,i=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id,e):null;return (await Promise.all(this.config.display.lines.map(l=>this.renderLine(l,e,t,n,r,o,i)))).filter(l=>l.length>0).join(`
|
|
8
|
-
`)}async renderLine(e,t,n,r,o,i,a){let l=this.getThemeColors(),g=t.workspace?.current_dir||t.cwd||"/",m=Object.entries(e.segments).filter(([u,d])=>d?.enabled).map(([u,d])=>({type:u,config:d})),f=l.reset;for(let u=0;u<m.length;u++){let d=m[u];if(!d)continue;let y=u===m.length-1,b=y?null:m[u+1],R=b?this.getSegmentBgColor(b.type,l):"",C=await this.renderSegment(d,t,n,r,o,i,a,l,g);C&&(f+=this.formatSegment(C.bgColor,C.fgColor,C.text,y?void 0:R));}return f}async renderSegment(e,t,n,r,o,i,a,l,g){return e.type==="directory"?this.segmentRenderer.renderDirectory(t,l,e.config):e.type==="model"?this.segmentRenderer.renderModel(t,l):e.type==="git"?await this.renderGitSegment(e.config,t,l,g):e.type==="session"?this.renderSessionSegment(e.config,n,l):e.type==="tmux"?await this.renderTmuxSegment(l):e.type==="context"?this.renderContextSegment(i,l):e.type==="metrics"?this.renderMetricsSegment(e.config,a,r,l):e.type==="block"?this.renderBlockSegment(e.config,r,l):e.type==="today"?this.renderTodaySegment(e.config,o,l):e.type==="version"?this.renderVersionSegment(e.config,t,l):null}async renderGitSegment(e,t,n,r){if(!this.needsSegmentInfo("git"))return null;let o=await this.gitService.getGitInfo(r,{showSha:e?.showSha,showWorkingTree:e?.showWorkingTree,showOperation:e?.showOperation,showTag:e?.showTag,showTimeSinceCommit:e?.showTimeSinceCommit,showStashCount:e?.showStashCount,showUpstream:e?.showUpstream,showRepoName:e?.showRepoName},t.workspace?.project_dir);return o?this.segmentRenderer.renderGit(o,n,e):null}renderSessionSegment(e,t,n){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderSession(t,n,r)}async renderTmuxSegment(e){if(!this.needsSegmentInfo("tmux"))return null;let t=await this.tmuxService.getSessionId();return this.segmentRenderer.renderTmux(t,e)}renderContextSegment(e,t){return this.needsSegmentInfo("context")?this.segmentRenderer.renderContext(e,t):null}renderMetricsSegment(e,t,n,r){return this.segmentRenderer.renderMetrics(t,r,n,e)}renderBlockSegment(e,t,n){return t?this.segmentRenderer.renderBlock(t,n,e):null}renderTodaySegment(e,t,n){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderToday(t,n,r)}renderVersionSegment(e,t,n){return this.segmentRenderer.renderVersion(t,n,e)}initializeSymbols(){return {right:this.config.display.style==="minimal"?"":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_lines_added:p.metrics_lines_added,metrics_lines_removed:p.metrics_lines_removed,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=O(e),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=O("dark"));let n=O("dark"),r=b=>{let R=t[b]||n[b];return {bg:ee(R.bg,true),fg:ee(R.fg,false)}},o=r("directory"),i=r("git"),a=r("model"),l=r("session"),g=r("block"),m=r("today"),f=r("tmux"),u=r("context"),d=r("metrics"),y=r("version");return {reset:N,modeBg:o.bg,modeFg:o.fg,gitBg:i.bg,gitFg:i.fg,modelBg:a.bg,modelFg:a.fg,sessionBg:l.bg,sessionFg:l.fg,blockBg:g.bg,blockFg:g.fg,todayBg:m.bg,todayFg:m.fg,tmuxBg:f.bg,tmuxFg:f.fg,contextBg:u.bg,contextFg:u.fg,metricsBg:d.bg,metricsFg:d.fg,versionBg:y.bg,versionFg:y.fg}}getSegmentBgColor(e,t){switch(e){case "directory":return t.modeBg;case "git":return t.gitBg;case "model":return t.modelBg;case "session":return t.sessionBg;case "block":return t.blockBg;case "today":return t.todayBg;case "tmux":return t.tmuxBg;case "context":return t.contextBg;case "metrics":return t.metricsBg;case "version":return t.versionBg;default:return t.modeBg}}formatSegment(e,t,n,r){let o=`${e}${t} ${n} `;if(r){let i=te(e);o+=`${N}${r}${i}${this.symbols.right}`;}else o+=`${N}${te(e)}${this.symbols.right}${N}`;return o}};var Se={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:"both"},today:{enabled:true,type:"tokens"},block:{enabled:false,type:"tokens",burnType:"tokens"},version:{enabled:false},tmux:{enabled:false},context:{enabled:true},metrics:{enabled:false,showResponseTime:true,showLastResponseTime:true,showDuration:true,showMessageCount:true,showLinesAdded:true,showLinesRemoved:true}}}]},budget:{session:{warningThreshold:80}}};function ae(s){return ["light","dark","nord","tokyo-night","rose-pine","custom"].includes(s)}function le(s){return s==="minimal"||s==="powerline"}function Q(s,e){let t={...s};for(let n in e){let r=e[n];if(r!==void 0)if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=t[n]||{};t[n]=Q(o,r);}else t[n]=r;}return t}function Xe(s,e){return s?w.existsSync(s)?s:null:[...e?[S.join(e,".claude-powerline.json")]:[],S.join(process.cwd(),".claude-powerline.json"),S.join($.homedir(),".claude","claude-powerline.json"),S.join($.homedir(),".config","claude-powerline","config.json")].find(w.existsSync)||null}function Ke(s){try{let e=w.readFileSync(s,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${s}: ${e instanceof Error?e.message:String(e)}`)}}function ze(){let s={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&ae(t)&&(s.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(le(n)?e.style=n:(console.warn(`Invalid display style '${n}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(s.display=e),s}function Qe(){return process.env.CLAUDE_POWERLINE_CONFIG}function Ze(s){let e={},t={},n=s.find(o=>o.startsWith("--theme="))?.split("=")[1];n&&ae(n)&&(e.theme=n);let r=s.find(o=>o.startsWith("--style="))?.split("=")[1];return r&&(le(r)?t.style=r:(console.warn(`Invalid display style '${r}' from CLI argument, falling back to 'minimal'`),t.style="minimal")),Object.keys(t).length>0&&(e.display=t),e}function et(s=process.argv,e){let t=JSON.parse(JSON.stringify(Se)),n=s.find(a=>a.startsWith("--config="))?.split("=")[1]||Qe(),r=Xe(n,e);if(r)try{let a=Ke(r);t=Q(t,a);}catch(a){console.warn(`Warning: ${a instanceof Error?a.message:String(a)}`);}t.display?.style&&!le(t.display.style)&&(console.warn(`Invalid display style '${t.display.style}' in config file, falling back to 'minimal'`),t.display.style="minimal"),t.theme&&!ae(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let o=ze();t=Q(t,o);let i=Ze(s);return t=Q(t,i),t}var ke=et;async function nt(){try{let s=$.platform(),e;if(s==="darwin")e=S.join($.homedir(),"Library","Fonts");else if(s==="linux")e=S.join($.homedir(),".local","share","fonts");else if(s==="win32")e=S.join($.homedir(),"AppData","Local","Microsoft","Windows","Fonts");else {console.log("Unsupported platform for font installation");return}w.existsSync(e)||w.mkdirSync(e,{recursive:!0}),console.log("Installing Powerline Fonts..."),console.log("Downloading from https://github.com/powerline/fonts");let t=S.join($.tmpdir(),"powerline-fonts"),n=()=>{w.existsSync(t)&&w.rmSync(t,{recursive:!0,force:!0});};h.on("SIGINT",n),h.on("SIGTERM",n);try{w.existsSync(t)&&w.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:$.tmpdir()}),console.log("Installing fonts...");let r=S.join(t,"install.sh");if(w.existsSync(r))w.chmodSync(r,493),execSync("./install.sh",{stdio:"inherit",cwd:t});else throw new Error("Install script not found in powerline fonts repository");console.log("Powerline fonts installation complete!"),console.log("Please restart your terminal and set your terminal font to a powerline font."),console.log("Popular choices: Source Code Pro Powerline, DejaVu Sans Mono Powerline, Ubuntu Mono Powerline");}finally{n(),h.removeListener("SIGINT",n),h.removeListener("SIGTERM",n);}}catch(s){console.error("Error installing fonts:",s instanceof Error?s.message:String(s)),console.log("You can manually install fonts from: https://github.com/powerline/fonts");}}function Te(){console.log(`
|
|
2
|
+
import b from'process';import _,{join,posix}from'path';import w,{existsSync,readFileSync,createReadStream}from'fs';import {exec,execSync}from'child_process';import U,{homedir}from'os';import {json}from'stream/consumers';import {promisify}from'util';import {get}from'https';import {URL}from'url';import {createHash}from'crypto';import {setTimeout}from'timers/promises';import {readdir,stat,readFile}from'fs/promises';import {createInterface}from'readline';function se(s,e){if(e&&(s.toLowerCase()==="transparent"||s.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(s.slice(1,3),16),n=parseInt(s.slice(3,5),16),r=parseInt(s.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${n};${r}m`}function oe(s){let e=s.match(/48;2;(\d+);(\d+);(\d+)/);return e?`\x1B[38;2;${e[1]};${e[2]};${e[3]}m`:s.replace("48","38")}var he={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 pe={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 ye={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 be={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 Ce={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:he,light:pe,nord:ye,"tokyo-night":be,"rose-pine":Ce};function W(s){return Re[s]||null}var c=(s,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${s}`,...e);};var S=promisify(exec),F=class{isGitRepo(e){try{return w.existsSync(_.join(e,".git"))}catch{return false}}async getGitInfo(e,t={},n){let r=n&&this.isGitRepo(n)?n:e;if(!this.isGitRepo(r))return null;try{let o=await this.getStatusWithBranchAsync(r),i=await this.getAheadBehindAsync(r),a={branch:o.branch||"detached",status:o.status,ahead:i.ahead,behind:i.behind};t.showWorkingTree&&o.workingTree&&(a.staged=o.workingTree.staged,a.unstaged=o.workingTree.unstaged,a.untracked=o.workingTree.untracked,a.conflicts=o.workingTree.conflicts);let l={},u={};t.showSha&&(l.sha=this.getShaAsync(r)),t.showTag&&(l.tag=this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(l.timeSinceCommit=this.getTimeSinceLastCommitAsync(r)),t.showStashCount&&(u.stashCount=this.getStashCountAsync(r)),t.showUpstream&&(u.upstream=this.getUpstreamAsync(r)),t.showRepoName&&(u.repoName=this.getRepoNameAsync(r));let g=new Map;for(let[d,m]of Object.entries(l))try{let f=await m;g.set(d,f);}catch{}return Object.keys(u).length>0&&(await Promise.allSettled(Object.entries(u).map(async([m,f])=>({key:m,value:await f})))).forEach(m=>{m.status==="fulfilled"&&g.set(m.value.key,m.value.value);}),t.showSha&&(a.sha=g.get("sha")||void 0),t.showOperation&&(a.operation=this.getOngoingOperation(r)||void 0),t.showTag&&(a.tag=g.get("tag")||void 0),t.showTimeSinceCommit&&(a.timeSinceCommit=g.get("timeSinceCommit")||void 0),t.showStashCount&&(a.stashCount=g.get("stashCount")||0),t.showUpstream&&(a.upstream=g.get("upstream")||void 0),t.showRepoName&&(a.repoName=g.get("repoName")||void 0,a.isWorktree=this.isWorktree(r)),a}catch{return null}}async getShaAsync(e){try{return (await S("git rev-parse --short=7 HEAD",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}getOngoingOperation(e){try{let t=_.join(e,".git");return w.existsSync(_.join(t,"MERGE_HEAD"))?"MERGE":w.existsSync(_.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":w.existsSync(_.join(t,"REVERT_HEAD"))?"REVERT":w.existsSync(_.join(t,"BISECT_LOG"))?"BISECT":w.existsSync(_.join(t,"rebase-merge"))||w.existsSync(_.join(t,"rebase-apply"))?"REBASE":null}catch{return null}}async getNearestTagAsync(e){try{return (await S("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim()||null}catch{return null}}async getTimeSinceLastCommitAsync(e){try{let n=(await S("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(!n)return null;let r=parseInt(n)*1e3,o=Date.now();return Math.floor((o-r)/1e3)}catch{return null}}async getStashCountAsync(e){try{let n=(await S("git stash list",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.split(`
|
|
3
|
+
`).length:0}catch{return 0}}async getUpstreamAsync(e){try{return (await S("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 S("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();return n?n.match(/\/([^/]+?)(\.git)?$/)?.[1]||_.basename(e):_.basename(e)}catch{return _.basename(e)}}isWorktree(e){try{let t=_.join(e,".git");return !!(w.existsSync(t)&&w.statSync(t).isFile())}catch{return false}}async getStatusWithBranchAsync(e){try{c(`[GIT-EXEC] Running git status in ${e}`);let r=(await S("git status --porcelain -b",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.split(`
|
|
4
|
+
`),o=null,i="clean",a=0,l=0,u=0,g=0;for(let d of r)if(d){if(d.startsWith("## ")){let f=d.substring(3).split("...")[0];f&&f!=="HEAD (no branch)"&&(o=f);continue}if(d.length>=2){let m=d.charAt(0),f=d.charAt(1);if(m==="?"&&f==="?"){u++,i==="clean"&&(i="dirty");continue}let h=m+f;if(["DD","AU","UD","UA","DU","AA","UU"].includes(h)){g++,i="conflicts";continue}m!==" "&&m!=="?"&&(a++,i==="clean"&&(i="dirty")),f!==" "&&f!=="?"&&(l++,i==="clean"&&(i="dirty"));}}return {branch:o||await this.getFallbackBranch(e),status:i,workingTree:{staged:a,unstaged:l,untracked:u,conflicts:g}}}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 S("git branch --show-current",{cwd:e,encoding:"utf8",timeout:2e3})).stdout.trim();if(n)return n}catch{try{let n=(await S("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([S("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:2e3}),S("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 Me=promisify(exec),M=class{async getSessionId(){try{if(!process.env.TMUX_PANE)return c("TMUX_PANE not set, not in tmux session"),null;c(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let t=(await Me("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}};function V(){let s=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let n=t.trim();existsSync(n)&&s.push(n);}),s.length===0){let t=homedir(),n=join(t,".config","claude"),r=join(t,".claude");existsSync(n)?s.push(n):existsSync(r)&&s.push(r);}return s}async function J(s){let e=[];for(let t of s){let n=join(t,"projects");if(existsSync(n))try{let r=await readdir(n,{withFileTypes:!0});for(let o of r)if(o.isDirectory()){let i=posix.join(n,o.name);e.push(i);}}catch(r){c(`Failed to read projects directory ${n}:`,r);}}return e}async function Y(s){let e=V(),t=await J(e);for(let n of t){let r=posix.join(n,`${s}.jsonl`);if(existsSync(r))return r}return null}async function ce(s){try{return (await stat(s)).mtime}catch{return null}}function Oe(s){let e=s.message?.id||(typeof s.raw.message=="object"&&s.raw.message!==null&&"id"in s.raw.message?s.raw.message.id:void 0),t="requestId"in s.raw?s.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}var Ne=1024*1024;async function A(s){try{let t=(await stat(s)).size,n;return t>Ne?(c(`Using streaming parser for large file ${s} (${Math.round(t/1024)}KB)`),n=await Ge(s)):n=await He(s),c(`Parsed ${n.length} entries from ${s}`),n}catch(e){return c(`Failed to read file ${s}:`,e),[]}}async function He(s){let t=(await readFile(s,"utf-8")).trim().split(`
|
|
5
|
+
`).filter(r=>r.trim()),n=[];for(let r of t)try{let o=JSON.parse(r);if(!o.timestamp)continue;let i={timestamp:new Date(o.timestamp),message:o.message,costUSD:typeof o.costUSD=="number"?o.costUSD:void 0,isSidechain:o.isSidechain===!0,raw:o};n.push(i);}catch(o){c(`Failed to parse JSONL line: ${o}`);continue}return n}async function Ge(s){return new Promise((e,t)=>{let n=[],r=createReadStream(s,{encoding:"utf8"}),o=createInterface({input:r,crlfDelay:1/0});o.on("line",i=>{let a=i.trim();if(a)try{let l=JSON.parse(a);if(!l.timestamp)return;let u={timestamp:new Date(l.timestamp),message:l.message,costUSD:typeof l.costUSD=="number"?l.costUSD:void 0,isSidechain:l.isSidechain===!0,raw:l};n.push(u);}catch(l){c(`Failed to parse JSONL line: ${l}`);}}),o.on("close",()=>{e(n);}),o.on("error",i=>{c(`Streaming parser error for ${s}:`,i),t(i);}),r.on("error",i=>{c(`File stream error for ${s}:`,i),t(i);});})}async function q(s,e,t=false){let n=V(),r=await J(n),o=new Set,i=r.map(async h=>{try{let D=(await readdir(h)).filter(R=>R.endsWith(".jsonl")).map(async R=>{let re=posix.join(h,R);if(existsSync(re)){let $e=await ce(re);return {filePath:re,mtime:$e}}return null});return (await Promise.all(D)).filter(R=>R?.mtime&&(!e||e(R.filePath,R.mtime)))}catch(y){return c(`Failed to read project directory ${h}:`,y),[]}}),l=(await Promise.all(i)).flat().filter(h=>h!==null);t&&l.sort((h,y)=>y.mtime.getTime()-h.mtime.getTime());let u=l.map(h=>h.filePath),g=[],d=u.map(async h=>(await A(h)).filter($=>!s||s($))),m=await Promise.all(d);for(let h of m)g.push(...h);g.sort((h,y)=>h.timestamp.getTime()-y.timestamp.getTime());let f=[];for(let h of g){let y=Oe(h);y&&o.has(y)||(y&&o.add(y),f.push(h));}return f}var P=class{static CACHE_DIR=_.join(homedir(),".claude","powerline");static USAGE_CACHE_DIR=_.join(this.CACHE_DIR,"usage");static LOCKS_DIR=_.join(this.CACHE_DIR,"locks");static isLocked(e){let t=_.join(this.LOCKS_DIR,e);if(!w.existsSync(t))return false;try{let n=w.readFileSync(t,"utf-8"),r=parseInt(n.trim(),10);if(isNaN(r))return c(`Invalid PID in lock file ${e}, removing stale lock`),w.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(o){return o.code==="ESRCH"?(c(`Removing stale lock file ${e} for dead process ${r}`),w.unlinkSync(t),!1):(c(`Error checking process ${r} for lock ${e}:`,o),!0)}}catch(n){return c(`Error reading lock file ${e}:`,n),true}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let o=_.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await w.promises.writeFile(o,a,{flag:"wx"}),c(`Lock acquired for ${e}`),!0}catch(l){if(l.code==="EEXIST")await setTimeout(50);else throw l}return c(`Failed to acquire lock for ${e} within ${t}ms`),false}static async releaseLock(e){let t=_.join(this.LOCKS_DIR,e);try{await w.promises.unlink(t),c(`Lock released for ${e}`);}catch(n){n.code!=="ENOENT"&&c(`Error releasing lock for ${e}:`,n);}}static async ensureCacheDirectories(){try{await Promise.all([w.promises.mkdir(this.CACHE_DIR,{recursive:!0}),w.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),w.promises.mkdir(this.LOCKS_DIR,{recursive:!0})]);}catch(e){c("Failed to create cache directories:",e);}}static createProjectHash(e){return createHash("md5").update(e).digest("hex").substring(0,8)}static async getUsageCache(e,t){let o="utf-8";await this.ensureCacheDirectories();let i=_.join(this.USAGE_CACHE_DIR,`${e}.json`),a=`${e}.usage.lock`;for(let l=0;l<3;l++){if(this.isLocked(a)){c(`Cache for ${e} is locked, waiting...`),await setTimeout(75);continue}try{let g=await w.promises.readFile(i,o),d=JSON.parse(g);return !t||d.timestamp>=t?(c(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(d.data)):(c(`${e} cache outdated: cache=${d.timestamp}, latest=${t}`),null)}catch(g){if(g.code==="ENOENT")return c(`No shared ${e} usage cache found`),null;let d=l+1;c(`Attempt ${d} failed to read ${e} cache: ${g.message}. Retrying...`),await setTimeout(75);}}return c(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(t=>({...t,timestamp:new Date(t.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){c(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=_.join(this.USAGE_CACHE_DIR,`${e}.json`),a=n||Date.now(),u=JSON.stringify({data:t,timestamp:a});await w.promises.writeFile(i,u,"utf-8"),c(`[CACHE-SET] ${e} disk cache stored`);}catch(i){c(`Failed to save ${e} usage cache:`,i);}finally{await this.releaseLock(r);}}static async getLatestTranscriptMtime(){try{let e=V(),t=await J(e),n=0;for(let r of t)try{let i=(await w.promises.readdir(r)).filter(a=>a.endsWith(".jsonl"));for(let a of i){let l=_.join(r,a),u=await ce(l);u&&u.getTime()>n&&(n=u.getTime());}}catch(o){c(`Failed to read project directory ${r}:`,o);continue}return n}catch(e){return c("Failed to get latest transcript mtime:",e),Date.now()}}};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}},E=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL="https://raw.githubusercontent.com/Owloops/claude-powerline/main/pricing.json";static async loadDiskCache(){let t=Date.now()-864e5;return await P.getUsageCache("pricing",t)}static async saveDiskCache(e){await P.setUsageCache("pricing",e);}static async fetchPricingData(){return new Promise(e=>{let t=new URL(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"},timeout:5e3},r=>{if(r.statusCode!==200){c(`HTTP ${r.statusCode}: ${r.statusMessage}`),e(null);return}let o="",i=0,a=1024*1024;r.on("data",l=>{if(i+=l.length,i>a){c("Response too large"),n.destroy(),e(null);return}o+=l;}),r.on("end",()=>{try{let u=JSON.parse(o),g=u._meta,d={};for(let[m,f]of Object.entries(u))m!=="_meta"&&(d[m]=f);this.validatePricingData(d)?(c(`Fetched fresh pricing from GitHub for ${Object.keys(d).length} models`),c(`Pricing last updated: ${g?.updated||"unknown"}`),e(d)):(c("Invalid pricing data structure"),e(null));}catch(l){c("Failed to parse JSON:",l),e(null);}}),r.on("error",l=>{c("Response error:",l),e(null);});});n.on("error",r=>{c("Request error:",r),e(null);}),n.on("timeout",()=>{c("Request timeout"),n.destroy(),e(null);}),n.end();})}static async getCurrentPricing(){if(this.executionCache!==null)return c(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return c(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),c(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(c(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(X).length} models`),this.executionCache=X,c(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(X).length} models`),X)}static validatePricingData(e){if(!e||typeof e!="object")return false;for(let[,t]of Object.entries(e)){if(!t||typeof t!="object")return false;let n=t;if(typeof n.input!="number"||typeof n.output!="number"||typeof n.cache_read!="number")return false}return true}static async getModelPricing(e){if(this.modelPricingCache.has(e))return c(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return t[e]?n=t[e]:n=this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),c(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[o,i]of Object.entries(t))if(o.toLowerCase()===n)return i;let r=[{pattern:["opus-4-1","claude-opus-4-1"],fallback:"claude-opus-4-1-20250805"},{pattern:["opus-4","claude-opus-4"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet-4","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:o,fallback:i}of r)if(o.some(a=>n.includes(a))&&t[i])return t[i];return t["claude-3-5-sonnet-20241022"]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let n=e.message?.usage;if(!n)return 0;let r=this.extractModelId(e),o=await this.getModelPricing(r),i=n.input_tokens||0,a=n.output_tokens||0,l=n.cache_creation_input_tokens||0,u=n.cache_read_input_tokens||0,g=i/1e6*o.input,d=a/1e6*o.output,m=u/1e6*o.cache_read,f=l/1e6*o.cache_write_5m;return g+d+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 qe(s){return {timestamp:s.timestamp.toISOString(),message:{usage:{input_tokens:s.message?.usage?.input_tokens||0,output_tokens:s.message?.usage?.output_tokens||0,cache_creation_input_tokens:s.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:s.message?.usage?.cache_read_input_tokens}},costUSD:s.costUSD}}var z=class{async getSessionUsage(e){try{let t=await Y(e);if(!t)return c(`No transcript found for session: ${e}`),null;c(`Found transcript at: ${t}`);let n=await A(t);if(n.length===0)return {totalCost:0,entries:[]};let r=[],o=0;for(let i of n)if(i.message?.usage){let a=qe(i);if(a.costUSD!==void 0)o+=a.costUSD;else {let l=await E.calculateCostForEntry(i.raw);a.costUSD=l,o+=l;}r.push(a);}return c(`Parsed ${r.length} usage entries, total cost: $${o.toFixed(4)}`),{totalCost:o,entries:r}}catch(t){return c(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,n)=>({input:t.input+(n.message.usage.input_tokens||0),output:t.output+(n.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(n.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(n.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e,t){let n=await this.getSessionUsage(e);if(!n||n.entries.length===0)return {cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};let r=this.calculateTokenBreakdown(n.entries),o=r.input+r.output+r.cacheCreation+r.cacheRead,i=n.totalCost,a=t?.cost?.total_cost_usd??null;return {cost:i??a,calculatedCost:i,officialCost:a,tokens:o,tokenBreakdown:r}}},L=class{sessionProvider=new z;async getUsageInfo(e,t){try{return c(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e,t)}}catch(n){return c(`Error getting usage info for session ${e}:`,n),{session:{cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null}}}}};var I=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 A(e);if(n.length===0)return c("No entries in transcript"),null;let r=null;for(let o=n.length-1;o>=0;o--){let i=n[o];if(i&&i.message?.usage?.input_tokens&&i.isSidechain!==!0){r=i,c(`Context segment: Found most recent entry at ${i.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let o=r.message.usage,i=(o.input_tokens||0)+(o.cache_read_input_tokens||0)+(o.cache_creation_input_tokens||0),a=t?this.getContextLimit(t):2e5;c(`Most recent main chain context: ${i} tokens (limit: ${a})`);let l=Math.min(100,Math.max(0,Math.round(i/a*100))),u=Math.round(a*.75),g=Math.min(100,Math.max(0,Math.round(i/u*100))),d=Math.max(0,100-g);return {inputTokens:i,percentage:l,usablePercentage:g,contextLeftPercentage:d,maxTokens:a,usableTokens:u}}return c("No main chain entries with usage data found"),null}catch(n){return c(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}};var j=class{async loadTranscriptEntries(e){try{let t=await Y(e);if(!t)return c(`No transcript found for session: ${e}`),[];c(`Loading transcript from: ${t}`);let r=(await readFile(t,"utf-8")).trim().split(`
|
|
6
|
+
`).filter(i=>i.trim()),o=[];for(let i of r)try{let a=JSON.parse(i);if(a.isSidechain===!0)continue;o.push(a);}catch(a){c(`Failed to parse JSONL line: ${a}`);continue}return c(`Loaded ${o.length} transcript entries`),o}catch(t){return c(`Error loading transcript for ${e}:`,t),[]}}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,r=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!r}).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let o of t)if(o.timestamp)try{let i=new Date(o.timestamp),a=o.type||o.message?.role||o.message?.type,l=o.type==="user"&&o.message?.content?.[0]?.type==="tool_result";if(a==="user"&&!l)n=i;else if(a==="assistant"&&n){let g=(i.getTime()-n.getTime())/1e3;g>.1&&g<300&&(r=g);}}catch{continue}return r}async getMetricsInfo(e,t){try{if(c(`Getting metrics from hook data for session: ${e}`),!t.cost)return c("No cost data available in hook data"),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null};let n=await this.loadTranscriptEntries(e),r=this.calculateMessageCount(n),o=this.calculateLastResponseTime(n);return {responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:o,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed}}catch(n){return c(`Error getting metrics from hook data for session ${e}:`,n),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,linesAdded:null,linesRemoved:null}}}};function k(s){return s===null?"$0.00":s<.01?"<$0.01":`$${s.toFixed(2)}`}function C(s){return s===null||s===0?"0 tokens":s>=1e6?`${(s/1e6).toFixed(1)}M tokens`:s>=1e3?`${(s/1e3).toFixed(1)}K tokens`:`${s} tokens`}function ue(s){if(!s)return "0 tokens";let e=[];if(s.input>0&&e.push(`${C(s.input).replace(" tokens","")}in`),s.output>0&&e.push(`${C(s.output).replace(" tokens","")}out`),s.cacheCreation>0||s.cacheRead>0){let t=s.cacheCreation+s.cacheRead;e.push(`${C(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function Se(s){return s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:s<86400?`${Math.floor(s/3600)}h`:s<604800?`${Math.floor(s/86400)}d`:`${Math.floor(s/604800)}w`}function ke(s){return s<60?`${s.toFixed(0)}s`:s<3600?`${(s/60).toFixed(0)}m`:s<86400?`${(s/3600).toFixed(1)}h`:`${(s/86400).toFixed(1)}d`}function Ke(s,e){return !e||e<=0||s<0?null:Math.min(100,s/e*100)}function ge(s,e,t=80){let n=Ke(s,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let r=`${n.toFixed(0)}%`,o=n>=t,i="";return o?i=` !${r}`:n>=50?i=` +${r}`:i=` ${r}`,{percentage:n,isWarning:o,displayText:i}}var O=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let r=e.workspace?.current_dir||e.cwd||"/",o=e.workspace?.project_dir;if(n?.showBasename)return {text:_.basename(r)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let i=process.env.HOME||process.env.USERPROFILE,a=r,l=o;return i&&(r.startsWith(i)&&(a=r.replace(i,"~")),o&&o.startsWith(i)&&(l=o.replace(i,"~"))),{text:this.getDisplayDirectoryName(a,l),bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let r=[];if(n?.showRepoName&&e.repoName&&(r.push(e.repoName),e.isWorktree&&r.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&r.push(`[${e.operation}]`),r.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&r.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&r.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?r.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?r.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&r.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let i=[];e.staged&&e.staged>0&&i.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&i.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&i.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&i.push(`!${e.conflicts}`),i.length>0&&r.push(`(${i.join(" ")})`);}if(n?.showUpstream&&e.upstream&&r.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&r.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let i=Se(e.timeSinceCommit);r.push(`${this.symbols.git_time} ${i}`);}let o=this.symbols.git_clean;return e.status==="conflicts"?o=this.symbols.git_conflicts:e.status==="dirty"&&(o=this.symbols.git_dirty),r.push(o),{text:r.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}renderModel(e,t){let n=e.model?.display_name||"Claude";return {text:`${this.symbols.model} ${n}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n){let r=n?.type||"cost",o=n?.costSource,i=this.config.budget?.session,a=o?this.formatSessionUsageDisplay(e.session,r,o):this.formatUsageWithBudget(e.session.cost,e.session.tokens,e.session.tokenBreakdown,r,i?.amount,i?.warningThreshold||80,i?.type);return {text:`${this.symbols.session_cost} ${a}`,bgColor:t.sessionBg,fgColor:t.sessionFg}}renderTmux(e,t){return e?{text:`tmux:${e}`,bgColor:t.tmuxBg,fgColor:t.tmuxFg}:{text:"tmux:none",bgColor:t.tmuxBg,fgColor:t.tmuxFg}}renderContext(e,t,n){if(!e)return {text:`${this.symbols.context_time} 0 (100%)`,bgColor:t.contextBg,fgColor:t.contextFg};let r=`${e.contextLeftPercentage}%`;return {text:n?.showPercentageOnly?`${this.symbols.context_time} ${r}`:`${this.symbols.context_time} ${e.inputTokens.toLocaleString()} (${r})`,bgColor:t.contextBg,fgColor:t.contextFg}}renderMetrics(e,t,n,r){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let o=[];if(r?.showLastResponseTime&&e.lastResponseTime!==null){let i=e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;o.push(`${this.symbols.metrics_last_response} ${i}`);}if(r?.showResponseTime!==false&&e.responseTime!==null){let i=e.responseTime<60?`${e.responseTime.toFixed(1)}s`:`${(e.responseTime/60).toFixed(1)}m`;o.push(`${this.symbols.metrics_response} ${i}`);}if(r?.showDuration!==false&&e.sessionDuration!==null){let i=ke(e.sessionDuration);o.push(`${this.symbols.metrics_duration} ${i}`);}return r?.showMessageCount!==false&&e.messageCount!==null&&o.push(`${this.symbols.metrics_messages} ${e.messageCount}`),r?.showLinesAdded!==false&&e.linesAdded!==null&&e.linesAdded>0&&o.push(`${this.symbols.metrics_lines_added} ${e.linesAdded}`),r?.showLinesRemoved!==false&&e.linesRemoved!==null&&e.linesRemoved>0&&o.push(`${this.symbols.metrics_lines_removed} ${e.linesRemoved}`),o.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:o.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,n){let r;if(e.cost===null&&e.tokens===null)r="No active block";else {let o=n?.type||"cost",i=n?.burnType,a=this.config.budget?.block,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,u;switch(o){case "cost":a?.amount&&a?.type==="cost"?u=this.formatUsageWithBudget(e.cost,null,null,"cost",a.amount,a.warningThreshold,a.type):u=k(e.cost);break;case "tokens":a?.amount&&a?.type==="tokens"?u=this.formatUsageWithBudget(null,e.tokens,null,"tokens",a.amount,a.warningThreshold,a.type):u=C(e.tokens);break;case "weighted":let d=a?.type==="tokens"?a.amount:void 0,m=C(e.weightedTokens);if(d&&e.weightedTokens!==null){let f=ge(e.weightedTokens,d,a?.warningThreshold||80);u=`${m}${f.displayText}`;}else u=`${m} (weighted)`;break;case "both":a?.amount?u=this.formatUsageWithBudget(e.cost,e.tokens,null,"both",a.amount,a.warningThreshold,a.type):u=`${k(e.cost)} / ${C(e.tokens)}`;break;case "time":u=l||"N/A";break;default:a?.amount&&a?.type==="cost"?u=this.formatUsageWithBudget(e.cost,null,null,"cost",a.amount,a.warningThreshold,a.type):u=k(e.cost);}let g="";if(i&&i!=="none")switch(i){case "cost":g=` | ${e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A"}`;break;case "tokens":g=` | ${e.tokenBurnRate!==null?`${C(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let f=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",h=e.tokenBurnRate!==null?`${C(Math.round(e.tokenBurnRate))}/h`:"N/A";g=` | ${f} / ${h}`;break}o==="time"?r=u:r=l?`${u}${g} (${l} left)`:`${u}${g}`;}return {text:`${this.symbols.block_cost} ${r}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let r=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,r?.amount,r?.warningThreshold,r?.type)}`,bgColor:t.todayBg,fgColor:t.todayFg}}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||_.basename(t)||"project":_.basename(e)||"root":_.basename(e)||"root"}formatUsageDisplay(e,t,n,r){switch(r){case "cost":return k(e);case "tokens":return C(t);case "both":return `${k(e)} (${C(t)})`;case "breakdown":return ue(n);default:return k(e)}}formatSessionUsageDisplay(e,t,n){let r=()=>n==="calculated"?e.calculatedCost:n==="official"?e.officialCost:e.cost;switch(t){case "cost":return k(r());case "tokens":return C(e.tokens);case "both":return `${k(r())} (${C(e.tokens)})`;case "breakdown":return ue(e.tokenBreakdown);default:return k(r())}}formatUsageWithBudget(e,t,n,r,o,i=80,a){let l=this.formatUsageDisplay(e,t,n,r);if(o&&o>0){let u=null;if(a==="tokens"&&t!==null?u=t:(a==="cost"&&e!==null||!a&&e!==null)&&(u=e),u!==null){let g=ge(u,o,i);return l+g.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 Ze(s){return s.includes("opus")?5:(s.includes("sonnet")||s.includes("haiku"),1)}function Qe(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},costUSD:s.costUSD||0,model:s.message?.model||"unknown"}}var Z=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],r=[...e].sort((a,l)=>a.timestamp.getTime()-l.timestamp.getTime()),o=null,i=[];for(let a of r){let l=a.timestamp;if(o==null)o=this.floorToHour(l),i=[a];else {let u=l.getTime()-o.getTime(),g=i[i.length-1];if(g==null)continue;let d=g.timestamp,m=l.getTime()-d.getTime();u>t||m>t?(n.push(i),o=this.floorToHour(l),i=[a]):i.push(a);}}return o!=null&&i.length>0&&n.push(i),n}createBlockInfo(e,t){let n=new Date,r=this.sessionDurationHours*60*60*1e3,o=new Date(e.getTime()+r),i=t[t.length-1],a=i!=null?i.timestamp:e,l=n.getTime()-a.getTime()<r&&n<o;return {block:t,isActive:l}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let r=n[0];if(!r)continue;let o=this.floorToHour(r.timestamp),i=this.createBlockInfo(o,n);if(i.isActive)return i.block}return null}async loadUsageEntries(){try{c("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await q(void 0,(l,u)=>u>=e,!0),r=[];for(let l of n)if(l.message?.usage){let u=Qe(l);!u.costUSD&&l.raw&&(u.costUSD=await E.calculateCostForEntry(l.raw)),r.push(u);}let o=this.identifySessionBlocks(r);c(`Block segment: Found ${o.length} session blocks`);let i=this.findActiveBlock(o),a=[];if(i&&i.length>0){c(`Block segment: Found active block with ${i.length} entries`);let l=i[0],u=i[i.length-1];l&&u&&c(`Block segment: Active block from ${l.timestamp.toISOString()} to ${u.timestamp.toISOString()}`),a=i;}else c("Block segment: No active block found"),a=[];return a}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,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((u,g)=>u+g.costUSD,0),n=e.reduce((u,g)=>u+g.usage.inputTokens+g.usage.outputTokens+g.usage.cacheCreationInputTokens+g.usage.cacheReadInputTokens,0),r=e.reduce((u,g)=>{let d=g.usage.inputTokens+g.usage.outputTokens+g.usage.cacheCreationInputTokens+g.usage.cacheReadInputTokens,m=Ze(g.model);return u+d*m},0),o=new Date,i=null;if(e.length>0){let u=e[0];if(u){let g=this.sessionDurationHours*60*60*1e3,d=this.floorToHour(u.timestamp),m=new Date(d.getTime()+g);i=Math.max(0,Math.round((m.getTime()-o.getTime())/(1e3*60)));}}let a=null,l=null;if(e.length>=1&&(t>0||n>0)){let u=e.map(m=>m.timestamp).sort((m,f)=>m.getTime()-f.getTime()),g=u[0],d=u[u.length-1];if(g&&d){let m=(d.getTime()-g.getTime())/6e4;if(m>0){t>0&&(a=t/m*60);let f=e.reduce((h,y)=>h+y.usage.inputTokens+y.usage.outputTokens,0);f>0&&(l=f/m*60);}}}return c(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${i}m remaining, burn rate: ${a?"$"+a.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,weightedTokens:r,timeRemaining:i,burnRate:a,tokenBurnRate:l}}catch(e){return c("Error getting active block info:",e),{cost:null,tokens:null,weightedTokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function N(s){let e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function et(s){return s.inputTokens+s.outputTokens+s.cacheCreationInputTokens+s.cacheReadInputTokens}function tt(s){return {timestamp:s.timestamp,usage:{inputTokens:s.message?.usage?.input_tokens||0,outputTokens:s.message?.usage?.output_tokens||0,cacheCreationInputTokens:s.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:s.message?.usage?.cache_read_input_tokens||0},costUSD:s.costUSD||0,model:s.message?.model||"unknown"}}var Q=class{async loadTodayEntries(){let t=N(new Date);c(`Today segment: Loading entries for date ${t}`);let n=await P.getLatestTranscriptMtime(),r=await P.getUsageCache("today",n);if(r)return c("Using shared today usage cache"),r;let o=new Date;o.setDate(o.getDate()-1),o.setHours(0,0,0,0);let i=(m,f)=>f>=o,a=new Date;a.setHours(0,0,0,0);let u=await q(m=>m.timestamp>=a,i,true),g=[],d=0;for(let m of u)if(N(m.timestamp)===t&&m.message?.usage){let h=tt(m);!h.costUSD&&m.raw&&(h.costUSD=await E.calculateCostForEntry(m.raw)),g.push(h),d++;}return c(`Today segment: Found ${d} entries for today (${t})`),await P.setUsageCache("today",g,n),g}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((o,i)=>o+i.costUSD,0),n=e.reduce((o,i)=>o+et(i.usage),0),r=e.reduce((o,i)=>({input:o.input+i.usage.inputTokens,output:o.output+i.usage.outputTokens,cacheCreation:o.cacheCreation+i.usage.cacheCreationInputTokens,cacheRead:o.cacheRead+i.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return c(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:r,date:N(new Date)}}catch(e){return c("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:N(new Date)}}}};var 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_lines_added:"+",metrics_lines_removed:"-",metrics_burn:"\u27E2",version:"\u25C8"};var ee=class{constructor(e){this.config=e;this.symbols=this.initializeSymbols();}symbols;_usageProvider;_blockProvider;_todayProvider;_contextProvider;_gitService;_tmuxService;_metricsProvider;_segmentRenderer;get usageProvider(){return this._usageProvider||(this._usageProvider=new L),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 I),this._contextProvider}get gitService(){return this._gitService||(this._gitService=new F),this._gitService}get tmuxService(){return this._tmuxService||(this._tmuxService=new M),this._tmuxService}get metricsProvider(){return this._metricsProvider||(this._metricsProvider=new j),this._metricsProvider}get segmentRenderer(){return this._segmentRenderer||(this._segmentRenderer=new O(this.config,this.symbols)),this._segmentRenderer}needsSegmentInfo(e){return this.config.display.lines.some(t=>t.segments[e]?.enabled)}async generateStatusline(e){let t=this.needsSegmentInfo("session")?await this.usageProvider.getUsageInfo(e.session_id,e):null,n=this.needsSegmentInfo("block")?await this.blockProvider.getActiveBlockInfo():null,r=this.needsSegmentInfo("today")?await this.todayProvider.getTodayInfo():null,o=this.needsSegmentInfo("context")?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,i=this.needsSegmentInfo("metrics")?await this.metricsProvider.getMetricsInfo(e.session_id,e):null;return (await Promise.all(this.config.display.lines.map(l=>this.renderLine(l,e,t,n,r,o,i)))).filter(l=>l.length>0).join(`
|
|
7
|
+
`)}async renderLine(e,t,n,r,o,i,a){let l=this.getThemeColors(),u=t.workspace?.current_dir||t.cwd||"/",g=Object.entries(e.segments).filter(([m,f])=>f?.enabled).map(([m,f])=>({type:m,config:f})),d=l.reset;for(let m=0;m<g.length;m++){let f=g[m];if(!f)continue;let h=m===g.length-1,y=h?null:g[m+1],$=y?this.getSegmentBgColor(y.type,l):"",D=await this.renderSegment(f,t,n,r,o,i,a,l,u);D&&(d+=this.formatSegment(D.bgColor,D.fgColor,D.text,h?void 0:$));}return d}async renderSegment(e,t,n,r,o,i,a,l,u){return e.type==="directory"?this.segmentRenderer.renderDirectory(t,l,e.config):e.type==="model"?this.segmentRenderer.renderModel(t,l):e.type==="git"?await this.renderGitSegment(e.config,t,l,u):e.type==="session"?this.renderSessionSegment(e.config,n,l):e.type==="tmux"?await this.renderTmuxSegment(l):e.type==="context"?this.renderContextSegment(e.config,i,l):e.type==="metrics"?this.renderMetricsSegment(e.config,a,r,l):e.type==="block"?this.renderBlockSegment(e.config,r,l):e.type==="today"?this.renderTodaySegment(e.config,o,l):e.type==="version"?this.renderVersionSegment(e.config,t,l):null}async renderGitSegment(e,t,n,r){if(!this.needsSegmentInfo("git"))return null;let o=await this.gitService.getGitInfo(r,{showSha:e?.showSha,showWorkingTree:e?.showWorkingTree,showOperation:e?.showOperation,showTag:e?.showTag,showTimeSinceCommit:e?.showTimeSinceCommit,showStashCount:e?.showStashCount,showUpstream:e?.showUpstream,showRepoName:e?.showRepoName},t.workspace?.project_dir);return o?this.segmentRenderer.renderGit(o,n,e):null}renderSessionSegment(e,t,n){return t?this.segmentRenderer.renderSession(t,n,e):null}async renderTmuxSegment(e){if(!this.needsSegmentInfo("tmux"))return null;let t=await this.tmuxService.getSessionId();return this.segmentRenderer.renderTmux(t,e)}renderContextSegment(e,t,n){return this.needsSegmentInfo("context")?this.segmentRenderer.renderContext(t,n,e):null}renderMetricsSegment(e,t,n,r){return this.segmentRenderer.renderMetrics(t,r,n,e)}renderBlockSegment(e,t,n){return t?this.segmentRenderer.renderBlock(t,n,e):null}renderTodaySegment(e,t,n){if(!t)return null;let r=e?.type||"cost";return this.segmentRenderer.renderToday(t,n,r)}renderVersionSegment(e,t,n){return this.segmentRenderer.renderVersion(t,n,e)}initializeSymbols(){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_lines_added:p.metrics_lines_added,metrics_lines_removed:p.metrics_lines_removed,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"),r=y=>{let $=t[y]||n[y];return {bg:se($.bg,true),fg:se($.fg,false)}},o=r("directory"),i=r("git"),a=r("model"),l=r("session"),u=r("block"),g=r("today"),d=r("tmux"),m=r("context"),f=r("metrics"),h=r("version");return {reset:H,modeBg:o.bg,modeFg:o.fg,gitBg:i.bg,gitFg:i.fg,modelBg:a.bg,modelFg:a.fg,sessionBg:l.bg,sessionFg:l.fg,blockBg:u.bg,blockFg:u.fg,todayBg:g.bg,todayFg:g.fg,tmuxBg:d.bg,tmuxFg:d.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,r){let o=`${e}${t} ${n} `;if(r){let i=oe(e);o+=`${H}${r}${i}${this.symbols.right}`;}else o+=`${H}${oe(e)}${this.symbols.right}${H}`;return o}};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",costSource:"calculated"},today:{enabled:true,type:"cost"},block:{enabled:false,type:"cost",burnType:"cost"},version:{enabled:false},tmux:{enabled:false},context:{enabled:true,showPercentageOnly:false},metrics:{enabled:false,showResponseTime:true,showLastResponseTime:true,showDuration:true,showMessageCount:true,showLinesAdded:true,showLinesRemoved:true}}}]},budget:{session:{warningThreshold:80},today:{warningThreshold:80,amount:50},block:{warningThreshold:80,amount:15}}};function de(s){return ["light","dark","nord","tokyo-night","rose-pine","custom"].includes(s)}function fe(s){return s==="minimal"||s==="powerline"}function ne(s,e){let t={...s};for(let n in e){let r=e[n];if(r!==void 0)if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=t[n]||{};t[n]=ne(o,r);}else t[n]=r;}return t}function nt(s,e){return s?w.existsSync(s)?s:null:[...e?[_.join(e,".claude-powerline.json")]:[],_.join(process.cwd(),".claude-powerline.json"),_.join(U.homedir(),".claude","claude-powerline.json"),_.join(U.homedir(),".config","claude-powerline","config.json")].find(w.existsSync)||null}function rt(s){try{let e=w.readFileSync(s,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${s}: ${e instanceof Error?e.message:String(e)}`)}}function st(){let s={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&de(t)&&(s.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(fe(n)?e.style=n:(console.warn(`Invalid display style '${n}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(s.display=e),s}function ot(){return process.env.CLAUDE_POWERLINE_CONFIG}function it(s){let e={},t={},n=s.find(o=>o.startsWith("--theme="))?.split("=")[1];n&&de(n)&&(e.theme=n);let r=s.find(o=>o.startsWith("--style="))?.split("=")[1];return r&&(fe(r)?t.style=r:(console.warn(`Invalid display style '${r}' from CLI argument, falling back to 'minimal'`),t.style="minimal")),Object.keys(t).length>0&&(e.display=t),e}function at(s=process.argv,e){let t=JSON.parse(JSON.stringify(Te)),n=s.find(a=>a.startsWith("--config="))?.split("=")[1]||ot(),r=nt(n,e);if(r)try{let a=rt(r);t=ne(t,a);}catch(a){console.warn(`Warning: ${a instanceof Error?a.message:String(a)}`);}t.display?.style&&!fe(t.display.style)&&(console.warn(`Invalid display style '${t.display.style}' in config file, falling back to 'minimal'`),t.display.style="minimal"),t.theme&&!de(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let o=st();t=ne(t,o);let i=it(s);return t=ne(t,i),t}var Pe=at;async function lt(){try{let s=U.platform(),e;if(s==="darwin")e=_.join(U.homedir(),"Library","Fonts");else if(s==="linux")e=_.join(U.homedir(),".local","share","fonts");else if(s==="win32")e=_.join(U.homedir(),"AppData","Local","Microsoft","Windows","Fonts");else {console.log("Unsupported platform for font installation");return}w.existsSync(e)||w.mkdirSync(e,{recursive:!0}),console.log("Installing Powerline Fonts..."),console.log("Downloading from https://github.com/powerline/fonts");let t=_.join(U.tmpdir(),"powerline-fonts"),n=()=>{w.existsSync(t)&&w.rmSync(t,{recursive:!0,force:!0});};b.on("SIGINT",n),b.on("SIGTERM",n);try{w.existsSync(t)&&w.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:U.tmpdir()}),console.log("Installing fonts...");let r=_.join(t,"install.sh");if(w.existsSync(r))w.chmodSync(r,493),execSync("./install.sh",{stdio:"inherit",cwd:t});else throw new Error("Install script not found in powerline fonts repository");console.log("Powerline fonts installation complete!"),console.log("Please restart your terminal and set your terminal font to a powerline font."),console.log("Popular choices: Source Code Pro Powerline, DejaVu Sans Mono Powerline, Ubuntu Mono Powerline");}finally{n(),b.removeListener("SIGINT",n),b.removeListener("SIGTERM",n);}}catch(s){console.error("Error installing fonts:",s instanceof Error?s.message:String(s)),console.log("You can manually install fonts from: https://github.com/powerline/fonts");}}function ve(){console.log(`
|
|
9
8
|
claude-powerline - Beautiful powerline statusline for Claude Code
|
|
10
9
|
|
|
11
10
|
Usage: claude-powerline [options]
|
|
@@ -24,7 +23,7 @@ Claude Code Options (for settings.json):
|
|
|
24
23
|
|
|
25
24
|
See example config at: https://github.com/Owloops/claude-powerline/blob/main/.claude-powerline.json
|
|
26
25
|
|
|
27
|
-
`);}async function
|
|
26
|
+
`);}async function ut(){try{let s=b.argv.includes("--help")||b.argv.includes("-h");b.argv.includes("--install-fonts")&&(await lt(),b.exit(0)),s&&(ve(),b.exit(0)),b.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
28
27
|
|
|
29
28
|
claude-powerline is designed to be used as a Claude Code statusLine command.
|
|
30
29
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -40,4 +39,4 @@ Add to ~/.claude/settings.json:
|
|
|
40
39
|
Run with --help for more options.
|
|
41
40
|
|
|
42
41
|
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`),
|
|
42
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-3-5-sonnet","display_name":"Claude"}}' | claude-powerline --style=powerline`),b.exit(1)),c(`Working directory: ${b.cwd()}`),c("Process args:",b.argv);let t=await json(b.stdin);c("Received hook data:",JSON.stringify(t,null,2)),t||(console.error("Error: No input data received from stdin"),ve(),b.exit(1));let n=t.workspace?.project_dir,r=Pe(b.argv,n),i=await new ee(r).generateStatusline(t);console.log(i);}catch(s){let e=s instanceof Error?s.message:String(s);console.error("Error generating statusline:",e),b.exit(1);}}ut();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owloops/claude-powerline",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.2",
|
|
4
4
|
"description": "Beautiful vim-style powerline statusline for Claude Code with real-time usage tracking, git integration, and custom themes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|