cursor-usage 0.2.1__tar.gz → 0.3.0__tar.gz

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.
Files changed (29) hide show
  1. cursor_usage-0.3.0/PKG-INFO +273 -0
  2. cursor_usage-0.3.0/README.md +250 -0
  3. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/pyproject.toml +3 -3
  4. cursor_usage-0.3.0/src/cursor_usage/__init__.py +3 -0
  5. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage/__main__.py +2 -0
  6. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage/api.py +24 -8
  7. cursor_usage-0.3.0/src/cursor_usage/auth.py +371 -0
  8. cursor_usage-0.3.0/src/cursor_usage/cli.py +183 -0
  9. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage/report.py +45 -19
  10. cursor_usage-0.3.0/src/cursor_usage.egg-info/PKG-INFO +273 -0
  11. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage.egg-info/SOURCES.txt +2 -0
  12. cursor_usage-0.3.0/tests/test_api.py +29 -0
  13. cursor_usage-0.3.0/tests/test_auth.py +370 -0
  14. cursor_usage-0.3.0/tests/test_cli.py +304 -0
  15. cursor_usage-0.2.1/PKG-INFO +0 -218
  16. cursor_usage-0.2.1/README.md +0 -195
  17. cursor_usage-0.2.1/src/cursor_usage/__init__.py +0 -3
  18. cursor_usage-0.2.1/src/cursor_usage/auth.py +0 -209
  19. cursor_usage-0.2.1/src/cursor_usage/cli.py +0 -168
  20. cursor_usage-0.2.1/src/cursor_usage.egg-info/PKG-INFO +0 -218
  21. cursor_usage-0.2.1/tests/test_auth.py +0 -52
  22. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/LICENSE +0 -0
  23. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/setup.cfg +0 -0
  24. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage.egg-info/dependency_links.txt +0 -0
  25. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage.egg-info/entry_points.txt +0 -0
  26. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage.egg-info/requires.txt +0 -0
  27. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/src/cursor_usage.egg-info/top_level.txt +0 -0
  28. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/tests/test_limits.py +0 -0
  29. {cursor_usage-0.2.1 → cursor_usage-0.3.0}/tests/test_report.py +0 -0
