@v1nvn/zai 0.43.0 → 0.45.0

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/src/format.ts ADDED
@@ -0,0 +1,656 @@
1
+ /**
2
+ * Usage-report line model: `reportLines` lays the report out once as ink-tagged
3
+ * segments (the pane draws those), and `render` joins them into the CLI's
4
+ * monospace terminal / hook-block `reason` bytes — no markdown; alignment comes
5
+ * from fixed-width columns and unicode block glyphs. Input is the parsed `data`
6
+ * of the three ZAI/ZHIPU monitor endpoints (model-usage, tool-usage,
7
+ * quota/limit — the last already passed through processQuotaLimit).
8
+ */
9
+
10
+ import {
11
+ bar,
12
+ bold,
13
+ dim,
14
+ doc,
15
+ fmtNum,
16
+ fmtTokens,
17
+ line,
18
+ meter,
19
+ MONTHS,
20
+ pad,
21
+ pad2,
22
+ plain,
23
+ rule,
24
+ RULE_WIDTH,
25
+ textOf,
26
+ } from '@v1nvn/agentic-core/draw';
27
+
28
+ import type { Line } from '@v1nvn/agentic-core/draw';
29
+
30
+ // Lower-half block eighths for vertical bars (1/8 .. 7/8); a full cell uses '█'.
31
+ const VBLOCKS = '▁▂▃▄▅▆▇';
32
+
33
+ export interface ModelMixEntry {
34
+ modelName?: string;
35
+ sortOrder?: number;
36
+ totalTokens?: number;
37
+ }
38
+
39
+ export interface ZaiModelUsage {
40
+ modelCallCount?: number[];
41
+ modelDataList?: ModelMixEntry[];
42
+ modelSummaryList?: ModelMixEntry[];
43
+ tokensUsage?: number[];
44
+ totalUsage?: { totalModelCallCount?: number; totalTokensUsage?: number };
45
+ x_time?: string[];
46
+ }
47
+
48
+ export interface ZaiToolUsage {
49
+ totalUsage?: {
50
+ totalNetworkSearchCount?: number;
51
+ totalSearchMcpCount?: number;
52
+ totalWebReadMcpCount?: number;
53
+ totalZreadMcpCount?: number;
54
+ };
55
+ }
56
+
57
+ export interface ZaiQuotaLimit {
58
+ currentUsage?: number;
59
+ nextResetTime?: string;
60
+ percentage?: number;
61
+ totol?: number;
62
+ type?: string;
63
+ usageDetails?: { modelCode?: string; usage?: number }[];
64
+ }
65
+
66
+ export interface ZaiQuota {
67
+ level?: string;
68
+ limits?: ZaiQuotaLimit[];
69
+ }
70
+
71
+ export interface RenderInput {
72
+ apiOffsetMin?: number;
73
+ localOffsetMin?: number;
74
+ model: ZaiModelUsage;
75
+ now?: Date;
76
+ platform: string;
77
+ quota: ZaiQuota;
78
+ tool: ZaiToolUsage;
79
+ }
80
+
81
+ interface Slot {
82
+ day: string;
83
+ h: number;
84
+ time: string;
85
+ }
86
+
87
+ function parseSlot(s: string | undefined): null | Slot {
88
+ const m = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/.exec(s ?? '');
89
+ if (!m) {
90
+ return null;
91
+ }
92
+ const [, mo, d, hh, mm] = m.slice(1) as [
93
+ string,
94
+ string,
95
+ string,
96
+ string,
97
+ string,
98
+ ];
99
+ return {
100
+ h: +hh,
101
+ day: `${MONTHS[+mo - 1]} ${d}`,
102
+ time: `${hh}:${mm}`,
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Re-express a naive "YYYY-MM-DD HH:MM" string from one UTC offset to another.
108
+ * Offsets are minutes east of UTC (Beijing = 480, IST = 330). Pure — does not
109
+ * depend on the runtime timezone, so it is deterministic under test.
110
+ */
111
+ function shiftSlot(
112
+ s: string,
113
+ fromOffsetMin: number,
114
+ toOffsetMin: number,
115
+ ): null | Slot {
116
+ const m = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/.exec(s);
117
+ if (!m) {
118
+ return null;
119
+ }
120
+ const [y, mo, d, hh, mm] = m.slice(1) as [
121
+ string,
122
+ string,
123
+ string,
124
+ string,
125
+ string,
126
+ ];
127
+ const utcMs = Date.UTC(+y, +mo - 1, +d, +hh, +mm) - fromOffsetMin * 60000;
128
+ const dt = new Date(utcMs + toOffsetMin * 60000);
129
+ return {
130
+ h: dt.getUTCHours(),
131
+ day: `${MONTHS[dt.getUTCMonth()]} ${pad2(dt.getUTCDate())}`,
132
+ time: `${pad2(dt.getUTCHours())}:${pad2(dt.getUTCMinutes())}`,
133
+ };
134
+ }
135
+
136
+ function friendlyTool(code: string | undefined): string {
137
+ switch ((code ?? '').toLowerCase()) {
138
+ case 'search-prime':
139
+ return 'web search';
140
+ case 'web-reader':
141
+ return 'web read';
142
+ default:
143
+ return code || 'other';
144
+ }
145
+ }
146
+
147
+ function idleRuns(tok: number[]): { i: number; j: number; len: number }[] {
148
+ const runs: { i: number; j: number; len: number }[] = [];
149
+ let i = 0;
150
+ while (i < tok.length) {
151
+ if ((tok[i] || 0) === 0) {
152
+ let j = i;
153
+ while (j < tok.length && (tok[j] || 0) === 0) {
154
+ j++;
155
+ }
156
+ runs.push({ i, j: j - 1, len: j - i });
157
+ i = j;
158
+ } else {
159
+ i++;
160
+ }
161
+ }
162
+ return runs;
163
+ }
164
+
165
+ function idleLabel(
166
+ run: { i: number; j: number; len: number },
167
+ x: string[],
168
+ slotFn: (s: string) => null | Slot,
169
+ ): string {
170
+ const a = slotFn(x[run.i] ?? '');
171
+ const b = slotFn(x[run.j] ?? '');
172
+ if (!a || !b) {
173
+ return `idle (${run.len}h)`;
174
+ }
175
+ const start = `${a.day} ${a.time}`;
176
+ const end = a.day === b.day ? b.time : `${b.day} ${b.time}`;
177
+ return `idle ${start} → ${end} (${run.len}h)`;
178
+ }
179
+
180
+ // Per the usage-revision notice: Mon–Fri 14:00–18:00 Beijing (UTC+8) are peak
181
+ // hours, where GLM-5.2 / GLM-5-Turbo tokens are billed at a 3× coefficient
182
+ // (GLM-4.7 stays 1× all day). A bucket labelled "HH:00" spans HH:00–HH+1, so
183
+ // the peak buckets are HH ∈ {14,15,16,17} on a weekday.
184
+ function isPeakBucket(s: string | undefined): boolean {
185
+ const m = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):/.exec(s ?? '');
186
+ if (!m) {
187
+ return false;
188
+ }
189
+ const [y, mo, d, hh] = m.slice(1) as [string, string, string, string];
190
+ const wd = new Date(Date.UTC(+y, +mo - 1, +d)).getUTCDay(); // 0=Sun … 6=Sat
191
+ return wd >= 1 && wd <= 5 && +hh >= 14 && +hh <= 17;
192
+ }
193
+
194
+ /** Local-time start/end of the 14:00–18:00 Beijing peak window (e.g. 11:30 / 15:30). */
195
+ function localPeakWindow(
196
+ apiOffsetMin: number,
197
+ toOffsetMin: number,
198
+ ): null | { end: string; start: string } {
199
+ const a = shiftSlot('2000-01-03 14:00', apiOffsetMin, toOffsetMin);
200
+ const b = shiftSlot('2000-01-03 18:00', apiOffsetMin, toOffsetMin);
201
+ if (!a || !b) {
202
+ return null;
203
+ }
204
+ return { start: a.time, end: b.time };
205
+ }
206
+
207
+ /**
208
+ * Vertical bar chart of hourly tokens. Returns an array of plain-text lines
209
+ * (without the section header), or null if there are fewer than 2 buckets.
210
+ *
211
+ * Bars are scaled to `maxTok` across `ROWS` rows; the topmost filled cell of a
212
+ * bar uses a fractional lower-block glyph (▁▂▃▄▅▆▇) for sub-row height. The
213
+ * y-axis labels only the peak (top) and 0 (baseline); the header window and the
214
+ * caller's peak annotation carry the exact values.
215
+ */
216
+ function hourlyVerticalChart({
217
+ x,
218
+ tok,
219
+ nh,
220
+ maxTok,
221
+ peakIdx,
222
+ slotFn,
223
+ }: {
224
+ maxTok: number;
225
+ nh: number;
226
+ peakIdx: number;
227
+ slotFn: (s: string) => null | Slot;
228
+ tok: number[];
229
+ x: string[];
230
+ }): null | string[] {
231
+ const ROWS = 6; // bar rows above the baseline
232
+ if (nh < 2 || maxTok <= 0) {
233
+ return null;
234
+ }
235
+
236
+ const lines: string[] = [];
237
+ const maxLab = fmtTokens(maxTok);
238
+ const L = maxLab.length;
239
+ const IND = 1; // leading indent
240
+ const AXIS = IND + L + 1; // axis spine col (1-space gap after the label)
241
+ const P0 = AXIS + 2; // first bar column (axis + 1-char gap)
242
+ const PW = RULE_WIDTH - P0; // columns available for bars + gaps
243
+ const slot = Math.max(1, Math.floor(PW / nh));
244
+ const barW = slot >= 2 ? slot - 1 : 1;
245
+ function barLeft(i: number): number {
246
+ return P0 + i * slot;
247
+ }
248
+ function barCenter(i: number): number {
249
+ return barLeft(i) + Math.floor(barW / 2);
250
+ }
251
+ const usedCols = nh * slot;
252
+ function blank(): string[] {
253
+ return Array<string>(RULE_WIDTH).fill(' ');
254
+ }
255
+
256
+ // bar glyph for hour i at row r (0 = bottom bar-row, ROWS-1 = top)
257
+ function glyph(i: number, r: number): string {
258
+ const v = tok[i] || 0;
259
+ if (v <= 0) {
260
+ return ' ';
261
+ }
262
+ const fill = (v / maxTok) * ROWS - r; // how much of row r the bar covers
263
+ if (fill >= 1) {
264
+ return '█';
265
+ }
266
+ if (fill > 0) {
267
+ let e = Math.round(fill * 8); // 1..7 eighths
268
+ if (e < 1) {
269
+ e = 1;
270
+ }
271
+ if (e > 7) {
272
+ e = 7;
273
+ }
274
+ return VBLOCKS[e - 1] ?? ' ';
275
+ }
276
+ return ' ';
277
+ }
278
+
279
+ // bar rows, top → bottom; top row carries the max label + '┤', rest are '│'
280
+ for (let r = ROWS - 1; r >= 0; r--) {
281
+ const line = blank();
282
+ line[AXIS] = r === ROWS - 1 ? '┤' : '│';
283
+ if (r === ROWS - 1) {
284
+ for (let k = 0; k < L; k++) {
285
+ line[AXIS - 1 - L + k] = maxLab[k] ?? ' ';
286
+ }
287
+ }
288
+ for (let i = 0; i < nh; i++) {
289
+ const g = glyph(i, r);
290
+ if (g !== ' ') {
291
+ for (let c = 0; c < barW; c++) {
292
+ line[barLeft(i) + c] = g;
293
+ }
294
+ }
295
+ }
296
+ lines.push(line.join('').trimEnd());
297
+ }
298
+
299
+ // x-axis ticks: first, last, and every bucket landing on a 6h boundary (local)
300
+ function slotOf(i: number): null | Slot {
301
+ return slotFn(x[i] ?? '');
302
+ }
303
+ function isTick(i: number): boolean {
304
+ if (i === 0 || i === nh - 1) {
305
+ return true;
306
+ }
307
+ const s = slotOf(i);
308
+ return !!s && s.h % 6 === 0;
309
+ }
310
+
311
+ // baseline: '0' label + corner '└' + '─' run, with '┬' under each tick
312
+ const base = blank();
313
+ base[AXIS - 2] = '0';
314
+ base[AXIS] = '└';
315
+ for (let c = AXIS + 1; c < P0 + usedCols; c++) {
316
+ base[c] = '─';
317
+ }
318
+ for (let i = 0; i < nh; i++) {
319
+ if (isTick(i)) {
320
+ base[barCenter(i)] = '┬';
321
+ }
322
+ }
323
+ lines.push(base.join('').trimEnd());
324
+
325
+ // hour labels under ticks (skip if too close to the previous label)
326
+ const hr = blank();
327
+ let last = -10;
328
+ for (let i = 0; i < nh; i++) {
329
+ if (!isTick(i)) {
330
+ continue;
331
+ }
332
+ const col = barCenter(i);
333
+ if (col - last < 3) {
334
+ continue;
335
+ }
336
+ const s = slotOf(i);
337
+ const txt = s ? pad2(s.h) : ' ';
338
+ hr[col] = txt.charAt(0);
339
+ hr[col + 1] = txt.charAt(1);
340
+ last = col;
341
+ }
342
+ lines.push(hr.join('').trimEnd());
343
+
344
+ // day labels under the first tick of each new local day
345
+ const day = blank();
346
+ let lastDay: null | string = null;
347
+ last = -10;
348
+ for (let i = 0; i < nh; i++) {
349
+ if (!isTick(i)) {
350
+ continue;
351
+ }
352
+ const s = slotOf(i);
353
+ if (!s || s.day === lastDay) {
354
+ continue;
355
+ }
356
+ const col = barCenter(i);
357
+ if (col - last >= s.day.length && col + s.day.length <= RULE_WIDTH) {
358
+ for (let k = 0; k < s.day.length; k++) {
359
+ day[col + k] = s.day[k] ?? ' ';
360
+ }
361
+ lastDay = s.day;
362
+ last = col + s.day.length;
363
+ }
364
+ }
365
+ if (day.some(c => c !== ' ')) {
366
+ lines.push(day.join('').trimEnd());
367
+ }
368
+
369
+ // peak-window (↑) and peak (◂) markers under bar centers
370
+ const mark = blank();
371
+ for (let i = 0; i < nh; i++) {
372
+ if (isPeakBucket(x[i])) {
373
+ mark[barCenter(i)] = '↑';
374
+ }
375
+ }
376
+ if (peakIdx >= 0) {
377
+ mark[barCenter(peakIdx)] = '◂';
378
+ }
379
+ if (mark.some(c => c !== ' ')) {
380
+ lines.push(mark.join('').trimEnd());
381
+ }
382
+
383
+ return lines;
384
+ }
385
+
386
+ export function reportLines({
387
+ platform,
388
+ model,
389
+ tool,
390
+ quota,
391
+ apiOffsetMin = 480,
392
+ localOffsetMin,
393
+ now = new Date(),
394
+ }: RenderInput): Line[] {
395
+ const out: Line[] = [];
396
+
397
+ // The monitor API labels every bucket in Beijing time (UTC+8). Shift each
398
+ // timestamp to the caller's offset (minutes east of UTC) for display.
399
+ // Defaults to the JS runtime's local zone.
400
+ const toOffset =
401
+ localOffsetMin != null ? localOffsetMin : -new Date().getTimezoneOffset();
402
+ function convertSlot(s: string): null | Slot {
403
+ return shiftSlot(s, apiOffsetMin, toOffset) ?? parseSlot(s);
404
+ }
405
+
406
+ const x = model.x_time ?? [];
407
+ const tok = model.tokensUsage ?? [];
408
+ const calls = model.modelCallCount ?? [];
409
+ const nh = x.length;
410
+
411
+ const tu = model.totalUsage ?? {};
412
+ const total =
413
+ tu.totalTokensUsage != null
414
+ ? tu.totalTokensUsage
415
+ : tok.reduce((a, b) => a + (b || 0), 0);
416
+ const totalCalls =
417
+ tu.totalModelCallCount != null
418
+ ? tu.totalModelCallCount
419
+ : calls.reduce((a, b) => a + (b || 0), 0);
420
+
421
+ let peakIdx = -1;
422
+ let peakTok = 0;
423
+ for (let i = 0; i < tok.length; i++) {
424
+ const t = tok[i] || 0;
425
+ if (t > peakTok) {
426
+ peakTok = t;
427
+ peakIdx = i;
428
+ }
429
+ }
430
+ const peakCalls = peakIdx >= 0 ? calls[peakIdx] || 0 : 0;
431
+ const pctPeak = total > 0 ? (peakTok / total) * 100 : 0;
432
+ const peakSlot = peakIdx >= 0 ? convertSlot(x[peakIdx] ?? '') : null;
433
+
434
+ const level = quota.level
435
+ ? quota.level.charAt(0).toUpperCase() + quota.level.slice(1)
436
+ : '';
437
+
438
+ const left = ` GLM Coding Plan${level ? ' · ' + level : ''}`;
439
+ const firstSlot = convertSlot(x[0] ?? '');
440
+ const lastSlot = convertSlot(x[nh - 1] ?? '');
441
+ const win =
442
+ firstSlot && lastSlot
443
+ ? `${firstSlot.day} ${firstSlot.time} → ${lastSlot.day} ${lastSlot.time} · ${nh}h`
444
+ : platform;
445
+ out.push(line(plain(rule())));
446
+ out.push(line(bold(left), dim(pad(win, RULE_WIDTH - left.length, 'left'))));
447
+ out.push(line(plain(rule())));
448
+
449
+ const head = plain(
450
+ ` ${fmtTokens(total)} tokens across ${fmtNum(totalCalls)} model calls`,
451
+ );
452
+ out.push(line());
453
+ if (peakIdx >= 0 && peakSlot) {
454
+ out.push(line(head, plain(' — ')));
455
+ out.push(
456
+ line(bold(`${Math.round(pctPeak)}%`), plain(' of it in a single hour')),
457
+ );
458
+ out.push(
459
+ line(
460
+ plain(
461
+ ` (${peakSlot.day} ${peakSlot.time}, ${fmtTokens(peakTok)} tokens / ${fmtNum(peakCalls)} calls).`,
462
+ ),
463
+ ),
464
+ );
465
+ } else {
466
+ out.push(line(head, plain('.')));
467
+ }
468
+
469
+ const activeHours = tok.filter(t => t > 0).length;
470
+ const longest = idleRuns(tok)
471
+ .filter(r => r.len >= 2)
472
+ .sort((a, b) => b.len - a.len)
473
+ .at(0);
474
+ const tt = tool.totalUsage ?? {};
475
+ const searchN = tt.totalNetworkSearchCount || 0;
476
+ const readN = tt.totalWebReadMcpCount || 0;
477
+ const zreadN = tt.totalZreadMcpCount || 0;
478
+ const toolTotal =
479
+ tt.totalSearchMcpCount != null
480
+ ? tt.totalSearchMcpCount
481
+ : searchN + readN + zreadN;
482
+
483
+ let peakWinActive = 0;
484
+ let peakWinTokens = 0;
485
+ for (let k = 0; k < nh; k++) {
486
+ if (isPeakBucket(x[k]) && (tok[k] || 0) > 0) {
487
+ peakWinActive++;
488
+ peakWinTokens += tok[k] || 0;
489
+ }
490
+ }
491
+ const peakWinPct = total > 0 ? (peakWinTokens / total) * 100 : 0;
492
+ const peakWin = localPeakWindow(apiOffsetMin, toOffset);
493
+
494
+ out.push(line());
495
+ out.push(
496
+ line(
497
+ plain(
498
+ ` Peak ${pad(peakSlot ? peakSlot.day + ' ' + peakSlot.time : '—', 15, 'right')}${pad(fmtTokens(peakTok), 7, 'left')} tokens · ${pad(fmtNum(peakCalls), 5, 'left')} calls`,
499
+ ),
500
+ ),
501
+ );
502
+ out.push(
503
+ line(
504
+ plain(
505
+ ` Active ${pad(`${activeHours} / ${nh} hours`, 15, 'right')}${longest ? idleLabel(longest, x, convertSlot) : 'no idle gaps'}`,
506
+ ),
507
+ ),
508
+ );
509
+ out.push(
510
+ line(
511
+ plain(
512
+ ` Tools ${pad(`${toolTotal} calls`, 15, 'right')}${searchN} searches · ${readN} reads${zreadN ? ` · ${zreadN} zread` : ''}`,
513
+ ),
514
+ ),
515
+ );
516
+ if (peakWin) {
517
+ out.push(
518
+ line(
519
+ plain(
520
+ ` Peak hrs Mon–Fri ${peakWin.start}–${peakWin.end} · GLM-5.2 3× · ${peakWinActive}h active · ${fmtTokens(peakWinTokens)} (`,
521
+ ),
522
+ bold(`${Math.round(peakWinPct)}%`),
523
+ plain(')'),
524
+ ),
525
+ );
526
+ }
527
+
528
+ out.push(line());
529
+ const chartHdr = ' Hourly tokens · ↑ peak hour ';
530
+ out.push(
531
+ line(dim(chartHdr + '─'.repeat(Math.max(0, RULE_WIDTH - chartHdr.length)))),
532
+ );
533
+ const maxTok = peakTok || 1;
534
+ const chartLines = hourlyVerticalChart({
535
+ x,
536
+ tok,
537
+ nh,
538
+ maxTok,
539
+ peakIdx,
540
+ slotFn: convertSlot,
541
+ });
542
+ if (chartLines) {
543
+ out.push(...chartLines.map((l): Line => line(plain(l))));
544
+ if (peakIdx >= 0 && peakSlot) {
545
+ out.push(
546
+ line(
547
+ plain(
548
+ ` ◂ peak ${peakSlot.day} ${peakSlot.time} ${fmtTokens(peakTok)} tokens · ${fmtNum(peakCalls)} calls`,
549
+ ),
550
+ ),
551
+ );
552
+ }
553
+ } else {
554
+ out.push(line(plain(' (not enough hourly data to chart)')));
555
+ }
556
+
557
+ out.push(line());
558
+ out.push(line(dim(' Model mix ' + '─'.repeat(Math.max(0, RULE_WIDTH - 11)))));
559
+ const mixSrc = model.modelSummaryList ?? model.modelDataList ?? [];
560
+ const denom = mixSrc.reduce((a, m) => a + (m.totalTokens ?? 0), 0) || 1;
561
+ const mixSorted = [...mixSrc].sort(
562
+ (a, b) => (a.sortOrder || 0) - (b.sortOrder || 0),
563
+ );
564
+ for (const m of mixSorted) {
565
+ const pct = ((m.totalTokens ?? 0) / denom) * 100;
566
+ out.push(
567
+ line(
568
+ plain(
569
+ ` ${pad(m.modelName || '?', 11, 'right')}${pad(fmtTokens(m.totalTokens), 8, 'left')} `,
570
+ ),
571
+ bold(pad(pct.toFixed(1) + '%', 6, 'left')),
572
+ plain(` ${bar(pct, 100, 20)}`),
573
+ ),
574
+ );
575
+ }
576
+
577
+ out.push(line());
578
+ out.push(line(dim(' Limits ' + '─'.repeat(Math.max(0, RULE_WIDTH - 8)))));
579
+
580
+ // The window does not bill on weekends, so the meter stays empty off Mon–Fri.
581
+ const bj = new Date(now.getTime() + apiOffsetMin * 60000);
582
+ const bjDay = bj.getUTCDay();
583
+ const inWindow = bjDay >= 1 && bjDay <= 5;
584
+ const elapsedMin = inWindow
585
+ ? Math.max(
586
+ 0,
587
+ Math.min(240, (bj.getUTCHours() - 14) * 60 + bj.getUTCMinutes()),
588
+ )
589
+ : 0;
590
+ if (peakWin) {
591
+ out.push(
592
+ line(
593
+ dim(` ${pad('Peak', 16, 'right')}`),
594
+ plain(`${pad(peakWin.start, 5, 'left')} `),
595
+ ...meter(Math.round((elapsedMin / 240) * 100), 22),
596
+ plain(` ${peakWin.end}`),
597
+ ),
598
+ );
599
+ }
600
+
601
+ const limits = quota.limits ?? [];
602
+ const mcp = limits.find(l => /mcp/i.test(l.type ?? ''));
603
+ const tok5 = limits.find(l => /token/i.test(l.type ?? ''));
604
+ if (tok5) {
605
+ const reset = new Date(tok5.nextResetTime ?? '').toLocaleTimeString(
606
+ 'en-IN',
607
+ );
608
+ out.push(
609
+ line(
610
+ dim(` ${pad('Tokens · 5h', 16, 'right')}`),
611
+ bold(pad(`${tok5.percentage || 0}%`, 5, 'left')),
612
+ plain(' '),
613
+ ...meter(tok5.percentage, 22),
614
+ plain(` ${reset}`),
615
+ ),
616
+ );
617
+ }
618
+
619
+ if (tok5 && mcp) {
620
+ out.push(line());
621
+ }
622
+
623
+ if (mcp) {
624
+ const reset = new Date(mcp.nextResetTime ?? '').toLocaleString('en-IN');
625
+ out.push(
626
+ line(
627
+ dim(` ${pad('MCP · this month', 16, 'right')}`),
628
+ bold(pad(`${mcp.percentage || 0}%`, 5, 'left')),
629
+ plain(' '),
630
+ ...meter(mcp.percentage, 22),
631
+ plain(` ${reset}`),
632
+ ),
633
+ );
634
+ const det = mcp.usageDetails ?? [];
635
+ const parts = det
636
+ .map(d => `${friendlyTool(d.modelCode)} ${fmtNum(d.usage)}`)
637
+ .join(' ');
638
+ if (parts) {
639
+ out.push(
640
+ line(
641
+ plain(
642
+ ` ${fmtNum(mcp.currentUsage)}M / ${fmtNum(mcp.totol)}M · ${parts}`,
643
+ ),
644
+ ),
645
+ );
646
+ }
647
+ }
648
+
649
+ out.push(line());
650
+ out.push(line(plain(rule())));
651
+ return out;
652
+ }
653
+
654
+ export function render(input: RenderInput): string {
655
+ return textOf(doc(...reportLines(input)));
656
+ }
package/src/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '@v1nvn/agentic-core';
3
+
4
+ import { render, reportLines } from './format.ts';
5
+ import { cliSpec, resolveConfig } from './resolve.ts';
6
+ import { fetchReport } from './usage.ts';
7
+
8
+ process.exitCode = await runCli(
9
+ cliSpec(async options => {
10
+ const input = await fetchReport(
11
+ resolveConfig(process.env, {
12
+ authToken: (options.authToken as string) || undefined,
13
+ baseUrl: (options.baseUrl as string) || undefined,
14
+ command: 'usage',
15
+ json: options.json === true,
16
+ }),
17
+ );
18
+ console.log(
19
+ options.json === true
20
+ ? JSON.stringify({ lines: reportLines(input) })
21
+ : render(input),
22
+ );
23
+ }),
24
+ process.argv.slice(2),
25
+ );