agy-bar 0.9.0 → 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 CHANGED
@@ -2,6 +2,29 @@
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
+
18
+ ## [0.9.1] - 2026-11-26
19
+
20
+ ### Added
21
+ - **Full 6-State Agent Activity Machine (`src/agent-state.mjs`)**:
22
+ - Unified session activity classification across terminal tab titles, statusline Line 1 badges, telemetry turn timers, and `agy-bar monitor`, aligned with Antigravity CLI's official `statusLine` payload schema (`agent_state`, `tool_confirmation_pending`, `subagents`, `task_count`, and native `cost.total_usd`).
23
+ - **Subagents / Background Tasks Active (`SUB N` / `TASK N` / `● [N]`)**: Replaced emoji `⚡N` with cohesive ASCII `SUB N` and `TASK N` badges on Line 1 (zero cross-terminal glyph-width drift). When the parent agent pauses (`agent_state: "idle"`) while subagents (`subagents[].status === "running"`) or background tasks (`task_count > 0`) are still executing, tab titles stay active (`● [N] <topic>` / `● <topic>`) instead of falsely showing `✓` complete.
24
+ - **Waiting for User Input / Approval (`?` / `CONFIRM` / `INPUT`)**: Displays `? <topic>` on the tab, bold amber `CONFIRM` (`tool_confirmation_pending: true`) or `INPUT` (`agent_state: "reviewing"`) on statusline Line 1, and `? confirm` / `? input` + `N waiting` summary in `agy-bar monitor`.
25
+ - **Error & Startup States (`✗ ERR` / `…`)**: Distinctly marks `error` (`✗` + bold red `ERR`) and `authenticating` / `initializing` (`…`) instead of falling back to `✓`.
26
+ - **Native `cost.total_usd` Compatibility**: Automatically incorporates AGY's native `cost.total_usd` field when reported alongside local DB/telemetry cost tracking.
27
+
5
28
  ## [0.9.0] - 2026-11-26
6
29
 
7
30
  ### Added
package/README.md CHANGED
@@ -14,6 +14,10 @@
14
14
 
15
15
  </div>
16
16
 
17
+ ![agy-bar live Ghostty terminal screenshot](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/live-statusline.png)
18
+
19
+ <sub>Real Ghostty capture: 10 running subagents (`⚡10`), live Git diff (`+14.3K -803`), no-TUN proxy (`PX 7897`), 1.01B cumulative tokens, 99% prompt cache TTL, TTFT & speed, live conversation spend, and 5h/7d quotas.</sub>
20
+
17
21
  ![agy-bar true-color statusline preview](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/preview.svg)
18
22
 
19
23
  ```sh
@@ -34,10 +38,10 @@ CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·15
34
38
 
35
39
  | Zone | What It Shows | Smart Behavior |
36
40
  | --- | --- | --- |
37
- | **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 busy badges (`● 34s · esc`, `⚡2` subagents, `PLAN` / `SANDBOX`, Vim `[NORMAL]`) |
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]`) |
38
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 |
39
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) |
40
- | **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 |
41
45
 
42
46
  ---
43
47
 
@@ -76,14 +80,13 @@ Running 3–5 `agy` sessions across different repos? Open `agy-bar monitor` in a
76
80
 
77
81
  ---
78
82
 
79
- ### 5. Automatic Terminal Tab Titles (`●` / `✓`) & Agent Summarization (`agy-bar title`)
83
+ ### 5. Automatic Terminal Tab Titles (`●` / `● [N]` / `?` / `✓`) & Agent Summarization (`agy-bar title`)
80
84
 
81
- Replaces identical `agy --dangerously-skip-permissions` tabs across Ghostty, iTerm2, Kitty, WezTerm, macOS Terminal, and VS Code with live state + conversation title via standard OSC 0/2 (zero extra tokens; safely skipped on native Windows):
85
+ Replaces identical `agy --dangerously-skip-permissions` tabs across Ghostty, iTerm2, Kitty, WezTerm, macOS Terminal, and VS Code with live activity state (`●` working, `● [N]` running subagents, `?` waiting for user input/confirmation, `✗` error, `✓` truly idle) + concise topic title via standard OSC 0/2 (zero extra tokens; safely skipped on native Windows):
82
86
 
83
- ```text
84
- Before: agy --dangerously-skip-permissions │ agy --dangerously-skip-permissions │ agy --dangerously-skip-permissions
85
- After: ● Fix Windows doctor check │ ✓ agy-bar (main*) │ ● Add 52-week stats heatmap
86
- ```
87
+ ![agy-bar live Ghostty tab titles comparison](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/live-tab-titles.png)
88
+
89
+ <sub>Real Ghostty tab bar: auto-synced tabs (`● agy-bar 开源状态栏`, `📊 agy-bar Token 热力图`) right next to an unmodified default `agy --dangerously-skip-per...` tab.</sub>
87
90
 
88
91
  > **Pro Tip — Auto-summarize tab titles on topic shifts (~10 tokens, zero extra API calls)**
89
92
  > Add this one line to your global `~/.gemini/antigravity-cli/AGENTS.md`:
package/README.zh-CN.md CHANGED
@@ -14,6 +14,10 @@
14
14
 
15
15
  </div>
16
16
 
17
+ ![agy-bar Ghostty 终端真机实拍](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/live-statusline.png)
18
+
19
+ <sub>Ghostty 真机实拍:10 并发子代理(`⚡10`)、实时代码增删(`+14.3K -803`)、免 TUN 本地代理(`PX 7897`)、1.01B 累计 Token、99% 缓存倒计时、TTFT/速率、本对话预估费用与 5h/7d 额度条。</sub>
20
+
17
21
  ![agy-bar 真彩渲染预览](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/preview.svg)