@@ -0,0 +1,273 @@
1
+ Metadata-Version: 2.4
2
+ Name: cursor-usage
3
+ Version: 0.3.0
4
+ Summary: CLI for Cursor usage, spend and cycle limits, with per-day breakdowns, CSV export and warning thresholds.
5
+ Author: cursor-usage contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/javaisbetterthanpython/cursor-usage
8
+ Project-URL: Issues, https://github.com/javaisbetterthanpython/cursor-usage/issues
9
+ Keywords: cursor,usage,spend,cli,ai,tokens,llm,rate-limit,subscription
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Utilities
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: keyring
21
+ Requires-Dist: keyring>=24; extra == "keyring"
22
+ Dynamic: license-file
23
+
24
+ <h1 align="center">📊 cursor-usage</h1>
25
+
26
+ <p align="center">
27
+ <b>Your Cursor usage, spend, and cycle limits — right from your terminal.</b>
28
+ </p>
29
+
30
+ <p align="center">
31
+ <a href="https://pypi.org/project/cursor-usage/"><img alt="PyPI" src="https://img.shields.io/pypi/v/cursor-usage?color=blue&label=PyPI"></a>
32
+ <img alt="Python" src="https://img.shields.io/badge/python-3.8%2B-blue">
33
+ <img alt="Platforms" src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey">
34
+ <img alt="Dependencies" src="https://img.shields.io/badge/dependencies-zero-brightgreen">
35
+ <img alt="License" src="https://img.shields.io/badge/license-MIT-green">
36
+ </p>
37
+
38
+ <p align="center">
39
+ <img src="https://raw.githubusercontent.com/javaisbetterthanpython/cursor-usage/main/docs/demo.gif" alt="cursor-usage demo" width="760">
40
+ </p>
41
+
42
+ ---
43
+
44
+ Cursor shows your usage only on its web dashboard. **`cursor-usage` gives you
45
+ usage, spend, and cycle limits from the shell** — for scripts, hooks, and AI agents
46
+ deciding when to back off, plus per-day reports and CSV exports. It uses the Cursor
47
+ session already on your machine.
48
+
49
+ ```text
50
+ $ cursor-usage --format short
51
+ composer 37% · other 12%
52
+ ```
53
+
54
+ ## ✨ Features
55
+
56
+ - **📊 Usage and spend** — per-model tokens and compute value for the current billing month or a custom time window.
57
+ - **📈 Cycle limits** — percentages used and remaining for Composer / Auto and Other models, plus included spend and the reset date when reported.
58
+ - **🚦 Thresholds for scripts** — `--warn [N]` exits 1 when either cycle bucket reaches N%.
59
+ - **📅 Per-day breakdown** — `--by-day` groups usage events by local calendar day.
60
+ - **💾 CSV export** — `--csv` saves individual events with timestamps, models, tokens, and cost.
61
+ - **🧾 Plain, JSON, or short** — readable reports, raw data, and a one-line status.
62
+ - **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.8+.
63
+ - **🔋 Zero dependencies** — pure Python standard library.
64
+ - **🔒 Local & private** — reads your existing Cursor session and sends it only to Cursor.
65
+
66
+ ## 🚀 Quickstart
67
+
68
+ ```bash
69
+ pip install cursor-usage
70
+ cursor-usage
71
+ ```
72
+
73
+ Run `cursor-agent login`, sign in at `cursor.com` in Firefox, or use an existing
74
+ Cursor app session on this machine.
75
+
76
+ ## 🧑‍💻 Usage
77
+
78
+ | Command | What it does |
79
+ |---|---|
80
+ | `cursor-usage` | Usage summary for the current billing month and cycle limits when available |
81
+ | `cursor-usage --by-day` | Add a per-day breakdown in plain format |
82
+ | `cursor-usage --csv FILE` | Export usage events in the selected window to CSV in plain format |
83
+ | `cursor-usage --days N` | Show usage from the last N days |
84
+ | `cursor-usage --month YYYY-MM` | Show usage from a specific UTC calendar month, up to the current time |
85
+ | `cursor-usage --start YYYY-MM-DD` | Set the inclusive start date in UTC |
86
+ | `cursor-usage --end YYYY-MM-DD` | Set the inclusive end date in UTC |
87
+ | `cursor-usage --page-size N` | Set events per API page for `--by-day` and `--csv` (default 1000) |
88
+ | `cursor-usage --warn [N]` | Exit 1 when either cycle bucket reaches N% (default 70) |
89
+ | `cursor-usage --format {plain,json,short}` | Choose output format (default plain) |
90
+ | `cursor-usage --json` | Print raw aggregated-usage JSON (alias for `--format json`) |
91
+ | `cursor-usage --limits-json` | Print raw current cycle-limits JSON, overriding `--format` |
92
+ | `cursor-usage -v`, `--verbose` | Log the credential source, expiry, rejections, and optional limits failures to stderr |
93
+ | `cursor-usage -V`, `--version` | Print the version |
94
+ | `cursor-usage -h`, `--help` | Show help |
95
+
96
+ Combine flags with a command such as `cursor-usage --by-day --csv june.csv --month 2026-06`.
97
+ When both `--json` and `--format` appear, the last one wins. The usage start
98
+ comes from `--start`, then `--days` (counting back from now), then `--month`,
99
+ then the current billing month. `--end` overrides the end boundary. After
100
+ validating the session, short format and `--limits-json` fetch cycle limits.
101
+ Cycle limits and warnings always use the current billing cycle.
102
+
103
+ <details>
104
+ <summary><b>📊 Example: <code>cursor-usage</code></b></summary>
105
+
106
+ ```text
107
+ ==============================================================================
108
+ CURSOR USAGE | you@example.com | 2026-06-04 -> 2026-06-09
109
+ ==============================================================================
110
+ Included value used : $875.81 (compute consumed; included in plan)
111
+ Tokens in=126,033,860 out=18,989,068
112
+ cacheRead=2,492,781,450 cacheWrite=8,322,520
113
+ ------------------------------------------------------------------------------
114
+ model $ value in tok out tok
115
+ ------------------------------------------------------------------------------
116
+ composer-2.5 460.14 95,638,983 13,315,470
117
+ claude-4.6-opus-high 233.71 786,434 1,059,451
118
+ gemini-3.5-flash 45.77 16,097,065 1,075,904
119
+ gpt-5.4-high 43.65 4,069,043 1,041,967
120
+ ...
121
+
122
+ ==============================================================================
123
+ CURSOR CYCLE LIMITS | resets 2026-07-04
124
+ ==============================================================================
125
+ Composer / Auto [###########...................] 36.7% used, 63.3% left
126
+ Other models [####..........................] 12.4% used, 87.6% left
127
+ Included usage $146.80 of $400.00 used ($253.20 left)
128
+ ```
129
+ </details>
130
+
131
+ <details>
132
+ <summary><b>📅 Example: <code>--by-day</code></b></summary>
133
+
134
+ ```text
135
+ ==============================================================================
136
+ CURSOR USAGE BY DAY | you@example.com | 2026-06-04 -> 2026-06-09
137
+ ==============================================================================
138
+ date events $ value in tok out tok
139
+ ------------------------------------------------------------------------------
140
+ 2026-06-04 433 324.46 38,602,275 6,080,617
141
+ 2026-06-05 368 252.58 40,616,543 6,469,309
142
+ 2026-06-06 416 121.06 29,686,247 4,497,010
143
+ 2026-06-07 444 177.71 17,128,795 1,942,132
144
+ ------------------------------------------------------------------------------
145
+ TOTAL 1,661 875.81 126,033,860 18,989,068
146
+ ```
147
+ </details>
148
+
149
+ <details>
150
+ <summary><b>💾 Example: <code>--csv usage.csv</code></b></summary>
151
+
152
+ The CSV has one row per usage event, sorted by timestamp.
153
+
154
+ ```text
155
+ datetime_local,timestamp_ms,date,model,kind,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,value_cents,charged_cents,requests_costs,is_headless,owning_user
156
+ ```
157
+ </details>
158
+
159
+ ## 🤖 Using it from scripts and agents
160
+
161
+ ```bash
162
+ cursor-usage --warn 70 || echo "back off"
163
+ cursor-usage --format short
164
+ cursor-usage --json
165
+ ```
166
+
167
+ The threshold check uses the reported percentages before rounding. An exact
168
+ match triggers the warning. One reported percentage is enough to check the
169
+ threshold. If both endpoints lack usable percentages, `--warn` reports an
170
+ error unless the plan reports unlimited usage. Short format rounds to whole
171
+ percentages and displays `unlimited` for an unlimited plan.
172
+
173
+ The command exits **0** on success, **1** when the threshold is reached or an
174
+ API or data error occurs, and **2** for invalid arguments or when no session
175
+ can be authenticated. A threshold match leaves the
176
+ requested output on stdout. Diagnostics go to stderr.
177
+
178
+ ## 🤔 How it works
179
+
180
+ The CLI finds your local Cursor web session and asks Cursor's dashboard API for
181
+ usage. The aggregated endpoint provides per-model totals. Cycle limits come
182
+ from the current-period endpoint, with the usage-summary endpoint as a
183
+ fallback. Per-day and CSV reports fetch the per-event log in pages.
184
+
185
+ The CLI collects sessions from all available sources and tries them in this
186
+ priority order. Within each group, it tries the latest expiry first.
187
+
188
+ 1. **Overrides** from `CURSOR_SESSION_TOKEN` and the session file. Set
189
+ `CURSOR_USAGE_SESSION_FILE` to choose the file path. The default is
190
+ `~/.config/cursor-usage/session` on macOS and Linux or
191
+ `%APPDATA%/cursor-usage/session` on Windows. On macOS and Linux, use
192
+ `chmod 600` on the file. The CLI skips files readable by group or others.
193
+ 2. **Saved sign-ins** from macOS Keychain, the `cursor-agent login` file, and
194
+ the optional OS keyring. On Linux, the login file is
195
+ `$XDG_CONFIG_HOME/cursor/auth.json` or `~/.config/cursor/auth.json` by
196
+ default. On Windows, the CLI tries `%APPDATA%/cursor/auth.json` when
197
+ available. OS keyring lookup waits up to five seconds.
198
+ 3. **Firefox** dashboard cookies across profiles, including Snap on Linux.
199
+ 4. **Cursor or Cursor Nightly** sessions from the app's SQLite state database.
200
+
201
+ The CLI skips Agent API tokens, encrypted or invalid credentials, and sessions
202
+ that expire within 60 seconds. It checks each distinct candidate once against
203
+ Cursor's identity endpoint and falls through if Cursor rejects it. With `-v`,
204
+ the CLI reports rejections and the source and UTC expiry of the accepted
205
+ session. If no session works, it lists each source's status and suggests
206
+ `cursor-agent login`.
207
+
208
+ For manual setup, open the Cursor dashboard in your browser and look under
209
+ Application or Storage in developer tools for the `WorkosCursorSessionToken`
210
+ cookie. The environment override and session file accept the cookie value
211
+ (`id::jwt`, including its URL-encoded form) or a raw session JWT. Put just the
212
+ value in the file. In Bash, you can set the environment override without
213
+ displaying the value or adding it to shell history.
214
+
215
+ ```bash
216
+ read -rs CURSOR_SESSION_TOKEN
217
+ export CURSOR_SESSION_TOKEN
218
+ cursor-usage
219
+ unset CURSOR_SESSION_TOKEN
220
+ ```
221
+
222
+ For the protocol and a recipe to rebuild the tool, see
223
+ **[docs/HOW_THIS_WAS_BUILT.md](docs/HOW_THIS_WAS_BUILT.md)**.
224
+
225
+ ## 🔒 Privacy & security
226
+
227
+ - Reads your existing local session. The Firefox lookup uses a private temporary
228
+ copy of the cookie database and its write-ahead log, then removes the copy.
229
+ - Sends the session cookie only to **`cursor.com`**. HTTP redirects are blocked.
230
+ - Keeps the session out of output and errors, including with `-v`.
231
+ - CSV exports contain your usage data. Git ignores `*.csv` in this repo.
232
+ - **No telemetry. No third-party calls.**
233
+
234
+ ## ⚠️ Good to know
235
+
236
+ - **`$ value` measures compute consumed.** With usage-based pricing off, the flat subscription covers those figures.
237
+ - The dashboard API is **undocumented** and Cursor may change it.
238
+ - Personal Cursor API keys authenticate the Agent API. Usage requires a Cursor web session.
239
+ - If your session expires, sign back in at `cursor.com`. Refresh any session
240
+ value you supplied manually before running the command again.
241
+
242
+ ## 🛠️ Install options
243
+
244
+ ```bash
245
+ pip install cursor-usage # from PyPI
246
+ pipx install cursor-usage # isolated command installation
247
+ pip install . # from a local clone
248
+ pip install "cursor-usage[keyring]" # optional OS keyring lookup
249
+ ```
250
+
251
+ Requires Python 3.8+.
252
+
253
+ ## 🤝 Contributing
254
+
255
+ Issues and PRs are welcome. After installing the local project with `pip install -e .`,
256
+ run the tests with:
257
+
258
+ ```bash
259
+ pip install pytest && pytest -q
260
+ ```
261
+
262
+ Tests use temporary files and mocked HTTP; they never contact the endpoint or
263
+ read your real credentials.
264
+
265
+ Regenerate the demo with `python3 docs/record_demo.py` after installing
266
+ [agg](https://github.com/asciinema/agg/releases) and the DejaVu Sans Mono font.
267
+ The recorder runs the CLI against illustrative responses with HTTP disabled.
268
+ Set `CURSOR_USAGE_DEMO_FONT_DIR` if the font is outside agg's font search path.
269
+ The README embeds the resulting `docs/demo.gif`.
270
+
271
+ ## 📄 License
272
+
273
+ [MIT](LICENSE) — do whatever you like.
@@ -0,0 +1,250 @@
1
+ <h1 align="center">📊 cursor-usage</h1>
2
+
3
+ <p align="center">
4
+ <b>Your Cursor usage, spend, and cycle limits — right from your terminal.</b>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://pypi.org/project/cursor-usage/"><img alt="PyPI" src="https://img.shields.io/pypi/v/cursor-usage?color=blue&label=PyPI"></a>
9
+ <img alt="Python" src="https://img.shields.io/badge/python-3.8%2B-blue">
10
+ <img alt="Platforms" src="https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey">
11
+ <img alt="Dependencies" src="https://img.shields.io/badge/dependencies-zero-brightgreen">
12
+ <img alt="License" src="https://img.shields.io/badge/license-MIT-green">
13
+ </p>
14
+
15
+ <p align="center">
16
+ <img src="https://raw.githubusercontent.com/javaisbetterthanpython/cursor-usage/main/docs/demo.gif" alt="cursor-usage demo" width="760">
17
+ </p>
18
+
19
+ ---
20
+
21
+ Cursor shows your usage only on its web dashboard. **`cursor-usage` gives you
22
+ usage, spend, and cycle limits from the shell** — for scripts, hooks, and AI agents
23
+ deciding when to back off, plus per-day reports and CSV exports. It uses the Cursor
24
+ session already on your machine.
25
+
26
+ ```text
27
+ $ cursor-usage --format short
28
+ composer 37% · other 12%
29
+ ```
30
+
31
+ ## ✨ Features
32
+
33
+ - **📊 Usage and spend** — per-model tokens and compute value for the current billing month or a custom time window.
34
+ - **📈 Cycle limits** — percentages used and remaining for Composer / Auto and Other models, plus included spend and the reset date when reported.
35
+ - **🚦 Thresholds for scripts** — `--warn [N]` exits 1 when either cycle bucket reaches N%.
36
+ - **📅 Per-day breakdown** — `--by-day` groups usage events by local calendar day.
37
+ - **💾 CSV export** — `--csv` saves individual events with timestamps, models, tokens, and cost.
38
+ - **🧾 Plain, JSON, or short** — readable reports, raw data, and a one-line status.
39
+ - **🌍 Cross-platform** — macOS, Linux, and Windows; Python 3.8+.
40
+ - **🔋 Zero dependencies** — pure Python standard library.
41
+ - **🔒 Local & private** — reads your existing Cursor session and sends it only to Cursor.
42
+
43
+ ## 🚀 Quickstart
44
+
45
+ ```bash
46
+ pip install cursor-usage
47
+ cursor-usage
48
+ ```
49
+
50
+ Run `cursor-agent login`, sign in at `cursor.com` in Firefox, or use an existing
51
+ Cursor app session on this machine.
52
+
53
+ ## 🧑‍💻 Usage
54
+
55
+ | Command | What it does |
56
+ |---|---|
57
+ | `cursor-usage` | Usage summary for the current billing month and cycle limits when available |
58
+ | `cursor-usage --by-day` | Add a per-day breakdown in plain format |
59
+ | `cursor-usage --csv FILE` | Export usage events in the selected window to CSV in plain format |
60
+ | `cursor-usage --days N` | Show usage from the last N days |
61
+ | `cursor-usage --month YYYY-MM` | Show usage from a specific UTC calendar month, up to the current time |
62
+ | `cursor-usage --start YYYY-MM-DD` | Set the inclusive start date in UTC |
63
+ | `cursor-usage --end YYYY-MM-DD` | Set the inclusive end date in UTC |
64
+ | `cursor-usage --page-size N` | Set events per API page for `--by-day` and `--csv` (default 1000) |
65
+ | `cursor-usage --warn [N]` | Exit 1 when either cycle bucket reaches N% (default 70) |
66
+ | `cursor-usage --format {plain,json,short}` | Choose output format (default plain) |
67
+ | `cursor-usage --json` | Print raw aggregated-usage JSON (alias for `--format json`) |
68
+ | `cursor-usage --limits-json` | Print raw current cycle-limits JSON, overriding `--format` |
69
+ | `cursor-usage -v`, `--verbose` | Log the credential source, expiry, rejections, and optional limits failures to stderr |
70
+ | `cursor-usage -V`, `--version` | Print the version |
71
+ | `cursor-usage -h`, `--help` | Show help |
72
+
73
+ Combine flags with a command such as `cursor-usage --by-day --csv june.csv --month 2026-06`.
74
+ When both `--json` and `--format` appear, the last one wins. The usage start
75
+ comes from `--start`, then `--days` (counting back from now), then `--month`,
76
+ then the current billing month. `--end` overrides the end boundary. After
77
+ validating the session, short format and `--limits-json` fetch cycle limits.
78
+ Cycle limits and warnings always use the current billing cycle.
79
+
80
+ <details>
81
+ <summary><b>📊 Example: <code>cursor-usage</code></b></summary>
82
+
83
+ ```text
84
+ ==============================================================================
85
+ CURSOR USAGE | you@example.com | 2026-06-04 -> 2026-06-09
86
+ ==============================================================================
87
+ Included value used : $875.81 (compute consumed; included in plan)
88
+ Tokens in=126,033,860 out=18,989,068
89
+ cacheRead=2,492,781,450 cacheWrite=8,322,520
90
+ ------------------------------------------------------------------------------
91
+ model $ value in tok out tok
92
+ ------------------------------------------------------------------------------
93
+ composer-2.5 460.14 95,638,983 13,315,470
94
+ claude-4.6-opus-high 233.71 786,434 1,059,451
95
+ gemini-3.5-flash 45.77 16,097,065 1,075,904
96
+ gpt-5.4-high 43.65 4,069,043 1,041,967
97
+ ...
98
+
99
+ ==============================================================================
100
+ CURSOR CYCLE LIMITS | resets 2026-07-04
101
+ ==============================================================================
102
+ Composer / Auto [###########...................] 36.7% used, 63.3% left
103
+ Other models [####..........................] 12.4% used, 87.6% left
104
+ Included usage $146.80 of $400.00 used ($253.20 left)
105
+ ```
106
+ </details>
107
+
108
+ <details>
109
+ <summary><b>📅 Example: <code>--by-day</code></b></summary>
110
+
111
+ ```text
112
+ ==============================================================================
113
+ CURSOR USAGE BY DAY | you@example.com | 2026-06-04 -> 2026-06-09
114
+ ==============================================================================
115
+ date events $ value in tok out tok
116
+ ------------------------------------------------------------------------------
117
+ 2026-06-04 433 324.46 38,602,275 6,080,617
118
+ 2026-06-05 368 252.58 40,616,543 6,469,309
119
+ 2026-06-06 416 121.06 29,686,247 4,497,010
120
+ 2026-06-07 444 177.71 17,128,795 1,942,132
121
+ ------------------------------------------------------------------------------
122
+ TOTAL 1,661 875.81 126,033,860 18,989,068
123
+ ```
124
+ </details>
125
+
126
+ <details>
127
+ <summary><b>💾 Example: <code>--csv usage.csv</code></b></summary>
128
+
129
+ The CSV has one row per usage event, sorted by timestamp.
130
+
131
+ ```text
132
+ datetime_local,timestamp_ms,date,model,kind,input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,value_cents,charged_cents,requests_costs,is_headless,owning_user
133
+ ```
134
+ </details>
135
+
136
+ ## 🤖 Using it from scripts and agents
137
+
138
+ ```bash
139
+ cursor-usage --warn 70 || echo "back off"
140
+ cursor-usage --format short
141
+ cursor-usage --json
142
+ ```
143
+
144
+ The threshold check uses the reported percentages before rounding. An exact
145
+ match triggers the warning. One reported percentage is enough to check the
146
+ threshold. If both endpoints lack usable percentages, `--warn` reports an
147
+ error unless the plan reports unlimited usage. Short format rounds to whole
148
+ percentages and displays `unlimited` for an unlimited plan.
149
+
150
+ The command exits **0** on success, **1** when the threshold is reached or an
151
+ API or data error occurs, and **2** for invalid arguments or when no session
152
+ can be authenticated. A threshold match leaves the
153
+ requested output on stdout. Diagnostics go to stderr.
154
+
155
+ ## 🤔 How it works
156
+
157
+ The CLI finds your local Cursor web session and asks Cursor's dashboard API for
158
+ usage. The aggregated endpoint provides per-model totals. Cycle limits come
159
+ from the current-period endpoint, with the usage-summary endpoint as a
160
+ fallback. Per-day and CSV reports fetch the per-event log in pages.
161
+
162
+ The CLI collects sessions from all available sources and tries them in this
163
+ priority order. Within each group, it tries the latest expiry first.
164
+
165
+ 1. **Overrides** from `CURSOR_SESSION_TOKEN` and the session file. Set
166
+ `CURSOR_USAGE_SESSION_FILE` to choose the file path. The default is
167
+ `~/.config/cursor-usage/session` on macOS and Linux or
168
+ `%APPDATA%/cursor-usage/session` on Windows. On macOS and Linux, use
169
+ `chmod 600` on the file. The CLI skips files readable by group or others.
170
+ 2. **Saved sign-ins** from macOS Keychain, the `cursor-agent login` file, and
171
+ the optional OS keyring. On Linux, the login file is
172
+ `$XDG_CONFIG_HOME/cursor/auth.json` or `~/.config/cursor/auth.json` by
173
+ default. On Windows, the CLI tries `%APPDATA%/cursor/auth.json` when
174
+ available. OS keyring lookup waits up to five seconds.
175
+ 3. **Firefox** dashboard cookies across profiles, including Snap on Linux.
176
+ 4. **Cursor or Cursor Nightly** sessions from the app's SQLite state database.
177
+
178
+ The CLI skips Agent API tokens, encrypted or invalid credentials, and sessions
179
+ that expire within 60 seconds. It checks each distinct candidate once against
180
+ Cursor's identity endpoint and falls through if Cursor rejects it. With `-v`,
181
+ the CLI reports rejections and the source and UTC expiry of the accepted
182
+ session. If no session works, it lists each source's status and suggests
183
+ `cursor-agent login`.
184
+
185
+ For manual setup, open the Cursor dashboard in your browser and look under
186
+ Application or Storage in developer tools for the `WorkosCursorSessionToken`
187
+ cookie. The environment override and session file accept the cookie value
188
+ (`id::jwt`, including its URL-encoded form) or a raw session JWT. Put just the
189
+ value in the file. In Bash, you can set the environment override without
190
+ displaying the value or adding it to shell history.
191
+
192
+ ```bash
193
+ read -rs CURSOR_SESSION_TOKEN
194
+ export CURSOR_SESSION_TOKEN
195
+ cursor-usage
196
+ unset CURSOR_SESSION_TOKEN
197
+ ```
198
+
199
+ For the protocol and a recipe to rebuild the tool, see
200
+ **[docs/HOW_THIS_WAS_BUILT.md](docs/HOW_THIS_WAS_BUILT.md)**.
201
+
202
+ ## 🔒 Privacy & security
203
+
204
+ - Reads your existing local session. The Firefox lookup uses a private temporary
205
+ copy of the cookie database and its write-ahead log, then removes the copy.
206
+ - Sends the session cookie only to **`cursor.com`**. HTTP redirects are blocked.
207
+ - Keeps the session out of output and errors, including with `-v`.
208
+ - CSV exports contain your usage data. Git ignores `*.csv` in this repo.
209
+ - **No telemetry. No third-party calls.**
210
+
211
+ ## ⚠️ Good to know
212
+
213
+ - **`$ value` measures compute consumed.** With usage-based pricing off, the flat subscription covers those figures.
214
+ - The dashboard API is **undocumented** and Cursor may change it.
215
+ - Personal Cursor API keys authenticate the Agent API. Usage requires a Cursor web session.
216
+ - If your session expires, sign back in at `cursor.com`. Refresh any session
217
+ value you supplied manually before running the command again.
218
+
219
+ ## 🛠️ Install options
220
+
221
+ ```bash
222
+ pip install cursor-usage # from PyPI
223
+ pipx install cursor-usage # isolated command installation
224
+ pip install . # from a local clone
225
+ pip install "cursor-usage[keyring]" # optional OS keyring lookup
226
+ ```
227
+
228
+ Requires Python 3.8+.
229
+
230
+ ## 🤝 Contributing
231
+
232
+ Issues and PRs are welcome. After installing the local project with `pip install -e .`,
233
+ run the tests with:
234
+
235
+ ```bash
236
+ pip install pytest && pytest -q
237
+ ```
238
+
239
+ Tests use temporary files and mocked HTTP; they never contact the endpoint or
240
+ read your real credentials.
241
+
242
+ Regenerate the demo with `python3 docs/record_demo.py` after installing
243
+ [agg](https://github.com/asciinema/agg/releases) and the DejaVu Sans Mono font.
244
+ The recorder runs the CLI against illustrative responses with HTTP disabled.
245
+ Set `CURSOR_USAGE_DEMO_FONT_DIR` if the font is outside agg's font search path.
246
+ The README embeds the resulting `docs/demo.gif`.
247
+
248
+ ## 📄 License
249
+
250
+ [MIT](LICENSE) — do whatever you like.
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cursor-usage"
7
- version = "0.2.1"
8
- description = "Cross-platform CLI to read your Cursor (cursor.com) usage, spend, and per-event logs."
7
+ version = "0.3.0"
8
+ description = "CLI for Cursor usage, spend and cycle limits, with per-day breakdowns, CSV export and warning thresholds."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
11
11
  requires-python = ">=3.8"
12
12
  authors = [{ name = "cursor-usage contributors" }]
13
- keywords = ["cursor", "usage", "spend", "cli", "ai", "tokens", "llm"]
13
+ keywords = ["cursor", "usage", "spend", "cli", "ai", "tokens", "llm", "rate-limit", "subscription"]
14
14
  classifiers = [
15
15
  "Development Status :: 4 - Beta",
16
16
  "Environment :: Console",
@@ -0,0 +1,3 @@
1
+ """cursor-usage: read your Cursor usage, spend and cycle limits."""
2
+
3
+ __version__ = "0.3.0"
@@ -1,3 +1,5 @@
1
+ """Run cursor-usage with ``python -m cursor_usage``."""
2
+
1
3
  import sys
2
4
 
3
5
  from .cli import main
@@ -13,6 +13,7 @@ Auth is the ``WorkosCursorSessionToken`` cookie, value ``<sub>::<jwt>`` (the ``:
13
13
  is sent URL-encoded as ``%3A%3A``).
14
14
  """
15
15
 
16
+ import http.client
16
17
  import json
17
18
  import urllib.error
18
19
  import urllib.request
@@ -24,10 +25,16 @@ USER_AGENT = "cursor-usage/%s" % __version__
24
25
 
25
26
 
26
27
  class CursorAPIError(RuntimeError):
27
- def __init__(self, status, body):
28
+ def __init__(self, status, url):
28
29
  self.status = status
29
- self.body = body
30
- super().__init__("HTTP %s: %s" % (status, body[:300]))
30
+ hint = "; sign in to Cursor again" if status in (401, 403) else ""
31
+ super().__init__(f"HTTP {status} from {url}{hint}")
32
+
33
+
34
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
35
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
36
+ # urllib otherwise forwards the Cookie header to redirect targets.
37
+ return None
31
38
 
32
39
 
33
40
  class CursorClient:
@@ -46,13 +53,22 @@ class CursorClient:
46
53
  data = json.dumps(body).encode("utf-8")
47
54
  headers["Content-Type"] = "application/json"
48
55
  headers["Origin"] = BASE # required: dashboard CSRF check
49
- req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
56
+ url = BASE + path
57
+ endpoint = url.split("?", 1)[0]
50
58
  try:
51
- with urllib.request.urlopen(req, timeout=self._timeout) as resp:
52
- raw = resp.read().decode("utf-8", "ignore")
59
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
60
+ opener = urllib.request.build_opener(_NoRedirect())
61
+ with opener.open(req, timeout=self._timeout) as resp:
62
+ raw = resp.read()
63
+ return json.loads(raw) if raw else {}
53
64
  except urllib.error.HTTPError as exc:
54
- raise CursorAPIError(exc.code, exc.read().decode("utf-8", "ignore"))
55
- return json.loads(raw) if raw else {}
65
+ exc.close()
66
+ raise CursorAPIError(exc.code, endpoint) from None
67
+ except (OSError, http.client.HTTPException):
68
+ raise RuntimeError(f"could not reach {endpoint}") from None
69
+ except (ValueError, TypeError):
70
+ # An invalid header can appear verbatim in the library error.
71
+ raise RuntimeError(f"invalid request or JSON response from {endpoint}") from None
56
72
 
57
73
  # -- endpoints ---------------------------------------------------------
58
74
  def me(self):