llmtop 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +259 -2
  3. package/bin/llmtop.mjs +101 -0
  4. package/dashboard/dist/apple-touch-icon.png +0 -0
  5. package/dashboard/dist/assets/index-BVbAwMVB.js +9 -0
  6. package/dashboard/dist/assets/index-Cp7Swcz5.css +1 -0
  7. package/dashboard/dist/assets/llmtop-lockup-DtFPJmhv.svg +1 -0
  8. package/dashboard/dist/assets/llmtop-lockup-reversed-D9OmQIVU.svg +1 -0
  9. package/dashboard/dist/favicon.ico +0 -0
  10. package/dashboard/dist/favicon.svg +1 -0
  11. package/dashboard/dist/index.html +19 -0
  12. package/dashboard/dist/llmtop-mark-192.png +0 -0
  13. package/dashboard/dist/llmtop-mark-512.png +0 -0
  14. package/dashboard/dist/site.webmanifest +11 -0
  15. package/dashboard/src/App.tsx +213 -0
  16. package/dashboard/src/controls/DateRange.tsx +108 -0
  17. package/dashboard/src/controls/Disclosure.tsx +15 -0
  18. package/dashboard/src/controls/Search.tsx +18 -0
  19. package/dashboard/src/controls/Select.tsx +48 -0
  20. package/dashboard/src/controls/popover.tsx +31 -0
  21. package/dashboard/src/dash.ts +23 -0
  22. package/dashboard/src/extra.test.ts +9 -0
  23. package/dashboard/src/extra.ts +16 -0
  24. package/dashboard/src/format.ts +29 -0
  25. package/dashboard/src/i18n.tsx +52 -0
  26. package/dashboard/src/index.ts +7 -0
  27. package/dashboard/src/main.tsx +7 -0
  28. package/dashboard/src/model.test.ts +110 -0
  29. package/dashboard/src/model.ts +255 -0
  30. package/dashboard/src/state.test.ts +48 -0
  31. package/dashboard/src/state.ts +61 -0
  32. package/dashboard/src/styles.css +401 -0
  33. package/dashboard/src/tip.ts +51 -0
  34. package/dashboard/src/treemap.test.ts +23 -0
  35. package/dashboard/src/treemap.ts +30 -0
  36. package/dashboard/src/ui.tsx +327 -0
  37. package/dashboard/src/views/Activity.tsx +177 -0
  38. package/dashboard/src/views/Context.tsx +183 -0
  39. package/dashboard/src/views/Models.tsx +155 -0
  40. package/dashboard/src/views/Overview.tsx +83 -0
  41. package/dashboard/src/views/Projects.tsx +116 -0
  42. package/dashboard/src/views/Sessions.tsx +54 -0
  43. package/dashboard/src/views/Subagents.tsx +102 -0
  44. package/docs/brand/README.md +91 -0
  45. package/docs/brand/brand.json +67 -0
  46. package/docs/brand/favicon.ico +0 -0
  47. package/docs/brand/png/apple-touch-icon.png +0 -0
  48. package/docs/brand/png/favicon-16.png +0 -0
  49. package/docs/brand/png/favicon-32.png +0 -0
  50. package/docs/brand/png/favicon-48.png +0 -0
  51. package/docs/brand/png/llmtop-lockup-reversed@2x.png +0 -0
  52. package/docs/brand/png/llmtop-lockup@2x.png +0 -0
  53. package/docs/brand/png/llmtop-mark-1024.png +0 -0
  54. package/docs/brand/png/llmtop-mark-192.png +0 -0
  55. package/docs/brand/png/llmtop-mark-512.png +0 -0
  56. package/docs/brand/png/llmtop-wordmark@2x.png +0 -0
  57. package/docs/brand/source/build_brand.py +173 -0
  58. package/docs/brand/svg/favicon.svg +1 -0
  59. package/docs/brand/svg/llmtop-glyph.svg +1 -0
  60. package/docs/brand/svg/llmtop-lockup-reversed.svg +1 -0
  61. package/docs/brand/svg/llmtop-lockup.svg +1 -0
  62. package/docs/brand/svg/llmtop-mark-light.svg +1 -0
  63. package/docs/brand/svg/llmtop-mark.svg +1 -0
  64. package/docs/brand/svg/llmtop-wordmark-reversed.svg +1 -0
  65. package/docs/brand/svg/llmtop-wordmark.svg +1 -0
  66. package/llmtop.config.example.json +10 -0
  67. package/package.json +71 -4
  68. package/prices.md +27 -0
  69. package/src/api.mjs +53 -0
  70. package/src/archive.mjs +142 -0
  71. package/src/config.mjs +55 -0
  72. package/src/context.mjs +151 -0
  73. package/src/dashboard.mjs +61 -0
  74. package/src/db.mjs +102 -0
  75. package/src/derive.mjs +346 -0
  76. package/src/effort.mjs +18 -0
  77. package/src/format.mjs +19 -0
  78. package/src/paths.mjs +82 -0
  79. package/src/prices-command.mjs +25 -0
  80. package/src/prices.mjs +146 -0
  81. package/src/providers/agy.mjs +438 -0
  82. package/src/providers/claude.mjs +274 -0
  83. package/src/providers/codex.mjs +589 -0
  84. package/src/providers/index.mjs +25 -0
  85. package/src/rebuilds.mjs +85 -0
  86. package/src/scan.mjs +214 -0
  87. package/src/serve.mjs +44 -0
  88. package/src/show.mjs +20 -0
  89. package/src/usage-command.mjs +110 -0
  90. package/src/usage.mjs +388 -0
  91. package/src/zone.mjs +15 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Trung Nguyen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,260 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="docs/brand/svg/llmtop-lockup-reversed.svg">
