@owloops/claude-powerline 1.6.2 → 1.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +10 -2822
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2796 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
}) : x)(function(
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
});
|
|
8
|
-
|
|
9
|
-
// src/index.ts
|
|
10
|
-
import process2 from "process";
|
|
11
|
-
import path4 from "path";
|
|
12
|
-
import fs3 from "fs";
|
|
13
|
-
import { execSync as execSync4 } from "child_process";
|
|
14
|
-
import os2 from "os";
|
|
15
|
-
import { json } from "stream/consumers";
|
|
16
|
-
|
|
17
|
-
// src/utils/colors.ts
|
|
18
|
-
function hexToAnsi(hex, isBackground) {
|
|
19
|
-
if (isBackground && (hex.toLowerCase() === "transparent" || hex.toLowerCase() === "none")) {
|
|
20
|
-
return "\x1B[49m";
|
|
21
|
-
}
|
|
22
|
-
const r = parseInt(hex.slice(1, 3), 16);
|
|
23
|
-
const g = parseInt(hex.slice(3, 5), 16);
|
|
24
|
-
const b = parseInt(hex.slice(5, 7), 16);
|
|
25
|
-
return `\x1B[${isBackground ? "48" : "38"};2;${r};${g};${b}m`;
|
|
26
|
-
}
|
|
27
|
-
function extractBgToFg(ansiCode) {
|
|
28
|
-
const match = ansiCode.match(/48;2;(\d+);(\d+);(\d+)/);
|
|
29
|
-
if (match) {
|
|
30
|
-
return `\x1B[38;2;${match[1]};${match[2]};${match[3]}m`;
|
|
31
|
-
}
|
|
32
|
-
return ansiCode.replace("48", "38");
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// src/themes/dark.ts
|
|
36
|
-
var darkTheme = {
|
|
37
|
-
directory: { bg: "#8b4513", fg: "#ffffff" },
|
|
38
|
-
git: { bg: "#404040", fg: "#ffffff" },
|
|
39
|
-
model: { bg: "#2d2d2d", fg: "#ffffff" },
|
|
40
|
-
session: { bg: "#202020", fg: "#00ffff" },
|
|
41
|
-
block: { bg: "#2a2a2a", fg: "#87ceeb" },
|
|
42
|
-
today: { bg: "#1a1a1a", fg: "#98fb98" },
|
|
43
|
-
tmux: { bg: "#2f4f2f", fg: "#90ee90" },
|
|
44
|
-
context: { bg: "#4a5568", fg: "#cbd5e0" },
|
|
45
|
-
metrics: { bg: "#374151", fg: "#d1d5db" },
|
|
46
|
-
version: { bg: "#3a3a4a", fg: "#b8b8d0" }
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
// src/themes/light.ts
|
|
50
|
-
var lightTheme = {
|
|
51
|
-
directory: { bg: "#ff6b47", fg: "#ffffff" },
|
|
52
|
-
git: { bg: "#4fb3d9", fg: "#ffffff" },
|
|
53
|
-
model: { bg: "#87ceeb", fg: "#000000" },
|
|
54
|
-
session: { bg: "#da70d6", fg: "#ffffff" },
|
|
55
|
-
block: { bg: "#6366f1", fg: "#ffffff" },
|
|
56
|
-
today: { bg: "#10b981", fg: "#ffffff" },
|
|
57
|
-
tmux: { bg: "#32cd32", fg: "#ffffff" },
|
|
58
|
-
context: { bg: "#718096", fg: "#ffffff" },
|
|
59
|
-
metrics: { bg: "#6b7280", fg: "#ffffff" },
|
|
60
|
-
version: { bg: "#8b7dd8", fg: "#ffffff" }
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
// src/themes/nord.ts
|
|
64
|
-
var nordTheme = {
|
|
65
|
-
directory: { bg: "#434c5e", fg: "#d8dee9" },
|
|
66
|
-
git: { bg: "#3b4252", fg: "#a3be8c" },
|
|
67
|
-
model: { bg: "#4c566a", fg: "#81a1c1" },
|
|
68
|
-
session: { bg: "#2e3440", fg: "#88c0d0" },
|
|
69
|
-
block: { bg: "#3b4252", fg: "#81a1c1" },
|
|
70
|
-
today: { bg: "#2e3440", fg: "#8fbcbb" },
|
|
71
|
-
tmux: { bg: "#2e3440", fg: "#8fbcbb" },
|
|
72
|
-
context: { bg: "#5e81ac", fg: "#eceff4" },
|
|
73
|
-
metrics: { bg: "#b48ead", fg: "#2e3440" },
|
|
74
|
-
version: { bg: "#434c5e", fg: "#88c0d0" }
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
// src/themes/tokyo-night.ts
|
|
78
|
-
var tokyoNightTheme = {
|
|
79
|
-
directory: { bg: "#2f334d", fg: "#82aaff" },
|
|
80
|
-
git: { bg: "#1e2030", fg: "#c3e88d" },
|
|
81
|
-
model: { bg: "#191b29", fg: "#fca7ea" },
|
|
82
|
-
session: { bg: "#222436", fg: "#86e1fc" },
|
|
83
|
-
block: { bg: "#2d3748", fg: "#7aa2f7" },
|
|
84
|
-
today: { bg: "#1a202c", fg: "#4fd6be" },
|
|
85
|
-
tmux: { bg: "#191b29", fg: "#4fd6be" },
|
|
86
|
-
context: { bg: "#414868", fg: "#c0caf5" },
|
|
87
|
-
metrics: { bg: "#3d59a1", fg: "#c0caf5" },
|
|
88
|
-
version: { bg: "#292e42", fg: "#bb9af7" }
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
// src/themes/rose-pine.ts
|
|
92
|
-
var rosePineTheme = {
|
|
93
|
-
directory: { bg: "#26233a", fg: "#c4a7e7" },
|
|
94
|
-
git: { bg: "#1f1d2e", fg: "#9ccfd8" },
|
|
95
|
-
model: { bg: "#191724", fg: "#ebbcba" },
|
|
96
|
-
session: { bg: "#26233a", fg: "#f6c177" },
|
|
97
|
-
block: { bg: "#2a273f", fg: "#eb6f92" },
|
|
98
|
-
today: { bg: "#232136", fg: "#9ccfd8" },
|
|
99
|
-
tmux: { bg: "#26233a", fg: "#908caa" },
|
|
100
|
-
context: { bg: "#393552", fg: "#e0def4" },
|
|
101
|
-
metrics: { bg: "#524f67", fg: "#e0def4" },
|
|
102
|
-
version: { bg: "#2a273f", fg: "#c4a7e7" }
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
// src/themes/index.ts
|
|
106
|
-
var BUILT_IN_THEMES = {
|
|
107
|
-
dark: darkTheme,
|
|
108
|
-
light: lightTheme,
|
|
109
|
-
nord: nordTheme,
|
|
110
|
-
"tokyo-night": tokyoNightTheme,
|
|
111
|
-
"rose-pine": rosePineTheme
|
|
112
|
-
};
|
|
113
|
-
function getTheme(themeName) {
|
|
114
|
-
return BUILT_IN_THEMES[themeName] || null;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// src/segments/git.ts
|
|
118
|
-
import { execSync } from "child_process";
|
|
119
|
-
import fs from "fs";
|
|
120
|
-
import path from "path";
|
|
121
|
-
|
|
122
|
-
// src/utils/logger.ts
|
|
123
|
-
var debug = (message, ...args) => {
|
|
124
|
-
if (process.env.CLAUDE_POWERLINE_DEBUG) {
|
|
125
|
-
console.error(`[DEBUG] ${message}`, ...args);
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
|
|
129
|
-
// src/segments/git.ts
|
|
130
|
-
var GitService = class {
|
|
131
|
-
cache = /* @__PURE__ */ new Map();
|
|
132
|
-
CACHE_TTL = 1e3;
|
|
133
|
-
isGitRepo(workingDir) {
|
|
134
|
-
try {
|
|
135
|
-
return fs.existsSync(path.join(workingDir, ".git"));
|
|
136
|
-
} catch {
|
|
137
|
-
return false;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
getGitInfo(workingDir, options = {}, projectDir) {
|
|
141
|
-
const gitDir = projectDir && this.isGitRepo(projectDir) ? projectDir : workingDir;
|
|
142
|
-
const optionsKey = JSON.stringify(options);
|
|
143
|
-
const cacheKey = `${gitDir}:${optionsKey}`;
|
|
144
|
-
const cached = this.cache.get(cacheKey);
|
|
145
|
-
const now = Date.now();
|
|
146
|
-
if (cached && now - cached.timestamp < this.CACHE_TTL) {
|
|
147
|
-
return cached.data;
|
|
148
|
-
}
|
|
149
|
-
if (!this.isGitRepo(gitDir)) {
|
|
150
|
-
this.cache.set(cacheKey, { data: null, timestamp: now });
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
try {
|
|
154
|
-
const branch = this.getBranch(gitDir);
|
|
155
|
-
const status = this.getStatus(gitDir);
|
|
156
|
-
const { ahead, behind } = this.getAheadBehind(gitDir);
|
|
157
|
-
const result = {
|
|
158
|
-
branch: branch || "detached",
|
|
159
|
-
status,
|
|
160
|
-
ahead,
|
|
161
|
-
behind
|
|
162
|
-
};
|
|
163
|
-
if (options.showSha) {
|
|
164
|
-
result.sha = this.getSha(gitDir) || void 0;
|
|
165
|
-
}
|
|
166
|
-
if (options.showWorkingTree) {
|
|
167
|
-
const counts = this.getWorkingTreeCounts(gitDir);
|
|
168
|
-
result.staged = counts.staged;
|
|
169
|
-
result.unstaged = counts.unstaged;
|
|
170
|
-
result.untracked = counts.untracked;
|
|
171
|
-
result.conflicts = counts.conflicts;
|
|
172
|
-
}
|
|
173
|
-
if (options.showOperation) {
|
|
174
|
-
result.operation = this.getOngoingOperation(gitDir) || void 0;
|
|
175
|
-
}
|
|
176
|
-
if (options.showTag) {
|
|
177
|
-
result.tag = this.getNearestTag(gitDir) || void 0;
|
|
178
|
-
}
|
|
179
|
-
if (options.showTimeSinceCommit) {
|
|
180
|
-
result.timeSinceCommit = this.getTimeSinceLastCommit(gitDir) || void 0;
|
|
181
|
-
}
|
|
182
|
-
if (options.showStashCount) {
|
|
183
|
-
result.stashCount = this.getStashCount(gitDir);
|
|
184
|
-
}
|
|
185
|
-
if (options.showUpstream) {
|
|
186
|
-
result.upstream = this.getUpstream(gitDir) || void 0;
|
|
187
|
-
}
|
|
188
|
-
if (options.showRepoName) {
|
|
189
|
-
result.repoName = this.getRepoName(gitDir) || void 0;
|
|
190
|
-
result.isWorktree = this.isWorktree(gitDir);
|
|
191
|
-
}
|
|
192
|
-
this.cache.set(cacheKey, { data: result, timestamp: now });
|
|
193
|
-
return result;
|
|
194
|
-
} catch {
|
|
195
|
-
this.cache.set(cacheKey, { data: null, timestamp: now });
|
|
196
|
-
return null;
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
getBranch(workingDir) {
|
|
200
|
-
try {
|
|
201
|
-
return execSync("git branch --show-current", {
|
|
202
|
-
cwd: workingDir,
|
|
203
|
-
encoding: "utf8",
|
|
204
|
-
timeout: 5e3
|
|
205
|
-
}).trim() || null;
|
|
206
|
-
} catch (error) {
|
|
207
|
-
debug(`Git branch command failed in ${workingDir}:`, error);
|
|
208
|
-
return null;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
getStatus(workingDir) {
|
|
212
|
-
try {
|
|
213
|
-
const gitStatus = execSync("git status --porcelain", {
|
|
214
|
-
cwd: workingDir,
|
|
215
|
-
encoding: "utf8",
|
|
216
|
-
timeout: 5e3
|
|
217
|
-
}).trim();
|
|
218
|
-
if (!gitStatus) return "clean";
|
|
219
|
-
if (gitStatus.includes("UU") || gitStatus.includes("AA") || gitStatus.includes("DD")) {
|
|
220
|
-
return "conflicts";
|
|
221
|
-
}
|
|
222
|
-
return "dirty";
|
|
223
|
-
} catch (error) {
|
|
224
|
-
debug(`Git status command failed in ${workingDir}:`, error);
|
|
225
|
-
return "clean";
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
getWorkingTreeCounts(workingDir) {
|
|
229
|
-
try {
|
|
230
|
-
const gitStatus = execSync("git status --porcelain=v1", {
|
|
231
|
-
cwd: workingDir,
|
|
232
|
-
encoding: "utf8",
|
|
233
|
-
timeout: 5e3
|
|
234
|
-
});
|
|
235
|
-
let staged = 0;
|
|
236
|
-
let unstaged = 0;
|
|
237
|
-
let untracked = 0;
|
|
238
|
-
let conflicts = 0;
|
|
239
|
-
if (!gitStatus.trim()) {
|
|
240
|
-
return { staged, unstaged, untracked, conflicts };
|
|
241
|
-
}
|
|
242
|
-
const lines = gitStatus.split("\n");
|
|
243
|
-
for (const line of lines) {
|
|
244
|
-
if (!line || line.length < 2) continue;
|
|
245
|
-
const indexStatus = line.charAt(0);
|
|
246
|
-
const worktreeStatus = line.charAt(1);
|
|
247
|
-
if (indexStatus === "?" && worktreeStatus === "?") {
|
|
248
|
-
untracked++;
|
|
249
|
-
continue;
|
|
250
|
-
}
|
|
251
|
-
const statusPair = indexStatus + worktreeStatus;
|
|
252
|
-
if (["DD", "AU", "UD", "UA", "DU", "AA", "UU"].includes(statusPair)) {
|
|
253
|
-
conflicts++;
|
|
254
|
-
continue;
|
|
255
|
-
}
|
|
256
|
-
if (indexStatus !== " " && indexStatus !== "?") {
|
|
257
|
-
staged++;
|
|
258
|
-
}
|
|
259
|
-
if (worktreeStatus !== " " && worktreeStatus !== "?") {
|
|
260
|
-
unstaged++;
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
return { staged, unstaged, untracked, conflicts };
|
|
264
|
-
} catch (error) {
|
|
265
|
-
debug(`Git working tree counts failed in ${workingDir}:`, error);
|
|
266
|
-
return { staged: 0, unstaged: 0, untracked: 0, conflicts: 0 };
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
getAheadBehind(workingDir) {
|
|
270
|
-
try {
|
|
271
|
-
const aheadResult = execSync("git rev-list --count @{u}..HEAD", {
|
|
272
|
-
cwd: workingDir,
|
|
273
|
-
encoding: "utf8",
|
|
274
|
-
timeout: 5e3
|
|
275
|
-
}).trim();
|
|
276
|
-
const behindResult = execSync("git rev-list --count HEAD..@{u}", {
|
|
277
|
-
cwd: workingDir,
|
|
278
|
-
encoding: "utf8",
|
|
279
|
-
timeout: 5e3
|
|
280
|
-
}).trim();
|
|
281
|
-
return {
|
|
282
|
-
ahead: parseInt(aheadResult) || 0,
|
|
283
|
-
behind: parseInt(behindResult) || 0
|
|
284
|
-
};
|
|
285
|
-
} catch (error) {
|
|
286
|
-
debug(`Git ahead/behind command failed in ${workingDir}:`, error);
|
|
287
|
-
return { ahead: 0, behind: 0 };
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
getSha(workingDir) {
|
|
291
|
-
try {
|
|
292
|
-
const sha = execSync("git rev-parse --short=7 HEAD", {
|
|
293
|
-
cwd: workingDir,
|
|
294
|
-
encoding: "utf8",
|
|
295
|
-
timeout: 5e3
|
|
296
|
-
}).trim();
|
|
297
|
-
return sha || null;
|
|
298
|
-
} catch {
|
|
299
|
-
return null;
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
getOngoingOperation(workingDir) {
|
|
303
|
-
try {
|
|
304
|
-
const gitDir = path.join(workingDir, ".git");
|
|
305
|
-
if (fs.existsSync(path.join(gitDir, "MERGE_HEAD"))) return "MERGE";
|
|
306
|
-
if (fs.existsSync(path.join(gitDir, "CHERRY_PICK_HEAD")))
|
|
307
|
-
return "CHERRY-PICK";
|
|
308
|
-
if (fs.existsSync(path.join(gitDir, "REVERT_HEAD"))) return "REVERT";
|
|
309
|
-
if (fs.existsSync(path.join(gitDir, "BISECT_LOG"))) return "BISECT";
|
|
310
|
-
if (fs.existsSync(path.join(gitDir, "rebase-merge")) || fs.existsSync(path.join(gitDir, "rebase-apply")))
|
|
311
|
-
return "REBASE";
|
|
312
|
-
return null;
|
|
313
|
-
} catch {
|
|
314
|
-
return null;
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
getNearestTag(workingDir) {
|
|
318
|
-
try {
|
|
319
|
-
const tag = execSync("git describe --tags --abbrev=0", {
|
|
320
|
-
cwd: workingDir,
|
|
321
|
-
encoding: "utf8",
|
|
322
|
-
timeout: 5e3
|
|
323
|
-
}).trim();
|
|
324
|
-
return tag || null;
|
|
325
|
-
} catch {
|
|
326
|
-
return null;
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
getTimeSinceLastCommit(workingDir) {
|
|
330
|
-
try {
|
|
331
|
-
const timestamp = execSync("git log -1 --format=%ct", {
|
|
332
|
-
cwd: workingDir,
|
|
333
|
-
encoding: "utf8",
|
|
334
|
-
timeout: 5e3
|
|
335
|
-
}).trim();
|
|
336
|
-
if (!timestamp) return null;
|
|
337
|
-
const commitTime = parseInt(timestamp) * 1e3;
|
|
338
|
-
const now = Date.now();
|
|
339
|
-
return Math.floor((now - commitTime) / 1e3);
|
|
340
|
-
} catch {
|
|
341
|
-
return null;
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
getStashCount(workingDir) {
|
|
345
|
-
try {
|
|
346
|
-
const stashList = execSync("git stash list", {
|
|
347
|
-
cwd: workingDir,
|
|
348
|
-
encoding: "utf8",
|
|
349
|
-
timeout: 5e3
|
|
350
|
-
}).trim();
|
|
351
|
-
if (!stashList) return 0;
|
|
352
|
-
return stashList.split("\n").length;
|
|
353
|
-
} catch {
|
|
354
|
-
return 0;
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
getUpstream(workingDir) {
|
|
358
|
-
try {
|
|
359
|
-
const upstream = execSync("git rev-parse --abbrev-ref @{u}", {
|
|
360
|
-
cwd: workingDir,
|
|
361
|
-
encoding: "utf8",
|
|
362
|
-
timeout: 5e3
|
|
363
|
-
}).trim();
|
|
364
|
-
return upstream || null;
|
|
365
|
-
} catch {
|
|
366
|
-
return null;
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
getRepoName(workingDir) {
|
|
370
|
-
try {
|
|
371
|
-
const remoteUrl = execSync("git config --get remote.origin.url", {
|
|
372
|
-
cwd: workingDir,
|
|
373
|
-
encoding: "utf8",
|
|
374
|
-
timeout: 5e3
|
|
375
|
-
}).trim();
|
|
376
|
-
if (!remoteUrl) return path.basename(workingDir);
|
|
377
|
-
const match = remoteUrl.match(/\/([^/]+?)(\.git)?$/);
|
|
378
|
-
return match?.[1] || path.basename(workingDir);
|
|
379
|
-
} catch {
|
|
380
|
-
return path.basename(workingDir);
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
isWorktree(workingDir) {
|
|
384
|
-
try {
|
|
385
|
-
const gitDir = path.join(workingDir, ".git");
|
|
386
|
-
if (fs.existsSync(gitDir) && fs.statSync(gitDir).isFile()) {
|
|
387
|
-
return true;
|
|
388
|
-
}
|
|
389
|
-
return false;
|
|
390
|
-
} catch {
|
|
391
|
-
return false;
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
};
|
|
395
|
-
|
|
396
|
-
// src/segments/tmux.ts
|
|
397
|
-
import { execSync as execSync2 } from "child_process";
|
|
398
|
-
var TmuxService = class {
|
|
399
|
-
getSessionId() {
|
|
400
|
-
try {
|
|
401
|
-
if (!process.env.TMUX_PANE) {
|
|
402
|
-
debug(`TMUX_PANE not set, not in tmux session`);
|
|
403
|
-
return null;
|
|
404
|
-
}
|
|
405
|
-
debug(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);
|
|
406
|
-
const sessionId = execSync2("tmux display-message -p '#S'", {
|
|
407
|
-
encoding: "utf8",
|
|
408
|
-
timeout: 1e3
|
|
409
|
-
}).trim();
|
|
410
|
-
debug(`Tmux session ID: ${sessionId || "empty"}`);
|
|
411
|
-
return sessionId || null;
|
|
412
|
-
} catch (error) {
|
|
413
|
-
debug(`Error getting tmux session ID:`, error);
|
|
414
|
-
return null;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
isInTmux() {
|
|
418
|
-
return !!process.env.TMUX_PANE;
|
|
419
|
-
}
|
|
420
|
-
};
|
|
421
|
-
|
|
422
|
-
// src/segments/pricing.ts
|
|
423
|
-
var OFFLINE_PRICING_DATA = {
|
|
424
|
-
"claude-3-haiku-20240307": {
|
|
425
|
-
name: "Claude 3 Haiku",
|
|
426
|
-
input: 0.25,
|
|
427
|
-
output: 1.25,
|
|
428
|
-
cache_write_5m: 0.3,
|
|
429
|
-
cache_write_1h: 0.5,
|
|
430
|
-
cache_read: 0.03
|
|
431
|
-
},
|
|
432
|
-
"claude-3-5-haiku-20241022": {
|
|
433
|
-
name: "Claude 3.5 Haiku",
|
|
434
|
-
input: 0.8,
|
|
435
|
-
output: 4,
|
|
436
|
-
cache_write_5m: 1,
|
|
437
|
-
cache_write_1h: 1.6,
|
|
438
|
-
cache_read: 0.08
|
|
439
|
-
},
|
|
440
|
-
"claude-3-5-haiku-latest": {
|
|
441
|
-
name: "Claude 3.5 Haiku Latest",
|
|
442
|
-
input: 1,
|
|
443
|
-
output: 5,
|
|
444
|
-
cache_write_5m: 1.25,
|
|
445
|
-
cache_write_1h: 2,
|
|
446
|
-
cache_read: 0.1
|
|
447
|
-
},
|
|
448
|
-
"claude-3-opus-latest": {
|
|
449
|
-
name: "Claude 3 Opus Latest",
|
|
450
|
-
input: 15,
|
|
451
|
-
output: 75,
|
|
452
|
-
cache_write_5m: 18.75,
|
|
453
|
-
cache_write_1h: 30,
|
|
454
|
-
cache_read: 1.5
|
|
455
|
-
},
|
|
456
|
-
"claude-3-opus-20240229": {
|
|
457
|
-
name: "Claude 3 Opus",
|
|
458
|
-
input: 15,
|
|
459
|
-
output: 75,
|
|
460
|
-
cache_write_5m: 18.75,
|
|
461
|
-
cache_write_1h: 30,
|
|
462
|
-
cache_read: 1.5
|
|
463
|
-
},
|
|
464
|
-
"claude-3-5-sonnet-latest": {
|
|
465
|
-
name: "Claude 3.5 Sonnet Latest",
|
|
466
|
-
input: 3,
|
|
467
|
-
output: 15,
|
|
468
|
-
cache_write_5m: 3.75,
|
|
469
|
-
cache_write_1h: 6,
|
|
470
|
-
cache_read: 0.3
|
|
471
|
-
},
|
|
472
|
-
"claude-3-5-sonnet-20240620": {
|
|
473
|
-
name: "Claude 3.5 Sonnet",
|
|
474
|
-
input: 3,
|
|
475
|
-
output: 15,
|
|
476
|
-
cache_write_5m: 3.75,
|
|
477
|
-
cache_write_1h: 6,
|
|
478
|
-
cache_read: 0.3
|
|
479
|
-
},
|
|
480
|
-
"claude-3-5-sonnet-20241022": {
|
|
481
|
-
name: "Claude 3.5 Sonnet",
|
|
482
|
-
input: 3,
|
|
483
|
-
output: 15,
|
|
484
|
-
cache_write_5m: 3.75,
|
|
485
|
-
cache_write_1h: 6,
|
|
486
|
-
cache_read: 0.3
|
|
487
|
-
},
|
|
488
|
-
"claude-opus-4-20250514": {
|
|
489
|
-
name: "Claude Opus 4",
|
|
490
|
-
input: 15,
|
|
491
|
-
output: 75,
|
|
492
|
-
cache_write_5m: 18.75,
|
|
493
|
-
cache_write_1h: 30,
|
|
494
|
-
cache_read: 1.5
|
|
495
|
-
},
|
|
496
|
-
"claude-opus-4-1": {
|
|
497
|
-
name: "Claude Opus 4.1",
|
|
498
|
-
input: 15,
|
|
499
|
-
output: 75,
|
|
500
|
-
cache_write_5m: 18.75,
|
|
501
|
-
cache_write_1h: 30,
|
|
502
|
-
cache_read: 1.5
|
|
503
|
-
},
|
|
504
|
-
"claude-opus-4-1-20250805": {
|
|
505
|
-
name: "Claude Opus 4.1",
|
|
506
|
-
input: 15,
|
|
507
|
-
output: 75,
|
|
508
|
-
cache_write_5m: 18.75,
|
|
509
|
-
cache_write_1h: 30,
|
|
510
|
-
cache_read: 1.5
|
|
511
|
-
},
|
|
512
|
-
"claude-sonnet-4-20250514": {
|
|
513
|
-
name: "Claude Sonnet 4",
|
|
514
|
-
input: 3,
|
|
515
|
-
output: 15,
|
|
516
|
-
cache_write_5m: 3.75,
|
|
517
|
-
cache_write_1h: 6,
|
|
518
|
-
cache_read: 0.3
|
|
519
|
-
},
|
|
520
|
-
"claude-4-opus-20250514": {
|
|
521
|
-
name: "Claude 4 Opus",
|
|
522
|
-
input: 15,
|
|
523
|
-
output: 75,
|
|
524
|
-
cache_write_5m: 18.75,
|
|
525
|
-
cache_write_1h: 30,
|
|
526
|
-
cache_read: 1.5
|
|
527
|
-
},
|
|
528
|
-
"claude-4-sonnet-20250514": {
|
|
529
|
-
name: "Claude 4 Sonnet",
|
|
530
|
-
input: 3,
|
|
531
|
-
output: 15,
|
|
532
|
-
cache_write_5m: 3.75,
|
|
533
|
-
cache_write_1h: 6,
|
|
534
|
-
cache_read: 0.3
|
|
535
|
-
},
|
|
536
|
-
"claude-3-7-sonnet-latest": {
|
|
537
|
-
name: "Claude 3.7 Sonnet Latest",
|
|
538
|
-
input: 3,
|
|
539
|
-
output: 15,
|
|
540
|
-
cache_write_5m: 3.75,
|
|
541
|
-
cache_write_1h: 6,
|
|
542
|
-
cache_read: 0.3
|
|
543
|
-
},
|
|
544
|
-
"claude-3-7-sonnet-20250219": {
|
|
545
|
-
name: "Claude 3.7 Sonnet",
|
|
546
|
-
input: 3,
|
|
547
|
-
output: 15,
|
|
548
|
-
cache_write_5m: 3.75,
|
|
549
|
-
cache_write_1h: 6,
|
|
550
|
-
cache_read: 0.3
|
|
551
|
-
}
|
|
552
|
-
};
|
|
553
|
-
var PricingService = class {
|
|
554
|
-
static memoryCache = /* @__PURE__ */ new Map();
|
|
555
|
-
static CACHE_TTL = 24 * 60 * 60 * 1e3;
|
|
556
|
-
static GITHUB_PRICING_URL = "https://raw.githubusercontent.com/Owloops/claude-powerline/main/pricing.json";
|
|
557
|
-
static getCacheFilePath() {
|
|
558
|
-
const { homedir: homedir2 } = __require("os");
|
|
559
|
-
const { join: join2 } = __require("path");
|
|
560
|
-
const { mkdirSync } = __require("fs");
|
|
561
|
-
const cacheDir = join2(homedir2(), ".claude", "cache");
|
|
562
|
-
try {
|
|
563
|
-
mkdirSync(cacheDir, { recursive: true });
|
|
564
|
-
} catch {
|
|
565
|
-
}
|
|
566
|
-
return join2(cacheDir, "pricing.json");
|
|
567
|
-
}
|
|
568
|
-
static loadDiskCache() {
|
|
569
|
-
try {
|
|
570
|
-
const { readFileSync: readFileSync2 } = __require("fs");
|
|
571
|
-
const cacheFile = this.getCacheFilePath();
|
|
572
|
-
const content = readFileSync2(cacheFile, "utf-8");
|
|
573
|
-
const cached = JSON.parse(content);
|
|
574
|
-
if (cached && cached.data && cached.timestamp) {
|
|
575
|
-
return cached;
|
|
576
|
-
}
|
|
577
|
-
} catch {
|
|
578
|
-
}
|
|
579
|
-
return null;
|
|
580
|
-
}
|
|
581
|
-
static saveDiskCache(data) {
|
|
582
|
-
try {
|
|
583
|
-
const { writeFileSync } = __require("fs");
|
|
584
|
-
const cacheFile = this.getCacheFilePath();
|
|
585
|
-
const cacheData = { data, timestamp: Date.now() };
|
|
586
|
-
writeFileSync(cacheFile, JSON.stringify(cacheData));
|
|
587
|
-
} catch (error) {
|
|
588
|
-
debug("Failed to save pricing cache to disk:", error);
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
static async getCurrentPricing() {
|
|
592
|
-
const now = Date.now();
|
|
593
|
-
const memCached = this.memoryCache.get("pricing");
|
|
594
|
-
if (memCached && now - memCached.timestamp < this.CACHE_TTL) {
|
|
595
|
-
debug(
|
|
596
|
-
`Using memory cached pricing data for ${Object.keys(memCached.data).length} models`
|
|
597
|
-
);
|
|
598
|
-
return memCached.data;
|
|
599
|
-
}
|
|
600
|
-
const diskCached = this.loadDiskCache();
|
|
601
|
-
if (diskCached && now - diskCached.timestamp < this.CACHE_TTL) {
|
|
602
|
-
this.memoryCache.clear();
|
|
603
|
-
this.memoryCache.set("pricing", diskCached);
|
|
604
|
-
debug(
|
|
605
|
-
`Using disk cached pricing data for ${Object.keys(diskCached.data).length} models`
|
|
606
|
-
);
|
|
607
|
-
return diskCached.data;
|
|
608
|
-
}
|
|
609
|
-
try {
|
|
610
|
-
const response = await globalThis.fetch(this.GITHUB_PRICING_URL, {
|
|
611
|
-
headers: {
|
|
612
|
-
"User-Agent": "claude-powerline",
|
|
613
|
-
"Cache-Control": "no-cache"
|
|
614
|
-
}
|
|
615
|
-
});
|
|
616
|
-
if (response.ok) {
|
|
617
|
-
const data = await response.json();
|
|
618
|
-
const dataObj = data;
|
|
619
|
-
const meta = dataObj._meta;
|
|
620
|
-
const pricingData = {};
|
|
621
|
-
for (const [key, value] of Object.entries(dataObj)) {
|
|
622
|
-
if (key !== "_meta") {
|
|
623
|
-
pricingData[key] = value;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
if (this.validatePricingData(pricingData)) {
|
|
627
|
-
this.memoryCache.clear();
|
|
628
|
-
this.memoryCache.set("pricing", {
|
|
629
|
-
data: pricingData,
|
|
630
|
-
timestamp: now
|
|
631
|
-
});
|
|
632
|
-
this.saveDiskCache(pricingData);
|
|
633
|
-
debug(
|
|
634
|
-
`Fetched fresh pricing from GitHub for ${Object.keys(pricingData).length} models`
|
|
635
|
-
);
|
|
636
|
-
debug(`Pricing last updated: ${meta?.updated || "unknown"}`);
|
|
637
|
-
return pricingData;
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
} catch (error) {
|
|
641
|
-
debug("Failed to fetch pricing from GitHub, using fallback:", error);
|
|
642
|
-
}
|
|
643
|
-
if (diskCached) {
|
|
644
|
-
this.memoryCache.set("pricing", diskCached);
|
|
645
|
-
debug(
|
|
646
|
-
`Using stale cached pricing data for ${Object.keys(diskCached.data).length} models`
|
|
647
|
-
);
|
|
648
|
-
return diskCached.data;
|
|
649
|
-
}
|
|
650
|
-
debug(
|
|
651
|
-
`Using offline pricing data for ${Object.keys(OFFLINE_PRICING_DATA).length} models`
|
|
652
|
-
);
|
|
653
|
-
return OFFLINE_PRICING_DATA;
|
|
654
|
-
}
|
|
655
|
-
static validatePricingData(data) {
|
|
656
|
-
if (!data || typeof data !== "object") return false;
|
|
657
|
-
for (const [, value] of Object.entries(data)) {
|
|
658
|
-
if (!value || typeof value !== "object") return false;
|
|
659
|
-
const pricing = value;
|
|
660
|
-
if (typeof pricing.input !== "number" || typeof pricing.output !== "number" || typeof pricing.cache_read !== "number") {
|
|
661
|
-
return false;
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
return true;
|
|
665
|
-
}
|
|
666
|
-
static async getModelPricing(modelId) {
|
|
667
|
-
const allPricing = await this.getCurrentPricing();
|
|
668
|
-
if (allPricing[modelId]) {
|
|
669
|
-
return allPricing[modelId];
|
|
670
|
-
}
|
|
671
|
-
return this.fuzzyMatchModel(modelId, allPricing);
|
|
672
|
-
}
|
|
673
|
-
static fuzzyMatchModel(modelId, allPricing) {
|
|
674
|
-
const lowerModelId = modelId.toLowerCase();
|
|
675
|
-
for (const [key, pricing] of Object.entries(allPricing)) {
|
|
676
|
-
if (key.toLowerCase() === lowerModelId) {
|
|
677
|
-
return pricing;
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
const patterns = [
|
|
681
|
-
{
|
|
682
|
-
pattern: ["opus-4-1", "claude-opus-4-1"],
|
|
683
|
-
fallback: "claude-opus-4-1-20250805"
|
|
684
|
-
},
|
|
685
|
-
{
|
|
686
|
-
pattern: ["opus-4", "claude-opus-4"],
|
|
687
|
-
fallback: "claude-opus-4-20250514"
|
|
688
|
-
},
|
|
689
|
-
{
|
|
690
|
-
pattern: ["sonnet-4", "claude-sonnet-4"],
|
|
691
|
-
fallback: "claude-sonnet-4-20250514"
|
|
692
|
-
},
|
|
693
|
-
{
|
|
694
|
-
pattern: ["sonnet-3.7", "3-7-sonnet"],
|
|
695
|
-
fallback: "claude-3-7-sonnet-20250219"
|
|
696
|
-
},
|
|
697
|
-
{
|
|
698
|
-
pattern: ["3-5-sonnet", "sonnet-3.5"],
|
|
699
|
-
fallback: "claude-3-5-sonnet-20241022"
|
|
700
|
-
},
|
|
701
|
-
{
|
|
702
|
-
pattern: ["3-5-haiku", "haiku-3.5"],
|
|
703
|
-
fallback: "claude-3-5-haiku-20241022"
|
|
704
|
-
},
|
|
705
|
-
{ pattern: ["haiku", "3-haiku"], fallback: "claude-3-haiku-20240307" },
|
|
706
|
-
{ pattern: ["opus"], fallback: "claude-opus-4-20250514" },
|
|
707
|
-
{ pattern: ["sonnet"], fallback: "claude-3-5-sonnet-20241022" }
|
|
708
|
-
];
|
|
709
|
-
for (const { pattern, fallback } of patterns) {
|
|
710
|
-
if (pattern.some((p) => lowerModelId.includes(p))) {
|
|
711
|
-
if (allPricing[fallback]) {
|
|
712
|
-
return allPricing[fallback];
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
return allPricing["claude-3-5-sonnet-20241022"] || {
|
|
717
|
-
name: `${modelId} (Unknown Model)`,
|
|
718
|
-
input: 3,
|
|
719
|
-
cache_write_5m: 3.75,
|
|
720
|
-
cache_write_1h: 6,
|
|
721
|
-
cache_read: 0.3,
|
|
722
|
-
output: 15
|
|
723
|
-
};
|
|
724
|
-
}
|
|
725
|
-
static async calculateCostForEntry(entry) {
|
|
726
|
-
const message = entry.message;
|
|
727
|
-
const usage = message?.usage;
|
|
728
|
-
if (!usage) return 0;
|
|
729
|
-
const modelId = this.extractModelId(entry);
|
|
730
|
-
const pricing = await this.getModelPricing(modelId);
|
|
731
|
-
const inputTokens = usage.input_tokens || 0;
|
|
732
|
-
const outputTokens = usage.output_tokens || 0;
|
|
733
|
-
const cacheCreationTokens = usage.cache_creation_input_tokens || 0;
|
|
734
|
-
const cacheReadTokens = usage.cache_read_input_tokens || 0;
|
|
735
|
-
const inputCost = inputTokens / 1e6 * pricing.input;
|
|
736
|
-
const outputCost = outputTokens / 1e6 * pricing.output;
|
|
737
|
-
const cacheReadCost = cacheReadTokens / 1e6 * pricing.cache_read;
|
|
738
|
-
const cacheCreationCost = cacheCreationTokens / 1e6 * pricing.cache_write_5m;
|
|
739
|
-
return inputCost + outputCost + cacheCreationCost + cacheReadCost;
|
|
740
|
-
}
|
|
741
|
-
static extractModelId(entry) {
|
|
742
|
-
if (entry.model && typeof entry.model === "string") {
|
|
743
|
-
return entry.model;
|
|
744
|
-
}
|
|
745
|
-
const message = entry.message;
|
|
746
|
-
if (message?.model) {
|
|
747
|
-
const model = message.model;
|
|
748
|
-
if (typeof model === "string") {
|
|
749
|
-
return model;
|
|
750
|
-
}
|
|
751
|
-
return model?.id || "claude-3-5-sonnet-20241022";
|
|
752
|
-
}
|
|
753
|
-
if (entry.model_id && typeof entry.model_id === "string") {
|
|
754
|
-
return entry.model_id;
|
|
755
|
-
}
|
|
756
|
-
return "claude-3-5-sonnet-20241022";
|
|
757
|
-
}
|
|
758
|
-
};
|
|
759
|
-
|
|
760
|
-
// src/utils/claude.ts
|
|
761
|
-
import { readdir, readFile, stat } from "fs/promises";
|
|
762
|
-
import { existsSync } from "fs";
|
|
763
|
-
import { join, posix } from "path";
|
|
764
|
-
import { homedir } from "os";
|
|
765
|
-
function getClaudePaths() {
|
|
766
|
-
const paths = [];
|
|
767
|
-
const envPath = process.env.CLAUDE_CONFIG_DIR;
|
|
768
|
-
if (envPath) {
|
|
769
|
-
envPath.split(",").forEach((path5) => {
|
|
770
|
-
const trimmedPath = path5.trim();
|
|
771
|
-
if (existsSync(trimmedPath)) {
|
|
772
|
-
paths.push(trimmedPath);
|
|
773
|
-
}
|
|
774
|
-
});
|
|
775
|
-
}
|
|
776
|
-
if (paths.length === 0) {
|
|
777
|
-
const homeDir = homedir();
|
|
778
|
-
const configPath = join(homeDir, ".config", "claude");
|
|
779
|
-
const claudePath = join(homeDir, ".claude");
|
|
780
|
-
if (existsSync(configPath)) {
|
|
781
|
-
paths.push(configPath);
|
|
782
|
-
} else if (existsSync(claudePath)) {
|
|
783
|
-
paths.push(claudePath);
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
return paths;
|
|
787
|
-
}
|
|
788
|
-
async function findProjectPaths(claudePaths) {
|
|
789
|
-
const projectPaths = [];
|
|
790
|
-
for (const claudePath of claudePaths) {
|
|
791
|
-
const projectsDir = join(claudePath, "projects");
|
|
792
|
-
if (existsSync(projectsDir)) {
|
|
793
|
-
try {
|
|
794
|
-
const entries = await readdir(projectsDir, { withFileTypes: true });
|
|
795
|
-
for (const entry of entries) {
|
|
796
|
-
if (entry.isDirectory()) {
|
|
797
|
-
const projectPath = posix.join(projectsDir, entry.name);
|
|
798
|
-
projectPaths.push(projectPath);
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
} catch (error) {
|
|
802
|
-
debug(`Failed to read projects directory ${projectsDir}:`, error);
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
return projectPaths;
|
|
807
|
-
}
|
|
808
|
-
async function findTranscriptFile(sessionId) {
|
|
809
|
-
const claudePaths = getClaudePaths();
|
|
810
|
-
const projectPaths = await findProjectPaths(claudePaths);
|
|
811
|
-
for (const projectPath of projectPaths) {
|
|
812
|
-
const transcriptPath = posix.join(projectPath, `${sessionId}.jsonl`);
|
|
813
|
-
if (existsSync(transcriptPath)) {
|
|
814
|
-
return transcriptPath;
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
return null;
|
|
818
|
-
}
|
|
819
|
-
async function getEarliestTimestamp(filePath) {
|
|
820
|
-
try {
|
|
821
|
-
const content = await readFile(filePath, "utf-8");
|
|
822
|
-
const lines = content.trim().split("\n");
|
|
823
|
-
let earliestDate = null;
|
|
824
|
-
for (const line of lines) {
|
|
825
|
-
if (!line.trim()) continue;
|
|
826
|
-
try {
|
|
827
|
-
const json2 = JSON.parse(line);
|
|
828
|
-
if (json2.timestamp && typeof json2.timestamp === "string") {
|
|
829
|
-
const date = new Date(json2.timestamp);
|
|
830
|
-
if (!isNaN(date.getTime())) {
|
|
831
|
-
if (earliestDate === null || date < earliestDate) {
|
|
832
|
-
earliestDate = date;
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
} catch {
|
|
837
|
-
continue;
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
return earliestDate;
|
|
841
|
-
} catch (error) {
|
|
842
|
-
debug(`Failed to get earliest timestamp for ${filePath}:`, error);
|
|
843
|
-
return null;
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
async function sortFilesByTimestamp(files, oldestFirst = true) {
|
|
847
|
-
const filesWithTimestamps = await Promise.all(
|
|
848
|
-
files.map(async (file) => ({
|
|
849
|
-
file,
|
|
850
|
-
timestamp: await getEarliestTimestamp(file)
|
|
851
|
-
}))
|
|
852
|
-
);
|
|
853
|
-
return filesWithTimestamps.sort((a, b) => {
|
|
854
|
-
if (a.timestamp === null && b.timestamp === null) return 0;
|
|
855
|
-
if (a.timestamp === null) return 1;
|
|
856
|
-
if (b.timestamp === null) return -1;
|
|
857
|
-
const sortOrder = oldestFirst ? 1 : -1;
|
|
858
|
-
return sortOrder * (a.timestamp.getTime() - b.timestamp.getTime());
|
|
859
|
-
}).map((item) => item.file);
|
|
860
|
-
}
|
|
861
|
-
async function getFileModificationDate(filePath) {
|
|
862
|
-
try {
|
|
863
|
-
const stats = await stat(filePath);
|
|
864
|
-
return stats.mtime;
|
|
865
|
-
} catch {
|
|
866
|
-
return null;
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
|
-
function createUniqueHash(entry) {
|
|
870
|
-
const messageId = entry.message?.id || (typeof entry.raw.message === "object" && entry.raw.message !== null && "id" in entry.raw.message ? entry.raw.message.id : void 0);
|
|
871
|
-
const requestId = "requestId" in entry.raw ? entry.raw.requestId : void 0;
|
|
872
|
-
if (!messageId || !requestId) {
|
|
873
|
-
return null;
|
|
874
|
-
}
|
|
875
|
-
return `${messageId}:${requestId}`;
|
|
876
|
-
}
|
|
877
|
-
async function parseJsonlFile(filePath) {
|
|
878
|
-
try {
|
|
879
|
-
const content = await readFile(filePath, "utf-8");
|
|
880
|
-
const lines = content.trim().split("\n").filter((line) => line.trim());
|
|
881
|
-
const entries = [];
|
|
882
|
-
for (const line of lines) {
|
|
883
|
-
try {
|
|
884
|
-
const raw = JSON.parse(line);
|
|
885
|
-
if (!raw.timestamp) continue;
|
|
886
|
-
const entry = {
|
|
887
|
-
timestamp: new Date(raw.timestamp),
|
|
888
|
-
message: raw.message,
|
|
889
|
-
costUSD: typeof raw.costUSD === "number" ? raw.costUSD : void 0,
|
|
890
|
-
isSidechain: raw.isSidechain === true,
|
|
891
|
-
raw
|
|
892
|
-
};
|
|
893
|
-
entries.push(entry);
|
|
894
|
-
} catch (parseError) {
|
|
895
|
-
debug(`Failed to parse JSONL line: ${parseError}`);
|
|
896
|
-
continue;
|
|
897
|
-
}
|
|
898
|
-
}
|
|
899
|
-
return entries;
|
|
900
|
-
} catch (error) {
|
|
901
|
-
debug(`Failed to read file ${filePath}:`, error);
|
|
902
|
-
return [];
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
async function loadEntriesFromProjects(timeFilter, fileFilter, sortFiles = false) {
|
|
906
|
-
const entries = [];
|
|
907
|
-
const claudePaths = getClaudePaths();
|
|
908
|
-
const projectPaths = await findProjectPaths(claudePaths);
|
|
909
|
-
const processedHashes = /* @__PURE__ */ new Set();
|
|
910
|
-
const allFiles = [];
|
|
911
|
-
for (const projectPath of projectPaths) {
|
|
912
|
-
try {
|
|
913
|
-
const files = await readdir(projectPath);
|
|
914
|
-
const jsonlFiles = files.filter((file) => file.endsWith(".jsonl"));
|
|
915
|
-
const fileStatsPromises = jsonlFiles.map(async (file) => {
|
|
916
|
-
const filePath = posix.join(projectPath, file);
|
|
917
|
-
if (existsSync(filePath)) {
|
|
918
|
-
const mtime = await getFileModificationDate(filePath);
|
|
919
|
-
return { filePath, mtime };
|
|
920
|
-
}
|
|
921
|
-
return null;
|
|
922
|
-
});
|
|
923
|
-
const fileStats = await Promise.all(fileStatsPromises);
|
|
924
|
-
for (const stat2 of fileStats) {
|
|
925
|
-
if (stat2?.mtime && (!fileFilter || fileFilter(stat2.filePath, stat2.mtime))) {
|
|
926
|
-
allFiles.push(stat2.filePath);
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
} catch (dirError) {
|
|
930
|
-
debug(`Failed to read project directory ${projectPath}:`, dirError);
|
|
931
|
-
continue;
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
if (sortFiles) {
|
|
935
|
-
const sortedFiles = await sortFilesByTimestamp(allFiles, false);
|
|
936
|
-
allFiles.length = 0;
|
|
937
|
-
allFiles.push(...sortedFiles);
|
|
938
|
-
}
|
|
939
|
-
for (const filePath of allFiles) {
|
|
940
|
-
const fileEntries = await parseJsonlFile(filePath);
|
|
941
|
-
for (const entry of fileEntries) {
|
|
942
|
-
const uniqueHash = createUniqueHash(entry);
|
|
943
|
-
if (uniqueHash && processedHashes.has(uniqueHash)) {
|
|
944
|
-
debug(`Skipping duplicate entry: ${uniqueHash}`);
|
|
945
|
-
continue;
|
|
946
|
-
}
|
|
947
|
-
if (uniqueHash) {
|
|
948
|
-
processedHashes.add(uniqueHash);
|
|
949
|
-
}
|
|
950
|
-
if (!timeFilter || timeFilter(entry)) {
|
|
951
|
-
entries.push(entry);
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
return entries;
|
|
956
|
-
}
|
|
957
|
-
|
|
958
|
-
// src/segments/session.ts
|
|
959
|
-
function convertToSessionEntry(entry) {
|
|
960
|
-
return {
|
|
961
|
-
timestamp: entry.timestamp.toISOString(),
|
|
962
|
-
message: {
|
|
963
|
-
usage: {
|
|
964
|
-
input_tokens: entry.message?.usage?.input_tokens || 0,
|
|
965
|
-
output_tokens: entry.message?.usage?.output_tokens || 0,
|
|
966
|
-
cache_creation_input_tokens: entry.message?.usage?.cache_creation_input_tokens,
|
|
967
|
-
cache_read_input_tokens: entry.message?.usage?.cache_read_input_tokens
|
|
968
|
-
}
|
|
969
|
-
},
|
|
970
|
-
costUSD: entry.costUSD
|
|
971
|
-
};
|
|
972
|
-
}
|
|
973
|
-
var SessionProvider = class {
|
|
974
|
-
async getSessionUsage(sessionId) {
|
|
975
|
-
try {
|
|
976
|
-
const transcriptPath = await findTranscriptFile(sessionId);
|
|
977
|
-
if (!transcriptPath) {
|
|
978
|
-
debug(`No transcript found for session: ${sessionId}`);
|
|
979
|
-
return null;
|
|
980
|
-
}
|
|
981
|
-
debug(`Found transcript at: ${transcriptPath}`);
|
|
982
|
-
const parsedEntries = await parseJsonlFile(transcriptPath);
|
|
983
|
-
if (parsedEntries.length === 0) {
|
|
984
|
-
return { totalCost: 0, entries: [] };
|
|
985
|
-
}
|
|
986
|
-
const entries = [];
|
|
987
|
-
let totalCost = 0;
|
|
988
|
-
for (const entry of parsedEntries) {
|
|
989
|
-
if (entry.message?.usage) {
|
|
990
|
-
const sessionEntry = convertToSessionEntry(entry);
|
|
991
|
-
if (sessionEntry.costUSD !== void 0) {
|
|
992
|
-
totalCost += sessionEntry.costUSD;
|
|
993
|
-
} else {
|
|
994
|
-
const cost = await PricingService.calculateCostForEntry(entry.raw);
|
|
995
|
-
sessionEntry.costUSD = cost;
|
|
996
|
-
totalCost += cost;
|
|
997
|
-
}
|
|
998
|
-
entries.push(sessionEntry);
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
debug(
|
|
1002
|
-
`Parsed ${entries.length} usage entries, total cost: $${totalCost.toFixed(4)}`
|
|
1003
|
-
);
|
|
1004
|
-
return { totalCost, entries };
|
|
1005
|
-
} catch (error) {
|
|
1006
|
-
debug(`Error reading session usage for ${sessionId}:`, error);
|
|
1007
|
-
return null;
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
calculateTokenBreakdown(entries) {
|
|
1011
|
-
return entries.reduce(
|
|
1012
|
-
(breakdown, entry) => ({
|
|
1013
|
-
input: breakdown.input + (entry.message.usage.input_tokens || 0),
|
|
1014
|
-
output: breakdown.output + (entry.message.usage.output_tokens || 0),
|
|
1015
|
-
cacheCreation: breakdown.cacheCreation + (entry.message.usage.cache_creation_input_tokens || 0),
|
|
1016
|
-
cacheRead: breakdown.cacheRead + (entry.message.usage.cache_read_input_tokens || 0)
|
|
1017
|
-
}),
|
|
1018
|
-
{ input: 0, output: 0, cacheCreation: 0, cacheRead: 0 }
|
|
1019
|
-
);
|
|
1020
|
-
}
|
|
1021
|
-
async getSessionInfo(sessionId) {
|
|
1022
|
-
const sessionUsage = await this.getSessionUsage(sessionId);
|
|
1023
|
-
if (!sessionUsage || sessionUsage.entries.length === 0) {
|
|
1024
|
-
return { cost: null, tokens: null, tokenBreakdown: null };
|
|
1025
|
-
}
|
|
1026
|
-
const tokenBreakdown = this.calculateTokenBreakdown(sessionUsage.entries);
|
|
1027
|
-
const totalTokens = tokenBreakdown.input + tokenBreakdown.output + tokenBreakdown.cacheCreation + tokenBreakdown.cacheRead;
|
|
1028
|
-
return {
|
|
1029
|
-
cost: sessionUsage.totalCost,
|
|
1030
|
-
tokens: totalTokens,
|
|
1031
|
-
tokenBreakdown
|
|
1032
|
-
};
|
|
1033
|
-
}
|
|
1034
|
-
};
|
|
1035
|
-
var UsageProvider = class {
|
|
1036
|
-
sessionProvider = new SessionProvider();
|
|
1037
|
-
async getUsageInfo(sessionId) {
|
|
1038
|
-
try {
|
|
1039
|
-
debug(`Starting usage info retrieval for session: ${sessionId}`);
|
|
1040
|
-
const sessionInfo = await this.sessionProvider.getSessionInfo(sessionId);
|
|
1041
|
-
return {
|
|
1042
|
-
session: sessionInfo
|
|
1043
|
-
};
|
|
1044
|
-
} catch (error) {
|
|
1045
|
-
debug(`Error getting usage info for session ${sessionId}:`, error);
|
|
1046
|
-
return {
|
|
1047
|
-
session: { cost: null, tokens: null, tokenBreakdown: null }
|
|
1048
|
-
};
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
};
|
|
1052
|
-
|
|
1053
|
-
// src/segments/context.ts
|
|
1054
|
-
import { readFileSync } from "fs";
|
|
1055
|
-
var ContextProvider = class {
|
|
1056
|
-
thresholds = {
|
|
1057
|
-
LOW: 50,
|
|
1058
|
-
MEDIUM: 80
|
|
1059
|
-
};
|
|
1060
|
-
getContextUsageThresholds() {
|
|
1061
|
-
return this.thresholds;
|
|
1062
|
-
}
|
|
1063
|
-
getContextLimit(_modelId) {
|
|
1064
|
-
return 2e5;
|
|
1065
|
-
}
|
|
1066
|
-
async calculateContextTokens(transcriptPath, modelId) {
|
|
1067
|
-
try {
|
|
1068
|
-
debug(`Calculating context tokens from transcript: ${transcriptPath}`);
|
|
1069
|
-
try {
|
|
1070
|
-
const content = readFileSync(transcriptPath, "utf-8");
|
|
1071
|
-
if (!content) {
|
|
1072
|
-
debug("Transcript file is empty");
|
|
1073
|
-
return null;
|
|
1074
|
-
}
|
|
1075
|
-
} catch {
|
|
1076
|
-
debug("Could not read transcript file");
|
|
1077
|
-
return null;
|
|
1078
|
-
}
|
|
1079
|
-
const parsedEntries = await parseJsonlFile(transcriptPath);
|
|
1080
|
-
if (parsedEntries.length === 0) {
|
|
1081
|
-
debug("No entries in transcript");
|
|
1082
|
-
return null;
|
|
1083
|
-
}
|
|
1084
|
-
let mostRecentEntry = null;
|
|
1085
|
-
for (let i = parsedEntries.length - 1; i >= 0; i--) {
|
|
1086
|
-
const entry = parsedEntries[i];
|
|
1087
|
-
if (!entry) continue;
|
|
1088
|
-
if (!entry.message?.usage?.input_tokens) continue;
|
|
1089
|
-
if (entry.isSidechain === true) continue;
|
|
1090
|
-
mostRecentEntry = entry;
|
|
1091
|
-
debug(
|
|
1092
|
-
`Context segment: Found most recent entry at ${entry.timestamp.toISOString()}, stopping search`
|
|
1093
|
-
);
|
|
1094
|
-
break;
|
|
1095
|
-
}
|
|
1096
|
-
if (mostRecentEntry?.message?.usage) {
|
|
1097
|
-
const usage = mostRecentEntry.message.usage;
|
|
1098
|
-
const contextLength = (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0);
|
|
1099
|
-
const contextLimit = modelId ? this.getContextLimit(modelId) : 2e5;
|
|
1100
|
-
debug(
|
|
1101
|
-
`Most recent main chain context: ${contextLength} tokens (limit: ${contextLimit})`
|
|
1102
|
-
);
|
|
1103
|
-
const percentage = Math.min(
|
|
1104
|
-
100,
|
|
1105
|
-
Math.max(0, Math.round(contextLength / contextLimit * 100))
|
|
1106
|
-
);
|
|
1107
|
-
const usableLimit = Math.round(contextLimit * 0.75);
|
|
1108
|
-
const usablePercentage = Math.min(
|
|
1109
|
-
100,
|
|
1110
|
-
Math.max(0, Math.round(contextLength / usableLimit * 100))
|
|
1111
|
-
);
|
|
1112
|
-
const contextLeftPercentage = Math.max(0, 100 - usablePercentage);
|
|
1113
|
-
return {
|
|
1114
|
-
inputTokens: contextLength,
|
|
1115
|
-
percentage,
|
|
1116
|
-
usablePercentage,
|
|
1117
|
-
contextLeftPercentage,
|
|
1118
|
-
maxTokens: contextLimit,
|
|
1119
|
-
usableTokens: usableLimit
|
|
1120
|
-
};
|
|
1121
|
-
}
|
|
1122
|
-
debug("No main chain entries with usage data found");
|
|
1123
|
-
return null;
|
|
1124
|
-
} catch (error) {
|
|
1125
|
-
debug(
|
|
1126
|
-
`Error reading transcript: ${error instanceof Error ? error.message : String(error)}`
|
|
1127
|
-
);
|
|
1128
|
-
return null;
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
};
|
|
1132
|
-
|
|
1133
|
-
// src/segments/metrics.ts
|
|
1134
|
-
import { readFile as readFile2 } from "fs/promises";
|
|
1135
|
-
var MetricsProvider = class {
|
|
1136
|
-
async loadTranscriptEntries(sessionId) {
|
|
1137
|
-
try {
|
|
1138
|
-
const transcriptPath = await findTranscriptFile(sessionId);
|
|
1139
|
-
if (!transcriptPath) {
|
|
1140
|
-
debug(`No transcript found for session: ${sessionId}`);
|
|
1141
|
-
return [];
|
|
1142
|
-
}
|
|
1143
|
-
debug(`Loading transcript from: ${transcriptPath}`);
|
|
1144
|
-
const content = await readFile2(transcriptPath, "utf-8");
|
|
1145
|
-
const lines = content.trim().split("\n").filter((line) => line.trim());
|
|
1146
|
-
const entries = [];
|
|
1147
|
-
for (const line of lines) {
|
|
1148
|
-
try {
|
|
1149
|
-
const entry = JSON.parse(line);
|
|
1150
|
-
if (entry.isSidechain === true) {
|
|
1151
|
-
continue;
|
|
1152
|
-
}
|
|
1153
|
-
entries.push(entry);
|
|
1154
|
-
} catch (parseError) {
|
|
1155
|
-
debug(`Failed to parse JSONL line: ${parseError}`);
|
|
1156
|
-
continue;
|
|
1157
|
-
}
|
|
1158
|
-
}
|
|
1159
|
-
debug(`Loaded ${entries.length} transcript entries`);
|
|
1160
|
-
return entries;
|
|
1161
|
-
} catch (error) {
|
|
1162
|
-
debug(`Error loading transcript for ${sessionId}:`, error);
|
|
1163
|
-
return [];
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
calculateResponseTimes(entries) {
|
|
1167
|
-
const userMessages = [];
|
|
1168
|
-
const assistantMessages = [];
|
|
1169
|
-
let lastUserMessageIndex = -1;
|
|
1170
|
-
let lastUserMessageTime = null;
|
|
1171
|
-
let lastResponseEndTime = null;
|
|
1172
|
-
let lastResponseEndIndex = -1;
|
|
1173
|
-
for (let i = 0; i < entries.length; i++) {
|
|
1174
|
-
const entry = entries[i];
|
|
1175
|
-
if (!entry || !entry.timestamp) continue;
|
|
1176
|
-
try {
|
|
1177
|
-
const timestamp = new Date(entry.timestamp);
|
|
1178
|
-
const messageType = entry.type || entry.message?.role || entry.message?.type;
|
|
1179
|
-
const isToolResult = entry.type === "user" && entry.message?.content?.[0]?.type === "tool_result";
|
|
1180
|
-
const isRealUserMessage = messageType === "user" && !isToolResult;
|
|
1181
|
-
if (isRealUserMessage) {
|
|
1182
|
-
userMessages.push(timestamp);
|
|
1183
|
-
lastUserMessageTime = timestamp;
|
|
1184
|
-
lastUserMessageIndex = i;
|
|
1185
|
-
lastResponseEndTime = null;
|
|
1186
|
-
lastResponseEndIndex = -1;
|
|
1187
|
-
debug(
|
|
1188
|
-
`Found user message at index ${i}, timestamp ${timestamp.toISOString()}`
|
|
1189
|
-
);
|
|
1190
|
-
} else if (lastUserMessageIndex >= 0) {
|
|
1191
|
-
const isPartOfResponse = messageType === "assistant" || isToolResult || messageType === "system" || entry.message?.usage;
|
|
1192
|
-
if (isPartOfResponse) {
|
|
1193
|
-
lastResponseEndTime = timestamp;
|
|
1194
|
-
lastResponseEndIndex = i;
|
|
1195
|
-
if (messageType === "assistant" || entry.message?.usage) {
|
|
1196
|
-
assistantMessages.push(timestamp);
|
|
1197
|
-
debug(
|
|
1198
|
-
`Found assistant message at index ${i}, timestamp ${timestamp.toISOString()}`
|
|
1199
|
-
);
|
|
1200
|
-
} else if (isToolResult) {
|
|
1201
|
-
debug(
|
|
1202
|
-
`Found tool result at index ${i}, timestamp ${timestamp.toISOString()}`
|
|
1203
|
-
);
|
|
1204
|
-
} else {
|
|
1205
|
-
debug(
|
|
1206
|
-
`Found ${messageType} message at index ${i}, timestamp ${timestamp.toISOString()}`
|
|
1207
|
-
);
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
} catch {
|
|
1212
|
-
continue;
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
if (userMessages.length === 0 || assistantMessages.length === 0) {
|
|
1216
|
-
return { average: null, last: null };
|
|
1217
|
-
}
|
|
1218
|
-
const responseTimes = [];
|
|
1219
|
-
for (const assistantTime of assistantMessages) {
|
|
1220
|
-
const priorUsers = userMessages.filter(
|
|
1221
|
-
(userTime) => userTime < assistantTime
|
|
1222
|
-
);
|
|
1223
|
-
if (priorUsers.length > 0) {
|
|
1224
|
-
const userTime = new Date(
|
|
1225
|
-
Math.max(...priorUsers.map((d) => d.getTime()))
|
|
1226
|
-
);
|
|
1227
|
-
const responseTime = (assistantTime.getTime() - userTime.getTime()) / 1e3;
|
|
1228
|
-
if (responseTime > 0.1 && responseTime < 300) {
|
|
1229
|
-
responseTimes.push(responseTime);
|
|
1230
|
-
debug(`Valid response time: ${responseTime.toFixed(1)}s`);
|
|
1231
|
-
} else {
|
|
1232
|
-
debug(
|
|
1233
|
-
`Rejected response time: ${responseTime.toFixed(1)}s (outside 0.1s-5m range)`
|
|
1234
|
-
);
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
let lastResponseTime = null;
|
|
1239
|
-
if (lastUserMessageTime && lastResponseEndTime && lastResponseEndIndex > lastUserMessageIndex) {
|
|
1240
|
-
const timeDiff = lastResponseEndTime.getTime() - lastUserMessageTime.getTime();
|
|
1241
|
-
const positionDiff = lastResponseEndIndex - lastUserMessageIndex;
|
|
1242
|
-
if (timeDiff === 0 && positionDiff > 0) {
|
|
1243
|
-
lastResponseTime = positionDiff * 0.1;
|
|
1244
|
-
debug(
|
|
1245
|
-
`Estimated last response time from position difference: ${lastResponseTime.toFixed(2)}s (${positionDiff} messages)`
|
|
1246
|
-
);
|
|
1247
|
-
} else if (timeDiff > 0) {
|
|
1248
|
-
lastResponseTime = timeDiff / 1e3;
|
|
1249
|
-
debug(
|
|
1250
|
-
`Last response time from timestamps: ${lastResponseTime.toFixed(2)}s`
|
|
1251
|
-
);
|
|
1252
|
-
}
|
|
1253
|
-
debug(
|
|
1254
|
-
`Last user message at index ${lastUserMessageIndex}, timestamp ${lastUserMessageTime.toISOString()}`
|
|
1255
|
-
);
|
|
1256
|
-
debug(
|
|
1257
|
-
`Last response end at index ${lastResponseEndIndex}, timestamp ${lastResponseEndTime.toISOString()}`
|
|
1258
|
-
);
|
|
1259
|
-
}
|
|
1260
|
-
if (responseTimes.length === 0 && lastResponseTime === null) {
|
|
1261
|
-
return { average: null, last: null };
|
|
1262
|
-
}
|
|
1263
|
-
const avgResponseTime = responseTimes.length > 0 ? responseTimes.reduce((sum, time) => sum + time, 0) / responseTimes.length : null;
|
|
1264
|
-
debug(
|
|
1265
|
-
`Calculated average response time: ${avgResponseTime?.toFixed(2) || "null"}s from ${responseTimes.length} measurements`
|
|
1266
|
-
);
|
|
1267
|
-
debug(`Last response time: ${lastResponseTime?.toFixed(2) || "null"}s`);
|
|
1268
|
-
return { average: avgResponseTime, last: lastResponseTime };
|
|
1269
|
-
}
|
|
1270
|
-
calculateSessionDuration(entries) {
|
|
1271
|
-
const timestamps = [];
|
|
1272
|
-
for (const entry of entries) {
|
|
1273
|
-
if (!entry.timestamp) continue;
|
|
1274
|
-
try {
|
|
1275
|
-
timestamps.push(new Date(entry.timestamp));
|
|
1276
|
-
} catch {
|
|
1277
|
-
continue;
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
if (timestamps.length < 2) {
|
|
1281
|
-
return null;
|
|
1282
|
-
}
|
|
1283
|
-
timestamps.sort((a, b) => a.getTime() - b.getTime());
|
|
1284
|
-
const lastTimestamp = timestamps[timestamps.length - 1];
|
|
1285
|
-
const firstTimestamp = timestamps[0];
|
|
1286
|
-
if (!lastTimestamp || !firstTimestamp) {
|
|
1287
|
-
return null;
|
|
1288
|
-
}
|
|
1289
|
-
const duration = (lastTimestamp.getTime() - firstTimestamp.getTime()) / 1e3;
|
|
1290
|
-
return duration > 0 ? duration : null;
|
|
1291
|
-
}
|
|
1292
|
-
calculateBurnRateDuration(entries) {
|
|
1293
|
-
if (entries.length === 0) return null;
|
|
1294
|
-
const now = /* @__PURE__ */ new Date();
|
|
1295
|
-
const timestamps = entries.map((entry) => entry.timestamp).filter(Boolean).map((ts) => new Date(ts)).filter((ts) => now.getTime() - ts.getTime() < 2 * 60 * 60 * 1e3).sort((a, b) => a.getTime() - b.getTime());
|
|
1296
|
-
if (timestamps.length === 0) return null;
|
|
1297
|
-
const sessionStart = timestamps[0];
|
|
1298
|
-
if (!sessionStart) return null;
|
|
1299
|
-
const durationFromStart = Math.max(
|
|
1300
|
-
(now.getTime() - sessionStart.getTime()) / 1e3,
|
|
1301
|
-
30 * 60
|
|
1302
|
-
);
|
|
1303
|
-
return durationFromStart;
|
|
1304
|
-
}
|
|
1305
|
-
calculateMessageCount(entries) {
|
|
1306
|
-
return entries.filter((entry) => {
|
|
1307
|
-
const messageType = entry.type || entry.message?.role || entry.message?.type;
|
|
1308
|
-
const isToolResult = entry.type === "user" && entry.message?.content?.[0]?.type === "tool_result";
|
|
1309
|
-
return messageType === "user" && !isToolResult;
|
|
1310
|
-
}).length;
|
|
1311
|
-
}
|
|
1312
|
-
async calculateTotalCost(entries) {
|
|
1313
|
-
let total = 0;
|
|
1314
|
-
const processedEntries = /* @__PURE__ */ new Set();
|
|
1315
|
-
for (const entry of entries) {
|
|
1316
|
-
const entryKey = `${entry.timestamp}-${JSON.stringify(entry.message?.usage || {})}`;
|
|
1317
|
-
if (processedEntries.has(entryKey)) {
|
|
1318
|
-
debug(`Skipping duplicate entry at ${entry.timestamp}`);
|
|
1319
|
-
continue;
|
|
1320
|
-
}
|
|
1321
|
-
processedEntries.add(entryKey);
|
|
1322
|
-
if (typeof entry.costUSD === "number") {
|
|
1323
|
-
total += entry.costUSD;
|
|
1324
|
-
} else if (entry.message?.usage) {
|
|
1325
|
-
const cost = await PricingService.calculateCostForEntry(entry);
|
|
1326
|
-
total += cost;
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
return Math.round(total * 1e4) / 1e4;
|
|
1330
|
-
}
|
|
1331
|
-
calculateTotalTokens(entries) {
|
|
1332
|
-
const processedEntries = /* @__PURE__ */ new Set();
|
|
1333
|
-
return entries.reduce((total, entry) => {
|
|
1334
|
-
const usage = entry.message?.usage;
|
|
1335
|
-
if (!usage) return total;
|
|
1336
|
-
const entryKey = `${entry.timestamp}-${JSON.stringify(usage)}`;
|
|
1337
|
-
if (processedEntries.has(entryKey)) {
|
|
1338
|
-
debug(`Skipping duplicate token entry at ${entry.timestamp}`);
|
|
1339
|
-
return total;
|
|
1340
|
-
}
|
|
1341
|
-
processedEntries.add(entryKey);
|
|
1342
|
-
return total + (usage.input_tokens || 0) + (usage.output_tokens || 0) + (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0);
|
|
1343
|
-
}, 0);
|
|
1344
|
-
}
|
|
1345
|
-
async getMetricsInfo(sessionId) {
|
|
1346
|
-
try {
|
|
1347
|
-
debug(`Starting metrics calculation for session: ${sessionId}`);
|
|
1348
|
-
const entries = await this.loadTranscriptEntries(sessionId);
|
|
1349
|
-
if (entries.length === 0) {
|
|
1350
|
-
return {
|
|
1351
|
-
responseTime: null,
|
|
1352
|
-
lastResponseTime: null,
|
|
1353
|
-
sessionDuration: null,
|
|
1354
|
-
messageCount: null,
|
|
1355
|
-
costBurnRate: null,
|
|
1356
|
-
tokenBurnRate: null
|
|
1357
|
-
};
|
|
1358
|
-
}
|
|
1359
|
-
const responseTimes = this.calculateResponseTimes(entries);
|
|
1360
|
-
const sessionDuration = this.calculateSessionDuration(entries);
|
|
1361
|
-
const messageCount = this.calculateMessageCount(entries);
|
|
1362
|
-
let costBurnRate = null;
|
|
1363
|
-
let tokenBurnRate = null;
|
|
1364
|
-
const burnRateDuration = this.calculateBurnRateDuration(entries);
|
|
1365
|
-
if (burnRateDuration && burnRateDuration > 60) {
|
|
1366
|
-
const hoursElapsed = burnRateDuration / 3600;
|
|
1367
|
-
if (hoursElapsed <= 0) {
|
|
1368
|
-
debug(`Invalid hours elapsed: ${hoursElapsed}`);
|
|
1369
|
-
} else {
|
|
1370
|
-
const totalCost = await this.calculateTotalCost(entries);
|
|
1371
|
-
const totalTokens = this.calculateTotalTokens(entries);
|
|
1372
|
-
if (totalCost > 0) {
|
|
1373
|
-
costBurnRate = Math.round(totalCost / hoursElapsed * 100) / 100;
|
|
1374
|
-
debug(
|
|
1375
|
-
`Cost burn rate: $${costBurnRate}/h (total: $${totalCost}, duration: ${hoursElapsed}h)`
|
|
1376
|
-
);
|
|
1377
|
-
}
|
|
1378
|
-
if (totalTokens > 0) {
|
|
1379
|
-
tokenBurnRate = Math.round(totalTokens / hoursElapsed);
|
|
1380
|
-
debug(
|
|
1381
|
-
`Token burn rate: ${tokenBurnRate}/h (total: ${totalTokens}, duration: ${hoursElapsed}h)`
|
|
1382
|
-
);
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
}
|
|
1386
|
-
debug(
|
|
1387
|
-
`Metrics calculated: avgResponseTime=${responseTimes.average?.toFixed(2) || "null"}s, lastResponseTime=${responseTimes.last?.toFixed(2) || "null"}s, sessionDuration=${sessionDuration?.toFixed(0) || "null"}s, messageCount=${messageCount}`
|
|
1388
|
-
);
|
|
1389
|
-
return {
|
|
1390
|
-
responseTime: responseTimes.average,
|
|
1391
|
-
lastResponseTime: responseTimes.last,
|
|
1392
|
-
sessionDuration,
|
|
1393
|
-
messageCount,
|
|
1394
|
-
costBurnRate,
|
|
1395
|
-
tokenBurnRate
|
|
1396
|
-
};
|
|
1397
|
-
} catch (error) {
|
|
1398
|
-
debug(`Error calculating metrics for session ${sessionId}:`, error);
|
|
1399
|
-
return {
|
|
1400
|
-
responseTime: null,
|
|
1401
|
-
lastResponseTime: null,
|
|
1402
|
-
sessionDuration: null,
|
|
1403
|
-
messageCount: null,
|
|
1404
|
-
costBurnRate: null,
|
|
1405
|
-
tokenBurnRate: null
|
|
1406
|
-
};
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
};
|
|
1410
|
-
|
|
1411
|
-
// src/segments/version.ts
|
|
1412
|
-
import { execSync as execSync3 } from "child_process";
|
|
1413
|
-
var VersionProvider = class {
|
|
1414
|
-
cachedVersion = null;
|
|
1415
|
-
cacheTimestamp = 0;
|
|
1416
|
-
CACHE_TTL = 3e4;
|
|
1417
|
-
getClaudeVersion() {
|
|
1418
|
-
const now = Date.now();
|
|
1419
|
-
if (this.cachedVersion !== null && now - this.cacheTimestamp < this.CACHE_TTL) {
|
|
1420
|
-
return this.cachedVersion;
|
|
1421
|
-
}
|
|
1422
|
-
try {
|
|
1423
|
-
const output = execSync3("claude --version", {
|
|
1424
|
-
encoding: "utf8",
|
|
1425
|
-
timeout: 1e3
|
|
1426
|
-
}).trim();
|
|
1427
|
-
const match = output.match(/^([\d.]+)/);
|
|
1428
|
-
if (match) {
|
|
1429
|
-
this.cachedVersion = `v${match[1]}`;
|
|
1430
|
-
this.cacheTimestamp = now;
|
|
1431
|
-
debug(`Claude Code version: ${this.cachedVersion}`);
|
|
1432
|
-
return this.cachedVersion;
|
|
1433
|
-
}
|
|
1434
|
-
debug(`Could not parse version from: ${output}`);
|
|
1435
|
-
return null;
|
|
1436
|
-
} catch (error) {
|
|
1437
|
-
debug(`Error getting Claude Code version:`, error);
|
|
1438
|
-
return null;
|
|
1439
|
-
}
|
|
1440
|
-
}
|
|
1441
|
-
async getVersionInfo() {
|
|
1442
|
-
const version = this.getClaudeVersion();
|
|
1443
|
-
return { version };
|
|
1444
|
-
}
|
|
1445
|
-
};
|
|
1446
|
-
|
|
1447
|
-
// src/segments/renderer.ts
|
|
1448
|
-
import path2 from "path";
|
|
1449
|
-
|
|
1450
|
-
// src/utils/formatters.ts
|
|
1451
|
-
function formatCost(cost) {
|
|
1452
|
-
if (cost === null) return "$0.00";
|
|
1453
|
-
if (cost < 0.01) return "<$0.01";
|
|
1454
|
-
return `$${cost.toFixed(2)}`;
|
|
1455
|
-
}
|
|
1456
|
-
function formatTokens(tokens) {
|
|
1457
|
-
if (tokens === null) return "0 tokens";
|
|
1458
|
-
if (tokens === 0) return "0 tokens";
|
|
1459
|
-
if (tokens >= 1e6) {
|
|
1460
|
-
return `${(tokens / 1e6).toFixed(1)}M tokens`;
|
|
1461
|
-
} else if (tokens >= 1e3) {
|
|
1462
|
-
return `${(tokens / 1e3).toFixed(1)}K tokens`;
|
|
1463
|
-
}
|
|
1464
|
-
return `${tokens} tokens`;
|
|
1465
|
-
}
|
|
1466
|
-
function formatTokenBreakdown(breakdown) {
|
|
1467
|
-
if (!breakdown) return "0 tokens";
|
|
1468
|
-
const parts = [];
|
|
1469
|
-
if (breakdown.input > 0) {
|
|
1470
|
-
parts.push(`${formatTokens(breakdown.input).replace(" tokens", "")}in`);
|
|
1471
|
-
}
|
|
1472
|
-
if (breakdown.output > 0) {
|
|
1473
|
-
parts.push(`${formatTokens(breakdown.output).replace(" tokens", "")}out`);
|
|
1474
|
-
}
|
|
1475
|
-
if (breakdown.cacheCreation > 0 || breakdown.cacheRead > 0) {
|
|
1476
|
-
const totalCached = breakdown.cacheCreation + breakdown.cacheRead;
|
|
1477
|
-
parts.push(`${formatTokens(totalCached).replace(" tokens", "")}cached`);
|
|
1478
|
-
}
|
|
1479
|
-
return parts.length > 0 ? parts.join(" + ") : "0 tokens";
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
// src/utils/budget.ts
|
|
1483
|
-
function calculateBudgetPercentage(cost, budget) {
|
|
1484
|
-
if (!budget || budget <= 0 || cost < 0) return null;
|
|
1485
|
-
return Math.min(100, cost / budget * 100);
|
|
1486
|
-
}
|
|
1487
|
-
function getBudgetStatus(cost, budget, warningThreshold = 80) {
|
|
1488
|
-
const percentage = calculateBudgetPercentage(cost, budget);
|
|
1489
|
-
if (percentage === null) {
|
|
1490
|
-
return {
|
|
1491
|
-
percentage: null,
|
|
1492
|
-
isWarning: false,
|
|
1493
|
-
displayText: ""
|
|
1494
|
-
};
|
|
1495
|
-
}
|
|
1496
|
-
const percentStr = `${percentage.toFixed(0)}%`;
|
|
1497
|
-
const isWarning = percentage >= warningThreshold;
|
|
1498
|
-
let displayText = "";
|
|
1499
|
-
if (isWarning) {
|
|
1500
|
-
displayText = ` !${percentStr}`;
|
|
1501
|
-
} else if (percentage >= 50) {
|
|
1502
|
-
displayText = ` +${percentStr}`;
|
|
1503
|
-
} else {
|
|
1504
|
-
displayText = ` ${percentStr}`;
|
|
1505
|
-
}
|
|
1506
|
-
return {
|
|
1507
|
-
percentage,
|
|
1508
|
-
isWarning,
|
|
1509
|
-
displayText
|
|
1510
|
-
};
|
|
1511
|
-
}
|
|
1512
|
-
|
|
1513
|
-
// src/segments/renderer.ts
|
|
1514
|
-
var SegmentRenderer = class {
|
|
1515
|
-
constructor(config, symbols) {
|
|
1516
|
-
this.config = config;
|
|
1517
|
-
this.symbols = symbols;
|
|
1518
|
-
}
|
|
1519
|
-
renderDirectory(hookData, colors, config) {
|
|
1520
|
-
const currentDir = hookData.workspace?.current_dir || hookData.cwd || "/";
|
|
1521
|
-
const projectDir = hookData.workspace?.project_dir;
|
|
1522
|
-
if (config?.showBasename) {
|
|
1523
|
-
const basename = path2.basename(currentDir) || "root";
|
|
1524
|
-
return {
|
|
1525
|
-
text: basename,
|
|
1526
|
-
bgColor: colors.modeBg,
|
|
1527
|
-
fgColor: colors.modeFg
|
|
1528
|
-
};
|
|
1529
|
-
}
|
|
1530
|
-
const homeDir = process.env.HOME || process.env.USERPROFILE;
|
|
1531
|
-
let displayDir = currentDir;
|
|
1532
|
-
let displayProjectDir = projectDir;
|
|
1533
|
-
if (homeDir) {
|
|
1534
|
-
if (currentDir.startsWith(homeDir)) {
|
|
1535
|
-
displayDir = currentDir.replace(homeDir, "~");
|
|
1536
|
-
}
|
|
1537
|
-
if (projectDir && projectDir.startsWith(homeDir)) {
|
|
1538
|
-
displayProjectDir = projectDir.replace(homeDir, "~");
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
const dirName = this.getDisplayDirectoryName(displayDir, displayProjectDir);
|
|
1542
|
-
return {
|
|
1543
|
-
text: dirName,
|
|
1544
|
-
bgColor: colors.modeBg,
|
|
1545
|
-
fgColor: colors.modeFg
|
|
1546
|
-
};
|
|
1547
|
-
}
|
|
1548
|
-
renderGit(gitInfo, colors, config) {
|
|
1549
|
-
if (!gitInfo) return null;
|
|
1550
|
-
const parts = [];
|
|
1551
|
-
if (config?.showRepoName && gitInfo.repoName) {
|
|
1552
|
-
parts.push(gitInfo.repoName);
|
|
1553
|
-
if (gitInfo.isWorktree) {
|
|
1554
|
-
parts.push(this.symbols.git_worktree);
|
|
1555
|
-
}
|
|
1556
|
-
}
|
|
1557
|
-
if (config?.showOperation && gitInfo.operation) {
|
|
1558
|
-
parts.push(`[${gitInfo.operation}]`);
|
|
1559
|
-
}
|
|
1560
|
-
parts.push(`${this.symbols.branch} ${gitInfo.branch}`);
|
|
1561
|
-
if (config?.showTag && gitInfo.tag) {
|
|
1562
|
-
parts.push(`${this.symbols.git_tag} ${gitInfo.tag}`);
|
|
1563
|
-
}
|
|
1564
|
-
if (config?.showSha && gitInfo.sha) {
|
|
1565
|
-
parts.push(`${this.symbols.git_sha} ${gitInfo.sha}`);
|
|
1566
|
-
}
|
|
1567
|
-
if (config?.showAheadBehind !== false) {
|
|
1568
|
-
if (gitInfo.ahead > 0 && gitInfo.behind > 0) {
|
|
1569
|
-
parts.push(
|
|
1570
|
-
`${this.symbols.git_ahead}${gitInfo.ahead}${this.symbols.git_behind}${gitInfo.behind}`
|
|
1571
|
-
);
|
|
1572
|
-
} else if (gitInfo.ahead > 0) {
|
|
1573
|
-
parts.push(`${this.symbols.git_ahead}${gitInfo.ahead}`);
|
|
1574
|
-
} else if (gitInfo.behind > 0) {
|
|
1575
|
-
parts.push(`${this.symbols.git_behind}${gitInfo.behind}`);
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
if (config?.showWorkingTree) {
|
|
1579
|
-
const counts = [];
|
|
1580
|
-
if (gitInfo.staged && gitInfo.staged > 0)
|
|
1581
|
-
counts.push(`+${gitInfo.staged}`);
|
|
1582
|
-
if (gitInfo.unstaged && gitInfo.unstaged > 0)
|
|
1583
|
-
counts.push(`~${gitInfo.unstaged}`);
|
|
1584
|
-
if (gitInfo.untracked && gitInfo.untracked > 0)
|
|
1585
|
-
counts.push(`?${gitInfo.untracked}`);
|
|
1586
|
-
if (gitInfo.conflicts && gitInfo.conflicts > 0)
|
|
1587
|
-
counts.push(`!${gitInfo.conflicts}`);
|
|
1588
|
-
if (counts.length > 0) {
|
|
1589
|
-
parts.push(`(${counts.join(" ")})`);
|
|
1590
|
-
}
|
|
1591
|
-
}
|
|
1592
|
-
if (config?.showUpstream && gitInfo.upstream) {
|
|
1593
|
-
parts.push(`${this.symbols.git_upstream}${gitInfo.upstream}`);
|
|
1594
|
-
}
|
|
1595
|
-
if (config?.showStashCount && gitInfo.stashCount && gitInfo.stashCount > 0) {
|
|
1596
|
-
parts.push(`${this.symbols.git_stash} ${gitInfo.stashCount}`);
|
|
1597
|
-
}
|
|
1598
|
-
if (config?.showTimeSinceCommit && gitInfo.timeSinceCommit !== void 0) {
|
|
1599
|
-
const time = this.formatTimeSince(gitInfo.timeSinceCommit);
|
|
1600
|
-
parts.push(`${this.symbols.git_time} ${time}`);
|
|
1601
|
-
}
|
|
1602
|
-
let gitStatusIcon = this.symbols.git_clean;
|
|
1603
|
-
if (gitInfo.status === "conflicts") {
|
|
1604
|
-
gitStatusIcon = this.symbols.git_conflicts;
|
|
1605
|
-
} else if (gitInfo.status === "dirty") {
|
|
1606
|
-
gitStatusIcon = this.symbols.git_dirty;
|
|
1607
|
-
}
|
|
1608
|
-
parts.push(gitStatusIcon);
|
|
1609
|
-
return {
|
|
1610
|
-
text: parts.join(" "),
|
|
1611
|
-
bgColor: colors.gitBg,
|
|
1612
|
-
fgColor: colors.gitFg
|
|
1613
|
-
};
|
|
1614
|
-
}
|
|
1615
|
-
formatTimeSince(seconds) {
|
|
1616
|
-
if (seconds < 60) return `${seconds}s`;
|
|
1617
|
-
if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
|
|
1618
|
-
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
|
|
1619
|
-
if (seconds < 604800) return `${Math.floor(seconds / 86400)}d`;
|
|
1620
|
-
return `${Math.floor(seconds / 604800)}w`;
|
|
1621
|
-
}
|
|
1622
|
-
renderModel(hookData, colors) {
|
|
1623
|
-
const modelName = hookData.model?.display_name || "Claude";
|
|
1624
|
-
return {
|
|
1625
|
-
text: `${this.symbols.model} ${modelName}`,
|
|
1626
|
-
bgColor: colors.modelBg,
|
|
1627
|
-
fgColor: colors.modelFg
|
|
1628
|
-
};
|
|
1629
|
-
}
|
|
1630
|
-
renderSession(usageInfo, colors, type = "cost") {
|
|
1631
|
-
const sessionBudget = this.config.budget?.session;
|
|
1632
|
-
const text = `${this.symbols.session_cost} ${this.formatUsageWithBudget(
|
|
1633
|
-
usageInfo.session.cost,
|
|
1634
|
-
usageInfo.session.tokens,
|
|
1635
|
-
usageInfo.session.tokenBreakdown,
|
|
1636
|
-
type,
|
|
1637
|
-
sessionBudget?.amount,
|
|
1638
|
-
sessionBudget?.warningThreshold || 80
|
|
1639
|
-
)}`;
|
|
1640
|
-
return {
|
|
1641
|
-
text,
|
|
1642
|
-
bgColor: colors.sessionBg,
|
|
1643
|
-
fgColor: colors.sessionFg
|
|
1644
|
-
};
|
|
1645
|
-
}
|
|
1646
|
-
renderTmux(sessionId, colors) {
|
|
1647
|
-
if (!sessionId) {
|
|
1648
|
-
return {
|
|
1649
|
-
text: `tmux:none`,
|
|
1650
|
-
bgColor: colors.tmuxBg,
|
|
1651
|
-
fgColor: colors.tmuxFg
|
|
1652
|
-
};
|
|
1653
|
-
}
|
|
1654
|
-
return {
|
|
1655
|
-
text: `tmux:${sessionId}`,
|
|
1656
|
-
bgColor: colors.tmuxBg,
|
|
1657
|
-
fgColor: colors.tmuxFg
|
|
1658
|
-
};
|
|
1659
|
-
}
|
|
1660
|
-
renderContext(contextInfo, colors) {
|
|
1661
|
-
if (!contextInfo) {
|
|
1662
|
-
return {
|
|
1663
|
-
text: `${this.symbols.context_time} 0 (100%)`,
|
|
1664
|
-
bgColor: colors.contextBg,
|
|
1665
|
-
fgColor: colors.contextFg
|
|
1666
|
-
};
|
|
1667
|
-
}
|
|
1668
|
-
const tokenDisplay = contextInfo.inputTokens.toLocaleString();
|
|
1669
|
-
const contextLeft = `${contextInfo.contextLeftPercentage}%`;
|
|
1670
|
-
return {
|
|
1671
|
-
text: `${this.symbols.context_time} ${tokenDisplay} (${contextLeft})`,
|
|
1672
|
-
bgColor: colors.contextBg,
|
|
1673
|
-
fgColor: colors.contextFg
|
|
1674
|
-
};
|
|
1675
|
-
}
|
|
1676
|
-
renderMetrics(metricsInfo, colors, _blockInfo, config) {
|
|
1677
|
-
if (!metricsInfo) {
|
|
1678
|
-
return {
|
|
1679
|
-
text: `${this.symbols.metrics_response} new`,
|
|
1680
|
-
bgColor: colors.metricsBg,
|
|
1681
|
-
fgColor: colors.metricsFg
|
|
1682
|
-
};
|
|
1683
|
-
}
|
|
1684
|
-
const parts = [];
|
|
1685
|
-
if (config?.showLastResponseTime) {
|
|
1686
|
-
const lastResponseTime = metricsInfo.lastResponseTime === null ? "0.0s" : metricsInfo.lastResponseTime < 60 ? `${metricsInfo.lastResponseTime.toFixed(1)}s` : `${(metricsInfo.lastResponseTime / 60).toFixed(1)}m`;
|
|
1687
|
-
parts.push(`${this.symbols.metrics_last_response} ${lastResponseTime}`);
|
|
1688
|
-
}
|
|
1689
|
-
if (config?.showResponseTime !== false && metricsInfo.responseTime !== null) {
|
|
1690
|
-
const responseTime = metricsInfo.responseTime < 60 ? `${metricsInfo.responseTime.toFixed(1)}s` : `${(metricsInfo.responseTime / 60).toFixed(1)}m`;
|
|
1691
|
-
parts.push(`${this.symbols.metrics_response} ${responseTime}`);
|
|
1692
|
-
}
|
|
1693
|
-
if (config?.showDuration !== false && metricsInfo.sessionDuration !== null) {
|
|
1694
|
-
const duration = this.formatDuration(metricsInfo.sessionDuration);
|
|
1695
|
-
parts.push(`${this.symbols.metrics_duration} ${duration}`);
|
|
1696
|
-
}
|
|
1697
|
-
if (config?.showMessageCount !== false && metricsInfo.messageCount !== null) {
|
|
1698
|
-
parts.push(
|
|
1699
|
-
`${this.symbols.metrics_messages} ${metricsInfo.messageCount}`
|
|
1700
|
-
);
|
|
1701
|
-
}
|
|
1702
|
-
if (parts.length === 0) {
|
|
1703
|
-
return {
|
|
1704
|
-
text: `${this.symbols.metrics_response} active`,
|
|
1705
|
-
bgColor: colors.metricsBg,
|
|
1706
|
-
fgColor: colors.metricsFg
|
|
1707
|
-
};
|
|
1708
|
-
}
|
|
1709
|
-
return {
|
|
1710
|
-
text: parts.join(" "),
|
|
1711
|
-
bgColor: colors.metricsBg,
|
|
1712
|
-
fgColor: colors.metricsFg
|
|
1713
|
-
};
|
|
1714
|
-
}
|
|
1715
|
-
renderBlock(blockInfo, colors, config) {
|
|
1716
|
-
let displayText;
|
|
1717
|
-
if (blockInfo.cost === null && blockInfo.tokens === null) {
|
|
1718
|
-
displayText = "No active block";
|
|
1719
|
-
} else {
|
|
1720
|
-
const type = config?.type || "cost";
|
|
1721
|
-
const burnType = config?.burnType;
|
|
1722
|
-
const timeStr = blockInfo.timeRemaining !== null ? (() => {
|
|
1723
|
-
const hours = Math.floor(blockInfo.timeRemaining / 60);
|
|
1724
|
-
const minutes = blockInfo.timeRemaining % 60;
|
|
1725
|
-
return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
|
|
1726
|
-
})() : null;
|
|
1727
|
-
let mainContent;
|
|
1728
|
-
switch (type) {
|
|
1729
|
-
case "cost":
|
|
1730
|
-
mainContent = formatCost(blockInfo.cost);
|
|
1731
|
-
break;
|
|
1732
|
-
case "tokens":
|
|
1733
|
-
mainContent = formatTokens(blockInfo.tokens);
|
|
1734
|
-
break;
|
|
1735
|
-
case "both":
|
|
1736
|
-
mainContent = `${formatCost(blockInfo.cost)} / ${formatTokens(blockInfo.tokens)}`;
|
|
1737
|
-
break;
|
|
1738
|
-
case "time":
|
|
1739
|
-
mainContent = timeStr || "N/A";
|
|
1740
|
-
break;
|
|
1741
|
-
default:
|
|
1742
|
-
mainContent = formatCost(blockInfo.cost);
|
|
1743
|
-
}
|
|
1744
|
-
let burnContent = "";
|
|
1745
|
-
if (burnType && burnType !== "none") {
|
|
1746
|
-
switch (burnType) {
|
|
1747
|
-
case "cost":
|
|
1748
|
-
const costBurnRate = blockInfo.burnRate !== null ? blockInfo.burnRate < 1 ? `${(blockInfo.burnRate * 100).toFixed(0)}\xA2/h` : `$${blockInfo.burnRate.toFixed(2)}/h` : "N/A";
|
|
1749
|
-
burnContent = ` | ${costBurnRate}`;
|
|
1750
|
-
break;
|
|
1751
|
-
case "tokens":
|
|
1752
|
-
const tokenBurnRate = blockInfo.tokenBurnRate !== null ? `${formatTokens(Math.round(blockInfo.tokenBurnRate))}/h` : "N/A";
|
|
1753
|
-
burnContent = ` | ${tokenBurnRate}`;
|
|
1754
|
-
break;
|
|
1755
|
-
case "both":
|
|
1756
|
-
const costBurn = blockInfo.burnRate !== null ? blockInfo.burnRate < 1 ? `${(blockInfo.burnRate * 100).toFixed(0)}\xA2/h` : `$${blockInfo.burnRate.toFixed(2)}/h` : "N/A";
|
|
1757
|
-
const tokenBurn = blockInfo.tokenBurnRate !== null ? `${formatTokens(Math.round(blockInfo.tokenBurnRate))}/h` : "N/A";
|
|
1758
|
-
burnContent = ` | ${costBurn} / ${tokenBurn}`;
|
|
1759
|
-
break;
|
|
1760
|
-
}
|
|
1761
|
-
}
|
|
1762
|
-
if (type === "time") {
|
|
1763
|
-
displayText = mainContent;
|
|
1764
|
-
} else {
|
|
1765
|
-
displayText = timeStr ? `${mainContent}${burnContent} (${timeStr} left)` : `${mainContent}${burnContent}`;
|
|
1766
|
-
}
|
|
1767
|
-
}
|
|
1768
|
-
return {
|
|
1769
|
-
text: `${this.symbols.block_cost} ${displayText}`,
|
|
1770
|
-
bgColor: colors.blockBg,
|
|
1771
|
-
fgColor: colors.blockFg
|
|
1772
|
-
};
|
|
1773
|
-
}
|
|
1774
|
-
renderToday(todayInfo, colors, type = "cost") {
|
|
1775
|
-
const todayBudget = this.config.budget?.today;
|
|
1776
|
-
const text = `${this.symbols.today_cost} ${this.formatUsageWithBudget(
|
|
1777
|
-
todayInfo.cost,
|
|
1778
|
-
todayInfo.tokens,
|
|
1779
|
-
todayInfo.tokenBreakdown,
|
|
1780
|
-
type,
|
|
1781
|
-
todayBudget?.amount,
|
|
1782
|
-
todayBudget?.warningThreshold
|
|
1783
|
-
)}`;
|
|
1784
|
-
return {
|
|
1785
|
-
text,
|
|
1786
|
-
bgColor: colors.todayBg,
|
|
1787
|
-
fgColor: colors.todayFg
|
|
1788
|
-
};
|
|
1789
|
-
}
|
|
1790
|
-
formatDuration(seconds) {
|
|
1791
|
-
if (seconds < 60) {
|
|
1792
|
-
return `${seconds.toFixed(0)}s`;
|
|
1793
|
-
} else if (seconds < 3600) {
|
|
1794
|
-
return `${(seconds / 60).toFixed(0)}m`;
|
|
1795
|
-
} else if (seconds < 86400) {
|
|
1796
|
-
return `${(seconds / 3600).toFixed(1)}h`;
|
|
1797
|
-
} else {
|
|
1798
|
-
return `${(seconds / 86400).toFixed(1)}d`;
|
|
1799
|
-
}
|
|
1800
|
-
}
|
|
1801
|
-
getDisplayDirectoryName(currentDir, projectDir) {
|
|
1802
|
-
if (currentDir.startsWith("~")) {
|
|
1803
|
-
return currentDir;
|
|
1804
|
-
}
|
|
1805
|
-
if (projectDir && projectDir !== currentDir) {
|
|
1806
|
-
if (currentDir.startsWith(projectDir)) {
|
|
1807
|
-
const relativePath = currentDir.slice(projectDir.length + 1);
|
|
1808
|
-
return relativePath || path2.basename(projectDir) || "project";
|
|
1809
|
-
}
|
|
1810
|
-
return path2.basename(currentDir) || "root";
|
|
1811
|
-
}
|
|
1812
|
-
return path2.basename(currentDir) || "root";
|
|
1813
|
-
}
|
|
1814
|
-
formatUsageDisplay(cost, tokens, tokenBreakdown, type) {
|
|
1815
|
-
switch (type) {
|
|
1816
|
-
case "cost":
|
|
1817
|
-
return formatCost(cost);
|
|
1818
|
-
case "tokens":
|
|
1819
|
-
return formatTokens(tokens);
|
|
1820
|
-
case "both":
|
|
1821
|
-
return `${formatCost(cost)} (${formatTokens(tokens)})`;
|
|
1822
|
-
case "breakdown":
|
|
1823
|
-
return formatTokenBreakdown(tokenBreakdown);
|
|
1824
|
-
default:
|
|
1825
|
-
return formatCost(cost);
|
|
1826
|
-
}
|
|
1827
|
-
}
|
|
1828
|
-
formatUsageWithBudget(cost, tokens, tokenBreakdown, type, budget, warningThreshold = 80) {
|
|
1829
|
-
const baseDisplay = this.formatUsageDisplay(
|
|
1830
|
-
cost,
|
|
1831
|
-
tokens,
|
|
1832
|
-
tokenBreakdown,
|
|
1833
|
-
type
|
|
1834
|
-
);
|
|
1835
|
-
if (budget && budget > 0 && cost !== null) {
|
|
1836
|
-
const budgetStatus = getBudgetStatus(cost, budget, warningThreshold);
|
|
1837
|
-
return baseDisplay + budgetStatus.displayText;
|
|
1838
|
-
}
|
|
1839
|
-
return baseDisplay;
|
|
1840
|
-
}
|
|
1841
|
-
renderVersion(versionInfo, colors, _config) {
|
|
1842
|
-
if (!versionInfo || !versionInfo.version) {
|
|
1843
|
-
return null;
|
|
1844
|
-
}
|
|
1845
|
-
return {
|
|
1846
|
-
text: `${this.symbols.version} ${versionInfo.version}`,
|
|
1847
|
-
bgColor: colors.versionBg,
|
|
1848
|
-
fgColor: colors.versionFg
|
|
1849
|
-
};
|
|
1850
|
-
}
|
|
1851
|
-
};
|
|
1852
|
-
|
|
1853
|
-
// src/segments/block.ts
|
|
1854
|
-
function convertToUsageEntry(entry) {
|
|
1855
|
-
return {
|
|
1856
|
-
timestamp: entry.timestamp,
|
|
1857
|
-
usage: {
|
|
1858
|
-
inputTokens: entry.message?.usage?.input_tokens || 0,
|
|
1859
|
-
outputTokens: entry.message?.usage?.output_tokens || 0,
|
|
1860
|
-
cacheCreationInputTokens: entry.message?.usage?.cache_creation_input_tokens || 0,
|
|
1861
|
-
cacheReadInputTokens: entry.message?.usage?.cache_read_input_tokens || 0
|
|
1862
|
-
},
|
|
1863
|
-
costUSD: entry.costUSD || 0,
|
|
1864
|
-
model: entry.message?.model || "unknown"
|
|
1865
|
-
};
|
|
1866
|
-
}
|
|
1867
|
-
var BlockProvider = class {
|
|
1868
|
-
sessionDurationHours = 5;
|
|
1869
|
-
floorToHour(timestamp) {
|
|
1870
|
-
const floored = new Date(timestamp);
|
|
1871
|
-
floored.setUTCMinutes(0, 0, 0);
|
|
1872
|
-
return floored;
|
|
1873
|
-
}
|
|
1874
|
-
identifySessionBlocks(entries) {
|
|
1875
|
-
if (entries.length === 0) return [];
|
|
1876
|
-
const sessionDurationMs = this.sessionDurationHours * 60 * 60 * 1e3;
|
|
1877
|
-
const blocks = [];
|
|
1878
|
-
const sortedEntries = [...entries].sort(
|
|
1879
|
-
(a, b) => a.timestamp.getTime() - b.timestamp.getTime()
|
|
1880
|
-
);
|
|
1881
|
-
let currentBlockStart = null;
|
|
1882
|
-
let currentBlockEntries = [];
|
|
1883
|
-
for (const entry of sortedEntries) {
|
|
1884
|
-
const entryTime = entry.timestamp;
|
|
1885
|
-
if (currentBlockStart == null) {
|
|
1886
|
-
currentBlockStart = this.floorToHour(entryTime);
|
|
1887
|
-
currentBlockEntries = [entry];
|
|
1888
|
-
} else {
|
|
1889
|
-
const timeSinceBlockStart = entryTime.getTime() - currentBlockStart.getTime();
|
|
1890
|
-
const lastEntry = currentBlockEntries[currentBlockEntries.length - 1];
|
|
1891
|
-
if (lastEntry == null) {
|
|
1892
|
-
continue;
|
|
1893
|
-
}
|
|
1894
|
-
const lastEntryTime = lastEntry.timestamp;
|
|
1895
|
-
const timeSinceLastEntry = entryTime.getTime() - lastEntryTime.getTime();
|
|
1896
|
-
if (timeSinceBlockStart > sessionDurationMs || timeSinceLastEntry > sessionDurationMs) {
|
|
1897
|
-
blocks.push(currentBlockEntries);
|
|
1898
|
-
currentBlockStart = this.floorToHour(entryTime);
|
|
1899
|
-
currentBlockEntries = [entry];
|
|
1900
|
-
} else {
|
|
1901
|
-
currentBlockEntries.push(entry);
|
|
1902
|
-
}
|
|
1903
|
-
}
|
|
1904
|
-
}
|
|
1905
|
-
if (currentBlockStart != null && currentBlockEntries.length > 0) {
|
|
1906
|
-
blocks.push(currentBlockEntries);
|
|
1907
|
-
}
|
|
1908
|
-
return blocks;
|
|
1909
|
-
}
|
|
1910
|
-
createBlockInfo(startTime, entries) {
|
|
1911
|
-
const now = /* @__PURE__ */ new Date();
|
|
1912
|
-
const sessionDurationMs = this.sessionDurationHours * 60 * 60 * 1e3;
|
|
1913
|
-
const endTime = new Date(startTime.getTime() + sessionDurationMs);
|
|
1914
|
-
const lastEntry = entries[entries.length - 1];
|
|
1915
|
-
const actualEndTime = lastEntry != null ? lastEntry.timestamp : startTime;
|
|
1916
|
-
const isActive = now.getTime() - actualEndTime.getTime() < sessionDurationMs && now < endTime;
|
|
1917
|
-
return { block: entries, isActive };
|
|
1918
|
-
}
|
|
1919
|
-
findActiveBlock(blocks) {
|
|
1920
|
-
for (let i = blocks.length - 1; i >= 0; i--) {
|
|
1921
|
-
const block = blocks[i];
|
|
1922
|
-
if (!block || block.length === 0) continue;
|
|
1923
|
-
const firstEntry = block[0];
|
|
1924
|
-
if (!firstEntry) continue;
|
|
1925
|
-
const blockStartTime = this.floorToHour(firstEntry.timestamp);
|
|
1926
|
-
const blockInfo = this.createBlockInfo(blockStartTime, block);
|
|
1927
|
-
if (blockInfo.isActive) {
|
|
1928
|
-
return blockInfo.block;
|
|
1929
|
-
}
|
|
1930
|
-
}
|
|
1931
|
-
return null;
|
|
1932
|
-
}
|
|
1933
|
-
async loadUsageEntries() {
|
|
1934
|
-
debug(`Block segment: Loading entries for dynamic session blocks`);
|
|
1935
|
-
const dayAgo = /* @__PURE__ */ new Date();
|
|
1936
|
-
dayAgo.setDate(dayAgo.getDate() - 1);
|
|
1937
|
-
const fileFilter = (_filePath, modTime) => {
|
|
1938
|
-
return modTime >= dayAgo;
|
|
1939
|
-
};
|
|
1940
|
-
const parsedEntries = await loadEntriesFromProjects(
|
|
1941
|
-
void 0,
|
|
1942
|
-
fileFilter,
|
|
1943
|
-
true
|
|
1944
|
-
);
|
|
1945
|
-
const allUsageEntries = [];
|
|
1946
|
-
for (const entry of parsedEntries) {
|
|
1947
|
-
if (entry.message?.usage) {
|
|
1948
|
-
const usageEntry = convertToUsageEntry(entry);
|
|
1949
|
-
if (!usageEntry.costUSD && entry.raw) {
|
|
1950
|
-
usageEntry.costUSD = await PricingService.calculateCostForEntry(
|
|
1951
|
-
entry.raw
|
|
1952
|
-
);
|
|
1953
|
-
}
|
|
1954
|
-
allUsageEntries.push(usageEntry);
|
|
1955
|
-
}
|
|
1956
|
-
}
|
|
1957
|
-
const sessionBlocks = this.identifySessionBlocks(allUsageEntries);
|
|
1958
|
-
debug(`Block segment: Found ${sessionBlocks.length} session blocks`);
|
|
1959
|
-
const activeBlock = this.findActiveBlock(sessionBlocks);
|
|
1960
|
-
if (activeBlock && activeBlock.length > 0) {
|
|
1961
|
-
debug(
|
|
1962
|
-
`Block segment: Found active block with ${activeBlock.length} entries`
|
|
1963
|
-
);
|
|
1964
|
-
const blockStart = activeBlock[0];
|
|
1965
|
-
const blockEnd = activeBlock[activeBlock.length - 1];
|
|
1966
|
-
if (blockStart && blockEnd) {
|
|
1967
|
-
debug(
|
|
1968
|
-
`Block segment: Active block from ${blockStart.timestamp.toISOString()} to ${blockEnd.timestamp.toISOString()}`
|
|
1969
|
-
);
|
|
1970
|
-
}
|
|
1971
|
-
return activeBlock;
|
|
1972
|
-
} else {
|
|
1973
|
-
debug(`Block segment: No active block found`);
|
|
1974
|
-
return [];
|
|
1975
|
-
}
|
|
1976
|
-
}
|
|
1977
|
-
async getActiveBlockInfo() {
|
|
1978
|
-
try {
|
|
1979
|
-
const entries = await this.loadUsageEntries();
|
|
1980
|
-
if (entries.length === 0) {
|
|
1981
|
-
debug("Block segment: No entries in current block");
|
|
1982
|
-
return {
|
|
1983
|
-
cost: null,
|
|
1984
|
-
tokens: null,
|
|
1985
|
-
timeRemaining: null,
|
|
1986
|
-
burnRate: null,
|
|
1987
|
-
tokenBurnRate: null
|
|
1988
|
-
};
|
|
1989
|
-
}
|
|
1990
|
-
const totalCost = entries.reduce((sum, entry) => sum + entry.costUSD, 0);
|
|
1991
|
-
const totalTokens = entries.reduce((sum, entry) => {
|
|
1992
|
-
return sum + entry.usage.inputTokens + entry.usage.outputTokens + entry.usage.cacheCreationInputTokens + entry.usage.cacheReadInputTokens;
|
|
1993
|
-
}, 0);
|
|
1994
|
-
const now = /* @__PURE__ */ new Date();
|
|
1995
|
-
let timeRemaining = null;
|
|
1996
|
-
if (entries.length > 0) {
|
|
1997
|
-
const firstEntry = entries[0];
|
|
1998
|
-
if (firstEntry) {
|
|
1999
|
-
const sessionDurationMs = this.sessionDurationHours * 60 * 60 * 1e3;
|
|
2000
|
-
const blockStartTime = this.floorToHour(firstEntry.timestamp);
|
|
2001
|
-
const sessionEndTime = new Date(
|
|
2002
|
-
blockStartTime.getTime() + sessionDurationMs
|
|
2003
|
-
);
|
|
2004
|
-
timeRemaining = Math.max(
|
|
2005
|
-
0,
|
|
2006
|
-
Math.round((sessionEndTime.getTime() - now.getTime()) / (1e3 * 60))
|
|
2007
|
-
);
|
|
2008
|
-
}
|
|
2009
|
-
}
|
|
2010
|
-
let burnRate = null;
|
|
2011
|
-
let tokenBurnRate = null;
|
|
2012
|
-
if (entries.length >= 1 && (totalCost > 0 || totalTokens > 0)) {
|
|
2013
|
-
const timestamps = entries.map((entry) => entry.timestamp).sort((a, b) => a.getTime() - b.getTime());
|
|
2014
|
-
const firstEntry = timestamps[0];
|
|
2015
|
-
const lastEntry = timestamps[timestamps.length - 1];
|
|
2016
|
-
if (firstEntry && lastEntry) {
|
|
2017
|
-
const durationMinutes = (lastEntry.getTime() - firstEntry.getTime()) / (1e3 * 60);
|
|
2018
|
-
if (durationMinutes > 0) {
|
|
2019
|
-
if (totalCost > 0) {
|
|
2020
|
-
burnRate = totalCost / durationMinutes * 60;
|
|
2021
|
-
}
|
|
2022
|
-
if (totalTokens > 0) {
|
|
2023
|
-
tokenBurnRate = totalTokens / durationMinutes * 60;
|
|
2024
|
-
}
|
|
2025
|
-
}
|
|
2026
|
-
}
|
|
2027
|
-
}
|
|
2028
|
-
debug(
|
|
2029
|
-
`Block segment: $${totalCost.toFixed(2)}, ${totalTokens} tokens, ${timeRemaining}m remaining, burn rate: ${burnRate ? "$" + burnRate.toFixed(2) + "/hr" : "N/A"}`
|
|
2030
|
-
);
|
|
2031
|
-
return {
|
|
2032
|
-
cost: totalCost,
|
|
2033
|
-
tokens: totalTokens,
|
|
2034
|
-
timeRemaining,
|
|
2035
|
-
burnRate,
|
|
2036
|
-
tokenBurnRate
|
|
2037
|
-
};
|
|
2038
|
-
} catch (error) {
|
|
2039
|
-
debug("Error getting active block info:", error);
|
|
2040
|
-
return {
|
|
2041
|
-
cost: null,
|
|
2042
|
-
tokens: null,
|
|
2043
|
-
timeRemaining: null,
|
|
2044
|
-
burnRate: null,
|
|
2045
|
-
tokenBurnRate: null
|
|
2046
|
-
};
|
|
2047
|
-
}
|
|
2048
|
-
}
|
|
2049
|
-
};
|
|
2050
|
-
|
|
2051
|
-
// src/segments/today.ts
|
|
2052
|
-
function formatDate(date) {
|
|
2053
|
-
const year = date.getFullYear();
|
|
2054
|
-
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
2055
|
-
const day = String(date.getDate()).padStart(2, "0");
|
|
2056
|
-
return `${year}-${month}-${day}`;
|
|
2057
|
-
}
|
|
2058
|
-
function getTotalTokens(usage) {
|
|
2059
|
-
return usage.inputTokens + usage.outputTokens + usage.cacheCreationInputTokens + usage.cacheReadInputTokens;
|
|
2060
|
-
}
|
|
2061
|
-
function convertToTodayEntry(entry) {
|
|
2062
|
-
return {
|
|
2063
|
-
timestamp: entry.timestamp,
|
|
2064
|
-
usage: {
|
|
2065
|
-
inputTokens: entry.message?.usage?.input_tokens || 0,
|
|
2066
|
-
outputTokens: entry.message?.usage?.output_tokens || 0,
|
|
2067
|
-
cacheCreationInputTokens: entry.message?.usage?.cache_creation_input_tokens || 0,
|
|
2068
|
-
cacheReadInputTokens: entry.message?.usage?.cache_read_input_tokens || 0
|
|
2069
|
-
},
|
|
2070
|
-
costUSD: entry.costUSD || 0,
|
|
2071
|
-
model: entry.message?.model || "unknown"
|
|
2072
|
-
};
|
|
2073
|
-
}
|
|
2074
|
-
var TodayProvider = class {
|
|
2075
|
-
cache = /* @__PURE__ */ new Map();
|
|
2076
|
-
CACHE_TTL = 3e5;
|
|
2077
|
-
async loadTodayEntries() {
|
|
2078
|
-
const today = /* @__PURE__ */ new Date();
|
|
2079
|
-
const todayDateString = formatDate(today);
|
|
2080
|
-
debug(`Today segment: Loading entries for date ${todayDateString}`);
|
|
2081
|
-
const weekAgo = /* @__PURE__ */ new Date();
|
|
2082
|
-
weekAgo.setDate(weekAgo.getDate() - 7);
|
|
2083
|
-
const fileFilter = (_filePath, modTime) => {
|
|
2084
|
-
return modTime >= weekAgo;
|
|
2085
|
-
};
|
|
2086
|
-
const parsedEntries = await loadEntriesFromProjects(
|
|
2087
|
-
void 0,
|
|
2088
|
-
fileFilter,
|
|
2089
|
-
true
|
|
2090
|
-
);
|
|
2091
|
-
const todayEntries = [];
|
|
2092
|
-
let entriesFound = 0;
|
|
2093
|
-
for (const entry of parsedEntries) {
|
|
2094
|
-
const entryDateString = formatDate(entry.timestamp);
|
|
2095
|
-
if (entryDateString === todayDateString && entry.message?.usage) {
|
|
2096
|
-
const todayEntry = convertToTodayEntry(entry);
|
|
2097
|
-
if (!todayEntry.costUSD && entry.raw) {
|
|
2098
|
-
todayEntry.costUSD = await PricingService.calculateCostForEntry(
|
|
2099
|
-
entry.raw
|
|
2100
|
-
);
|
|
2101
|
-
}
|
|
2102
|
-
todayEntries.push(todayEntry);
|
|
2103
|
-
entriesFound++;
|
|
2104
|
-
}
|
|
2105
|
-
}
|
|
2106
|
-
debug(
|
|
2107
|
-
`Today segment: Found ${entriesFound} entries for today (${todayDateString})`
|
|
2108
|
-
);
|
|
2109
|
-
return todayEntries;
|
|
2110
|
-
}
|
|
2111
|
-
async getTodayEntries() {
|
|
2112
|
-
const cacheKey = "today";
|
|
2113
|
-
const cached = this.cache.get(cacheKey);
|
|
2114
|
-
const now = Date.now();
|
|
2115
|
-
if (cached && now - cached.timestamp < this.CACHE_TTL) {
|
|
2116
|
-
return cached.data;
|
|
2117
|
-
}
|
|
2118
|
-
this.cache.clear();
|
|
2119
|
-
try {
|
|
2120
|
-
const entries = await this.loadTodayEntries();
|
|
2121
|
-
this.cache.set(cacheKey, { data: entries, timestamp: now });
|
|
2122
|
-
return entries;
|
|
2123
|
-
} catch (error) {
|
|
2124
|
-
debug("Error loading today's entries:", error);
|
|
2125
|
-
return [];
|
|
2126
|
-
}
|
|
2127
|
-
}
|
|
2128
|
-
async getTodayInfo() {
|
|
2129
|
-
try {
|
|
2130
|
-
const entries = await this.getTodayEntries();
|
|
2131
|
-
if (entries.length === 0) {
|
|
2132
|
-
return {
|
|
2133
|
-
cost: null,
|
|
2134
|
-
tokens: null,
|
|
2135
|
-
tokenBreakdown: null,
|
|
2136
|
-
date: formatDate(/* @__PURE__ */ new Date())
|
|
2137
|
-
};
|
|
2138
|
-
}
|
|
2139
|
-
const totalCost = entries.reduce((sum, entry) => sum + entry.costUSD, 0);
|
|
2140
|
-
const totalTokens = entries.reduce(
|
|
2141
|
-
(sum, entry) => sum + getTotalTokens(entry.usage),
|
|
2142
|
-
0
|
|
2143
|
-
);
|
|
2144
|
-
const tokenBreakdown = entries.reduce(
|
|
2145
|
-
(breakdown, entry) => ({
|
|
2146
|
-
input: breakdown.input + entry.usage.inputTokens,
|
|
2147
|
-
output: breakdown.output + entry.usage.outputTokens,
|
|
2148
|
-
cacheCreation: breakdown.cacheCreation + entry.usage.cacheCreationInputTokens,
|
|
2149
|
-
cacheRead: breakdown.cacheRead + entry.usage.cacheReadInputTokens
|
|
2150
|
-
}),
|
|
2151
|
-
{
|
|
2152
|
-
input: 0,
|
|
2153
|
-
output: 0,
|
|
2154
|
-
cacheCreation: 0,
|
|
2155
|
-
cacheRead: 0
|
|
2156
|
-
}
|
|
2157
|
-
);
|
|
2158
|
-
debug(
|
|
2159
|
-
`Today segment: $${totalCost.toFixed(2)}, ${totalTokens} tokens total`
|
|
2160
|
-
);
|
|
2161
|
-
return {
|
|
2162
|
-
cost: totalCost,
|
|
2163
|
-
tokens: totalTokens,
|
|
2164
|
-
tokenBreakdown,
|
|
2165
|
-
date: formatDate(/* @__PURE__ */ new Date())
|
|
2166
|
-
};
|
|
2167
|
-
} catch (error) {
|
|
2168
|
-
debug("Error getting today's info:", error);
|
|
2169
|
-
return {
|
|
2170
|
-
cost: null,
|
|
2171
|
-
tokens: null,
|
|
2172
|
-
tokenBreakdown: null,
|
|
2173
|
-
date: formatDate(/* @__PURE__ */ new Date())
|
|
2174
|
-
};
|
|
2175
|
-
}
|
|
2176
|
-
}
|
|
2177
|
-
};
|
|
2178
|
-
|
|
2179
|
-
// src/powerline.ts
|
|
2180
|
-
var PowerlineRenderer = class {
|
|
2181
|
-
constructor(config) {
|
|
2182
|
-
this.config = config;
|
|
2183
|
-
this.symbols = this.initializeSymbols();
|
|
2184
|
-
this.usageProvider = new UsageProvider();
|
|
2185
|
-
this.blockProvider = new BlockProvider();
|
|
2186
|
-
this.todayProvider = new TodayProvider();
|
|
2187
|
-
this.contextProvider = new ContextProvider();
|
|
2188
|
-
this.gitService = new GitService();
|
|
2189
|
-
this.tmuxService = new TmuxService();
|
|
2190
|
-
this.metricsProvider = new MetricsProvider();
|
|
2191
|
-
this.versionProvider = new VersionProvider();
|
|
2192
|
-
this.segmentRenderer = new SegmentRenderer(config, this.symbols);
|
|
2193
|
-
}
|
|
2194
|
-
symbols;
|
|
2195
|
-
usageProvider;
|
|
2196
|
-
blockProvider;
|
|
2197
|
-
todayProvider;
|
|
2198
|
-
contextProvider;
|
|
2199
|
-
gitService;
|
|
2200
|
-
tmuxService;
|
|
2201
|
-
metricsProvider;
|
|
2202
|
-
versionProvider;
|
|
2203
|
-
segmentRenderer;
|
|
2204
|
-
needsUsageInfo() {
|
|
2205
|
-
return this.config.display.lines.some(
|
|
2206
|
-
(line) => line.segments.session?.enabled
|
|
2207
|
-
);
|
|
2208
|
-
}
|
|
2209
|
-
needsGitInfo() {
|
|
2210
|
-
return this.config.display.lines.some((line) => line.segments.git?.enabled);
|
|
2211
|
-
}
|
|
2212
|
-
needsTmuxInfo() {
|
|
2213
|
-
return this.config.display.lines.some(
|
|
2214
|
-
(line) => line.segments.tmux?.enabled
|
|
2215
|
-
);
|
|
2216
|
-
}
|
|
2217
|
-
needsContextInfo() {
|
|
2218
|
-
return this.config.display.lines.some(
|
|
2219
|
-
(line) => line.segments.context?.enabled
|
|
2220
|
-
);
|
|
2221
|
-
}
|
|
2222
|
-
needsMetricsInfo() {
|
|
2223
|
-
return this.config.display.lines.some(
|
|
2224
|
-
(line) => line.segments.metrics?.enabled
|
|
2225
|
-
);
|
|
2226
|
-
}
|
|
2227
|
-
needsBlockInfo() {
|
|
2228
|
-
return this.config.display.lines.some(
|
|
2229
|
-
(line) => line.segments.block?.enabled
|
|
2230
|
-
);
|
|
2231
|
-
}
|
|
2232
|
-
needsTodayInfo() {
|
|
2233
|
-
return this.config.display.lines.some(
|
|
2234
|
-
(line) => line.segments.today?.enabled
|
|
2235
|
-
);
|
|
2236
|
-
}
|
|
2237
|
-
needsVersionInfo() {
|
|
2238
|
-
return this.config.display.lines.some(
|
|
2239
|
-
(line) => line.segments.version?.enabled
|
|
2240
|
-
);
|
|
2241
|
-
}
|
|
2242
|
-
async generateStatusline(hookData) {
|
|
2243
|
-
const usageInfo = this.needsUsageInfo() ? await this.usageProvider.getUsageInfo(hookData.session_id) : null;
|
|
2244
|
-
const blockInfo = this.needsBlockInfo() ? await this.blockProvider.getActiveBlockInfo() : null;
|
|
2245
|
-
const todayInfo = this.needsTodayInfo() ? await this.todayProvider.getTodayInfo() : null;
|
|
2246
|
-
const contextInfo = this.needsContextInfo() ? await this.contextProvider.calculateContextTokens(
|
|
2247
|
-
hookData.transcript_path,
|
|
2248
|
-
hookData.model?.id
|
|
2249
|
-
) : null;
|
|
2250
|
-
const metricsInfo = this.needsMetricsInfo() ? await this.metricsProvider.getMetricsInfo(hookData.session_id) : null;
|
|
2251
|
-
const versionInfo = this.needsVersionInfo() ? await this.versionProvider.getVersionInfo() : null;
|
|
2252
|
-
const lines = this.config.display.lines.map(
|
|
2253
|
-
(lineConfig) => this.renderLine(
|
|
2254
|
-
lineConfig,
|
|
2255
|
-
hookData,
|
|
2256
|
-
usageInfo,
|
|
2257
|
-
blockInfo,
|
|
2258
|
-
todayInfo,
|
|
2259
|
-
contextInfo,
|
|
2260
|
-
metricsInfo,
|
|
2261
|
-
versionInfo
|
|
2262
|
-
)
|
|
2263
|
-
).filter((line) => line.length > 0);
|
|
2264
|
-
return lines.join("\n");
|
|
2265
|
-
}
|
|
2266
|
-
renderLine(lineConfig, hookData, usageInfo, blockInfo, todayInfo, contextInfo, metricsInfo, versionInfo) {
|
|
2267
|
-
const colors = this.getThemeColors();
|
|
2268
|
-
const currentDir = hookData.workspace?.current_dir || hookData.cwd || "/";
|
|
2269
|
-
const segments = Object.entries(lineConfig.segments).filter(
|
|
2270
|
-
([_, config]) => config?.enabled
|
|
2271
|
-
).map(([type, config]) => ({ type, config }));
|
|
2272
|
-
let line = colors.reset;
|
|
2273
|
-
for (let i = 0; i < segments.length; i++) {
|
|
2274
|
-
const segment = segments[i];
|
|
2275
|
-
if (!segment) continue;
|
|
2276
|
-
const isLast = i === segments.length - 1;
|
|
2277
|
-
const nextSegment = !isLast ? segments[i + 1] : null;
|
|
2278
|
-
const nextBgColor = nextSegment ? this.getSegmentBgColor(nextSegment.type, colors) : "";
|
|
2279
|
-
const segmentData = this.renderSegment(
|
|
2280
|
-
segment,
|
|
2281
|
-
hookData,
|
|
2282
|
-
usageInfo,
|
|
2283
|
-
blockInfo,
|
|
2284
|
-
todayInfo,
|
|
2285
|
-
contextInfo,
|
|
2286
|
-
metricsInfo,
|
|
2287
|
-
versionInfo,
|
|
2288
|
-
colors,
|
|
2289
|
-
currentDir
|
|
2290
|
-
);
|
|
2291
|
-
if (segmentData) {
|
|
2292
|
-
line += this.formatSegment(
|
|
2293
|
-
segmentData.bgColor,
|
|
2294
|
-
segmentData.fgColor,
|
|
2295
|
-
segmentData.text,
|
|
2296
|
-
isLast ? void 0 : nextBgColor
|
|
2297
|
-
);
|
|
2298
|
-
}
|
|
2299
|
-
}
|
|
2300
|
-
return line;
|
|
2301
|
-
}
|
|
2302
|
-
renderSegment(segment, hookData, usageInfo, blockInfo, todayInfo, contextInfo, metricsInfo, versionInfo, colors, currentDir) {
|
|
2303
|
-
switch (segment.type) {
|
|
2304
|
-
case "directory":
|
|
2305
|
-
return this.segmentRenderer.renderDirectory(
|
|
2306
|
-
hookData,
|
|
2307
|
-
colors,
|
|
2308
|
-
segment.config
|
|
2309
|
-
);
|
|
2310
|
-
case "git":
|
|
2311
|
-
if (!this.needsGitInfo()) return null;
|
|
2312
|
-
const gitConfig = segment.config;
|
|
2313
|
-
const gitInfo = this.gitService.getGitInfo(
|
|
2314
|
-
currentDir,
|
|
2315
|
-
{
|
|
2316
|
-
showSha: gitConfig?.showSha,
|
|
2317
|
-
showWorkingTree: gitConfig?.showWorkingTree,
|
|
2318
|
-
showOperation: gitConfig?.showOperation,
|
|
2319
|
-
showTag: gitConfig?.showTag,
|
|
2320
|
-
showTimeSinceCommit: gitConfig?.showTimeSinceCommit,
|
|
2321
|
-
showStashCount: gitConfig?.showStashCount,
|
|
2322
|
-
showUpstream: gitConfig?.showUpstream,
|
|
2323
|
-
showRepoName: gitConfig?.showRepoName
|
|
2324
|
-
},
|
|
2325
|
-
hookData.workspace?.project_dir
|
|
2326
|
-
);
|
|
2327
|
-
return gitInfo ? this.segmentRenderer.renderGit(gitInfo, colors, gitConfig) : null;
|
|
2328
|
-
case "model":
|
|
2329
|
-
return this.segmentRenderer.renderModel(hookData, colors);
|
|
2330
|
-
case "session":
|
|
2331
|
-
if (!usageInfo) return null;
|
|
2332
|
-
const usageType = segment.config?.type || "cost";
|
|
2333
|
-
return this.segmentRenderer.renderSession(usageInfo, colors, usageType);
|
|
2334
|
-
case "tmux":
|
|
2335
|
-
if (!this.needsTmuxInfo()) return null;
|
|
2336
|
-
const tmuxSessionId = this.tmuxService.getSessionId();
|
|
2337
|
-
return this.segmentRenderer.renderTmux(tmuxSessionId, colors);
|
|
2338
|
-
case "context":
|
|
2339
|
-
if (!this.needsContextInfo()) return null;
|
|
2340
|
-
return this.segmentRenderer.renderContext(contextInfo, colors);
|
|
2341
|
-
case "metrics":
|
|
2342
|
-
const metricsConfig = segment.config;
|
|
2343
|
-
return this.segmentRenderer.renderMetrics(
|
|
2344
|
-
metricsInfo,
|
|
2345
|
-
colors,
|
|
2346
|
-
blockInfo,
|
|
2347
|
-
metricsConfig
|
|
2348
|
-
);
|
|
2349
|
-
case "block":
|
|
2350
|
-
if (!blockInfo) return null;
|
|
2351
|
-
const blockConfig = segment.config;
|
|
2352
|
-
return this.segmentRenderer.renderBlock(blockInfo, colors, blockConfig);
|
|
2353
|
-
case "today":
|
|
2354
|
-
if (!todayInfo) return null;
|
|
2355
|
-
const todayType = segment.config?.type || "cost";
|
|
2356
|
-
return this.segmentRenderer.renderToday(todayInfo, colors, todayType);
|
|
2357
|
-
case "version":
|
|
2358
|
-
if (!versionInfo) return null;
|
|
2359
|
-
const versionConfig = segment.config;
|
|
2360
|
-
return this.segmentRenderer.renderVersion(
|
|
2361
|
-
versionInfo,
|
|
2362
|
-
colors,
|
|
2363
|
-
versionConfig
|
|
2364
|
-
);
|
|
2365
|
-
default:
|
|
2366
|
-
return null;
|
|
2367
|
-
}
|
|
2368
|
-
}
|
|
2369
|
-
initializeSymbols() {
|
|
2370
|
-
const isMinimalStyle = this.config.display.style === "minimal";
|
|
2371
|
-
return {
|
|
2372
|
-
right: isMinimalStyle ? "" : "\uE0B0",
|
|
2373
|
-
branch: "\u2387",
|
|
2374
|
-
model: "\u26A1",
|
|
2375
|
-
git_clean: "\u2713",
|
|
2376
|
-
git_dirty: "\u25CF",
|
|
2377
|
-
git_conflicts: "\u26A0",
|
|
2378
|
-
git_ahead: "\u2191",
|
|
2379
|
-
git_behind: "\u2193",
|
|
2380
|
-
git_worktree: "\u29C9",
|
|
2381
|
-
git_tag: "\u2302",
|
|
2382
|
-
git_sha: "\u266F",
|
|
2383
|
-
git_upstream: "\u2192",
|
|
2384
|
-
git_stash: "\u29C7",
|
|
2385
|
-
git_time: "\u25F7",
|
|
2386
|
-
session_cost: "\xA7",
|
|
2387
|
-
block_cost: "\u25F1",
|
|
2388
|
-
today_cost: "\u2609",
|
|
2389
|
-
context_time: "\u25D4",
|
|
2390
|
-
metrics_response: "\u29D6",
|
|
2391
|
-
metrics_last_response: "\u0394",
|
|
2392
|
-
metrics_duration: "\u29D7",
|
|
2393
|
-
metrics_messages: "\u27D0",
|
|
2394
|
-
metrics_burn: "\u27E2",
|
|
2395
|
-
version: "\u25C8"
|
|
2396
|
-
};
|
|
2397
|
-
}
|
|
2398
|
-
getThemeColors() {
|
|
2399
|
-
const theme = this.config.theme;
|
|
2400
|
-
let colorTheme;
|
|
2401
|
-
if (theme === "custom") {
|
|
2402
|
-
colorTheme = this.config.colors?.custom;
|
|
2403
|
-
if (!colorTheme) {
|
|
2404
|
-
throw new Error(
|
|
2405
|
-
"Custom theme selected but no colors provided in configuration"
|
|
2406
|
-
);
|
|
2407
|
-
}
|
|
2408
|
-
} else {
|
|
2409
|
-
colorTheme = getTheme(theme);
|
|
2410
|
-
if (!colorTheme) {
|
|
2411
|
-
console.warn(
|
|
2412
|
-
`Built-in theme '${theme}' not found, falling back to 'dark' theme`
|
|
2413
|
-
);
|
|
2414
|
-
colorTheme = getTheme("dark");
|
|
2415
|
-
}
|
|
2416
|
-
}
|
|
2417
|
-
const fallbackTheme = getTheme("dark");
|
|
2418
|
-
return {
|
|
2419
|
-
reset: "\x1B[0m",
|
|
2420
|
-
modeBg: hexToAnsi(
|
|
2421
|
-
colorTheme.directory?.bg || fallbackTheme.directory.bg,
|
|
2422
|
-
true
|
|
2423
|
-
),
|
|
2424
|
-
modeFg: hexToAnsi(
|
|
2425
|
-
colorTheme.directory?.fg || fallbackTheme.directory.fg,
|
|
2426
|
-
false
|
|
2427
|
-
),
|
|
2428
|
-
gitBg: hexToAnsi(colorTheme.git?.bg || fallbackTheme.git.bg, true),
|
|
2429
|
-
gitFg: hexToAnsi(colorTheme.git?.fg || fallbackTheme.git.fg, false),
|
|
2430
|
-
modelBg: hexToAnsi(colorTheme.model?.bg || fallbackTheme.model.bg, true),
|
|
2431
|
-
modelFg: hexToAnsi(colorTheme.model?.fg || fallbackTheme.model.fg, false),
|
|
2432
|
-
sessionBg: hexToAnsi(
|
|
2433
|
-
colorTheme.session?.bg || fallbackTheme.session.bg,
|
|
2434
|
-
true
|
|
2435
|
-
),
|
|
2436
|
-
sessionFg: hexToAnsi(
|
|
2437
|
-
colorTheme.session?.fg || fallbackTheme.session.fg,
|
|
2438
|
-
false
|
|
2439
|
-
),
|
|
2440
|
-
blockBg: hexToAnsi(colorTheme.block?.bg || fallbackTheme.block.bg, true),
|
|
2441
|
-
blockFg: hexToAnsi(colorTheme.block?.fg || fallbackTheme.block.fg, false),
|
|
2442
|
-
todayBg: hexToAnsi(colorTheme.today?.bg || fallbackTheme.today.bg, true),
|
|
2443
|
-
todayFg: hexToAnsi(colorTheme.today?.fg || fallbackTheme.today.fg, false),
|
|
2444
|
-
tmuxBg: hexToAnsi(colorTheme.tmux?.bg || fallbackTheme.tmux.bg, true),
|
|
2445
|
-
tmuxFg: hexToAnsi(colorTheme.tmux?.fg || fallbackTheme.tmux.fg, false),
|
|
2446
|
-
contextBg: hexToAnsi(
|
|
2447
|
-
colorTheme.context?.bg || fallbackTheme.context.bg,
|
|
2448
|
-
true
|
|
2449
|
-
),
|
|
2450
|
-
contextFg: hexToAnsi(
|
|
2451
|
-
colorTheme.context?.fg || fallbackTheme.context.fg,
|
|
2452
|
-
false
|
|
2453
|
-
),
|
|
2454
|
-
metricsBg: hexToAnsi(
|
|
2455
|
-
colorTheme.metrics?.bg || fallbackTheme.metrics.bg,
|
|
2456
|
-
true
|
|
2457
|
-
),
|
|
2458
|
-
metricsFg: hexToAnsi(
|
|
2459
|
-
colorTheme.metrics?.fg || fallbackTheme.metrics.fg,
|
|
2460
|
-
false
|
|
2461
|
-
),
|
|
2462
|
-
versionBg: hexToAnsi(
|
|
2463
|
-
colorTheme.version?.bg || fallbackTheme.version.bg,
|
|
2464
|
-
true
|
|
2465
|
-
),
|
|
2466
|
-
versionFg: hexToAnsi(
|
|
2467
|
-
colorTheme.version?.fg || fallbackTheme.version.fg,
|
|
2468
|
-
false
|
|
2469
|
-
)
|
|
2470
|
-
};
|
|
2471
|
-
}
|
|
2472
|
-
getSegmentBgColor(segmentType, colors) {
|
|
2473
|
-
switch (segmentType) {
|
|
2474
|
-
case "directory":
|
|
2475
|
-
return colors.modeBg;
|
|
2476
|
-
case "git":
|
|
2477
|
-
return colors.gitBg;
|
|
2478
|
-
case "model":
|
|
2479
|
-
return colors.modelBg;
|
|
2480
|
-
case "session":
|
|
2481
|
-
return colors.sessionBg;
|
|
2482
|
-
case "block":
|
|
2483
|
-
return colors.blockBg;
|
|
2484
|
-
case "today":
|
|
2485
|
-
return colors.todayBg;
|
|
2486
|
-
case "tmux":
|
|
2487
|
-
return colors.tmuxBg;
|
|
2488
|
-
case "context":
|
|
2489
|
-
return colors.contextBg;
|
|
2490
|
-
case "metrics":
|
|
2491
|
-
return colors.metricsBg;
|
|
2492
|
-
case "version":
|
|
2493
|
-
return colors.versionBg;
|
|
2494
|
-
default:
|
|
2495
|
-
return colors.modeBg;
|
|
2496
|
-
}
|
|
2497
|
-
}
|
|
2498
|
-
formatSegment(bgColor, fgColor, text, nextBgColor) {
|
|
2499
|
-
let output = `${bgColor}${fgColor} ${text} `;
|
|
2500
|
-
const reset = "\x1B[0m";
|
|
2501
|
-
if (nextBgColor) {
|
|
2502
|
-
const arrowFgColor = extractBgToFg(bgColor);
|
|
2503
|
-
output += `${reset}${nextBgColor}${arrowFgColor}${this.symbols.right}`;
|
|
2504
|
-
} else {
|
|
2505
|
-
output += `${reset}${extractBgToFg(bgColor)}${this.symbols.right}${reset}`;
|
|
2506
|
-
}
|
|
2507
|
-
return output;
|
|
2508
|
-
}
|
|
2509
|
-
};
|
|
2510
|
-
|
|
2511
|
-
// src/config/loader.ts
|
|
2512
|
-
import fs2 from "fs";
|
|
2513
|
-
import path3 from "path";
|
|
2514
|
-
import os from "os";
|
|
2515
|
-
|
|
2516
|
-
// src/config/defaults.ts
|
|
2517
|
-
var DEFAULT_CONFIG = {
|
|
2518
|
-
theme: "dark",
|
|
2519
|
-
display: {
|
|
2520
|
-
style: "minimal",
|
|
2521
|
-
lines: [
|
|
2522
|
-
{
|
|
2523
|
-
segments: {
|
|
2524
|
-
directory: {
|
|
2525
|
-
enabled: true,
|
|
2526
|
-
showBasename: true
|
|
2527
|
-
},
|
|
2528
|
-
git: {
|
|
2529
|
-
enabled: true,
|
|
2530
|
-
showSha: false,
|
|
2531
|
-
showWorkingTree: false,
|
|
2532
|
-
showOperation: false,
|
|
2533
|
-
showTag: false,
|
|
2534
|
-
showTimeSinceCommit: false,
|
|
2535
|
-
showStashCount: false,
|
|
2536
|
-
showUpstream: false,
|
|
2537
|
-
showRepoName: false
|
|
2538
|
-
},
|
|
2539
|
-
model: { enabled: true },
|
|
2540
|
-
session: { enabled: true, type: "tokens" },
|
|
2541
|
-
today: { enabled: false, type: "cost" },
|
|
2542
|
-
block: { enabled: true, type: "cost", burnType: "cost" },
|
|
2543
|
-
version: { enabled: false },
|
|
2544
|
-
tmux: { enabled: false },
|
|
2545
|
-
context: { enabled: true },
|
|
2546
|
-
metrics: {
|
|
2547
|
-
enabled: false,
|
|
2548
|
-
showResponseTime: true,
|
|
2549
|
-
showLastResponseTime: false,
|
|
2550
|
-
showDuration: true,
|
|
2551
|
-
showMessageCount: true
|
|
2552
|
-
}
|
|
2553
|
-
}
|
|
2554
|
-
}
|
|
2555
|
-
]
|
|
2556
|
-
},
|
|
2557
|
-
budget: {
|
|
2558
|
-
session: {
|
|
2559
|
-
warningThreshold: 80
|
|
2560
|
-
},
|
|
2561
|
-
today: {
|
|
2562
|
-
warningThreshold: 80,
|
|
2563
|
-
amount: 50
|
|
2564
|
-
}
|
|
2565
|
-
}
|
|
2566
|
-
};
|
|
2567
|
-
|
|
2568
|
-
// src/config/loader.ts
|
|
2569
|
-
function isValidTheme(theme) {
|
|
2570
|
-
return [
|
|
2571
|
-
"light",
|
|
2572
|
-
"dark",
|
|
2573
|
-
"nord",
|
|
2574
|
-
"tokyo-night",
|
|
2575
|
-
"rose-pine",
|
|
2576
|
-
"custom"
|
|
2577
|
-
].includes(theme);
|
|
2578
|
-
}
|
|
2579
|
-
function isValidStyle(style) {
|
|
2580
|
-
return style === "minimal" || style === "powerline";
|
|
2581
|
-
}
|
|
2582
|
-
function deepMerge(target, source) {
|
|
2583
|
-
const result = { ...target };
|
|
2584
|
-
for (const key in source) {
|
|
2585
|
-
const sourceValue = source[key];
|
|
2586
|
-
if (sourceValue !== void 0) {
|
|
2587
|
-
if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue)) {
|
|
2588
|
-
const targetValue = result[key] || {};
|
|
2589
|
-
result[key] = deepMerge(
|
|
2590
|
-
targetValue,
|
|
2591
|
-
sourceValue
|
|
2592
|
-
);
|
|
2593
|
-
} else {
|
|
2594
|
-
result[key] = sourceValue;
|
|
2595
|
-
}
|
|
2596
|
-
}
|
|
2597
|
-
}
|
|
2598
|
-
return result;
|
|
2599
|
-
}
|
|
2600
|
-
function findConfigFile(customPath, projectDir) {
|
|
2601
|
-
if (customPath) {
|
|
2602
|
-
return fs2.existsSync(customPath) ? customPath : null;
|
|
2603
|
-
}
|
|
2604
|
-
const locations = [
|
|
2605
|
-
...projectDir ? [path3.join(projectDir, ".claude-powerline.json")] : [],
|
|
2606
|
-
path3.join(process.cwd(), ".claude-powerline.json"),
|
|
2607
|
-
path3.join(os.homedir(), ".claude", "claude-powerline.json"),
|
|
2608
|
-
path3.join(os.homedir(), ".config", "claude-powerline", "config.json")
|
|
2609
|
-
];
|
|
2610
|
-
return locations.find(fs2.existsSync) || null;
|
|
2611
|
-
}
|
|
2612
|
-
function loadConfigFile(filePath) {
|
|
2613
|
-
try {
|
|
2614
|
-
const content = fs2.readFileSync(filePath, "utf-8");
|
|
2615
|
-
return JSON.parse(content);
|
|
2616
|
-
} catch (error) {
|
|
2617
|
-
throw new Error(
|
|
2618
|
-
`Failed to load config file ${filePath}: ${error instanceof Error ? error.message : String(error)}`
|
|
2619
|
-
);
|
|
2620
|
-
}
|
|
2621
|
-
}
|
|
2622
|
-
function loadEnvConfig() {
|
|
2623
|
-
const config = {};
|
|
2624
|
-
const display = {};
|
|
2625
|
-
const theme = process.env.CLAUDE_POWERLINE_THEME;
|
|
2626
|
-
if (theme && isValidTheme(theme)) {
|
|
2627
|
-
config.theme = theme;
|
|
2628
|
-
}
|
|
2629
|
-
const style = process.env.CLAUDE_POWERLINE_STYLE;
|
|
2630
|
-
if (style) {
|
|
2631
|
-
if (isValidStyle(style)) {
|
|
2632
|
-
display.style = style;
|
|
2633
|
-
} else {
|
|
2634
|
-
console.warn(
|
|
2635
|
-
`Invalid display style '${style}' from environment variable, falling back to 'minimal'`
|
|
2636
|
-
);
|
|
2637
|
-
display.style = "minimal";
|
|
2638
|
-
}
|
|
2639
|
-
}
|
|
2640
|
-
if (Object.keys(display).length > 0) {
|
|
2641
|
-
config.display = display;
|
|
2642
|
-
}
|
|
2643
|
-
return config;
|
|
2644
|
-
}
|
|
2645
|
-
function getConfigPathFromEnv() {
|
|
2646
|
-
return process.env.CLAUDE_POWERLINE_CONFIG;
|
|
2647
|
-
}
|
|
2648
|
-
function parseCLIOverrides(args) {
|
|
2649
|
-
const config = {};
|
|
2650
|
-
const display = {};
|
|
2651
|
-
const theme = args.find((arg) => arg.startsWith("--theme="))?.split("=")[1];
|
|
2652
|
-
if (theme && isValidTheme(theme)) {
|
|
2653
|
-
config.theme = theme;
|
|
2654
|
-
}
|
|
2655
|
-
const style = args.find((arg) => arg.startsWith("--style="))?.split("=")[1];
|
|
2656
|
-
if (style) {
|
|
2657
|
-
if (isValidStyle(style)) {
|
|
2658
|
-
display.style = style;
|
|
2659
|
-
} else {
|
|
2660
|
-
console.warn(
|
|
2661
|
-
`Invalid display style '${style}' from CLI argument, falling back to 'minimal'`
|
|
2662
|
-
);
|
|
2663
|
-
display.style = "minimal";
|
|
2664
|
-
}
|
|
2665
|
-
}
|
|
2666
|
-
if (Object.keys(display).length > 0) {
|
|
2667
|
-
config.display = display;
|
|
2668
|
-
}
|
|
2669
|
-
return config;
|
|
2670
|
-
}
|
|
2671
|
-
function loadConfig(args = process.argv, projectDir) {
|
|
2672
|
-
let config = JSON.parse(JSON.stringify(DEFAULT_CONFIG));
|
|
2673
|
-
const configPath = args.find((arg) => arg.startsWith("--config="))?.split("=")[1] || getConfigPathFromEnv();
|
|
2674
|
-
const configFile = findConfigFile(configPath, projectDir);
|
|
2675
|
-
if (configFile) {
|
|
2676
|
-
try {
|
|
2677
|
-
const fileConfig = loadConfigFile(configFile);
|
|
2678
|
-
config = deepMerge(config, fileConfig);
|
|
2679
|
-
} catch (err) {
|
|
2680
|
-
console.warn(
|
|
2681
|
-
`Warning: ${err instanceof Error ? err.message : String(err)}`
|
|
2682
|
-
);
|
|
2683
|
-
}
|
|
2684
|
-
}
|
|
2685
|
-
if (config.display?.style && !isValidStyle(config.display.style)) {
|
|
2686
|
-
console.warn(
|
|
2687
|
-
`Invalid display style '${config.display.style}' in config file, falling back to 'minimal'`
|
|
2688
|
-
);
|
|
2689
|
-
config.display.style = "minimal";
|
|
2690
|
-
}
|
|
2691
|
-
if (config.theme && !isValidTheme(config.theme)) {
|
|
2692
|
-
console.warn(
|
|
2693
|
-
`Invalid theme '${config.theme}' in config file, falling back to 'dark'`
|
|
2694
|
-
);
|
|
2695
|
-
config.theme = "dark";
|
|
2696
|
-
}
|
|
2697
|
-
const envConfig = loadEnvConfig();
|
|
2698
|
-
config = deepMerge(config, envConfig);
|
|
2699
|
-
const cliOverrides = parseCLIOverrides(args);
|
|
2700
|
-
config = deepMerge(config, cliOverrides);
|
|
2701
|
-
return config;
|
|
2702
|
-
}
|
|
2703
|
-
var loadConfigFromCLI = loadConfig;
|
|
2704
|
-
|
|
2705
|
-
// src/index.ts
|
|
2706
|
-
async function installFonts() {
|
|
2707
|
-
try {
|
|
2708
|
-
const platform = os2.platform();
|
|
2709
|
-
let fontDir;
|
|
2710
|
-
if (platform === "darwin") {
|
|
2711
|
-
fontDir = path4.join(os2.homedir(), "Library", "Fonts");
|
|
2712
|
-
} else if (platform === "linux") {
|
|
2713
|
-
fontDir = path4.join(os2.homedir(), ".local", "share", "fonts");
|
|
2714
|
-
} else if (platform === "win32") {
|
|
2715
|
-
fontDir = path4.join(
|
|
2716
|
-
os2.homedir(),
|
|
2717
|
-
"AppData",
|
|
2718
|
-
"Local",
|
|
2719
|
-
"Microsoft",
|
|
2720
|
-
"Windows",
|
|
2721
|
-
"Fonts"
|
|
2722
|
-
);
|
|
2723
|
-
} else {
|
|
2724
|
-
console.log("Unsupported platform for font installation");
|
|
2725
|
-
return;
|
|
2726
|
-
}
|
|
2727
|
-
if (!fs3.existsSync(fontDir)) {
|
|
2728
|
-
fs3.mkdirSync(fontDir, { recursive: true });
|
|
2729
|
-
}
|
|
2730
|
-
console.log("\u{1F4E6} Installing Powerline Fonts...");
|
|
2731
|
-
console.log("Downloading from https://github.com/powerline/fonts");
|
|
2732
|
-
const tempDir = path4.join(os2.tmpdir(), "powerline-fonts");
|
|
2733
|
-
const cleanup = () => {
|
|
2734
|
-
if (fs3.existsSync(tempDir)) {
|
|
2735
|
-
fs3.rmSync(tempDir, { recursive: true, force: true });
|
|
2736
|
-
}
|
|
2737
|
-
};
|
|
2738
|
-
process2.on("SIGINT", cleanup);
|
|
2739
|
-
process2.on("SIGTERM", cleanup);
|
|
2740
|
-
try {
|
|
2741
|
-
if (fs3.existsSync(tempDir)) {
|
|
2742
|
-
fs3.rmSync(tempDir, { recursive: true, force: true });
|
|
2743
|
-
}
|
|
2744
|
-
console.log("Cloning powerline fonts repository...");
|
|
2745
|
-
execSync4(
|
|
2746
|
-
"git clone --depth=1 https://github.com/powerline/fonts.git powerline-fonts",
|
|
2747
|
-
{
|
|
2748
|
-
stdio: "inherit",
|
|
2749
|
-
cwd: os2.tmpdir()
|
|
2750
|
-
}
|
|
2751
|
-
);
|
|
2752
|
-
console.log("Installing fonts...");
|
|
2753
|
-
const installScript = path4.join(tempDir, "install.sh");
|
|
2754
|
-
if (fs3.existsSync(installScript)) {
|
|
2755
|
-
fs3.chmodSync(installScript, 493);
|
|
2756
|
-
execSync4("./install.sh", { stdio: "inherit", cwd: tempDir });
|
|
2757
|
-
} else {
|
|
2758
|
-
throw new Error(
|
|
2759
|
-
"Install script not found in powerline fonts repository"
|
|
2760
|
-
);
|
|
2761
|
-
}
|
|
2762
|
-
console.log("\u2705 Powerline fonts installation complete!");
|
|
2763
|
-
console.log(
|
|
2764
|
-
"Please restart your terminal and set your terminal font to a powerline font."
|
|
2765
|
-
);
|
|
2766
|
-
console.log(
|
|
2767
|
-
"Popular choices: Source Code Pro Powerline, DejaVu Sans Mono Powerline, Ubuntu Mono Powerline"
|
|
2768
|
-
);
|
|
2769
|
-
} finally {
|
|
2770
|
-
cleanup();
|
|
2771
|
-
process2.removeListener("SIGINT", cleanup);
|
|
2772
|
-
process2.removeListener("SIGTERM", cleanup);
|
|
2773
|
-
}
|
|
2774
|
-
} catch (error) {
|
|
2775
|
-
console.error(
|
|
2776
|
-
"Error installing fonts:",
|
|
2777
|
-
error instanceof Error ? error.message : String(error)
|
|
2778
|
-
);
|
|
2779
|
-
console.log(
|
|
2780
|
-
"\u{1F4A1} You can manually install fonts from: https://github.com/powerline/fonts"
|
|
2781
|
-
);
|
|
2782
|
-
}
|
|
2783
|
-
}
|
|
2784
|
-
async function main() {
|
|
2785
|
-
try {
|
|
2786
|
-
const showHelp = process2.argv.includes("--help") || process2.argv.includes("-h");
|
|
2787
|
-
const installFontsFlag = process2.argv.includes("--install-fonts");
|
|
2788
|
-
if (installFontsFlag) {
|
|
2789
|
-
await installFonts();
|
|
2790
|
-
process2.exit(0);
|
|
2791
|
-
}
|
|
2792
|
-
if (showHelp) {
|
|
2793
|
-
console.log(`
|
|
2
|
+
import C from'process';import T,{posix,join}from'path';import x,{readFileSync,existsSync}from'fs';import {execSync}from'child_process';import B,{homedir}from'os';import {json}from'stream/consumers';import {readFile,readdir,stat}from'fs/promises';var R=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function b(r,e){if(e&&(r.toLowerCase()==="transparent"||r.toLowerCase()==="none"))return "\x1B[49m";let t=parseInt(r.slice(1,3),16),n=parseInt(r.slice(3,5),16),s=parseInt(r.slice(5,7),16);return `\x1B[${e?"48":"38"};2;${t};${n};${s}m`}function ee(r){let e=r.match(/48;2;(\d+);(\d+);(\d+)/);return e?`\x1B[38;2;${e[1]};${e[2]};${e[3]}m`:r.replace("48","38")}var ie={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 ae={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 ce={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 le={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 ue={directory:{bg:"#26233a",fg:"#c4a7e7"},git:{bg:"#1f1d2e",fg:"#9ccfd8"},model:{bg:"#191724",fg:"#ebbcba"},session:{bg:"#26233a",fg:"#f6c177"},block:{bg:"#2a273f",fg:"#eb6f92"},today:{bg:"#232136",fg:"#9ccfd8"},tmux:{bg:"#26233a",fg:"#908caa"},context:{bg:"#393552",fg:"#e0def4"},metrics:{bg:"#524f67",fg:"#e0def4"},version:{bg:"#2a273f",fg:"#c4a7e7"}};var ke={dark:ie,light:ae,nord:ce,"tokyo-night":le,"rose-pine":ue};function V(r){return ke[r]||null}var l=(r,...e)=>{process.env.CLAUDE_POWERLINE_DEBUG&&console.error(`[DEBUG] ${r}`,...e);};var U=class{cache=new Map;CACHE_TTL=1e3;isGitRepo(e){try{return x.existsSync(T.join(e,".git"))}catch{return false}}getGitInfo(e,t={},n){let s=n&&this.isGitRepo(n)?n:e,i=JSON.stringify(t),o=`${s}:${i}`,c=this.cache.get(o),a=Date.now();if(c&&a-c.timestamp<this.CACHE_TTL)return c.data;if(!this.isGitRepo(s))return this.cache.set(o,{data:null,timestamp:a}),null;try{let u=this.getBranch(s),f=this.getStatus(s),{ahead:g,behind:d}=this.getAheadBehind(s),m={branch:u||"detached",status:f,ahead:g,behind:d};if(t.showSha&&(m.sha=this.getSha(s)||void 0),t.showWorkingTree){let p=this.getWorkingTreeCounts(s);m.staged=p.staged,m.unstaged=p.unstaged,m.untracked=p.untracked,m.conflicts=p.conflicts;}return t.showOperation&&(m.operation=this.getOngoingOperation(s)||void 0),t.showTag&&(m.tag=this.getNearestTag(s)||void 0),t.showTimeSinceCommit&&(m.timeSinceCommit=this.getTimeSinceLastCommit(s)||void 0),t.showStashCount&&(m.stashCount=this.getStashCount(s)),t.showUpstream&&(m.upstream=this.getUpstream(s)||void 0),t.showRepoName&&(m.repoName=this.getRepoName(s)||void 0,m.isWorktree=this.isWorktree(s)),this.cache.set(o,{data:m,timestamp:a}),m}catch{return this.cache.set(o,{data:null,timestamp:a}),null}}getBranch(e){try{return execSync("git branch --show-current",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch(t){return l(`Git branch command failed in ${e}:`,t),null}}getStatus(e){try{let t=execSync("git status --porcelain",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return t?t.includes("UU")||t.includes("AA")||t.includes("DD")?"conflicts":"dirty":"clean"}catch(t){return l(`Git status command failed in ${e}:`,t),"clean"}}getWorkingTreeCounts(e){try{let t=execSync("git status --porcelain=v1",{cwd:e,encoding:"utf8",timeout:5e3}),n=0,s=0,i=0,o=0;if(!t.trim())return {staged:n,unstaged:s,untracked:i,conflicts:o};let c=t.split(`
|
|
3
|
+
`);for(let a of c){if(!a||a.length<2)continue;let u=a.charAt(0),f=a.charAt(1);if(u==="?"&&f==="?"){i++;continue}let g=u+f;if(["DD","AU","UD","UA","DU","AA","UU"].includes(g)){o++;continue}u!==" "&&u!=="?"&&n++,f!==" "&&f!=="?"&&s++;}return {staged:n,unstaged:s,untracked:i,conflicts:o}}catch(t){return l(`Git working tree counts failed in ${e}:`,t),{staged:0,unstaged:0,untracked:0,conflicts:0}}}getAheadBehind(e){try{let t=execSync("git rev-list --count @{u}..HEAD",{cwd:e,encoding:"utf8",timeout:5e3}).trim(),n=execSync("git rev-list --count HEAD..@{u}",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return {ahead:parseInt(t)||0,behind:parseInt(n)||0}}catch(t){return l(`Git ahead/behind command failed in ${e}:`,t),{ahead:0,behind:0}}}getSha(e){try{return execSync("git rev-parse --short=7 HEAD",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}getOngoingOperation(e){try{let t=T.join(e,".git");return x.existsSync(T.join(t,"MERGE_HEAD"))?"MERGE":x.existsSync(T.join(t,"CHERRY_PICK_HEAD"))?"CHERRY-PICK":x.existsSync(T.join(t,"REVERT_HEAD"))?"REVERT":x.existsSync(T.join(t,"BISECT_LOG"))?"BISECT":x.existsSync(T.join(t,"rebase-merge"))||x.existsSync(T.join(t,"rebase-apply"))?"REBASE":null}catch{return null}}getNearestTag(e){try{return execSync("git describe --tags --abbrev=0",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}getTimeSinceLastCommit(e){try{let t=execSync("git log -1 --format=%ct",{cwd:e,encoding:"utf8",timeout:5e3}).trim();if(!t)return null;let n=parseInt(t)*1e3,s=Date.now();return Math.floor((s-n)/1e3)}catch{return null}}getStashCount(e){try{let t=execSync("git stash list",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return t?t.split(`
|
|
4
|
+
`).length:0}catch{return 0}}getUpstream(e){try{return execSync("git rev-parse --abbrev-ref @{u}",{cwd:e,encoding:"utf8",timeout:5e3}).trim()||null}catch{return null}}getRepoName(e){try{let t=execSync("git config --get remote.origin.url",{cwd:e,encoding:"utf8",timeout:5e3}).trim();return t?t.match(/\/([^/]+?)(\.git)?$/)?.[1]||T.basename(e):T.basename(e)}catch{return T.basename(e)}}isWorktree(e){try{let t=T.join(e,".git");return !!(x.existsSync(t)&&x.statSync(t).isFile())}catch{return false}}};var F=class{getSessionId(){try{if(!process.env.TMUX_PANE)return l("TMUX_PANE not set, not in tmux session"),null;l(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let e=execSync("tmux display-message -p '#S'",{encoding:"utf8",timeout:1e3}).trim();return l(`Tmux session ID: ${e||"empty"}`),e||null}catch(e){return l("Error getting tmux session ID:",e),null}}isInTmux(){return !!process.env.TMUX_PANE}};var ge={"claude-3-haiku-20240307":{name:"Claude 3 Haiku",input:.25,output:1.25,cache_write_5m:.3,cache_write_1h:.5,cache_read:.03},"claude-3-5-haiku-20241022":{name:"Claude 3.5 Haiku",input:.8,output:4,cache_write_5m:1,cache_write_1h:1.6,cache_read:.08},"claude-3-5-haiku-latest":{name:"Claude 3.5 Haiku Latest",input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-3-opus-latest":{name:"Claude 3 Opus Latest",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-3-opus-20240229":{name:"Claude 3 Opus",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-3-5-sonnet-latest":{name:"Claude 3.5 Sonnet Latest",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-5-sonnet-20240620":{name:"Claude 3.5 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-5-sonnet-20241022":{name:"Claude 3.5 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-20250514":{name:"Claude Opus 4",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:"Claude Opus 4.1",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:"Claude Opus 4.1",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:"Claude Sonnet 4",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:"Claude 4 Opus",input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:"Claude 4 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-7-sonnet-latest":{name:"Claude 3.7 Sonnet Latest",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-3-7-sonnet-20250219":{name:"Claude 3.7 Sonnet",input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}},S=class{static memoryCache=new Map;static CACHE_TTL=1440*60*1e3;static GITHUB_PRICING_URL="https://raw.githubusercontent.com/Owloops/claude-powerline/main/pricing.json";static getCacheFilePath(){let{homedir:e}=R("os"),{join:t}=R("path"),{mkdirSync:n}=R("fs"),s=t(e(),".claude","cache");try{n(s,{recursive:!0});}catch{}return t(s,"pricing.json")}static loadDiskCache(){try{let{readFileSync:e}=R("fs"),t=this.getCacheFilePath(),n=e(t,"utf-8"),s=JSON.parse(n);if(s&&s.data&&s.timestamp)return s}catch{}return null}static saveDiskCache(e){try{let{writeFileSync:t}=R("fs"),n=this.getCacheFilePath(),s={data:e,timestamp:Date.now()};t(n,JSON.stringify(s));}catch(t){l("Failed to save pricing cache to disk:",t);}}static async getCurrentPricing(){let e=Date.now(),t=this.memoryCache.get("pricing");if(t&&e-t.timestamp<this.CACHE_TTL)return l(`Using memory cached pricing data for ${Object.keys(t.data).length} models`),t.data;let n=this.loadDiskCache();if(n&&e-n.timestamp<this.CACHE_TTL)return this.memoryCache.clear(),this.memoryCache.set("pricing",n),l(`Using disk cached pricing data for ${Object.keys(n.data).length} models`),n.data;try{let s=await globalThis.fetch(this.GITHUB_PRICING_URL,{headers:{"User-Agent":"claude-powerline","Cache-Control":"no-cache"}});if(s.ok){let o=await s.json(),c=o._meta,a={};for(let[u,f]of Object.entries(o))u!=="_meta"&&(a[u]=f);if(this.validatePricingData(a))return this.memoryCache.clear(),this.memoryCache.set("pricing",{data:a,timestamp:e}),this.saveDiskCache(a),l(`Fetched fresh pricing from GitHub for ${Object.keys(a).length} models`),l(`Pricing last updated: ${c?.updated||"unknown"}`),a}}catch(s){l("Failed to fetch pricing from GitHub, using fallback:",s);}return n?(this.memoryCache.set("pricing",n),l(`Using stale cached pricing data for ${Object.keys(n.data).length} models`),n.data):(l(`Using offline pricing data for ${Object.keys(ge).length} models`),ge)}static validatePricingData(e){if(!e||typeof e!="object")return false;for(let[,t]of Object.entries(e)){if(!t||typeof t!="object")return false;let n=t;if(typeof n.input!="number"||typeof n.output!="number"||typeof n.cache_read!="number")return false}return true}static async getModelPricing(e){let t=await this.getCurrentPricing();return t[e]?t[e]:this.fuzzyMatchModel(e,t)}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[i,o]of Object.entries(t))if(i.toLowerCase()===n)return o;let s=[{pattern:["opus-4-1","claude-opus-4-1"],fallback:"claude-opus-4-1-20250805"},{pattern:["opus-4","claude-opus-4"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet-4","claude-sonnet-4"],fallback:"claude-sonnet-4-20250514"},{pattern:["sonnet-3.7","3-7-sonnet"],fallback:"claude-3-7-sonnet-20250219"},{pattern:["3-5-sonnet","sonnet-3.5"],fallback:"claude-3-5-sonnet-20241022"},{pattern:["3-5-haiku","haiku-3.5"],fallback:"claude-3-5-haiku-20241022"},{pattern:["haiku","3-haiku"],fallback:"claude-3-haiku-20240307"},{pattern:["opus"],fallback:"claude-opus-4-20250514"},{pattern:["sonnet"],fallback:"claude-3-5-sonnet-20241022"}];for(let{pattern:i,fallback:o}of s)if(i.some(c=>n.includes(c))&&t[o])return t[o];return t["claude-3-5-sonnet-20241022"]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let n=e.message?.usage;if(!n)return 0;let s=this.extractModelId(e),i=await this.getModelPricing(s),o=n.input_tokens||0,c=n.output_tokens||0,a=n.cache_creation_input_tokens||0,u=n.cache_read_input_tokens||0,f=o/1e6*i.input,g=c/1e6*i.output,d=u/1e6*i.cache_read,m=a/1e6*i.cache_write_5m;return f+g+m+d}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 de(){let r=[],e=process.env.CLAUDE_CONFIG_DIR;if(e&&e.split(",").forEach(t=>{let n=t.trim();existsSync(n)&&r.push(n);}),r.length===0){let t=homedir(),n=join(t,".config","claude"),s=join(t,".claude");existsSync(n)?r.push(n):existsSync(s)&&r.push(s);}return r}async function pe(r){let e=[];for(let t of r){let n=join(t,"projects");if(existsSync(n))try{let s=await readdir(n,{withFileTypes:!0});for(let i of s)if(i.isDirectory()){let o=posix.join(n,i.name);e.push(o);}}catch(s){l(`Failed to read projects directory ${n}:`,s);}}return e}async function W(r){let e=de(),t=await pe(e);for(let n of t){let s=posix.join(n,`${r}.jsonl`);if(existsSync(s))return s}return null}async function ve(r){try{let t=(await readFile(r,"utf-8")).trim().split(`
|
|
5
|
+
`),n=null;for(let s of t)if(s.trim())try{let i=JSON.parse(s);if(i.timestamp&&typeof i.timestamp=="string"){let o=new Date(i.timestamp);isNaN(o.getTime())||(n===null||o<n)&&(n=o);}}catch{continue}return n}catch(e){return l(`Failed to get earliest timestamp for ${r}:`,e),null}}async function $e(r,e=true){return (await Promise.all(r.map(async n=>({file:n,timestamp:await ve(n)})))).sort((n,s)=>n.timestamp===null&&s.timestamp===null?0:n.timestamp===null?1:s.timestamp===null?-1:(e?1:-1)*(n.timestamp.getTime()-s.timestamp.getTime())).map(n=>n.file)}async function Pe(r){try{return (await stat(r)).mtime}catch{return null}}function Ee(r){let e=r.message?.id||(typeof r.raw.message=="object"&&r.raw.message!==null&&"id"in r.raw.message?r.raw.message.id:void 0),t="requestId"in r.raw?r.raw.requestId:void 0;return !e||!t?null:`${e}:${t}`}async function M(r){try{let t=(await readFile(r,"utf-8")).trim().split(`
|
|
6
|
+
`).filter(s=>s.trim()),n=[];for(let s of t)try{let i=JSON.parse(s);if(!i.timestamp)continue;let o={timestamp:new Date(i.timestamp),message:i.message,costUSD:typeof i.costUSD=="number"?i.costUSD:void 0,isSidechain:i.isSidechain===!0,raw:i};n.push(o);}catch(i){l(`Failed to parse JSONL line: ${i}`);continue}return n}catch(e){return l(`Failed to read file ${r}:`,e),[]}}async function J(r,e,t=false){let n=[],s=de(),i=await pe(s),o=new Set,c=[];for(let a of i)try{let g=(await readdir(a)).filter(m=>m.endsWith(".jsonl")).map(async m=>{let p=posix.join(a,m);if(existsSync(p)){let w=await Pe(p);return {filePath:p,mtime:w}}return null}),d=await Promise.all(g);for(let m of d)m?.mtime&&(!e||e(m.filePath,m.mtime))&&c.push(m.filePath);}catch(u){l(`Failed to read project directory ${a}:`,u);continue}if(t){let a=await $e(c,false);c.length=0,c.push(...a);}for(let a of c){let u=await M(a);for(let f of u){let g=Ee(f);if(g&&o.has(g)){l(`Skipping duplicate entry: ${g}`);continue}g&&o.add(g),n.push(f);}}return n}function Be(r){return {timestamp:r.timestamp.toISOString(),message:{usage:{input_tokens:r.message?.usage?.input_tokens||0,output_tokens:r.message?.usage?.output_tokens||0,cache_creation_input_tokens:r.message?.usage?.cache_creation_input_tokens,cache_read_input_tokens:r.message?.usage?.cache_read_input_tokens}},costUSD:r.costUSD}}var q=class{async getSessionUsage(e){try{let t=await W(e);if(!t)return l(`No transcript found for session: ${e}`),null;l(`Found transcript at: ${t}`);let n=await M(t);if(n.length===0)return {totalCost:0,entries:[]};let s=[],i=0;for(let o of n)if(o.message?.usage){let c=Be(o);if(c.costUSD!==void 0)i+=c.costUSD;else {let a=await S.calculateCostForEntry(o.raw);c.costUSD=a,i+=a;}s.push(c);}return l(`Parsed ${s.length} usage entries, total cost: $${i.toFixed(4)}`),{totalCost:i,entries:s}}catch(t){return l(`Error reading session usage for ${e}:`,t),null}}calculateTokenBreakdown(e){return e.reduce((t,n)=>({input:t.input+(n.message.usage.input_tokens||0),output:t.output+(n.message.usage.output_tokens||0),cacheCreation:t.cacheCreation+(n.message.usage.cache_creation_input_tokens||0),cacheRead:t.cacheRead+(n.message.usage.cache_read_input_tokens||0)}),{input:0,output:0,cacheCreation:0,cacheRead:0})}async getSessionInfo(e){let t=await this.getSessionUsage(e);if(!t||t.entries.length===0)return {cost:null,tokens:null,tokenBreakdown:null};let n=this.calculateTokenBreakdown(t.entries),s=n.input+n.output+n.cacheCreation+n.cacheRead;return {cost:t.totalCost,tokens:s,tokenBreakdown:n}}},I=class{sessionProvider=new q;async getUsageInfo(e){try{return l(`Starting usage info retrieval for session: ${e}`),{session:await this.sessionProvider.getSessionInfo(e)}}catch(t){return l(`Error getting usage info for session ${e}:`,t),{session:{cost:null,tokens:null,tokenBreakdown:null}}}}};var L=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}getContextLimit(e){return 2e5}async calculateContextTokens(e,t){try{l(`Calculating context tokens from transcript: ${e}`);try{if(!readFileSync(e,"utf-8"))return l("Transcript file is empty"),null}catch{return l("Could not read transcript file"),null}let n=await M(e);if(n.length===0)return l("No entries in transcript"),null;let s=null;for(let i=n.length-1;i>=0;i--){let o=n[i];if(o&&o.message?.usage?.input_tokens&&o.isSidechain!==!0){s=o,l(`Context segment: Found most recent entry at ${o.timestamp.toISOString()}, stopping search`);break}}if(s?.message?.usage){let i=s.message.usage,o=(i.input_tokens||0)+(i.cache_read_input_tokens||0)+(i.cache_creation_input_tokens||0),c=t?this.getContextLimit(t):2e5;l(`Most recent main chain context: ${o} tokens (limit: ${c})`);let a=Math.min(100,Math.max(0,Math.round(o/c*100))),u=Math.round(c*.75),f=Math.min(100,Math.max(0,Math.round(o/u*100))),g=Math.max(0,100-f);return {inputTokens:o,percentage:a,usablePercentage:f,contextLeftPercentage:g,maxTokens:c,usableTokens:u}}return l("No main chain entries with usage data found"),null}catch(n){return l(`Error reading transcript: ${n instanceof Error?n.message:String(n)}`),null}}};var j=class{async loadTranscriptEntries(e){try{let t=await W(e);if(!t)return l(`No transcript found for session: ${e}`),[];l(`Loading transcript from: ${t}`);let s=(await readFile(t,"utf-8")).trim().split(`
|
|
7
|
+
`).filter(o=>o.trim()),i=[];for(let o of s)try{let c=JSON.parse(o);if(c.isSidechain===!0)continue;i.push(c);}catch(c){l(`Failed to parse JSONL line: ${c}`);continue}return l(`Loaded ${i.length} transcript entries`),i}catch(t){return l(`Error loading transcript for ${e}:`,t),[]}}calculateResponseTimes(e){let t=[],n=[],s=-1,i=null,o=null,c=-1;for(let g=0;g<e.length;g++){let d=e[g];if(!(!d||!d.timestamp))try{let m=new Date(d.timestamp),p=d.type||d.message?.role||d.message?.type,w=d.type==="user"&&d.message?.content?.[0]?.type==="tool_result";p==="user"&&!w?(t.push(m),i=m,s=g,o=null,c=-1,l(`Found user message at index ${g}, timestamp ${m.toISOString()}`)):s>=0&&(p==="assistant"||w||p==="system"||d.message?.usage)&&(o=m,c=g,p==="assistant"||d.message?.usage?(n.push(m),l(`Found assistant message at index ${g}, timestamp ${m.toISOString()}`)):w?l(`Found tool result at index ${g}, timestamp ${m.toISOString()}`):l(`Found ${p} message at index ${g}, timestamp ${m.toISOString()}`));}catch{continue}}if(t.length===0||n.length===0)return {average:null,last:null};let a=[];for(let g of n){let d=t.filter(m=>m<g);if(d.length>0){let m=new Date(Math.max(...d.map(w=>w.getTime()))),p=(g.getTime()-m.getTime())/1e3;p>.1&&p<300?(a.push(p),l(`Valid response time: ${p.toFixed(1)}s`)):l(`Rejected response time: ${p.toFixed(1)}s (outside 0.1s-5m range)`);}}let u=null;if(i&&o&&c>s){let g=o.getTime()-i.getTime(),d=c-s;g===0&&d>0?(u=d*.1,l(`Estimated last response time from position difference: ${u.toFixed(2)}s (${d} messages)`)):g>0&&(u=g/1e3,l(`Last response time from timestamps: ${u.toFixed(2)}s`)),l(`Last user message at index ${s}, timestamp ${i.toISOString()}`),l(`Last response end at index ${c}, timestamp ${o.toISOString()}`);}if(a.length===0&&u===null)return {average:null,last:null};let f=a.length>0?a.reduce((g,d)=>g+d,0)/a.length:null;return l(`Calculated average response time: ${f?.toFixed(2)||"null"}s from ${a.length} measurements`),l(`Last response time: ${u?.toFixed(2)||"null"}s`),{average:f,last:u}}calculateSessionDuration(e){let t=[];for(let o of e)if(o.timestamp)try{t.push(new Date(o.timestamp));}catch{continue}if(t.length<2)return null;t.sort((o,c)=>o.getTime()-c.getTime());let n=t[t.length-1],s=t[0];if(!n||!s)return null;let i=(n.getTime()-s.getTime())/1e3;return i>0?i:null}calculateBurnRateDuration(e){if(e.length===0)return null;let t=new Date,n=e.map(o=>o.timestamp).filter(Boolean).map(o=>new Date(o)).filter(o=>t.getTime()-o.getTime()<7200*1e3).sort((o,c)=>o.getTime()-c.getTime());if(n.length===0)return null;let s=n[0];return s?Math.max((t.getTime()-s.getTime())/1e3,1800):null}calculateMessageCount(e){return e.filter(t=>{let n=t.type||t.message?.role||t.message?.type,s=t.type==="user"&&t.message?.content?.[0]?.type==="tool_result";return n==="user"&&!s}).length}async calculateTotalCost(e){let t=0,n=new Set;for(let s of e){let i=`${s.timestamp}-${JSON.stringify(s.message?.usage||{})}`;if(n.has(i)){l(`Skipping duplicate entry at ${s.timestamp}`);continue}if(n.add(i),typeof s.costUSD=="number")t+=s.costUSD;else if(s.message?.usage){let o=await S.calculateCostForEntry(s);t+=o;}}return Math.round(t*1e4)/1e4}calculateTotalTokens(e){let t=new Set;return e.reduce((n,s)=>{let i=s.message?.usage;if(!i)return n;let o=`${s.timestamp}-${JSON.stringify(i)}`;return t.has(o)?(l(`Skipping duplicate token entry at ${s.timestamp}`),n):(t.add(o),n+(i.input_tokens||0)+(i.output_tokens||0)+(i.cache_creation_input_tokens||0)+(i.cache_read_input_tokens||0))},0)}async getMetricsInfo(e){try{l(`Starting metrics calculation for session: ${e}`);let t=await this.loadTranscriptEntries(e);if(t.length===0)return {responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,costBurnRate:null,tokenBurnRate:null};let n=this.calculateResponseTimes(t),s=this.calculateSessionDuration(t),i=this.calculateMessageCount(t),o=null,c=null,a=this.calculateBurnRateDuration(t);if(a&&a>60){let u=a/3600;if(u<=0)l(`Invalid hours elapsed: ${u}`);else {let f=await this.calculateTotalCost(t),g=this.calculateTotalTokens(t);f>0&&(o=Math.round(f/u*100)/100,l(`Cost burn rate: $${o}/h (total: $${f}, duration: ${u}h)`)),g>0&&(c=Math.round(g/u),l(`Token burn rate: ${c}/h (total: ${g}, duration: ${u}h)`));}}return l(`Metrics calculated: avgResponseTime=${n.average?.toFixed(2)||"null"}s, lastResponseTime=${n.last?.toFixed(2)||"null"}s, sessionDuration=${s?.toFixed(0)||"null"}s, messageCount=${i}`),{responseTime:n.average,lastResponseTime:n.last,sessionDuration:s,messageCount:i,costBurnRate:o,tokenBurnRate:c}}catch(t){return l(`Error calculating metrics for session ${e}:`,t),{responseTime:null,lastResponseTime:null,sessionDuration:null,messageCount:null,costBurnRate:null,tokenBurnRate:null}}}};var O=class{cachedVersion=null;cacheTimestamp=0;CACHE_TTL=3e4;getClaudeVersion(){let e=Date.now();if(this.cachedVersion!==null&&e-this.cacheTimestamp<this.CACHE_TTL)return this.cachedVersion;try{let t=execSync("claude --version",{encoding:"utf8",timeout:1e3}).trim(),n=t.match(/^([\d.]+)/);return n?(this.cachedVersion=`v${n[1]}`,this.cacheTimestamp=e,l(`Claude Code version: ${this.cachedVersion}`),this.cachedVersion):(l(`Could not parse version from: ${t}`),null)}catch(t){return l("Error getting Claude Code version:",t),null}}async getVersionInfo(){return {version:this.getClaudeVersion()}}};function $(r){return r===null?"$0.00":r<.01?"<$0.01":`$${r.toFixed(2)}`}function _(r){return r===null||r===0?"0 tokens":r>=1e6?`${(r/1e6).toFixed(1)}M tokens`:r>=1e3?`${(r/1e3).toFixed(1)}K tokens`:`${r} tokens`}function he(r){if(!r)return "0 tokens";let e=[];if(r.input>0&&e.push(`${_(r.input).replace(" tokens","")}in`),r.output>0&&e.push(`${_(r.output).replace(" tokens","")}out`),r.cacheCreation>0||r.cacheRead>0){let t=r.cacheCreation+r.cacheRead;e.push(`${_(t).replace(" tokens","")}cached`);}return e.length>0?e.join(" + "):"0 tokens"}function Fe(r,e){return !e||e<=0||r<0?null:Math.min(100,r/e*100)}function ye(r,e,t=80){let n=Fe(r,e);if(n===null)return {percentage:null,isWarning:false,displayText:""};let s=`${n.toFixed(0)}%`,i=n>=t,o="";return i?o=` !${s}`:n>=50?o=` +${s}`:o=` ${s}`,{percentage:n,isWarning:i,displayText:o}}var A=class{constructor(e,t){this.config=e;this.symbols=t;}renderDirectory(e,t,n){let s=e.workspace?.current_dir||e.cwd||"/",i=e.workspace?.project_dir;if(n?.showBasename)return {text:T.basename(s)||"root",bgColor:t.modeBg,fgColor:t.modeFg};let o=process.env.HOME||process.env.USERPROFILE,c=s,a=i;return o&&(s.startsWith(o)&&(c=s.replace(o,"~")),i&&i.startsWith(o)&&(a=i.replace(o,"~"))),{text:this.getDisplayDirectoryName(c,a),bgColor:t.modeBg,fgColor:t.modeFg}}renderGit(e,t,n){if(!e)return null;let s=[];if(n?.showRepoName&&e.repoName&&(s.push(e.repoName),e.isWorktree&&s.push(this.symbols.git_worktree)),n?.showOperation&&e.operation&&s.push(`[${e.operation}]`),s.push(`${this.symbols.branch} ${e.branch}`),n?.showTag&&e.tag&&s.push(`${this.symbols.git_tag} ${e.tag}`),n?.showSha&&e.sha&&s.push(`${this.symbols.git_sha} ${e.sha}`),n?.showAheadBehind!==false&&(e.ahead>0&&e.behind>0?s.push(`${this.symbols.git_ahead}${e.ahead}${this.symbols.git_behind}${e.behind}`):e.ahead>0?s.push(`${this.symbols.git_ahead}${e.ahead}`):e.behind>0&&s.push(`${this.symbols.git_behind}${e.behind}`)),n?.showWorkingTree){let o=[];e.staged&&e.staged>0&&o.push(`+${e.staged}`),e.unstaged&&e.unstaged>0&&o.push(`~${e.unstaged}`),e.untracked&&e.untracked>0&&o.push(`?${e.untracked}`),e.conflicts&&e.conflicts>0&&o.push(`!${e.conflicts}`),o.length>0&&s.push(`(${o.join(" ")})`);}if(n?.showUpstream&&e.upstream&&s.push(`${this.symbols.git_upstream}${e.upstream}`),n?.showStashCount&&e.stashCount&&e.stashCount>0&&s.push(`${this.symbols.git_stash} ${e.stashCount}`),n?.showTimeSinceCommit&&e.timeSinceCommit!==void 0){let o=this.formatTimeSince(e.timeSinceCommit);s.push(`${this.symbols.git_time} ${o}`);}let i=this.symbols.git_clean;return e.status==="conflicts"?i=this.symbols.git_conflicts:e.status==="dirty"&&(i=this.symbols.git_dirty),s.push(i),{text:s.join(" "),bgColor:t.gitBg,fgColor:t.gitFg}}formatTimeSince(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:e<604800?`${Math.floor(e/86400)}d`:`${Math.floor(e/604800)}w`}renderModel(e,t){let n=e.model?.display_name||"Claude";return {text:`${this.symbols.model} ${n}`,bgColor:t.modelBg,fgColor:t.modelFg}}renderSession(e,t,n="cost"){let s=this.config.budget?.session;return {text:`${this.symbols.session_cost} ${this.formatUsageWithBudget(e.session.cost,e.session.tokens,e.session.tokenBreakdown,n,s?.amount,s?.warningThreshold||80)}`,bgColor:t.sessionBg,fgColor:t.sessionFg}}renderTmux(e,t){return e?{text:`tmux:${e}`,bgColor:t.tmuxBg,fgColor:t.tmuxFg}:{text:"tmux:none",bgColor:t.tmuxBg,fgColor:t.tmuxFg}}renderContext(e,t){if(!e)return {text:`${this.symbols.context_time} 0 (100%)`,bgColor:t.contextBg,fgColor:t.contextFg};let n=e.inputTokens.toLocaleString(),s=`${e.contextLeftPercentage}%`;return {text:`${this.symbols.context_time} ${n} (${s})`,bgColor:t.contextBg,fgColor:t.contextFg}}renderMetrics(e,t,n,s){if(!e)return {text:`${this.symbols.metrics_response} new`,bgColor:t.metricsBg,fgColor:t.metricsFg};let i=[];if(s?.showLastResponseTime){let o=e.lastResponseTime===null?"0.0s":e.lastResponseTime<60?`${e.lastResponseTime.toFixed(1)}s`:`${(e.lastResponseTime/60).toFixed(1)}m`;i.push(`${this.symbols.metrics_last_response} ${o}`);}if(s?.showResponseTime!==false&&e.responseTime!==null){let o=e.responseTime<60?`${e.responseTime.toFixed(1)}s`:`${(e.responseTime/60).toFixed(1)}m`;i.push(`${this.symbols.metrics_response} ${o}`);}if(s?.showDuration!==false&&e.sessionDuration!==null){let o=this.formatDuration(e.sessionDuration);i.push(`${this.symbols.metrics_duration} ${o}`);}return s?.showMessageCount!==false&&e.messageCount!==null&&i.push(`${this.symbols.metrics_messages} ${e.messageCount}`),i.length===0?{text:`${this.symbols.metrics_response} active`,bgColor:t.metricsBg,fgColor:t.metricsFg}:{text:i.join(" "),bgColor:t.metricsBg,fgColor:t.metricsFg}}renderBlock(e,t,n){let s;if(e.cost===null&&e.tokens===null)s="No active block";else {let i=n?.type||"cost",o=n?.burnType,c=e.timeRemaining!==null?(()=>{let f=Math.floor(e.timeRemaining/60),g=e.timeRemaining%60;return f>0?`${f}h ${g}m`:`${g}m`})():null,a;switch(i){case "cost":a=$(e.cost);break;case "tokens":a=_(e.tokens);break;case "both":a=`${$(e.cost)} / ${_(e.tokens)}`;break;case "time":a=c||"N/A";break;default:a=$(e.cost);}let u="";if(o&&o!=="none")switch(o){case "cost":u=` | ${e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A"}`;break;case "tokens":u=` | ${e.tokenBurnRate!==null?`${_(Math.round(e.tokenBurnRate))}/h`:"N/A"}`;break;case "both":let d=e.burnRate!==null?e.burnRate<1?`${(e.burnRate*100).toFixed(0)}\xA2/h`:`$${e.burnRate.toFixed(2)}/h`:"N/A",m=e.tokenBurnRate!==null?`${_(Math.round(e.tokenBurnRate))}/h`:"N/A";u=` | ${d} / ${m}`;break}i==="time"?s=a:s=c?`${a}${u} (${c} left)`:`${a}${u}`;}return {text:`${this.symbols.block_cost} ${s}`,bgColor:t.blockBg,fgColor:t.blockFg}}renderToday(e,t,n="cost"){let s=this.config.budget?.today;return {text:`${this.symbols.today_cost} ${this.formatUsageWithBudget(e.cost,e.tokens,e.tokenBreakdown,n,s?.amount,s?.warningThreshold)}`,bgColor:t.todayBg,fgColor:t.todayFg}}formatDuration(e){return e<60?`${e.toFixed(0)}s`:e<3600?`${(e/60).toFixed(0)}m`:e<86400?`${(e/3600).toFixed(1)}h`:`${(e/86400).toFixed(1)}d`}getDisplayDirectoryName(e,t){return e.startsWith("~")?e:t&&t!==e?e.startsWith(t)?e.slice(t.length+1)||T.basename(t)||"project":T.basename(e)||"root":T.basename(e)||"root"}formatUsageDisplay(e,t,n,s){switch(s){case "cost":return $(e);case "tokens":return _(t);case "both":return `${$(e)} (${_(t)})`;case "breakdown":return he(n);default:return $(e)}}formatUsageWithBudget(e,t,n,s,i,o=80){let c=this.formatUsageDisplay(e,t,n,s);if(i&&i>0&&e!==null){let a=ye(e,i,o);return c+a.displayText}return c}renderVersion(e,t,n){return !e||!e.version?null:{text:`${this.symbols.version} ${e.version}`,bgColor:t.versionBg,fgColor:t.versionFg}}};function Me(r){return {timestamp:r.timestamp,usage:{inputTokens:r.message?.usage?.input_tokens||0,outputTokens:r.message?.usage?.output_tokens||0,cacheCreationInputTokens:r.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:r.message?.usage?.cache_read_input_tokens||0},costUSD:r.costUSD||0,model:r.message?.model||"unknown"}}var Y=class{sessionDurationHours=5;floorToHour(e){let t=new Date(e);return t.setUTCMinutes(0,0,0),t}identifySessionBlocks(e){if(e.length===0)return [];let t=this.sessionDurationHours*60*60*1e3,n=[],s=[...e].sort((c,a)=>c.timestamp.getTime()-a.timestamp.getTime()),i=null,o=[];for(let c of s){let a=c.timestamp;if(i==null)i=this.floorToHour(a),o=[c];else {let u=a.getTime()-i.getTime(),f=o[o.length-1];if(f==null)continue;let g=f.timestamp,d=a.getTime()-g.getTime();u>t||d>t?(n.push(o),i=this.floorToHour(a),o=[c]):o.push(c);}}return i!=null&&o.length>0&&n.push(o),n}createBlockInfo(e,t){let n=new Date,s=this.sessionDurationHours*60*60*1e3,i=new Date(e.getTime()+s),o=t[t.length-1],c=o!=null?o.timestamp:e,a=n.getTime()-c.getTime()<s&&n<i;return {block:t,isActive:a}}findActiveBlock(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.length===0)continue;let s=n[0];if(!s)continue;let i=this.floorToHour(s.timestamp),o=this.createBlockInfo(i,n);if(o.isActive)return o.block}return null}async loadUsageEntries(){l("Block segment: Loading entries for dynamic session blocks");let e=new Date;e.setDate(e.getDate()-1);let n=await J(void 0,(c,a)=>a>=e,true),s=[];for(let c of n)if(c.message?.usage){let a=Me(c);!a.costUSD&&c.raw&&(a.costUSD=await S.calculateCostForEntry(c.raw)),s.push(a);}let i=this.identifySessionBlocks(s);l(`Block segment: Found ${i.length} session blocks`);let o=this.findActiveBlock(i);if(o&&o.length>0){l(`Block segment: Found active block with ${o.length} entries`);let c=o[0],a=o[o.length-1];return c&&a&&l(`Block segment: Active block from ${c.timestamp.toISOString()} to ${a.timestamp.toISOString()}`),o}else return l("Block segment: No active block found"),[]}async getActiveBlockInfo(){try{let e=await this.loadUsageEntries();if(e.length===0)return l("Block segment: No entries in current block"),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null};let t=e.reduce((a,u)=>a+u.costUSD,0),n=e.reduce((a,u)=>a+u.usage.inputTokens+u.usage.outputTokens+u.usage.cacheCreationInputTokens+u.usage.cacheReadInputTokens,0),s=new Date,i=null;if(e.length>0){let a=e[0];if(a){let u=this.sessionDurationHours*60*60*1e3,f=this.floorToHour(a.timestamp),g=new Date(f.getTime()+u);i=Math.max(0,Math.round((g.getTime()-s.getTime())/(1e3*60)));}}let o=null,c=null;if(e.length>=1&&(t>0||n>0)){let a=e.map(g=>g.timestamp).sort((g,d)=>g.getTime()-d.getTime()),u=a[0],f=a[a.length-1];if(u&&f){let g=(f.getTime()-u.getTime())/6e4;g>0&&(t>0&&(o=t/g*60),n>0&&(c=n/g*60));}}return l(`Block segment: $${t.toFixed(2)}, ${n} tokens, ${i}m remaining, burn rate: ${o?"$"+o.toFixed(2)+"/hr":"N/A"}`),{cost:t,tokens:n,timeRemaining:i,burnRate:o,tokenBurnRate:c}}catch(e){return l("Error getting active block info:",e),{cost:null,tokens:null,timeRemaining:null,burnRate:null,tokenBurnRate:null}}}};function N(r){let e=r.getFullYear(),t=String(r.getMonth()+1).padStart(2,"0"),n=String(r.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}function Ie(r){return r.inputTokens+r.outputTokens+r.cacheCreationInputTokens+r.cacheReadInputTokens}function Le(r){return {timestamp:r.timestamp,usage:{inputTokens:r.message?.usage?.input_tokens||0,outputTokens:r.message?.usage?.output_tokens||0,cacheCreationInputTokens:r.message?.usage?.cache_creation_input_tokens||0,cacheReadInputTokens:r.message?.usage?.cache_read_input_tokens||0},costUSD:r.costUSD||0,model:r.message?.model||"unknown"}}var z=class{cache=new Map;CACHE_TTL=3e5;async loadTodayEntries(){let t=N(new Date);l(`Today segment: Loading entries for date ${t}`);let n=new Date;n.setDate(n.getDate()-7);let i=await J(void 0,(a,u)=>u>=n,true),o=[],c=0;for(let a of i)if(N(a.timestamp)===t&&a.message?.usage){let f=Le(a);!f.costUSD&&a.raw&&(f.costUSD=await S.calculateCostForEntry(a.raw)),o.push(f),c++;}return l(`Today segment: Found ${c} entries for today (${t})`),o}async getTodayEntries(){let e="today",t=this.cache.get(e),n=Date.now();if(t&&n-t.timestamp<this.CACHE_TTL)return t.data;this.cache.clear();try{let s=await this.loadTodayEntries();return this.cache.set(e,{data:s,timestamp:n}),s}catch(s){return l("Error loading today's entries:",s),[]}}async getTodayInfo(){try{let e=await this.getTodayEntries();if(e.length===0)return {cost:null,tokens:null,tokenBreakdown:null,date:N(new Date)};let t=e.reduce((i,o)=>i+o.costUSD,0),n=e.reduce((i,o)=>i+Ie(o.usage),0),s=e.reduce((i,o)=>({input:i.input+o.usage.inputTokens,output:i.output+o.usage.outputTokens,cacheCreation:i.cacheCreation+o.usage.cacheCreationInputTokens,cacheRead:i.cacheRead+o.usage.cacheReadInputTokens}),{input:0,output:0,cacheCreation:0,cacheRead:0});return l(`Today segment: $${t.toFixed(2)}, ${n} tokens total`),{cost:t,tokens:n,tokenBreakdown:s,date:N(new Date)}}catch(e){return l("Error getting today's info:",e),{cost:null,tokens:null,tokenBreakdown:null,date:N(new Date)}}}};var X=class{constructor(e){this.config=e;this.symbols=this.initializeSymbols(),this.usageProvider=new I,this.blockProvider=new Y,this.todayProvider=new z,this.contextProvider=new L,this.gitService=new U,this.tmuxService=new F,this.metricsProvider=new j,this.versionProvider=new O,this.segmentRenderer=new A(e,this.symbols);}symbols;usageProvider;blockProvider;todayProvider;contextProvider;gitService;tmuxService;metricsProvider;versionProvider;segmentRenderer;needsUsageInfo(){return this.config.display.lines.some(e=>e.segments.session?.enabled)}needsGitInfo(){return this.config.display.lines.some(e=>e.segments.git?.enabled)}needsTmuxInfo(){return this.config.display.lines.some(e=>e.segments.tmux?.enabled)}needsContextInfo(){return this.config.display.lines.some(e=>e.segments.context?.enabled)}needsMetricsInfo(){return this.config.display.lines.some(e=>e.segments.metrics?.enabled)}needsBlockInfo(){return this.config.display.lines.some(e=>e.segments.block?.enabled)}needsTodayInfo(){return this.config.display.lines.some(e=>e.segments.today?.enabled)}needsVersionInfo(){return this.config.display.lines.some(e=>e.segments.version?.enabled)}async generateStatusline(e){let t=this.needsUsageInfo()?await this.usageProvider.getUsageInfo(e.session_id):null,n=this.needsBlockInfo()?await this.blockProvider.getActiveBlockInfo():null,s=this.needsTodayInfo()?await this.todayProvider.getTodayInfo():null,i=this.needsContextInfo()?await this.contextProvider.calculateContextTokens(e.transcript_path,e.model?.id):null,o=this.needsMetricsInfo()?await this.metricsProvider.getMetricsInfo(e.session_id):null,c=this.needsVersionInfo()?await this.versionProvider.getVersionInfo():null;return this.config.display.lines.map(u=>this.renderLine(u,e,t,n,s,i,o,c)).filter(u=>u.length>0).join(`
|
|
8
|
+
`)}renderLine(e,t,n,s,i,o,c,a){let u=this.getThemeColors(),f=t.workspace?.current_dir||t.cwd||"/",g=Object.entries(e.segments).filter(([m,p])=>p?.enabled).map(([m,p])=>({type:m,config:p})),d=u.reset;for(let m=0;m<g.length;m++){let p=g[m];if(!p)continue;let w=m===g.length-1,D=w?null:g[m+1],G=D?this.getSegmentBgColor(D.type,u):"",P=this.renderSegment(p,t,n,s,i,o,c,a,u,f);P&&(d+=this.formatSegment(P.bgColor,P.fgColor,P.text,w?void 0:G));}return d}renderSegment(e,t,n,s,i,o,c,a,u,f){switch(e.type){case "directory":return this.segmentRenderer.renderDirectory(t,u,e.config);case "git":if(!this.needsGitInfo())return null;let g=e.config,d=this.gitService.getGitInfo(f,{showSha:g?.showSha,showWorkingTree:g?.showWorkingTree,showOperation:g?.showOperation,showTag:g?.showTag,showTimeSinceCommit:g?.showTimeSinceCommit,showStashCount:g?.showStashCount,showUpstream:g?.showUpstream,showRepoName:g?.showRepoName},t.workspace?.project_dir);return d?this.segmentRenderer.renderGit(d,u,g):null;case "model":return this.segmentRenderer.renderModel(t,u);case "session":if(!n)return null;let m=e.config?.type||"cost";return this.segmentRenderer.renderSession(n,u,m);case "tmux":if(!this.needsTmuxInfo())return null;let p=this.tmuxService.getSessionId();return this.segmentRenderer.renderTmux(p,u);case "context":return this.needsContextInfo()?this.segmentRenderer.renderContext(o,u):null;case "metrics":let w=e.config;return this.segmentRenderer.renderMetrics(c,u,s,w);case "block":if(!s)return null;let D=e.config;return this.segmentRenderer.renderBlock(s,u,D);case "today":if(!i)return null;let G=e.config?.type||"cost";return this.segmentRenderer.renderToday(i,u,G);case "version":if(!a)return null;let P=e.config;return this.segmentRenderer.renderVersion(a,u,P);default:return null}}initializeSymbols(){return {right:this.config.display.style==="minimal"?"":"\uE0B0",branch:"\u2387",model:"\u26A1",git_clean:"\u2713",git_dirty:"\u25CF",git_conflicts:"\u26A0",git_ahead:"\u2191",git_behind:"\u2193",git_worktree:"\u29C9",git_tag:"\u2302",git_sha:"\u266F",git_upstream:"\u2192",git_stash:"\u29C7",git_time:"\u25F7",session_cost:"\xA7",block_cost:"\u25F1",today_cost:"\u2609",context_time:"\u25D4",metrics_response:"\u29D6",metrics_last_response:"\u0394",metrics_duration:"\u29D7",metrics_messages:"\u27D0",metrics_burn:"\u27E2",version:"\u25C8"}}getThemeColors(){let e=this.config.theme,t;if(e==="custom"){if(t=this.config.colors?.custom,!t)throw new Error("Custom theme selected but no colors provided in configuration")}else t=V(e),t||(console.warn(`Built-in theme '${e}' not found, falling back to 'dark' theme`),t=V("dark"));let n=V("dark");return {reset:"\x1B[0m",modeBg:b(t.directory?.bg||n.directory.bg,true),modeFg:b(t.directory?.fg||n.directory.fg,false),gitBg:b(t.git?.bg||n.git.bg,true),gitFg:b(t.git?.fg||n.git.fg,false),modelBg:b(t.model?.bg||n.model.bg,true),modelFg:b(t.model?.fg||n.model.fg,false),sessionBg:b(t.session?.bg||n.session.bg,true),sessionFg:b(t.session?.fg||n.session.fg,false),blockBg:b(t.block?.bg||n.block.bg,true),blockFg:b(t.block?.fg||n.block.fg,false),todayBg:b(t.today?.bg||n.today.bg,true),todayFg:b(t.today?.fg||n.today.fg,false),tmuxBg:b(t.tmux?.bg||n.tmux.bg,true),tmuxFg:b(t.tmux?.fg||n.tmux.fg,false),contextBg:b(t.context?.bg||n.context.bg,true),contextFg:b(t.context?.fg||n.context.fg,false),metricsBg:b(t.metrics?.bg||n.metrics.bg,true),metricsFg:b(t.metrics?.fg||n.metrics.fg,false),versionBg:b(t.version?.bg||n.version.bg,true),versionFg:b(t.version?.fg||n.version.fg,false)}}getSegmentBgColor(e,t){switch(e){case "directory":return t.modeBg;case "git":return t.gitBg;case "model":return t.modelBg;case "session":return t.sessionBg;case "block":return t.blockBg;case "today":return t.todayBg;case "tmux":return t.tmuxBg;case "context":return t.contextBg;case "metrics":return t.metricsBg;case "version":return t.versionBg;default:return t.modeBg}}formatSegment(e,t,n,s){let i=`${e}${t} ${n} `,o="\x1B[0m";if(s){let c=ee(e);i+=`${o}${s}${c}${this.symbols.right}`;}else i+=`${o}${ee(e)}${this.symbols.right}${o}`;return i}};var be={theme:"dark",display:{style:"minimal",lines:[{segments:{directory:{enabled:true,showBasename:true},git:{enabled:true,showSha:false,showWorkingTree:false,showOperation:false,showTag:false,showTimeSinceCommit:false,showStashCount:false,showUpstream:false,showRepoName:false},model:{enabled:true},session:{enabled:true,type:"tokens"},today:{enabled:false,type:"cost"},block:{enabled:true,type:"cost",burnType:"cost"},version:{enabled:false},tmux:{enabled:false},context:{enabled:true},metrics:{enabled:false,showResponseTime:true,showLastResponseTime:false,showDuration:true,showMessageCount:true}}}]},budget:{session:{warningThreshold:80},today:{warningThreshold:80,amount:50}}};function oe(r){return ["light","dark","nord","tokyo-night","rose-pine","custom"].includes(r)}function re(r){return r==="minimal"||r==="powerline"}function Z(r,e){let t={...r};for(let n in e){let s=e[n];if(s!==void 0)if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let i=t[n]||{};t[n]=Z(i,s);}else t[n]=s;}return t}function je(r,e){return r?x.existsSync(r)?r:null:[...e?[T.join(e,".claude-powerline.json")]:[],T.join(process.cwd(),".claude-powerline.json"),T.join(B.homedir(),".claude","claude-powerline.json"),T.join(B.homedir(),".config","claude-powerline","config.json")].find(x.existsSync)||null}function Oe(r){try{let e=x.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){throw new Error(`Failed to load config file ${r}: ${e instanceof Error?e.message:String(e)}`)}}function Ae(){let r={},e={},t=process.env.CLAUDE_POWERLINE_THEME;t&&oe(t)&&(r.theme=t);let n=process.env.CLAUDE_POWERLINE_STYLE;return n&&(re(n)?e.style=n:(console.warn(`Invalid display style '${n}' from environment variable, falling back to 'minimal'`),e.style="minimal")),Object.keys(e).length>0&&(r.display=e),r}function Ne(){return process.env.CLAUDE_POWERLINE_CONFIG}function He(r){let e={},t={},n=r.find(i=>i.startsWith("--theme="))?.split("=")[1];n&&oe(n)&&(e.theme=n);let s=r.find(i=>i.startsWith("--style="))?.split("=")[1];return s&&(re(s)?t.style=s:(console.warn(`Invalid display style '${s}' from CLI argument, falling back to 'minimal'`),t.style="minimal")),Object.keys(t).length>0&&(e.display=t),e}function Ge(r=process.argv,e){let t=JSON.parse(JSON.stringify(be)),n=r.find(c=>c.startsWith("--config="))?.split("=")[1]||Ne(),s=je(n,e);if(s)try{let c=Oe(s);t=Z(t,c);}catch(c){console.warn(`Warning: ${c instanceof Error?c.message:String(c)}`);}t.display?.style&&!re(t.display.style)&&(console.warn(`Invalid display style '${t.display.style}' in config file, falling back to 'minimal'`),t.display.style="minimal"),t.theme&&!oe(t.theme)&&(console.warn(`Invalid theme '${t.theme}' in config file, falling back to 'dark'`),t.theme="dark");let i=Ae();t=Z(t,i);let o=He(r);return t=Z(t,o),t}var we=Ge;async function We(){try{let r=B.platform(),e;if(r==="darwin")e=T.join(B.homedir(),"Library","Fonts");else if(r==="linux")e=T.join(B.homedir(),".local","share","fonts");else if(r==="win32")e=T.join(B.homedir(),"AppData","Local","Microsoft","Windows","Fonts");else {console.log("Unsupported platform for font installation");return}x.existsSync(e)||x.mkdirSync(e,{recursive:!0}),console.log("\u{1F4E6} Installing Powerline Fonts..."),console.log("Downloading from https://github.com/powerline/fonts");let t=T.join(B.tmpdir(),"powerline-fonts"),n=()=>{x.existsSync(t)&&x.rmSync(t,{recursive:!0,force:!0});};C.on("SIGINT",n),C.on("SIGTERM",n);try{x.existsSync(t)&&x.rmSync(t,{recursive:!0,force:!0}),console.log("Cloning powerline fonts repository..."),execSync("git clone --depth=1 https://github.com/powerline/fonts.git powerline-fonts",{stdio:"inherit",cwd:B.tmpdir()}),console.log("Installing fonts...");let s=T.join(t,"install.sh");if(x.existsSync(s))x.chmodSync(s,493),execSync("./install.sh",{stdio:"inherit",cwd:t});else throw new Error("Install script not found in powerline fonts repository");console.log("\u2705 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(),C.removeListener("SIGINT",n),C.removeListener("SIGTERM",n);}}catch(r){console.error("Error installing fonts:",r instanceof Error?r.message:String(r)),console.log("\u{1F4A1} You can manually install fonts from: https://github.com/powerline/fonts");}}async function Je(){try{let r=C.argv.includes("--help")||C.argv.includes("-h");C.argv.includes("--install-fonts")&&(await We(),C.exit(0)),r&&(console.log(`
|
|
2794
9
|
claude-powerline - Beautiful powerline statusline for Claude Code
|
|
2795
10
|
|
|
2796
11
|
Usage: claude-powerline [options]
|
|
@@ -2809,11 +24,7 @@ Claude Code Options (for settings.json):
|
|
|
2809
24
|
|
|
2810
25
|
See example config at: https://github.com/Owloops/claude-powerline/blob/main/.claude-powerline.json
|
|
2811
26
|
|
|
2812
|
-
`)
|
|
2813
|
-
process2.exit(0);
|
|
2814
|
-
}
|
|
2815
|
-
if (process2.stdin.isTTY === true) {
|
|
2816
|
-
console.error(`Error: This tool requires input from Claude Code
|
|
27
|
+
`),C.exit(0)),C.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
2817
28
|
|
|
2818
29
|
claude-powerline is designed to be used as a Claude Code statusLine command.
|
|
2819
30
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -2829,16 +40,7 @@ Add to ~/.claude/settings.json:
|
|
|
2829
40
|
Run with --help for more options.
|
|
2830
41
|
|
|
2831
42
|
To test output manually:
|
|
2832
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-3-5-sonnet","display_name":"Claude"}}' | claude-powerline --style=powerline`);
|
|
2833
|
-
process2.exit(1);
|
|
2834
|
-
}
|
|
2835
|
-
debug(`Working directory: ${process2.cwd()}`);
|
|
2836
|
-
debug(`Process args:`, process2.argv);
|
|
2837
|
-
const hookData = await json(process2.stdin);
|
|
2838
|
-
debug(`Received hook data:`, JSON.stringify(hookData, null, 2));
|
|
2839
|
-
if (!hookData) {
|
|
2840
|
-
console.error("Error: No input data received from stdin");
|
|
2841
|
-
console.log(`
|
|
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`),C.exit(1)),l(`Working directory: ${C.cwd()}`),l("Process args:",C.argv);let t=await json(C.stdin);l("Received hook data:",JSON.stringify(t,null,2)),t||(console.error("Error: No input data received from stdin"),console.log(`
|
|
2842
44
|
claude-powerline - Beautiful powerline statusline for Claude Code
|
|
2843
45
|
|
|
2844
46
|
Usage: claude-powerline [options]
|
|
@@ -2851,19 +53,5 @@ Options:
|
|
|
2851
53
|
-h, --help Show this help
|
|
2852
54
|
|
|
2853
55
|
See example config at: https://github.com/Owloops/claude-powerline/blob/main/.claude-powerline.json
|
|
2854
|
-
`);
|
|
2855
|
-
process2.exit(1);
|
|
2856
|
-
}
|
|
2857
|
-
const projectDir = hookData.workspace?.project_dir;
|
|
2858
|
-
const config = loadConfigFromCLI(process2.argv, projectDir);
|
|
2859
|
-
const renderer = new PowerlineRenderer(config);
|
|
2860
|
-
const statusline = await renderer.generateStatusline(hookData);
|
|
2861
|
-
console.log(statusline);
|
|
2862
|
-
} catch (error) {
|
|
2863
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2864
|
-
console.error("Error generating statusline:", errorMessage);
|
|
2865
|
-
process2.exit(1);
|
|
2866
|
-
}
|
|
2867
|
-
}
|
|
2868
|
-
main();
|
|
56
|
+
`),C.exit(1));let n=t.workspace?.project_dir,s=we(C.argv,n),o=await new X(s).generateStatusline(t);console.log(o);}catch(r){let e=r instanceof Error?r.message:String(r);console.error("Error generating statusline:",e),C.exit(1);}}Je();//# sourceMappingURL=index.js.map
|
|
2869
57
|
//# sourceMappingURL=index.js.map
|