agy-bar 0.9.1 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/package.json +1 -1
- package/src/monitor.mjs +30 -11
- package/src/quota-sync.mjs +290 -0
- package/src/render.mjs +17 -6
- package/src/statusline.mjs +13 -8
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to **agy-bar** are documented here.
|
|
4
4
|
|
|
5
|
+
## [0.9.2] - 2026-11-26
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- **Cross-Terminal Local Quota Freshness Sync (`src/quota-sync.mjs`)**:
|
|
9
|
+
- Shares observed account quota snapshots locally across concurrent `agy` terminals via atomic `~/.gemini/config/agy-bar/quota-cache.json` (zero network requests, zero extra disk writes when idle, hashed non-PII account isolation).
|
|
10
|
+
- Whenever **any** `agy` terminal triggers a new 5h/7d reset window (newer `reset_time`) or consumes quota in the same window (strictly lower `remaining_fraction`), all other idle terminals and `agy-bar monitor` automatically display the freshest quota on their very next refresh instead of staying stuck on stale `0% (due)` or outdated percentages.
|
|
11
|
+
- **Clearer Expired-Reset `(ready)` Indicator (`src/render.mjs`, `src/monitor.mjs`)**:
|
|
12
|
+
- When a `5h` bucket's `reset_time` has already passed (`reset_time <= now`) and the sibling `7d` weekly cap still has remaining quota, replaces alarming bold-red `0% (due)` with calm amber `0%` + green `(ready)` so you can tell at a glance that the reset point has passed and sending a message will refresh it.
|
|
13
|
+
- Keeps bold-red `0% (due)` when the sibling `7d` weekly bucket is also exhausted (`0%` and not yet due).
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
- **Epoch-Zero Reset Sentinel (`1970-01-01T00:00:00Z`)**: Stopped rendering misleading `(due)` on unused 100% buckets whose protobuf zero timestamp (`1970-01-01T00:00:00Z`) indicates the window has not started yet.
|
|
17
|
+
|
|
5
18
|
## [0.9.1] - 2026-11-26
|
|
6
19
|
|
|
7
20
|
### Added
|
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·15
|
|
|
41
41
|
| **Line 1 · Left** | `~/code/agy-bar (main* +142 -38) · PX 7897` | Compact `~` path (`dirStyle`), live Git diff lines (tracked + untracked text, 3s cache), active proxy port badge, plus on-demand state badges (`CONFIRM` / `INPUT` when waiting on you, `ERR`, `● 34s · esc`, `SUB N` subagents, `TASK N` background tasks, `PLAN` / `SANDBOX`, Vim `[NORMAL]`) |
|
|
42
42
|
| **Line 1 · Right** | `DAY 136M/$13.2 · WK 810M · MO 875M · ALL 906M │ Model` | Calm neutral cumulative token/spend strip + active model & reasoning effort; sheds gracefully on narrow split panes |
|
|
43
43
|
| **Line 2 · Left** | `CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·158t/s │ ~$0.18` | Unified health context gauge (`→/compact` at danger), 5-min prompt cache TTL countdown, exact first-token latency + streaming decode speed, and live conversation spend (rolls up nested subagent costs automatically, refreshing every 20s while subagents run) |
|
|
44
|
-
| **Line 2 · Right** | `5h ▮▮▮▮▮▯ 85% (2h30m) │ 7d ▮▮▮▮▯▯ 64% (3d)` | Active model pool quotas (**Gemini 4 Neon / Carbon / Hydrogen / Argon** & **Claude 3p**) with reset countdowns |
|
|
44
|
+
| **Line 2 · Right** | `5h ▮▮▮▮▮▯ 85% (2h30m) │ 7d ▮▮▮▮▯▯ 64% (3d)` | Active model pool quotas (**Gemini 4 Neon / Carbon / Hydrogen / Argon** & **Claude 3p**) with live reset countdowns, local cross-terminal freshness sync, and green `(ready)` hint once a 5h reset point has passed |
|
|
45
45
|
|
|
46
46
|
---
|
|
47
47
|
|
package/README.zh-CN.md
CHANGED
|
@@ -41,7 +41,7 @@ CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·15
|
|
|
41
41
|
| **第一行 · 左侧** | `~/code/agy-bar (main* +142 -38) · PX 7897` | 精简 `~` 路径(`dirStyle`)、当前改动实时增删行数(含已追踪修改与新建文本文件,3s 缓存)、本地代理端口徽章;按需亮起状态徽章(等待确认/输入 `CONFIRM`/`INPUT`、报错 `ERR`、工作态 `● 34s · esc`、并行子代理 `SUB N`、后台任务 `TASK N`、`PLAN`/`SANDBOX`、Vim `[NORMAL]`) |
|
|
42
42
|
| **第一行 · 右侧** | `DAY 136M/$13.2 · WK 810M · MO 875M · ALL 906M │ 模型` | 低饱和中性配色汇总今日/本周/本月/累计用量与今日费用 + 当前模型与思考强度;窄分屏自动分级退让 |
|
|
43
43
|
| **第二行 · 左侧** | `CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·158t/s │ ~$0.18` | 统一健康色上下文条(危急提示 `→/compact`)、5 分钟缓存保活倒计时、首字时间 + 纯解码速率、本对话预估费用(自动归集所有子代理与嵌套孙代理开销,子代理运行中每 20 秒准实时刷新) |
|
|
44
|
-
| **第二行 · 右侧** | `5h ▮▮▮▮▮▯ 85% (2h30m) │ 7d ▮▮▮▮▯▯ 64% (3d)` | 自动匹配当前模型额度池(**Gemini 4 Neon / Carbon / Hydrogen / Argon** 与 **Claude 3p
|
|
44
|
+
| **第二行 · 右侧** | `5h ▮▮▮▮▮▯ 85% (2h30m) │ 7d ▮▮▮▮▯▯ 64% (3d)` | 自动匹配当前模型额度池(**Gemini 4 Neon / Carbon / Hydrogen / Argon** 与 **Claude 3p**),支持多终端本地自动同步最新额度快照,5h 到点未刷新时直观提示绿色 `(ready)` |
|
|
45
45
|
|
|
46
46
|
---
|
|
47
47
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-bar",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.2",
|
|
4
4
|
"description": "Zero-dependency terminal statusline, no-TUN proxy launcher, exact TTFT & tok/s speed, 5-min cache TTL countdown, live pricing cache, automatic tab titles, 52-week token heatmap, and multi-CLI monitor for Antigravity CLI (agy).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/monitor.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { bold, clipPlain, detectColorDepth, fg, visibleWidth } from './ansi.mjs';
|
|
2
2
|
import { loadConfig } from './config.mjs';
|
|
3
3
|
import { formatUsd } from './pricing.mjs';
|
|
4
|
+
import { isBucketResetDue, isWeeklyBucketBlocking, mergeQuotaSnapshots, readSharedQuota } from './quota-sync.mjs';
|
|
4
5
|
import { formatReset, formatTtft, renderBar } from './render.mjs';
|
|
5
6
|
import { listSessions } from './telemetry.mjs';
|
|
6
7
|
import { resolvePalette } from './themes.mjs';
|
|
@@ -108,7 +109,7 @@ function describeMonitorState(session, p, useColor) {
|
|
|
108
109
|
|
|
109
110
|
export function renderMonitorFrame(
|
|
110
111
|
sessions,
|
|
111
|
-
{ now = Date.now(), config = loadConfig(), color = true, env = process.env, columns = process.stdout.columns || 98 } = {},
|
|
112
|
+
{ now = Date.now(), config = loadConfig(), color = true, env = process.env, columns = process.stdout.columns || 98, sharedQuota = null } = {},
|
|
112
113
|
) {
|
|
113
114
|
const resolved = resolvePalette(config.theme, { env });
|
|
114
115
|
const colorDepth = detectColorDepth(env);
|
|
@@ -126,17 +127,33 @@ export function renderMonitorFrame(
|
|
|
126
127
|
);
|
|
127
128
|
lines.push(fg('─'.repeat(ruleWidth), p.sep, useColor));
|
|
128
129
|
|
|
129
|
-
//
|
|
130
|
-
const latestQuota =
|
|
130
|
+
// Merge quota across shared cache + all sessions so the freshest reset window and usage always win.
|
|
131
|
+
const latestQuota = mergeQuotaSnapshots(
|
|
132
|
+
[sharedQuota, ...sessions.map((s) => ({ quota: s.quota, observedAt: s.updatedAt }))],
|
|
133
|
+
now,
|
|
134
|
+
);
|
|
131
135
|
if (latestQuota) {
|
|
136
|
+
const labelOrder = Object.keys(QUOTA_LABELS);
|
|
137
|
+
const sortedEntries = Object.entries(latestQuota).sort(([a], [b]) => {
|
|
138
|
+
const ia = labelOrder.indexOf(a);
|
|
139
|
+
const ib = labelOrder.indexOf(b);
|
|
140
|
+
return (ia < 0 ? 999 : ia) - (ib < 0 ? 999 : ib) || a.localeCompare(b);
|
|
141
|
+
});
|
|
132
142
|
const qItems = [];
|
|
133
|
-
for (const [id, q] of
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
const
|
|
137
|
-
const
|
|
143
|
+
for (const [id, q] of sortedEntries) {
|
|
144
|
+
const frac = typeof q.remaining_fraction === 'number' ? q.remaining_fraction : q.remaining;
|
|
145
|
+
if (typeof frac !== 'number') continue;
|
|
146
|
+
const pct = Math.round(frac * 100);
|
|
147
|
+
const due = isBucketResetDue(q, now);
|
|
148
|
+
const blockedByWeekly = due && isWeeklyBucketBlocking(id, latestQuota, now);
|
|
149
|
+
const resetReady = due && !blockedByWeekly;
|
|
150
|
+
const rawTone = pct <= config.quotaDanger ? p.danger : pct <= config.quotaWarn ? p.warn : p.good;
|
|
151
|
+
const tone = resetReady && pct <= config.quotaDanger ? p.warn : rawTone;
|
|
152
|
+
const bar = renderBar(frac, { width: 6, style: config.barStyle, fillColor: tone, trackColor: p.track, color: useColor });
|
|
153
|
+
const resetText = resetReady ? 'ready' : formatReset(q, now);
|
|
154
|
+
const resetPart = resetText ? fg(` (${resetText})`, resetReady ? p.good : p.muted, useColor) : '';
|
|
138
155
|
const label = QUOTA_LABELS[id] || id;
|
|
139
|
-
qItems.push(`${fg(label, p.muted, useColor)} ${bar} ${fg(`${pct}%`, tone, useColor)}${
|
|
156
|
+
qItems.push(`${fg(label, p.muted, useColor)} ${bar} ${fg(`${pct}%`, tone, useColor)}${resetPart}`);
|
|
140
157
|
}
|
|
141
158
|
if (qItems.length > 0) {
|
|
142
159
|
lines.push(`${fg('Quota: ', p.muted, useColor)}${qItems.join(fg(' │ ', p.sep, useColor))}`);
|
|
@@ -205,9 +222,11 @@ export function renderMonitorFrame(
|
|
|
205
222
|
|
|
206
223
|
export async function startMonitor({ intervalMs = 1000, once = false, color = true, baseDir } = {}) {
|
|
207
224
|
const renderOnce = () => {
|
|
225
|
+
const now = Date.now();
|
|
208
226
|
const config = loadConfig();
|
|
209
|
-
const sessions = listSessions({ baseDir, prune: true });
|
|
210
|
-
|
|
227
|
+
const sessions = listSessions({ baseDir, now, prune: true });
|
|
228
|
+
const sharedQuota = readSharedQuota({ baseDir, now })?.buckets || null;
|
|
229
|
+
return renderMonitorFrame(sessions, { now, config, color, sharedQuota });
|
|
211
230
|
};
|
|
212
231
|
|
|
213
232
|
if (once || !process.stdout.isTTY) {
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { configDir } from './config.mjs';
|
|
6
|
+
import { writeFileAtomic } from './fs-atomic.mjs';
|
|
7
|
+
|
|
8
|
+
// Go / protobuf zero timestamp ("1970-01-01T00:00:00Z") indicates an unused window, not an expired one.
|
|
9
|
+
export const EPOCH_SENTINEL_MS = 86_400_000;
|
|
10
|
+
export const RESET_TOLERANCE_MS = 5_000;
|
|
11
|
+
export const MAX_CACHE_AGE_MS = 6 * 60 * 60 * 1000;
|
|
12
|
+
const FRACTION_EPSILON = 1e-6;
|
|
13
|
+
|
|
14
|
+
const WEEKLY_SIBLING_BUCKET = Object.freeze({
|
|
15
|
+
'gemini-5h': 'gemini-weekly',
|
|
16
|
+
'3p-5h': '3p-weekly',
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
function nonNeg(value) {
|
|
20
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function readFraction(bucket) {
|
|
24
|
+
if (!bucket || typeof bucket !== 'object') return null;
|
|
25
|
+
const f = nonNeg(bucket.remaining_fraction ?? bucket.remaining);
|
|
26
|
+
return f !== null ? Math.min(1, f) : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function quotaCachePath(baseDir = configDir(homedir())) {
|
|
30
|
+
return join(baseDir, 'quota-cache.json');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function parseRealResetTs(bucket) {
|
|
34
|
+
if (!bucket || typeof bucket !== 'object' || typeof bucket.reset_time !== 'string') return null;
|
|
35
|
+
const ts = Date.parse(bucket.reset_time);
|
|
36
|
+
return Number.isFinite(ts) && ts > EPOCH_SENTINEL_MS ? ts : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isEpochSentinelReset(bucket) {
|
|
40
|
+
if (!bucket || typeof bucket !== 'object' || typeof bucket.reset_time !== 'string') return false;
|
|
41
|
+
const ts = Date.parse(bucket.reset_time);
|
|
42
|
+
return Number.isFinite(ts) && ts <= EPOCH_SENTINEL_MS;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function isBucketResetDue(bucket, now = Date.now()) {
|
|
46
|
+
if (!bucket || typeof bucket !== 'object' || bucket.disabled === true) return false;
|
|
47
|
+
if (isEpochSentinelReset(bucket)) return false;
|
|
48
|
+
const resetTs = parseRealResetTs(bucket);
|
|
49
|
+
if (resetTs !== null) return resetTs <= now;
|
|
50
|
+
const resetSec = nonNeg(bucket.reset_in_seconds);
|
|
51
|
+
return resetSec !== null && resetSec <= 0;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function isWeeklyBucketBlocking(bucketId, quotaMap, now = Date.now()) {
|
|
55
|
+
const weeklyId = WEEKLY_SIBLING_BUCKET[bucketId];
|
|
56
|
+
if (!weeklyId || !quotaMap || typeof quotaMap !== 'object') return false;
|
|
57
|
+
const weekly = quotaMap[weeklyId];
|
|
58
|
+
if (!weekly || typeof weekly !== 'object' || weekly.disabled === true) return false;
|
|
59
|
+
const weeklyFrac = readFraction(weekly);
|
|
60
|
+
if (weeklyFrac === null || weeklyFrac > 0.005) return false;
|
|
61
|
+
return !isBucketResetDue(weekly, now);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function extractAccountKey(payload) {
|
|
65
|
+
const raw =
|
|
66
|
+
payload?.account?.email ||
|
|
67
|
+
payload?.user_email ||
|
|
68
|
+
payload?.account?.id ||
|
|
69
|
+
payload?.account_id ||
|
|
70
|
+
payload?.user_id ||
|
|
71
|
+
'';
|
|
72
|
+
const cleaned = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
|
|
73
|
+
if (!cleaned) return 'default';
|
|
74
|
+
return createHash('sha1').update(cleaned).digest('hex').slice(0, 12);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function normalizeQuotaBucket(raw, observedAt = Date.now()) {
|
|
78
|
+
if (!raw || typeof raw !== 'object' || raw.disabled === true) return null;
|
|
79
|
+
const remaining_fraction = readFraction(raw);
|
|
80
|
+
const remaining_amount = nonNeg(raw.remaining_amount);
|
|
81
|
+
if (remaining_fraction === null && remaining_amount === null) return null;
|
|
82
|
+
|
|
83
|
+
const reset_time = typeof raw.reset_time === 'string' && raw.reset_time.trim() ? raw.reset_time.trim() : null;
|
|
84
|
+
const reset_ts = parseRealResetTs({ reset_time });
|
|
85
|
+
const reset_in_seconds = nonNeg(raw.reset_in_seconds);
|
|
86
|
+
const obs = nonNeg(raw.observedAt) ?? observedAt;
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
remaining_fraction,
|
|
90
|
+
remaining_amount,
|
|
91
|
+
reset_time,
|
|
92
|
+
reset_ts,
|
|
93
|
+
reset_in_seconds,
|
|
94
|
+
observedAt: obs,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function pickFresherBucket(incoming, cached, now = Date.now()) {
|
|
99
|
+
if (!incoming && !cached) return { bucket: null, source: 'none', changedCache: false };
|
|
100
|
+
if (!incoming) return { bucket: cached, source: 'cached', changedCache: false };
|
|
101
|
+
if (!cached) return { bucket: incoming, source: 'incoming', changedCache: true };
|
|
102
|
+
|
|
103
|
+
if (now - cached.observedAt > MAX_CACHE_AGE_MS) {
|
|
104
|
+
return { bucket: incoming, source: 'incoming', changedCache: true };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const inTs = incoming.reset_ts;
|
|
108
|
+
const caTs = cached.reset_ts;
|
|
109
|
+
|
|
110
|
+
// Case 1 & 2: Both buckets carry real reset timestamps.
|
|
111
|
+
if (inTs !== null && caTs !== null) {
|
|
112
|
+
if (caTs > inTs + RESET_TOLERANCE_MS) {
|
|
113
|
+
return { bucket: cached, source: 'cached', changedCache: false };
|
|
114
|
+
}
|
|
115
|
+
if (inTs > caTs + RESET_TOLERANCE_MS) {
|
|
116
|
+
return { bucket: incoming, source: 'incoming', changedCache: true };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Same window: remaining quota is monotonically non-increasing until reset_time changes.
|
|
120
|
+
if (incoming.remaining_fraction !== null && cached.remaining_fraction !== null) {
|
|
121
|
+
if (cached.remaining_fraction < incoming.remaining_fraction - FRACTION_EPSILON) {
|
|
122
|
+
return { bucket: cached, source: 'cached', changedCache: false };
|
|
123
|
+
}
|
|
124
|
+
if (incoming.remaining_fraction < cached.remaining_fraction - FRACTION_EPSILON) {
|
|
125
|
+
return { bucket: incoming, source: 'incoming', changedCache: true };
|
|
126
|
+
}
|
|
127
|
+
return { bucket: incoming, source: 'incoming', changedCache: false };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (incoming.remaining_amount !== null && cached.remaining_amount !== null) {
|
|
131
|
+
if (cached.remaining_amount < incoming.remaining_amount) {
|
|
132
|
+
return { bucket: cached, source: 'cached', changedCache: false };
|
|
133
|
+
}
|
|
134
|
+
if (incoming.remaining_amount < cached.remaining_amount) {
|
|
135
|
+
return { bucket: incoming, source: 'incoming', changedCache: true };
|
|
136
|
+
}
|
|
137
|
+
return { bucket: incoming, source: 'incoming', changedCache: false };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return { bucket: incoming, source: 'incoming', changedCache: false };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Case 3a: Incoming is an unused/sentinel bucket (e.g. 100%, 1970-01-01) while cache has a real window.
|
|
144
|
+
if (inTs === null && caTs !== null) {
|
|
145
|
+
const inFull = incoming.remaining_fraction !== null && incoming.remaining_fraction >= 0.999;
|
|
146
|
+
if (caTs > now && inFull && (cached.remaining_fraction === null || cached.remaining_fraction < 0.999)) {
|
|
147
|
+
return { bucket: cached, source: 'cached', changedCache: false };
|
|
148
|
+
}
|
|
149
|
+
if (caTs <= now && inFull) {
|
|
150
|
+
return { bucket: incoming, source: 'incoming', changedCache: true };
|
|
151
|
+
}
|
|
152
|
+
return { bucket: incoming, source: 'incoming', changedCache: false };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Case 3b: Incoming has a real window while cache is an unused/sentinel bucket.
|
|
156
|
+
if (inTs !== null && caTs === null) {
|
|
157
|
+
if (inTs > now) {
|
|
158
|
+
return { bucket: incoming, source: 'incoming', changedCache: true };
|
|
159
|
+
}
|
|
160
|
+
const caFull = cached.remaining_fraction !== null && cached.remaining_fraction >= 0.999;
|
|
161
|
+
if (caFull && cached.observedAt > inTs) {
|
|
162
|
+
return { bucket: cached, source: 'cached', changedCache: false };
|
|
163
|
+
}
|
|
164
|
+
return { bucket: incoming, source: 'incoming', changedCache: false };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Case 4: Neither has a real reset_time (e.g. synthetic fixtures with only reset_in_seconds).
|
|
168
|
+
return { bucket: incoming, source: 'incoming', changedCache: false };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function materializeBucket(baseRaw, winner, now) {
|
|
172
|
+
const out = baseRaw && typeof baseRaw === 'object' ? { ...baseRaw } : {};
|
|
173
|
+
if (winner.remaining_fraction !== null) {
|
|
174
|
+
out.remaining_fraction = winner.remaining_fraction;
|
|
175
|
+
} else {
|
|
176
|
+
delete out.remaining_fraction;
|
|
177
|
+
}
|
|
178
|
+
if (winner.remaining_amount !== null) {
|
|
179
|
+
out.remaining_amount = winner.remaining_amount;
|
|
180
|
+
} else {
|
|
181
|
+
delete out.remaining_amount;
|
|
182
|
+
}
|
|
183
|
+
if (winner.reset_time !== null) {
|
|
184
|
+
out.reset_time = winner.reset_time;
|
|
185
|
+
} else {
|
|
186
|
+
delete out.reset_time;
|
|
187
|
+
}
|
|
188
|
+
if (winner.reset_ts !== null) {
|
|
189
|
+
out.reset_in_seconds = Math.max(0, Math.round((winner.reset_ts - now) / 1000));
|
|
190
|
+
} else if (winner.reset_in_seconds !== null) {
|
|
191
|
+
out.reset_in_seconds = winner.reset_in_seconds;
|
|
192
|
+
} else {
|
|
193
|
+
delete out.reset_in_seconds;
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function readSharedQuota({ baseDir = configDir(homedir()), now = Date.now(), accountKey = 'default' } = {}) {
|
|
199
|
+
const filePath = quotaCachePath(baseDir);
|
|
200
|
+
if (!existsSync(filePath)) return null;
|
|
201
|
+
try {
|
|
202
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
203
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.buckets || typeof parsed.buckets !== 'object') return null;
|
|
204
|
+
const cachedAccount = typeof parsed.accountKey === 'string' ? parsed.accountKey : 'default';
|
|
205
|
+
if (accountKey !== 'default' && cachedAccount !== 'default' && cachedAccount !== accountKey) {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
const buckets = {};
|
|
209
|
+
for (const [id, raw] of Object.entries(parsed.buckets)) {
|
|
210
|
+
const norm = normalizeQuotaBucket(raw, nonNeg(parsed.updatedAt) ?? now);
|
|
211
|
+
if (norm && now - norm.observedAt <= MAX_CACHE_AGE_MS) {
|
|
212
|
+
buckets[id] = norm;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
accountKey: cachedAccount,
|
|
217
|
+
updatedAt: nonNeg(parsed.updatedAt) ?? now,
|
|
218
|
+
buckets,
|
|
219
|
+
};
|
|
220
|
+
} catch {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function mergeQuotaSnapshots(snapshots = [], now = Date.now()) {
|
|
226
|
+
const merged = {};
|
|
227
|
+
for (const item of snapshots) {
|
|
228
|
+
if (!item || typeof item !== 'object') continue;
|
|
229
|
+
const isWrapped = Object.hasOwn(item, 'quota');
|
|
230
|
+
const snap = isWrapped ? item.quota : item;
|
|
231
|
+
const obs = isWrapped ? nonNeg(item.observedAt) ?? now : now;
|
|
232
|
+
if (!snap || typeof snap !== 'object') continue;
|
|
233
|
+
for (const [id, raw] of Object.entries(snap)) {
|
|
234
|
+
const incoming = normalizeQuotaBucket(raw, obs);
|
|
235
|
+
if (!incoming) continue;
|
|
236
|
+
const existing = merged[id] || null;
|
|
237
|
+
const { bucket } = pickFresherBucket(incoming, existing, now);
|
|
238
|
+
if (bucket) merged[id] = bucket;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return Object.keys(merged).length > 0 ? merged : null;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function syncSharedQuota(
|
|
245
|
+
rawQuota,
|
|
246
|
+
{ baseDir = configDir(homedir()), now = Date.now(), accountKey = 'default' } = {},
|
|
247
|
+
) {
|
|
248
|
+
if (!rawQuota || typeof rawQuota !== 'object') return rawQuota;
|
|
249
|
+
|
|
250
|
+
const existingCache = readSharedQuota({ baseDir, now, accountKey });
|
|
251
|
+
const nextCacheBuckets = existingCache ? { ...existingCache.buckets } : {};
|
|
252
|
+
const mergedQuota = { ...rawQuota };
|
|
253
|
+
|
|
254
|
+
let anyAdopted = false;
|
|
255
|
+
let cacheDirty = !existingCache;
|
|
256
|
+
|
|
257
|
+
for (const [id, rawBucket] of Object.entries(rawQuota)) {
|
|
258
|
+
if (!rawBucket || typeof rawBucket !== 'object' || rawBucket.disabled === true) continue;
|
|
259
|
+
const incoming = normalizeQuotaBucket(rawBucket, now);
|
|
260
|
+
if (!incoming) continue;
|
|
261
|
+
|
|
262
|
+
const cached = nextCacheBuckets[id] || null;
|
|
263
|
+
const { bucket: winner, source, changedCache } = pickFresherBucket(incoming, cached, now);
|
|
264
|
+
if (!winner) continue;
|
|
265
|
+
|
|
266
|
+
if (source === 'cached') {
|
|
267
|
+
mergedQuota[id] = materializeBucket(rawBucket, winner, now);
|
|
268
|
+
anyAdopted = true;
|
|
269
|
+
} else if (changedCache) {
|
|
270
|
+
nextCacheBuckets[id] = winner;
|
|
271
|
+
cacheDirty = true;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (cacheDirty && Object.keys(nextCacheBuckets).length > 0) {
|
|
276
|
+
try {
|
|
277
|
+
const payload = {
|
|
278
|
+
version: 1,
|
|
279
|
+
accountKey: accountKey !== 'default' ? accountKey : existingCache?.accountKey || 'default',
|
|
280
|
+
updatedAt: now,
|
|
281
|
+
buckets: nextCacheBuckets,
|
|
282
|
+
};
|
|
283
|
+
writeFileAtomic(quotaCachePath(baseDir), JSON.stringify(payload) + '\n');
|
|
284
|
+
} catch {
|
|
285
|
+
// Never fail statusline rendering due to disk issues.
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return anyAdopted ? mergedQuota : rawQuota;
|
|
290
|
+
}
|
package/src/render.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { classifyAgentActivity, countRunningSubagents } from './agent-state.mjs'
|
|
|
3
3
|
import { bold, clipAnsi, detectColorDepth, fg, sanitizeText, visibleWidth } from './ansi.mjs';
|
|
4
4
|
import { BAR_STYLES, DEFAULT_CONFIG, normalizeConfig } from './config.mjs';
|
|
5
5
|
import { formatUsd } from './pricing.mjs';
|
|
6
|
+
import { isBucketResetDue, isEpochSentinelReset, isWeeklyBucketBlocking } from './quota-sync.mjs';
|
|
6
7
|
import { resolvePalette } from './themes.mjs';
|
|
7
8
|
|
|
8
9
|
export { countRunningSubagents };
|
|
@@ -48,6 +49,7 @@ function formatCompactUsd(amount) {
|
|
|
48
49
|
|
|
49
50
|
export function formatReset(bucket, now = Date.now()) {
|
|
50
51
|
if (!bucket || typeof bucket !== 'object') return '';
|
|
52
|
+
if (isEpochSentinelReset(bucket)) return '';
|
|
51
53
|
const ts = typeof bucket.reset_time === 'string' ? Date.parse(bucket.reset_time) : NaN;
|
|
52
54
|
const seconds = Number.isFinite(ts) ? (ts - now) / 1000 : nonNegNumber(bucket.reset_in_seconds);
|
|
53
55
|
if (seconds === null) return '';
|
|
@@ -664,15 +666,19 @@ function buildSessionSegment(opts, config, palette, color, telemetry) {
|
|
|
664
666
|
return fg(parts.join('·'), palette.muted, color);
|
|
665
667
|
}
|
|
666
668
|
|
|
667
|
-
function buildQuotaSegment(entries, opts, config, palette, color, now) {
|
|
669
|
+
function buildQuotaSegment(entries, opts, config, palette, color, now, rawQuota = null) {
|
|
668
670
|
if (!entries.length) return '';
|
|
669
671
|
const { show, barStyle, barWidth, quotaWarn, quotaDanger } = config;
|
|
670
|
-
const
|
|
672
|
+
const quotaMap = rawQuota && typeof rawQuota === 'object' ? rawQuota : Object.fromEntries(entries.map((e) => [e.id, e.bucket]));
|
|
673
|
+
const parts = entries.map(({ id, label, bucket }) => {
|
|
671
674
|
const fraction = nonNegNumber(bucket.remaining_fraction);
|
|
672
675
|
const amount = nonNegNumber(bucket.remaining_amount);
|
|
673
676
|
const pct = fraction !== null ? Math.round(fraction * 100) : null;
|
|
674
677
|
const valText = pct !== null ? `${pct}%` : amount !== null ? formatTokens(amount) : '--';
|
|
675
|
-
const
|
|
678
|
+
const due = isBucketResetDue(bucket, now);
|
|
679
|
+
const blockedByWeekly = due && isWeeklyBucketBlocking(id, quotaMap, now);
|
|
680
|
+
const resetReady = due && !blockedByWeekly;
|
|
681
|
+
const baseTone =
|
|
676
682
|
pct === null
|
|
677
683
|
? palette.muted
|
|
678
684
|
: pct <= quotaDanger
|
|
@@ -680,6 +686,7 @@ function buildQuotaSegment(entries, opts, config, palette, color, now) {
|
|
|
680
686
|
: pct <= quotaWarn
|
|
681
687
|
? palette.warn
|
|
682
688
|
: palette.good;
|
|
689
|
+
const tone = resetReady && pct !== null && pct <= quotaDanger ? palette.warn : baseTone;
|
|
683
690
|
|
|
684
691
|
const pieces = [fg(label, palette.muted, color)];
|
|
685
692
|
if (opts.withQuotaBar && show.quotaBar && fraction !== null) {
|
|
@@ -695,8 +702,12 @@ function buildQuotaSegment(entries, opts, config, palette, color, now) {
|
|
|
695
702
|
}
|
|
696
703
|
pieces.push(pct !== null && pct <= quotaWarn ? bold(fg(valText, tone, color), color) : fg(valText, palette.text, color));
|
|
697
704
|
if (opts.withReset && show.reset) {
|
|
698
|
-
|
|
699
|
-
|
|
705
|
+
if (resetReady) {
|
|
706
|
+
pieces.push(fg('(ready)', palette.good, color));
|
|
707
|
+
} else {
|
|
708
|
+
const reset = formatReset(bucket, now);
|
|
709
|
+
if (reset) pieces.push(fg(`(${reset})`, palette.muted, color));
|
|
710
|
+
}
|
|
700
711
|
}
|
|
701
712
|
return pieces.join(' ');
|
|
702
713
|
});
|
|
@@ -759,7 +770,7 @@ function renderMetricsRow(
|
|
|
759
770
|
if (sessionSeg) leftParts.push(sessionSeg);
|
|
760
771
|
|
|
761
772
|
const left = joinWithSep(leftParts, stage.tight ? ' ' : sep, palette, color);
|
|
762
|
-
const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now);
|
|
773
|
+
const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now, payload?.quota);
|
|
763
774
|
const minGap = left && right ? 2 : 0;
|
|
764
775
|
chosenLeft = left;
|
|
765
776
|
chosenRight = right;
|
package/src/statusline.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { loadConfig } from './config.mjs';
|
|
|
6
6
|
import { readGitInfo } from './git.mjs';
|
|
7
7
|
import { getOrRefreshUsageSummary } from './history-scan.mjs';
|
|
8
8
|
import { maybeTriggerBackgroundPricingSync } from './pricing-sync.mjs';
|
|
9
|
+
import { extractAccountKey, syncSharedQuota } from './quota-sync.mjs';
|
|
9
10
|
import { renderFallback, renderStatusline } from './render.mjs';
|
|
10
11
|
import { readLatestStepTiming } from './step-timing.mjs';
|
|
11
12
|
import { syncTabTitle } from './tab-title.mjs';
|
|
@@ -27,8 +28,12 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
|
|
|
27
28
|
const payload = JSON.parse(raw);
|
|
28
29
|
const now = Date.now();
|
|
29
30
|
maybeCaptureRedactedPayload(payload);
|
|
30
|
-
const
|
|
31
|
-
|
|
31
|
+
const syncedQuota = payload?.quota
|
|
32
|
+
? syncSharedQuota(payload.quota, { now, accountKey: extractAccountKey(payload) })
|
|
33
|
+
: null;
|
|
34
|
+
const effectivePayload = syncedQuota && syncedQuota !== payload.quota ? { ...payload, quota: syncedQuota } : payload;
|
|
35
|
+
const prevSession = peekSessionState(effectivePayload);
|
|
36
|
+
const cwd = effectivePayload?.workspace?.current_dir || effectivePayload?.cwd || null;
|
|
32
37
|
const wantGitStatus = Boolean(config.show.gitDirty || config.show.gitDiff);
|
|
33
38
|
const canReuseGitStatus = Boolean(
|
|
34
39
|
wantGitStatus &&
|
|
@@ -51,9 +56,9 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
|
|
|
51
56
|
})
|
|
52
57
|
: null;
|
|
53
58
|
const stepTiming = config.dbTiming
|
|
54
|
-
? await readLatestStepTiming(
|
|
59
|
+
? await readLatestStepTiming(effectivePayload, { prevDbStamp: prevSession?.dbStamp ?? null })
|
|
55
60
|
: null;
|
|
56
|
-
const telemetry = recordTelemetry(
|
|
61
|
+
const telemetry = recordTelemetry(effectivePayload, {
|
|
57
62
|
now,
|
|
58
63
|
git,
|
|
59
64
|
stepTiming,
|
|
@@ -62,7 +67,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
|
|
|
62
67
|
enableLedger: config.ledger,
|
|
63
68
|
});
|
|
64
69
|
|
|
65
|
-
const activity = classifyAgentActivity(
|
|
70
|
+
const activity = classifyAgentActivity(effectivePayload);
|
|
66
71
|
let usageSummary = null;
|
|
67
72
|
if (
|
|
68
73
|
config.show.todayTokens ||
|
|
@@ -82,7 +87,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
|
|
|
82
87
|
});
|
|
83
88
|
}
|
|
84
89
|
|
|
85
|
-
const nativeCostUsd = extractNativeCostUsd(
|
|
90
|
+
const nativeCostUsd = extractNativeCostUsd(effectivePayload);
|
|
86
91
|
const effectiveSessionCostUsd = Math.max(telemetry.sessionCostUsd || 0, usageSummary?.sessionCostUsd || 0, nativeCostUsd || 0);
|
|
87
92
|
const effectiveTelemetry =
|
|
88
93
|
effectiveSessionCostUsd !== telemetry.sessionCostUsd
|
|
@@ -90,7 +95,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
|
|
|
90
95
|
: telemetry;
|
|
91
96
|
|
|
92
97
|
if (!plain && config.tabTitle) {
|
|
93
|
-
const tab = syncTabTitle(
|
|
98
|
+
const tab = syncTabTitle(effectivePayload, {
|
|
94
99
|
config,
|
|
95
100
|
git,
|
|
96
101
|
customTitle: telemetry.customTitle,
|
|
@@ -108,7 +113,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
|
|
|
108
113
|
maybeTriggerBackgroundPricingSync({ enabled: true, now, env });
|
|
109
114
|
}
|
|
110
115
|
|
|
111
|
-
const rendered = renderStatusline(
|
|
116
|
+
const rendered = renderStatusline(effectivePayload, {
|
|
112
117
|
config,
|
|
113
118
|
now,
|
|
114
119
|
color,
|