18
22
 
19
23
  ```sh
@@ -34,10 +38,10 @@ CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·15
34
38
 
35
39
  | 区域 | 显示内容 | 贴心细节 |
36
40
  | --- | --- | --- |
37
- | **第一行 · 左侧** | `~/code/agy-bar (main* +142 -38) · PX 7897` | 精简 `~` 路径(`dirStyle`)、当前改动实时增删行数(含已追踪修改与新建文本文件,3s 缓存)、本地代理端口徽章;仅在工作态按需亮起 `● 34s · esc`、并行子代理 `⚡2`、`PLAN`/`SANDBOX`、Vim `[NORMAL]` |
41
+ | **第一行 · 左侧** | `~/code/agy-bar (main* +142 -38) · PX 7897` | 精简 `~` 路径(`dirStyle`)、当前改动实时增删行数(含已追踪修改与新建文本文件,3s 缓存)、本地代理端口徽章;按需亮起状态徽章(等待确认/输入 `CONFIRM`/`INPUT`、报错 `ERR`、工作态 `● 34s · esc`、并行子代理 `SUB N`、后台任务 `TASK N`、`PLAN`/`SANDBOX`、Vim `[NORMAL]`) |
38
42
  | **第一行 · 右侧** | `DAY 136M/$13.2 · WK 810M · MO 875M · ALL 906M │ 模型` | 低饱和中性配色汇总今日/本周/本月/累计用量与今日费用 + 当前模型与思考强度;窄分屏自动分级退让 |
39
43
  | **第二行 · 左侧** | `CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·158t/s │ ~$0.18` | 统一健康色上下文条(危急提示 `→/compact`)、5 分钟缓存保活倒计时、首字时间 + 纯解码速率、本对话预估费用(自动归集所有子代理与嵌套孙代理开销,子代理运行中每 20 秒准实时刷新) |
40
- | **第二行 · 右侧** | `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)` |
41
45
 
42
46
  ---
43
47
 
@@ -76,14 +80,13 @@ CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·15
76
80
 
77
81
  ---
78
82
 
79
- ### 5. 终端标签页标题自动同步 (`●` / `✓`) 与 Agent 摘要 (`agy-bar title`)
83
+ ### 5. 终端标签页标题自动同步 (`●` / `● [N]` / `?` / `✓`) 与 Agent 摘要 (`agy-bar title`)
80
84
 
81
- 彻底告别多开时所有标签页都叫 `agy --dangerously-skip-permissions` 的烦恼:在 macOS / Linux / WSL 下的 Ghostty、iTerm2、Kitty、WezTerm、Terminal.app、VS Code 中通过标准 OSC 0/2 自动同步工作状态与会话标题(零额外 Token;原生 Windows 自动安全跳过):
85
+ 彻底告别多开时所有标签页都叫 `agy --dangerously-skip-permissions` 的烦恼:在 macOS / Linux / WSL 下的 Ghostty、iTerm2、Kitty、WezTerm、Terminal.app、VS Code 中通过标准 OSC 0/2 自动同步精确状态(`●` 工作中、`● [N]` 子代理运行中、`?` 等待你确认/输入、`✗` 报错、`✓` 全部完成)与精简主题(零额外 Token;原生 Windows 自动安全跳过):
82
86
 
83
- ```text
84
- 之前: agy --dangerously-skip-permissions │ agy --dangerously-skip-permissions │ agy --dangerously-skip-permissions
85
- 之后: ● 修复 Windows 兼容性 │ ✓ agy-bar (main*) │ ● 新增 52 周热力图统计
86
- ```
87
+ ![agy-bar Ghostty 标签页标题真机对比](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/live-tab-titles.png)
88
+
89
+ <sub>Ghostty 标签栏真机对比:左侧已自动同步为 `● agy-bar 开源状态栏`、`📊 agy-bar Token 热力图`,右侧为未启用前的默认 `agy --dangerously-skip-per...`。</sub>
87
90
 
88
91
  > **进阶技巧 — 让 Agent 换话题时自动缩写标签名(仅耗 ~10 tokens,零额外 API 调用)**
89
92
  > 在你的全局 `~/.gemini/antigravity-cli/AGENTS.md` 里加上这一句即可:
package/bin/agy-bar.mjs CHANGED
@@ -455,6 +455,9 @@ export async function main(argv = process.argv.slice(2)) {
455
455
  const renderedTitle = buildTabTitle(
456
456
  {
457
457
  agent_state: updated.agentState,
458
+ subagents: updated.runningSubagents || 0,
459
+ task_count: updated.runningTasks || 0,
460
+ tool_confirmation_pending: Boolean(updated.toolConfirmationPending),
458
461
  conversation_title: updated.conversationTitle,
459
462
  cwd: updated.cwd,
460
463
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-bar",
3
- "version": "0.9.0",
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",
@@ -8,7 +8,7 @@
8
8
  "homepage": "https://github.com/xy-tuoren/agy-bar",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "https://github.com/xy-tuoren/agy-bar.git"
11
+ "url": "git+https://github.com/xy-tuoren/agy-bar.git"
12
12
  },
13
13
  "bugs": {
14
14
  "url": "https://github.com/xy-tuoren/agy-bar/issues"
@@ -34,7 +34,7 @@
34
34
  "node": ">=20.0.0"
35
35
  },
36
36
  "bin": {
37
- "agy-bar": "./bin/agy-bar.mjs"
37
+ "agy-bar": "bin/agy-bar.mjs"
38
38
  },
39
39
  "files": [
40
40
  "AGENTS.md",
@@ -0,0 +1,186 @@
1
+ const MAIN_BUSY_STATES = Object.freeze(new Set(['working', 'tool_use', 'thinking']));
2
+ const STARTUP_STATES = Object.freeze(new Set(['authenticating', 'initializing']));
3
+ const RUNNING_SUBAGENT_STATUSES = Object.freeze(new Set(['running', 'working', 'active', 'in_progress']));
4
+
5
+ function nonNegNumber(value) {
6
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
7
+ }
8
+
9
+ export function countRunningSubagents(payload) {
10
+ const raw = payload?.subagents;
11
+ if (!raw) return 0;
12
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) return Math.floor(raw);
13
+ if (Array.isArray(raw)) {
14
+ let count = 0;
15
+ for (const item of raw) {
16
+ if (!item || typeof item !== 'object') continue;
17
+ const st = String(item.status || item.state || '').trim().toLowerCase();
18
+ if (item.running === true || RUNNING_SUBAGENT_STATUSES.has(st)) {
19
+ count += 1;
20
+ }
21
+ }
22
+ return count;
23
+ }
24
+ if (typeof raw === 'object') {
25
+ const n = nonNegNumber(raw.running ?? raw.active);
26
+ return n !== null ? Math.floor(n) : 0;
27
+ }
28
+ return 0;
29
+ }
30
+
31
+ export function countRunningTasks(payload) {
32
+ const n = nonNegNumber(payload?.task_count);
33
+ return n !== null ? Math.floor(n) : 0;
34
+ }
35
+
36
+ export function isToolConfirmationPending(payload) {
37
+ return payload?.tool_confirmation_pending === true;
38
+ }
39
+
40
+ export function extractNativeCostUsd(payload) {
41
+ const n = nonNegNumber(payload?.cost?.total_usd);
42
+ return n !== null && n > 0 ? n : null;
43
+ }
44
+
45
+ /**
46
+ * Single source of truth for classifying Antigravity CLI session activity across
47
+ * tab titles, statusline badges, telemetry timers, and multi-CLI monitor.
48
+ *
49
+ * Official AGY agent_state values:
50
+ * idle | working | tool_use | reviewing | authenticating | initializing | error
51
+ * Plus auxiliary live signals:
52
+ * tool_confirmation_pending, subagents[].status === 'running', task_count > 0
53
+ */
54
+ export function classifyAgentActivity(payload = {}) {
55
+ const raw = typeof payload?.agent_state === 'string' ? payload.agent_state.trim().toLowerCase() : '';
56
+ const rawState = raw || 'idle';
57
+ const runningSubagents = countRunningSubagents(payload);
58
+ const runningTasks = countRunningTasks(payload);
59
+ const confirmPending = isToolConfirmationPending(payload);
60
+
61
+ if (confirmPending) {
62
+ return Object.freeze({
63
+ kind: 'confirm',
64
+ rawState,
65
+ needsAttention: true,
66
+ isMainBusy: false,
67
+ isActive: true,
68
+ runningSubagents,
69
+ runningTasks,
70
+ confirmPending: true,
71
+ tabPrefix: '? ',
72
+ statusBadge: 'CONFIRM',
73
+ monitorLabel: 'confirm',
74
+ });
75
+ }
76
+
77
+ if (rawState === 'reviewing') {
78
+ return Object.freeze({
79
+ kind: 'input',
80
+ rawState,
81
+ needsAttention: true,
82
+ isMainBusy: false,
83
+ isActive: true,
84
+ runningSubagents,
85
+ runningTasks,
86
+ confirmPending: false,
87
+ tabPrefix: '? ',
88
+ statusBadge: 'INPUT',
89
+ monitorLabel: 'input',
90
+ });
91
+ }
92
+
93
+ if (rawState === 'error') {
94
+ return Object.freeze({
95
+ kind: 'error',
96
+ rawState,
97
+ needsAttention: true,
98
+ isMainBusy: false,
99
+ isActive: false,
100
+ runningSubagents,
101
+ runningTasks,
102
+ confirmPending: false,
103
+ tabPrefix: '✗ ',
104
+ statusBadge: 'ERR',
105
+ monitorLabel: 'error',
106
+ });
107
+ }
108
+
109
+ if (MAIN_BUSY_STATES.has(rawState)) {
110
+ return Object.freeze({
111
+ kind: 'working',
112
+ rawState,
113
+ needsAttention: false,
114
+ isMainBusy: true,
115
+ isActive: true,
116
+ runningSubagents,
117
+ runningTasks,
118
+ confirmPending: false,
119
+ tabPrefix: '● ',
120
+ statusBadge: null,
121
+ monitorLabel: rawState,
122
+ });
123
+ }
124
+
125
+ if (runningSubagents > 0) {
126
+ return Object.freeze({
127
+ kind: 'subagents',
128
+ rawState,
129
+ needsAttention: false,
130
+ isMainBusy: false,
131
+ isActive: true,
132
+ runningSubagents,
133
+ runningTasks,
134
+ confirmPending: false,
135
+ tabPrefix: `● [${runningSubagents}] `,
136
+ statusBadge: null,
137
+ monitorLabel: `sub:${runningSubagents}`,
138
+ });
139
+ }
140
+
141
+ if (runningTasks > 0) {
142
+ return Object.freeze({
143
+ kind: 'tasks',
144
+ rawState,
145
+ needsAttention: false,
146
+ isMainBusy: false,
147
+ isActive: true,
148
+ runningSubagents,
149
+ runningTasks,
150
+ confirmPending: false,
151
+ tabPrefix: '● ',
152
+ statusBadge: null,
153
+ monitorLabel: `task:${runningTasks}`,
154
+ });
155
+ }
156
+
157
+ if (STARTUP_STATES.has(rawState)) {
158
+ return Object.freeze({
159
+ kind: 'startup',
160
+ rawState,
161
+ needsAttention: false,
162
+ isMainBusy: false,
163
+ isActive: true,
164
+ runningSubagents,
165
+ runningTasks,
166
+ confirmPending: false,
167
+ tabPrefix: '… ',
168
+ statusBadge: null,
169
+ monitorLabel: rawState === 'authenticating' ? 'auth' : 'init',
170
+ });
171
+ }
172
+
173
+ return Object.freeze({
174
+ kind: 'idle',
175
+ rawState,
176
+ needsAttention: false,
177
+ isMainBusy: false,
178
+ isActive: false,
179
+ runningSubagents,
180
+ runningTasks,
181
+ confirmPending: false,
182
+ tabPrefix: '✓ ',
183
+ statusBadge: null,
184
+ monitorLabel: 'idle',
185
+ });
186
+ }
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';
@@ -48,9 +49,67 @@ function padLeft(text, len) {
48
49
  return w >= len ? s : ' '.repeat(len - w) + s;
49
50
  }
50
51
 
52
+ function describeMonitorState(session, p, useColor) {
53
+ const kind = session.activityKind || (session.isBusy ? 'working' : 'idle');
54
+ if (kind === 'confirm' || kind === 'input') {
55
+ return {
56
+ dot: bold(fg('?', p.warn, useColor), useColor),
57
+ label: kind,
58
+ tone: p.warn,
59
+ strong: true,
60
+ };
61
+ }
62
+ if (kind === 'error') {
63
+ return {
64
+ dot: bold(fg('✗', p.danger, useColor), useColor),
65
+ label: 'error',
66
+ tone: p.danger,
67
+ strong: true,
68
+ };
69
+ }
70
+ if (kind === 'subagents') {
71
+ return {
72
+ dot: fg('●', p.accent, useColor),
73
+ label: `sub:${session.runningSubagents || 1}`,
74
+ tone: p.accent,
75
+ strong: false,
76
+ };
77
+ }
78
+ if (kind === 'tasks') {
79
+ return {
80
+ dot: fg('●', p.accent, useColor),
81
+ label: `task:${session.runningTasks || 1}`,
82
+ tone: p.accent,
83
+ strong: false,
84
+ };
85
+ }
86
+ if (kind === 'startup') {
87
+ return {
88
+ dot: fg('…', p.muted, useColor),
89
+ label: session.agentState === 'authenticating' ? 'auth' : 'init',
90
+ tone: p.muted,
91
+ strong: false,
92
+ };
93
+ }
94
+ if (kind === 'working') {
95
+ return {
96
+ dot: fg('●', p.warn, useColor),
97
+ label: session.agentState || 'working',
98
+ tone: p.warn,
99
+ strong: false,
100
+ };
101
+ }
102
+ return {
103
+ dot: session.ageMs <= 5 * 60 * 1000 ? fg('●', p.good, useColor) : fg('○', p.muted, useColor),
104
+ label: session.agentState || 'idle',
105
+ tone: p.text,
106
+ strong: false,
107
+ };
108
+ }
109
+
51
110
  export function renderMonitorFrame(
52
111
  sessions,
53
- { 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 } = {},
54
113
  ) {
55
114
  const resolved = resolvePalette(config.theme, { env });
56
115
  const colorDepth = detectColorDepth(env);
@@ -60,23 +119,41 @@ export function renderMonitorFrame(
60
119
  const ruleWidth = Math.min(104, Math.max(76, columns || 98));
61
120
 
62
121
  const activeCount = sessions.filter((s) => s.ageMs <= 5 * 60 * 1000).length;
122
+ const waitingCount = sessions.filter((s) => s.activityKind === 'confirm' || s.activityKind === 'input').length;
123
+ const waitSuffix = waitingCount > 0 ? ` · ${waitingCount} waiting` : '';
63
124
  lines.push(
64
125
  bold(fg('agy-bar monitor', p.accent, useColor), useColor) +
65
- fg(` · ${sessions.length} recent CLI session${sessions.length === 1 ? '' : 's'} (${activeCount} active) · Ctrl+C to quit`, p.muted, useColor),
126
+ fg(` · ${sessions.length} recent CLI session${sessions.length === 1 ? '' : 's'} (${activeCount} active${waitSuffix}) · Ctrl+C to quit`, p.muted, useColor),
66
127
  );
67
128
  lines.push(fg('─'.repeat(ruleWidth), p.sep, useColor));
68
129
 
69
- // Show latest observed global quota from most recent session that has quota data.
70
- const latestQuota = sessions.find((s) => s.quota)?.quota;
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
+ );
71
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
+ });
72
142
  const qItems = [];
73
- for (const [id, q] of Object.entries(latestQuota)) {
74
- const pct = Math.round(q.remaining * 100);
75
- const tone = pct <= config.quotaDanger ? p.danger : pct <= config.quotaWarn ? p.warn : p.good;
76
- const bar = renderBar(q.remaining, { width: 6, style: config.barStyle, fillColor: tone, trackColor: p.track, color: useColor });
77
- const reset = formatReset(q, now);
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) : '';
78
155
  const label = QUOTA_LABELS[id] || id;
79
- qItems.push(`${fg(label, p.muted, useColor)} ${bar} ${fg(`${pct}%`, tone, useColor)}${reset ? fg(` (${reset})`, p.muted, useColor) : ''}`);
156
+ qItems.push(`${fg(label, p.muted, useColor)} ${bar} ${fg(`${pct}%`, tone, useColor)}${resetPart}`);
80
157
  }
81
158
  if (qItems.length > 0) {
82
159
  lines.push(`${fg('Quota: ', p.muted, useColor)}${qItems.join(fg(' │ ', p.sep, useColor))}`);
@@ -101,8 +178,9 @@ export function renderMonitorFrame(
101
178
  const healthyCtxColor = config.colorMode === 'distinct' ? p.accent : p.good;
102
179
 
103
180
  for (const s of sessions) {
104
- const dot = s.isBusy ? fg('●', p.warn, useColor) : s.ageMs <= 5 * 60 * 1000 ? fg('●', p.good, useColor) : fg('○', p.muted, useColor);
105
- const stateLabel = padRight(s.agentState || 'idle', 8);
181
+ const state = describeMonitorState(s, p, useColor);
182
+ const stateLabel = padRight(state.label, 8);
183
+ const styledState = state.strong ? bold(fg(stateLabel, state.tone, useColor), useColor) : fg(stateLabel, state.tone, useColor);
106
184
  const ws = s.workspaceName || s.sessionId.slice(0, 10);
107
185
  const branchPart = s.branch ? `:${s.branch}${s.dirty ? '*' : ''}` : '';
108
186
  const wsCell = padRight(`${ws}${branchPart}`, 22);
@@ -128,7 +206,7 @@ export function renderMonitorFrame(
128
206
  const costCell = padLeft(typeof s.sessionCostUsd === 'number' && s.sessionCostUsd > 0 ? formatUsd(s.sessionCostUsd) : '--', 7);
129
207
 
130
208
  lines.push(
131
- `${dot} ${fg(stateLabel, s.isBusy ? p.warn : p.text, useColor)} ` +
209
+ `${state.dot} ${styledState} ` +
132
210
  `${fg(wsCell, p.branch, useColor)} ` +
133
211
  `${fg(modelCell, p.text, useColor)} ` +
134
212
  `${ctxBar} ${fg(ctxText, ctxTone, useColor)} ` +
@@ -144,9 +222,11 @@ export function renderMonitorFrame(
144
222
 
145
223
  export async function startMonitor({ intervalMs = 1000, once = false, color = true, baseDir } = {}) {
146
224
  const renderOnce = () => {
225
+ const now = Date.now();
147
226
  const config = loadConfig();
148
- const sessions = listSessions({ baseDir, prune: true });
149
- return renderMonitorFrame(sessions, { config, color });
227
+ const sessions = listSessions({ baseDir, now, prune: true });
228
+ const sharedQuota = readSharedQuota({ baseDir, now })?.buckets || null;
229
+ return renderMonitorFrame(sessions, { now, config, color, sharedQuota });
150
230
  };
151
231
 
152
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
@@ -1,9 +1,13 @@
1
1
  import { homedir } from 'node:os';
2
+ import { classifyAgentActivity, countRunningSubagents } from './agent-state.mjs';
2
3
  import { bold, clipAnsi, detectColorDepth, fg, sanitizeText, visibleWidth } from './ansi.mjs';
3
4
  import { BAR_STYLES, DEFAULT_CONFIG, normalizeConfig } from './config.mjs';
4
5
  import { formatUsd } from './pricing.mjs';
6
+ import { isBucketResetDue, isEpochSentinelReset, isWeeklyBucketBlocking } from './quota-sync.mjs';
5
7
  import { resolvePalette } from './themes.mjs';
6
8
 
9
+ export { countRunningSubagents };
10
+
7
11
  const KNOWN_BUCKETS = Object.freeze({
8
12
  'gemini-5h': Object.freeze({ group: 'Gemini', kind: '5h', label: '5h' }),
9
13
  'gemini-weekly': Object.freeze({ group: 'Gemini', kind: 'weekly', label: '7d' }),
@@ -45,6 +49,7 @@ function formatCompactUsd(amount) {
45
49
 
46
50
  export function formatReset(bucket, now = Date.now()) {
47
51
  if (!bucket || typeof bucket !== 'object') return '';
52
+ if (isEpochSentinelReset(bucket)) return '';
48
53
  const ts = typeof bucket.reset_time === 'string' ? Date.parse(bucket.reset_time) : NaN;
49
54
  const seconds = Number.isFinite(ts) ? (ts - now) / 1000 : nonNegNumber(bucket.reset_in_seconds);
50
55
  if (seconds === null) return '';
@@ -233,28 +238,6 @@ export function extractActiveProxyLabel(env = {}) {
233
238
  }
234
239
  }
235
240
 
236
- export function countRunningSubagents(payload) {
237
- const raw = payload?.subagents;
238
- if (!raw) return 0;
239
- if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) return Math.floor(raw);
240
- if (Array.isArray(raw)) {
241
- let count = 0;
242
- for (const item of raw) {
243
- if (!item || typeof item !== 'object') continue;
244
- const st = String(item.status || item.state || '').toLowerCase();
245
- if (item.running === true || st === 'running' || st === 'working' || st === 'active' || st === 'in_progress') {
246
- count += 1;
247
- }
248
- }
249
- return count;
250
- }
251
- if (typeof raw === 'object') {
252
- const n = nonNegNumber(raw.running ?? raw.active);
253
- return n !== null ? Math.floor(n) : 0;
254
- }
255
- return 0;
256
- }
257
-
258
241
  export function formatTurnElapsed(seconds) {
259
242
  const sec = nonNegNumber(seconds);
260
243
  if (sec === null || sec < 1) return '';
@@ -282,11 +265,20 @@ function formatModeBadges(payload, show, palette, color) {
282
265
  return joinWithSep(badges, ' · ', palette, color);
283
266
  }
284
267
 
285
- function formatSubagentsBadge(payload, show, palette, color) {
286
- if (!show.subagents) return '';
287
- const running = countRunningSubagents(payload);
288
- if (running <= 0) return '';
289
- return bold(fg(`⚡${running}`, palette.accent, color), color);
268
+ function formatAttentionBadge(activity, show, palette, color) {
269
+ if (!activity.statusBadge || (!show.mode && !show.hint)) return '';
270
+ const tone = activity.kind === 'error' ? palette.danger : palette.warn;
271
+ return bold(fg(activity.statusBadge, tone, color), color);
272
+ }
273
+
274
+ function formatSubagentsBadge(activity, show, palette, color) {
275
+ if (!show.subagents || activity.runningSubagents <= 0) return '';
276
+ return `${fg('SUB', palette.muted, color)} ${bold(fg(String(activity.runningSubagents), palette.accent, color), color)}`;
277
+ }
278
+
279
+ function formatTasksBadge(activity, show, palette, color) {
280
+ if (!show.subagents || activity.runningTasks <= 0) return '';
281
+ return `${fg('TASK', palette.muted, color)} ${fg(String(activity.runningTasks), palette.accent, color)}`;
290
282
  }
291
283
 
292
284
  function formatBusySegment(isBusy, telemetry, show, palette, color) {
@@ -460,11 +452,13 @@ function formatUsageSummarySegment(
460
452
 
461
453
  function renderMetaLine(payload, width, config, palette, color, git, usageSummary = null, telemetry = null, env = {}, home = homedir()) {
462
454
  const { show, dirStyle } = config;
463
- const isBusy = ['working', 'tool_use', 'thinking'].includes(payload?.agent_state);
455
+ const activity = classifyAgentActivity(payload);
464
456
  const vimBadge = formatVimBadge(payload, show, palette, color);
457
+ const attentionBadge = formatAttentionBadge(activity, show, palette, color);
465
458
  const modeBadge = formatModeBadges(payload, show, palette, color);
466
- const subagentsBadge = formatSubagentsBadge(payload, show, palette, color);
467
- const busySeg = formatBusySegment(isBusy, telemetry, show, palette, color);
459
+ const subagentsBadge = formatSubagentsBadge(activity, show, palette, color);
460
+ const tasksBadge = formatTasksBadge(activity, show, palette, color);
461
+ const busySeg = formatBusySegment(activity.isMainBusy, telemetry, show, palette, color);
468
462
  const proxyBadge = formatProxyBadge(env, show, palette, color);
469
463
  const modelText = show.model ? formatModelName(payload?.model, show.effort) : '';
470
464
  const modelSeg = modelText ? fg(modelText, palette.muted, color) : '';
@@ -513,12 +507,12 @@ function renderMetaLine(payload, width, config, palette, color, git, usageSummar
513
507
  home,
514
508
  });
515
509
 
516
- const leftFull = joinWithSep([vimBadge, modeBadge, subagentsBadge, busySeg, wsFull, proxyBadge], ' · ', palette, color);
517
- const leftNoDiff = joinWithSep([vimBadge, modeBadge, subagentsBadge, busySeg, wsNoDiff, proxyBadge], ' · ', palette, color);
518
- const leftShort = joinWithSep([vimBadge, modeBadge, subagentsBadge, busySeg, wsShort, proxyBadge], ' · ', palette, color);
519
- const leftNoProxy = joinWithSep([vimBadge, modeBadge, subagentsBadge, busySeg, wsShort], ' · ', palette, color);
520
- const leftCompact = joinWithSep([vimBadge, modeBadge, subagentsBadge, busySeg, wsShort || gitOnly], ' · ', palette, color);
521
- const leftMinimal = vimBadge || modeBadge || subagentsBadge || busySeg || gitOnly;
510
+ const leftFull = joinWithSep([vimBadge, attentionBadge, modeBadge, subagentsBadge, tasksBadge, busySeg, wsFull, proxyBadge], ' · ', palette, color);
511
+ const leftNoDiff = joinWithSep([vimBadge, attentionBadge, modeBadge, subagentsBadge, tasksBadge, busySeg, wsNoDiff, proxyBadge], ' · ', palette, color);
512
+ const leftShort = joinWithSep([vimBadge, attentionBadge, modeBadge, subagentsBadge, tasksBadge, busySeg, wsShort, proxyBadge], ' · ', palette, color);
513
+ const leftNoProxy = joinWithSep([vimBadge, attentionBadge, modeBadge, subagentsBadge, tasksBadge, busySeg, wsShort], ' · ', palette, color);
514
+ const leftCompact = joinWithSep([vimBadge, attentionBadge, modeBadge, subagentsBadge, busySeg, wsShort || gitOnly], ' · ', palette, color);
515
+ const leftMinimal = attentionBadge || vimBadge || modeBadge || subagentsBadge || busySeg || gitOnly;
522
516
 
523
517
  const pairs = [
524
518
  [leftFull, rightFull],
@@ -672,15 +666,19 @@ function buildSessionSegment(opts, config, palette, color, telemetry) {
672
666
  return fg(parts.join('·'), palette.muted, color);
673
667
  }
674
668
 
675
- function buildQuotaSegment(entries, opts, config, palette, color, now) {
669
+ function buildQuotaSegment(entries, opts, config, palette, color, now, rawQuota = null) {
676
670
  if (!entries.length) return '';
677
671
  const { show, barStyle, barWidth, quotaWarn, quotaDanger } = config;
678
- const parts = entries.map(({ label, bucket }) => {
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 }) => {
679
674
  const fraction = nonNegNumber(bucket.remaining_fraction);
680
675
  const amount = nonNegNumber(bucket.remaining_amount);
681
676
  const pct = fraction !== null ? Math.round(fraction * 100) : null;
682
677
  const valText = pct !== null ? `${pct}%` : amount !== null ? formatTokens(amount) : '--';
683
- const tone =
678
+ const due = isBucketResetDue(bucket, now);
679
+ const blockedByWeekly = due && isWeeklyBucketBlocking(id, quotaMap, now);
680
+ const resetReady = due && !blockedByWeekly;
681
+ const baseTone =
684
682
  pct === null
685
683
  ? palette.muted
686
684
  : pct <= quotaDanger
@@ -688,6 +686,7 @@ function buildQuotaSegment(entries, opts, config, palette, color, now) {
688
686
  : pct <= quotaWarn
689
687
  ? palette.warn
690
688
  : palette.good;
689
+ const tone = resetReady && pct !== null && pct <= quotaDanger ? palette.warn : baseTone;
691
690
 
692
691
  const pieces = [fg(label, palette.muted, color)];
693
692
  if (opts.withQuotaBar && show.quotaBar && fraction !== null) {
@@ -703,8 +702,12 @@ function buildQuotaSegment(entries, opts, config, palette, color, now) {
703
702
  }
704
703
  pieces.push(pct !== null && pct <= quotaWarn ? bold(fg(valText, tone, color), color) : fg(valText, palette.text, color));
705
704
  if (opts.withReset && show.reset) {
706
- const reset = formatReset(bucket, now);
707
- if (reset) pieces.push(fg(`(${reset})`, palette.muted, color));
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
+ }
708
711
  }
709
712
  return pieces.join(' ');
710
713
  });
@@ -767,7 +770,7 @@ function renderMetricsRow(
767
770
  if (sessionSeg) leftParts.push(sessionSeg);
768
771
 
769
772
  const left = joinWithSep(leftParts, stage.tight ? ' ' : sep, palette, color);
770
- const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now);
773
+ const right = buildQuotaSegment(quotaEntries, stage, config, palette, color, now, payload?.quota);
771
774
  const minGap = left && right ? 2 : 0;
772
775
  chosenLeft = left;
773
776
  chosenRight = right;
@@ -1,11 +1,13 @@
1
1
  import { realpathSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { classifyAgentActivity, extractNativeCostUsd } from './agent-state.mjs';
4
5
  import { loadConfig } from './config.mjs';
5
6
  import { readGitInfo } from './git.mjs';
6
7
  import { getOrRefreshUsageSummary } from './history-scan.mjs';
7
8
  import { maybeTriggerBackgroundPricingSync } from './pricing-sync.mjs';
8
- import { countRunningSubagents, renderFallback, renderStatusline } from './render.mjs';
9
+ import { extractAccountKey, syncSharedQuota } from './quota-sync.mjs';
10
+ import { renderFallback, renderStatusline } from './render.mjs';
9
11
  import { readLatestStepTiming } from './step-timing.mjs';
10
12
  import { syncTabTitle } from './tab-title.mjs';
11
13
  import { maybeCaptureRedactedPayload, peekSessionState, recordTelemetry, updateSessionTabTitle } from './telemetry.mjs';
@@ -26,8 +28,12 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
26
28
  const payload = JSON.parse(raw);
27
29
  const now = Date.now();
28
30
  maybeCaptureRedactedPayload(payload);
29
- const prevSession = peekSessionState(payload);
30
- const cwd = payload?.workspace?.current_dir || payload?.cwd || null;
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;
31
37
  const wantGitStatus = Boolean(config.show.gitDirty || config.show.gitDiff);
32
38
  const canReuseGitStatus = Boolean(
33
39
  wantGitStatus &&
@@ -50,9 +56,9 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
50
56
  })
51
57
  : null;
52
58
  const stepTiming = config.dbTiming
53
- ? await readLatestStepTiming(payload, { prevDbStamp: prevSession?.dbStamp ?? null })
59
+ ? await readLatestStepTiming(effectivePayload, { prevDbStamp: prevSession?.dbStamp ?? null })
54
60
  : null;
55
- const telemetry = recordTelemetry(payload, {
61
+ const telemetry = recordTelemetry(effectivePayload, {
56
62
  now,
57
63
  git,
58
64
  stepTiming,
@@ -61,6 +67,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
61
67
  enableLedger: config.ledger,
62
68
  });
63
69
 
70
+ const activity = classifyAgentActivity(effectivePayload);
64
71
  let usageSummary = null;
65
72
  if (
66
73
  config.show.todayTokens ||
@@ -75,19 +82,20 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
75
82
  sessionId: telemetry.sessionId,
76
83
  deltaTokens: telemetry.turnTokensDelta || 0,
77
84
  deltaCostUsd: telemetry.turnCostDeltaUsd || 0,
78
- hasRunningSubagents: countRunningSubagents(payload) > 0,
85
+ hasRunningSubagents: activity.runningSubagents > 0,
79
86
  allowScan: config.dbTiming,
80
87
  });
81
88
  }
82
89
 
83
- const effectiveSessionCostUsd = Math.max(telemetry.sessionCostUsd || 0, usageSummary?.sessionCostUsd || 0);
90
+ const nativeCostUsd = extractNativeCostUsd(effectivePayload);
91
+ const effectiveSessionCostUsd = Math.max(telemetry.sessionCostUsd || 0, usageSummary?.sessionCostUsd || 0, nativeCostUsd || 0);
84
92
  const effectiveTelemetry =
85
93
  effectiveSessionCostUsd !== telemetry.sessionCostUsd
86
94
  ? { ...telemetry, sessionCostUsd: effectiveSessionCostUsd }
87
95
  : telemetry;
88
96
 
89
97
  if (!plain && config.tabTitle) {
90
- const tab = syncTabTitle(payload, {
98
+ const tab = syncTabTitle(effectivePayload, {
91
99
  config,
92
100
  git,
93
101
  customTitle: telemetry.customTitle,
@@ -105,7 +113,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
105
113
  maybeTriggerBackgroundPricingSync({ enabled: true, now, env });
106
114
  }
107
115
 
108
- const rendered = renderStatusline(payload, {
116
+ const rendered = renderStatusline(effectivePayload, {
109
117
  config,
110
118
  now,
111
119
  color,
package/src/tab-title.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { accessSync, closeSync, constants, openSync, writeSync } from 'node:fs';
3
3
  import { basename } from 'node:path';
4
+ import { classifyAgentActivity } from './agent-state.mjs';
4
5
  import { clipPlain, sanitizeText, visibleWidth } from './ansi.mjs';
5
6
 
6
7
  const VALID_TTY_RE = /^(?:tty[a-z0-9]+|pts\/\d+)$/i;
@@ -41,8 +42,8 @@ export function buildTabTitle(
41
42
  ) {
42
43
  const source = config.tabTitleSource || 'auto';
43
44
  const maxCols = config.tabTitleMaxLen || 26;
44
- const isBusy = ['working', 'tool_use', 'thinking'].includes(payload?.agent_state);
45
- const prefix = isBusy ? '● ' : '✓ ';
45
+ const activity = classifyAgentActivity(payload);
46
+ const prefix = activity.tabPrefix;
46
47
 
47
48
  const rawCwd = payload?.workspace?.current_dir || payload?.cwd || '';
48
49
  const dirName = rawCwd ? sanitizeText(basename(rawCwd)) : '';
package/src/telemetry.mjs CHANGED
@@ -2,13 +2,12 @@ import { createHash } from 'node:crypto';
2
2
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, join } from 'node:path';
5
+ import { classifyAgentActivity } from './agent-state.mjs';
5
6
  import { sanitizeText } from './ansi.mjs';
6
7
  import { configDir } from './config.mjs';
7
8
  import { writeFileAtomic } from './fs-atomic.mjs';
8
9
  import { estimateCost } from './pricing.mjs';
9
10
 
10
- const BUSY_STATES = new Set(['working', 'tool_use', 'thinking']);
11
-
12
11
  function nonNeg(value) {
13
12
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
14
13
  }
@@ -188,12 +187,13 @@ export function recordTelemetry(
188
187
  const curCacheRead = nonNeg(usage?.cache_read_input_tokens) ?? 0;
189
188
  const curCacheWrite = nonNeg(usage?.cache_creation_input_tokens) ?? 0;
190
189
 
191
- const isBusy = BUSY_STATES.has(p.agent_state);
192
- const wasBusy = Boolean(prev?.isBusy);
190
+ const activity = classifyAgentActivity(p);
191
+ const isMainBusy = activity.isMainBusy;
192
+ const wasMainBusy = Boolean(prev?.isMainBusy ?? (prev?.activityKind ? prev.activityKind === 'working' : prev?.isBusy));
193
193
 
194
194
  let turnStartedAt = prev?.turnStartedAt ?? null;
195
195
  let turnFirstTokenAt = prev?.turnFirstTokenAt ?? null;
196
- if (isBusy && (!wasBusy || turnStartedAt === null)) {
196
+ if (isMainBusy && (!wasMainBusy || turnStartedAt === null)) {
197
197
  turnStartedAt = now;
198
198
  turnFirstTokenAt = null;
199
199
  }
@@ -363,13 +363,13 @@ export function recordTelemetry(
363
363
  }
364
364
  }
365
365
 
366
- if (!isBusy) {
366
+ if (!isMainBusy) {
367
367
  turnStartedAt = null;
368
368
  turnFirstTokenAt = null;
369
369
  }
370
370
 
371
371
  const turnElapsedSec =
372
- isBusy && turnStartedAt !== null && now >= turnStartedAt ? Math.floor((now - turnStartedAt) / 1000) : null;
372
+ isMainBusy && turnStartedAt !== null && now >= turnStartedAt ? Math.floor((now - turnStartedAt) / 1000) : null;
373
373
 
374
374
  const cwd = p.workspace?.current_dir || p.cwd || prev?.cwd || null;
375
375
  const cacheTtlMs = Math.max(30, cacheTtlSec) * 1000;
@@ -399,7 +399,13 @@ export function recordTelemetry(
399
399
  gitCheckedAt: git?.dirtyChecked ? now : prev?.gitCheckedAt ?? null,
400
400
  dbStamp: stepTiming?.dbStamp ?? prev?.dbStamp ?? null,
401
401
  agentState: sanitizeText(p.agent_state || '') || 'idle',
402
- isBusy,
402
+ activityKind: activity.kind,
403
+ needsAttention: activity.needsAttention,
404
+ runningSubagents: activity.runningSubagents,
405
+ runningTasks: activity.runningTasks,
406
+ toolConfirmationPending: activity.confirmPending,
407
+ isMainBusy,
408
+ isBusy: activity.isActive,
403
409
  conversationTitle,
404
410
  customTitle,
405
411
  customTitleBase,