5
+ <img alt="llmtop" src="docs/brand/svg/llmtop-lockup.svg" width="360">
6
+ </picture>
7
+
8
+ **Local usage and cost analytics for Claude Code, Codex and Antigravity**
9
+
10
+ _Transcripts are archived into SQLite and priced on your own machine. The server binds to `127.0.0.1` only, and neither the server nor the dashboard makes a network request._
11
+
12
+ [![License](https://img.shields.io/badge/license-MIT-blue)](#license)
13
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D22.15-blue)](package.json)
14
+ [![Last commit](https://img.shields.io/github/last-commit/nguyencanhtrung/llmtop)](https://github.com/nguyencanhtrung/llmtop/commits/main)
15
+
16
+ [Quickstart](#quickstart) · [Features](#features) · [Commands](#commands) · [Docs](#documentation) · [License](#license)
17
+
18
+ <picture>
19
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/overview-dark.png">
20
+ <img src="docs/assets/overview-light.png" alt="Overview dashboard showing output tokens, cost, sessions, cache reads, cache savings and output speed for the last 30 days with daily charts" width="900">
21
+ </picture>
22
+
23
+ <sub>Every figure in these screenshots is synthetic demo data served by <code>make demo</code>.</sub>
24
+
25
+ </div>
26
+
27
+ ## Overview
28
+
29
+ llmtop is a local dashboard and CLI for developers using AI coding agents. It archives local transcripts from Claude Code (`~/.claude/projects`), Codex (`~/.codex/sessions`) and Antigravity CLI (`~/.gemini/antigravity-cli`), ingests them into SQLite through `node:sqlite`, and prices every request against [prices.md](prices.md). Providers with no local transcripts are skipped automatically. Seven views and a matching CLI answer what summary totals hide: which repository costs the most, which sessions ran long, which models and subagents did the work, why the prompt cache rebuilt, and what carrying long context costs.
30
+
31
+ Nothing leaves your machine. The HTTP server binds to `127.0.0.1` only, and neither the server nor the browser app makes any outbound network request. Archives and the SQLite database live under `~/.config/llmtop/data/` by default: `archive/<provider>/` keeps an append-only copy of each transcript so history survives host deletion, while `usage.db` is disposable and rebuilt from the archive whenever the schema changes. Cost figures use list prices from [prices.md](prices.md); on a subscription plan, cost represents quota spent rather than direct billing.
32
+
33
+ ## Features
34
+
35
+ - **Multi-provider transcript archiving.** Reads Claude Code, Codex and Antigravity CLI transcripts into append-only zstd-compressed frames under `~/.config/llmtop/data/archive/<provider>/`, keeping line numbers stable so `session:line` references never drift even if the host removes old files.
36
+ - **Prompt cache rebuild analysis.** Tracks every cache rebuild, its extra write cost compared to reading, and its cause: session start, compaction, idle break past the cache lifetime (`5–15m`, `15–60m`, `>1h`), or other.
37
+ - **Context and compaction replay.** Measures what each compaction costs, breaks down context-reading cost by carried context size, and replays main conversations counterfactually to compare compaction thresholds.
38
+ - **Project cost treemap.** Groups sessions by repository (nearest `.git` directory above the session working directory, or folder name fallback) and sizes tiles by cost.
39
+ - **Model and subagent breakdown.** Reports output and thinking tokens per request, requests per owner turn, tool calls and failure share, output speed, effort-level cost, and the share of work delegated to subagents by model.
40
+ - **Sortable session explorer.** Lists every conversation with its title, length, model, cost, and cache lapse count.
41
+ - **Matching CLI and dashboard.** Provides `scan`, `show`, `usage`, `prices`, and `serve` (with `--json` on listing commands). For the same window and filters, `usage` and the dashboard report identical totals.
42
+ - **Bilingual local dashboard.** Built with Vite, React and TypeScript with automatic light/dark themes, English and Vietnamese UI strings, and zero runtime npm dependencies at install time (bundled UI assets + Node's built-in `node:sqlite`).
43
+ - **Private by default.** Serves exclusively on `127.0.0.1` with no telemetry, remote API calls, or asset CDNs.
44
+
45
+ <p align="center">
46
+ <picture>
47
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/cache-dark.png">
48
+ <img src="docs/assets/cache-light.png" alt="Activity view showing prompt cache rebuilds by cause and extra cost" width="900">
49
+ </picture>
50
+ <br>
51
+ <sub>Cache rebuilds by cause and extra cost.</sub>
52
+ </p>
53
+
54
+ <p align="center">
55
+ <picture>
56
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/context-dark.png">
57
+ <img src="docs/assets/context-light.png" alt="Context view replaying sessions with compaction at alternative thresholds against the current threshold" width="900">
58
+ </picture>
59
+ <br>
60
+ <sub>Compaction cost and counterfactual context replay across compaction points.</sub>
61
+ </p>
62
+
63
+ <p align="center">
64
+ <picture>
65
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/treemap-dark.png">
66
+ <img src="docs/assets/treemap-light.png" alt="Projects view showing a treemap of cost per repository" width="900">
67
+ </picture>
68
+ <br>
69
+ <sub>Repository cost share treemap.</sub>
70
+ </p>
71
+
72
+ <p align="center">
73
+ <picture>
74
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/models-dark.png">
75
+ <img src="docs/assets/models-light.png" alt="Subagents view showing output tokens per model for the main thread and delegated subagents" width="900">
76
+ </picture>
77
+ <br>
78
+ <sub>Main thread and subagent output by model.</sub>
79
+ </p>
80
+
81
+ <p align="center">
82
+ <picture>
83
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/sessions-dark.png">
84
+ <img src="docs/assets/sessions-light.png" alt="Sessions view showing a table of conversations sorted by cost" width="900">
85
+ </picture>
86
+ <br>
87
+ <sub>Sortable sessions table with length, model, cost and cache lapses.</sub>
88
+ </p>
89
+
90
+ ## Prerequisites
91
+
92
+ - **Node.js 22.15 or later** (required by [package.json](package.json) for built-in `node:sqlite` and zstd support) and **npm**
93
+ - **Local agent transcripts** from at least one supported tool (`~/.claude/projects`, `~/.codex/sessions`, or `~/.gemini/antigravity-cli`); optional if previewing with `make demo`
94
+ - Optional: **`make`** for convenience targets (every workflow also runs directly via `npm` and `node`)
95
+ - Optional: **Google Chrome or Chromium** only if regenerating README screenshots with `make screenshots` (set `CHROME` to override the binary path)
96
+
97
+ ## Quickstart
98
+
99
+ Install globally from npm (zero runtime dependencies):
100
+
101
+ ```bash
102
+ npm install -g llmtop
103
+ llmtop serve
104
+ ```
105
+
106
+ Or run once without installing:
107
+
108
+ ```bash
109
+ npx llmtop serve
110
+ ```
111
+
112
+ Open <http://localhost:4310>. Your first visit scans local transcripts into `~/.config/llmtop/data/`; use the Refresh button in the sidebar footer to scan again. Pass `--port <n>` to `llmtop serve` to use another port, or press `Ctrl+C` to stop.
113
+
114
+ <details>
115
+ <summary><strong>From source (development)</strong></summary>
116
+
117
+ ```bash
118
+ git clone https://github.com/nguyencanhtrung/llmtop.git
119
+ cd llmtop
120
+ make start
121
+ ```
122
+
123
+ `make start` installs dependencies via `npm ci` when needed, builds `dashboard/dist`, starts the server in the background on `http://localhost:4310` (`data/serve.pid`, `data/serve.log`), and returns once ready. Stop it anytime with `make stop`. Without `make`, run `npm install` then `npm start`.
124
+
125
+ To explore ten weeks of synthetic usage data without scanning your local transcripts, run `make demo` and open <http://localhost:4311>.
126
+
127
+ </details>
128
+
129
+ ## Commands
130
+
131
+ | CLI command | `make` target | What it does |
132
+ | --- | --- | --- |
133
+ | `llmtop serve [--port n]` | `make start` | Serve the dashboard on `http://localhost:<port>` (`make start` runs in the background) |
134
+ | | `make stop` | Stop the background server started by `make start` |
135
+ | `npm run dev` | `make dev` | Serve the dashboard with Vite hot reload in the foreground |
136
+ | `node test/fixtures/demo.mjs` | `make demo` | Serve ten weeks of synthetic demo data at `http://localhost:4311` |
137
+ | `llmtop scan` | `make scan` | Archive new transcript lines and ingest them into `usage.db` |
138
+ | `llmtop usage --days 30 --by model` | `make usage DAYS=30 BY=model` | Show tokens and cost in the terminal; `ARGS="..."` passes extra flags |
139
+ | `llmtop prices` | `make prices` | Check [prices.md](prices.md) against host-recorded session costs |
140
+ | `npm test` | `make test` | Run the `node --test` suite on synthetic data |
141
+ | `npm run check` | `make check` | Type-check `dashboard/` with TypeScript |
142
+ | `npm run build` | `make build` | Type-check and build `dashboard/dist` |
143
+
144
+ Run `make` alone to list targets. Full CLI reference:
145
+
146
+ ```text
147
+ llmtop scan archive new transcript lines and ingest them
148
+ llmtop show <session>:<line> print one archived record
149
+ llmtop usage [--days n | --since d --until d] [--by day|model|provider|effort|project|session|hour|tool|skill|subagent]
150
+ [--provider name] [--project name] [--model family] [--effort level]
151
+ llmtop prices the price table checked against the host's cost records
152
+ llmtop serve [--port n] the built dashboard on http://localhost:<port>
153
+ llmtop --help | --version show CLI usage or installed version
154
+ ```
155
+
156
+ Listing commands accept `--json`. For one window and one set of filters, `usage` and the dashboard report the same totals.
157
+
158
+ ## How it works
159
+
160
+ <details>
161
+ <summary><strong>Where data lives</strong></summary>
162
+
163
+ ```text
164
+ ~/.config/llmtop/
165
+ ├── config.json optional configuration file
166
+ └── data/
167
+ ├── archive/
168
+ │ ├── claude/ append-only .jsonl.zst frames, line numbers stable
169
+ │ ├── codex/ append-only .jsonl.zst frames + session_index.jsonl
170
+ │ └── agy/ append-only .jsonl.zst frames
171
+ └── usage.db SQLite database rebuilt from archive on schema changes
172
+ ```
173
+
174
+ The archive preserves transcripts even if the host tool later deletes them. Deleting `usage.db` is safe and the next `llmtop scan` rebuilds it from `archive/`. In a cloned repository, if `llmtop.config.json` exists in the repo root and `~/.config/llmtop/config.json` does not, the local repo config is still used for convenience.
175
+
176
+ A session's project is resolved to the nearest directory at or above its working directory containing `.git`; if none exists, the directory's own name is used.
177
+
178
+ </details>
179
+
180
+ <details>
181
+ <summary><strong>How cost is computed</strong></summary>
182
+
183
+ When a host records session cost, llmtop preserves that total and spreads it across the session's requests weighted by their token counts priced on their date from [prices.md](prices.md) (USD per million tokens, effective from each row's `from` date until a later row for the same model). Sessions without a host cost record are estimated from [prices.md](prices.md) and marked as estimated. `prices` and the scan report highlight mismatches between host cost records and the table; append a new dated row when a price changes rather than editing historical rows.
184
+
185
+ Each request cost is split into context reads, cache writes, output, and web search. Background calls not written to transcripts (such as Haiku calls for `WebSearch`) are split using host-recorded per-model token totals; web search covers cost above token prices on models that ran web searches. Models missing from [prices.md](prices.md) remain `"Not split"`.
186
+
187
+ Cache savings compare each request's bill without the prompt cache (cache reads priced as uncached input) against the actual bill including cache write premiums. Because raw savings scale with total volume, the Overview compares periods using the share of cost spent reading context instead, where a rise indicates worse cache efficiency.
188
+
189
+ </details>
190
+
191
+ <details>
192
+ <summary><strong>Cache rebuilds</strong></summary>
193
+
194
+ Prompt caches make reading prior context cheap, while rebuilding the cache writes most of the context again at a much higher rate. llmtop flags a request as a rebuild when it writes at least 20,000 tokens to the cache and more than half of all tokens it read or wrote, or when it is the first request of a thread after a compaction and writes at least 20,000 tokens. The Activity view and `usage` group rebuilds by cause:
195
+
196
+ | Cause | Meaning |
197
+ | --- | --- |
198
+ | At session start | First request of a thread (main conversation or subagent); unavoidable |
199
+ | At compaction | A compaction occurred since the thread's previous request |
200
+ | After idle | Gap since the previous request exceeded cache lifetime (`1h` if the latest write used 1h cache, else `5m`; bucketed as `5–15m`, `15–60m`, `>1h`) |
201
+ | Other | Any other rebuild not explained by the causes above |
202
+
203
+ Extra rebuild cost equals the rewritten tokens priced as cache writes (`5m` and `1h` as recorded, defaulting unsplit writes to `1h`) minus the same tokens priced as cache reads. The Sessions view surfaces idle rebuild counts per session as cache lapses. The `20,000`-token and `50%` thresholds are fixed conventions rather than host-reported events; models without a price row count rebuilds without an extra-cost figure.
204
+
205
+ </details>
206
+
207
+ <details>
208
+ <summary><strong>Compaction and the context</strong></summary>
209
+
210
+ When a conversation approaches its context limit, the agent writes a summary and continues from the compacted context. Transcripts record pre-compaction and post-compaction context sizes and durations when available; older transcripts with only summaries still count the compaction event.
211
+
212
+ Each compaction costs the summary request plus the subsequent cache rebuild. Because summary requests are not written to transcripts directly, llmtop attributes host-recorded tokens beyond transcript requests evenly across a session's compactions per model.
213
+
214
+ The Context view buckets context-reading cost by the context size carried by each request, with a dedicated row for unattributed host-recorded cost so totals match the Overview. The current compaction point is the median pre-compaction context across the last five automatic main-thread compactions per model family; counterfactual replay estimates total cost at alternative compaction thresholds using list prices (excluding files re-read after compaction, so thresholds below the current one may cost more in practice than shown).
215
+
216
+ </details>
217
+
218
+ <details>
219
+ <summary><strong>Skills</strong></summary>
220
+
221
+ The Activity view and `usage --by skill` count skill invocations by name across user slash commands that load a skill (excluding built-in commands like `/compact`) and agent skill calls, including failed calls. Each skill is grouped by where it was loaded from:
222
+
223
+ | Source | Location |
224
+ | --- | --- |
225
+ | Project | `.claude/skills/` in a repository |
226
+ | Personal | `~/.claude/skills/` |
227
+ | Plugin | Installed plugin (`plugin:skill`) |
228
+ | Built-in | Bundled agent skills |
229
+ | Other | Unmatched or unrecorded directory |
230
+
231
+ </details>
232
+
233
+ <details>
234
+ <summary><strong>Configuration (optional)</strong></summary>
235
+
236
+ Create `~/.config/llmtop/config.json` (using [llmtop.config.example.json](llmtop.config.example.json) as a reference), or set `XDG_CONFIG_HOME` / `LLMTOP_CONFIG` to point elsewhere (`LLMTOP_DATA` overrides the data folder). All keys are optional; relative paths resolve from the config file's directory, and unknown keys pass through untouched.
237
+
238
+ | Key | Default | Meaning |
239
+ | --- | --- | --- |
240
+ | `providers` | `{ "claude": { "transcripts": "~/.claude/projects" }, "codex": { "transcripts": "~/.codex/sessions" }, "agy": { "transcripts": "~/.gemini/antigravity-cli" } }` | Enabled transcript sources (`claude`, `codex`, `agy`); any other provider key raises an error |
241
+ | `data` | `data` (inside `~/.config/llmtop`) | Directory for `archive/` and `usage.db` |
242
+ | `port` | `4310` | HTTP server port |
243
+ | `timeZone` | System time zone | Time zone used to bucket days and hours |
244
+ | `prices` | `prices.md` bundled in package | Markdown price table |
245
+
246
+ </details>
247
+
248
+ ## Documentation
249
+
250
+ | Topic | Document |
251
+ | --- | --- |
252
+ | Pricing table & model rates | [prices.md](prices.md) |
253
+ | Example configuration | [llmtop.config.example.json](llmtop.config.example.json) |
254
+ | Brand kit, logo rules & tokens | [Brand guide](docs/brand/README.md) · [Brand tokens](docs/brand/brand.json) |
255
+ | Issues, branches, commits & PRs | [CONTRIBUTING.md](CONTRIBUTING.md) |
256
+ | Agent guide & repository layout | [CLAUDE.md](CLAUDE.md) · [AGENTS.md](AGENTS.md) |
257
+
258
+ ## License
259
+
260
+ Licensed under the [MIT License](LICENSE) (`Copyright (c) 2026 Trung Nguyen`). Third-party dependencies retain their own licenses.
package/bin/llmtop.mjs ADDED
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { loadConfig, ROOT } from "../src/config.mjs";
5
+ import { localTime } from "../src/format.mjs";
6
+ import { pricesCommand } from "../src/prices-command.mjs";
7
+ import { scan, scanReport } from "../src/scan.mjs";
8
+ import { serve } from "../src/serve.mjs";
9
+ import { show } from "../src/show.mjs";
10
+ import { usageCommand } from "../src/usage-command.mjs";
11
+
12
+ const { version: VERSION } = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
13
+
14
+ const USAGE = `usage: llmtop <command> [options]
15
+
16
+ scan archive new transcript lines and ingest them
17
+ show <session>:<line> print one archived record
18
+ usage [--days n | --since d --until d] [--by day|model|provider|effort|project|session|hour|tool|skill|subagent]
19
+ [--provider name] [--project name] [--model family] [--effort level]
20
+ prices the price table checked against the host's cost records
21
+ serve [--port n] the built dashboard on http://localhost:<port>
22
+
23
+ Options:
24
+ -h, --help show this help message
25
+ -v, --version show version (${VERSION})
26
+
27
+ Listing commands accept --json. Config and data default to ~/.config/llmtop
28
+ (override with LLMTOP_CONFIG and LLMTOP_DATA).`;
29
+
30
+ const COMMANDS = {
31
+ async scan({ config, out }) {
32
+ const t = await scan(config);
33
+ reportScan(t, out);
34
+ return t.prices.errors.length ? 1 : 0;
35
+ },
36
+ async show({ config, positional, out }) {
37
+ out.write(`${await show(config, positional[0])}\n`);
38
+ },
39
+ usage: usageCommand,
40
+ async serve({ config, options, out }) {
41
+ const port = options.port === undefined ? config.port : Number(options.port);
42
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new UsageError(`--port needs a port number, got ${options.port}`);
43
+ const at = localTime(config.timeZone);
44
+ const server = await serve(config, { port, onScan: (t) => reportScan(t, out, `${at(new Date().toISOString())} `) });
45
+ out.write(`dashboard at http://localhost:${server.address().port}: its Refresh button scans again, Ctrl+C to stop\n`);
46
+ },
47
+ prices: pricesCommand,
48
+ };
49
+
50
+ // Options are --name value or --flag; FLAGS lists the ones without a value.
51
+ const FLAGS = new Set(["json"]);
52
+ function parseArgs(argv) {
53
+ const positional = [];
54
+ const options = {};
55
+ for (let i = 0; i < argv.length; i++) {
56
+ const arg = argv[i];
57
+ if (!arg.startsWith("--")) {
58
+ positional.push(arg);
59
+ continue;
60
+ }
61
+ const name = arg.slice(2);
62
+ if (FLAGS.has(name)) options[name] = true;
63
+ else if (i + 1 < argv.length) options[name] = argv[++i];
64
+ else throw new UsageError(`option --${name} needs a value`);
65
+ }
66
+ return { positional, options };
67
+ }
68
+
69
+ class UsageError extends Error {}
70
+
71
+ function reportScan(t, out, prefix = "") {
72
+ const { lines, errors } = scanReport(t);
73
+ for (const l of lines) out.write(`${prefix}${l}\n`);
74
+ for (const e of errors) process.stderr.write(`${prefix}${e}\n`);
75
+ }
76
+
77
+ async function main(argv) {
78
+ const [command, ...rest] = argv;
79
+ if (command === "-v" || command === "--version" || command === "version") {
80
+ process.stdout.write(`${VERSION}\n`);
81
+ return 0;
82
+ }
83
+ if (command === "-h" || command === "--help" || command === "help") {
84
+ process.stdout.write(`${USAGE}\n`);
85
+ return 0;
86
+ }
87
+ const run = COMMANDS[command];
88
+ if (!run) {
89
+ process.stderr.write(`${command ? `unknown command: ${command}\n\n` : ""}${USAGE}\n`);
90
+ return 2;
91
+ }
92
+ const { positional, options } = parseArgs(rest);
93
+ return (await run({ config: loadConfig(), positional, options, out: process.stdout })) ?? 0;
94
+ }
95
+
96
+ try {
97
+ process.exitCode = await main(process.argv.slice(2));
98
+ } catch (err) {
99
+ process.stderr.write(`${err instanceof UsageError ? `${err.message}\n\n${USAGE}` : `error: ${err.message}`}\n`);
100
+ process.exitCode = err instanceof UsageError ? 2 : 1;
101
+ }