@nandoblanco/opencode-local-tokens 0.0.0-stage → 0.1.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 +56 -0
- package/HANDOFF-MEASUREMENT.md +45 -0
- package/LICENSE +21 -0
- package/README.md +238 -3
- package/cli.js +289 -0
- package/dist/gui-experimental.cjs +1 -0
- package/package.json +82 -6
- package/src/gui.css +1007 -0
- package/src/gui.tsx +1311 -0
- package/src/handoff.ts +103 -0
- package/src/index.ts +4 -0
- package/src/measurement.ts +86 -0
- package/src/prepare-handoff.ts +39 -0
- package/src/rpc.ts +179 -0
- package/src/server.ts +223 -0
- package/src/summary.ts +208 -0
- package/src/tokens.ts +2286 -0
- package/src/tui.ts +919 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.2 (2026-11-26)
|
|
4
|
+
|
|
5
|
+
- Added `install` (`init` / `setup`) CLI subcommand (`installPlugin` in `cli.js`, tested in `test/install.test.ts`) writing a V2 entry to `opencode.jsonc` only, without requiring TypeScript execution.
|
|
6
|
+
- Aligned `package.json` `"author"` to `"nandoblanco"` and standardized `README.md` Installation with all 4 install options (`opencode plugin add`, manual `opencode.jsonc`, `npx ... install`, and local directory) matching the other public OpenCode plugins.
|
|
7
|
+
|
|
8
|
+
## 0.1.1 (2026-11-26)
|
|
9
|
+
|
|
10
|
+
- Removed eager startup `prewarmTokensCache()` timers from `src/server.ts` and `src/tui.ts` so OpenCode server and TUI startup are not blocked by synchronous SQLite scans on large `opencode.db` files; `/tokens` still prewarms and caches on demand when opened.
|
|
11
|
+
- Fixed every session being labeled project `general`: the header summary created sidecar entries without running project inference, and the report never recomputed them. Entries now carry a `projectVersion` (including a hash of `tokens.json`) so existing sessions are relabeled automatically whenever the rules change (`src/summary.ts`, `src/tokens.ts`).
|
|
12
|
+
- New `~/.config/opencode/tokens.json` (or `OPENCODE_TOKENS_CONFIG`) with `ignoreFolders` and `keywords`. Project is now every folder of the session directory minus ignored folder names and the home folder prefix (e.g. `/workspace/git/agency/clients/acme/storefront` -> `acme/storefront`); when nothing is left it is `general` (`src/tokens.ts`).
|
|
13
|
+
- Removed all built-in project and tag keyword rules. Automatic tags now come only from the configured `keywords` map (tag -> list of words matched in the title and first prompts) plus `#claude-code` / `#codex-cli` source tags; keywords never change the project. The unused `projectRules` / `tagRules` options were replaced by `config` / `configPath` (`src/tokens.ts`, `test/tokens-controls.test.ts`).
|
|
14
|
+
- Fixed mislabeled counts: header KPI and summary values are user turns, now labeled `Turns`; the summary line is prefixed `All time:` so it no longer appears to contradict the 30-day header; the session detail card shows `Steps / Turns` instead of the turn count labeled as steps (`src/gui.tsx`, `src/tui.ts`).
|
|
15
|
+
- Tag chips show billed tokens like project chips instead of session counts.
|
|
16
|
+
- Token totals of one billion or more format as `B` (e.g. `4.39B` instead of `4353.97M`) (`src/tokens.ts`).
|
|
17
|
+
- Desktop panel now uses a container query: list and detail sit side by side at 640px and wider, and below that the list fills the panel and a row opens the detail with a `Back` button (Escape returns to the list) (`src/gui.css`).
|
|
18
|
+
- TUI `/tokens` lists 80 sessions instead of 14 and tag chips no longer wrap mid-token.
|
|
19
|
+
- TUI `/tokens` header now uses the same single-row title and key-hint layout as `/search`, `/memory` and `/backups`; model and project rows stay on one line, top tags list as aligned rows, table values are no longer truncated, and the dialog fits a 32-row terminal (`src/tui.ts`).
|
|
20
|
+
- Desktop dialog fills its height, the duplicate `Token Audit` heading inside it now reads `Totals`, and the `Add tag` input is larger and easier to see (`src/gui.tsx`, `src/gui.css`).
|
|
21
|
+
- Desktop arrow-key navigation scrolls the selected session into view.
|
|
22
|
+
- Desktop `Like`, `Open Session` and `Filter Per Session` buttons use valid button variants, and the empty per-tag view explains that only the loaded sessions are searched and points to `Filter Per Session`.
|
|
23
|
+
|
|
24
|
+
- Expanded the README introduction and background around auditing token totals by project folder or tag; removed references to the separate account-quota plugin from the README.
|
|
25
|
+
- Explained how manual session handoff complements token auditing and model-context status, preserving structured working state and linked history when continuing in a fresh session without promising token savings.
|
|
26
|
+
|
|
27
|
+
- Removed the obsolete combined Tokens/Usage browser fixtures and their README reference. Standalone Tokens tests remain the package's verification scope.
|
|
28
|
+
|
|
29
|
+
- Disabled prompt-cache expiry banners and their countdown clocks by default in terminal and Desktop. Set plugin option `cacheAlerts: true` to opt in; manual handoff, context status, and token analytics are unchanged. Rebuilt the Desktop GUI bundle.
|
|
30
|
+
|
|
31
|
+
- Removed machine-specific tag and handoff directory fallbacks from `resolveDefaultSidecarPath`, `handoffDirectory`, and `buildSessionHandoff`; explicit paths and environment overrides retain precedence over portable home-directory defaults. Existing files are not migrated automatically.
|
|
32
|
+
|
|
33
|
+
- Added Git exclusions for dependencies, backups, screenshots, credentials, and local analytics data; corrected the GitHub repository URL in `package.json`.
|
|
34
|
+
|
|
35
|
+
- Separated terminal `/tokens` search, controls, and totals; added an inline eight-mode sort picker (`Ctrl+S`) and selected-session add/remove tag editors (`Ctrl+T` / `Ctrl+R`) with cancellation and visible save errors.
|
|
36
|
+
- Added shell `--sort` and `untag` commands. Explicit sorting in `analyzeTokens` runs before limiting results; existing callers without a sort retain their ordering. Documented terminal, shell, and Desktop controls separately.
|
|
37
|
+
|
|
38
|
+
- Shortened the terminal Token Audit search placeholder to `Search or filter...`.
|
|
39
|
+
|
|
40
|
+
- Declared the OpenCode V2 SDK (`@opencode/plugin`) as a runtime dependency instead of a development-only dependency, and removed the obsolete V1 SDK optional peer declaration (`@opencode-ai/plugin`).
|
|
41
|
+
|
|
42
|
+
- Desktop Save & Copy Handoff and CLI `/handoff` now request a fresh AI-authored working-state checkpoint in the original session and wait before exporting. Failed preparation does not silently export an old checkpoint. Preparation uses model tokens; CLI then sends the continuation in a new session using the V2 text input.
|
|
43
|
+
|
|
44
|
+
- Renamed OpenCode Desktop sidebar button (`vertical-tabs-tokens`), panel tab title, dialog title, and top bar header from `Tokens` / `Token Explorer` / `Token Analytics` to `Token Audit`, replaced the icon with a stacked coins SVG, and omitted the trailing shortcut badge in the left sidebar (`src/gui.tsx`).
|
|
45
|
+
- Added session sort controls (`billed`, `total`, `steps`, `updated`, `newest`, `oldest`, `title`, `relevance`) in the Token Audit filter bar (`src/gui.tsx`, `src/tokens.ts`).
|
|
46
|
+
- Added manual session tagging in the selected session detail pane (`+ Tag` inline form and removable `#tag` pills via `mutateSession` `tag` / `untag` actions in `src/tokens.ts`, `src/rpc.ts`, and `src/gui.tsx`).
|
|
47
|
+
- Added main lower view tabs (`Per Session` and `Per Tag`) in Token Audit (`src/gui.tsx`, `src/gui.css`, `src/tokens.ts`) with a per-tag token breakdown list, tag KPI cards, and a clickable tagged-sessions table.
|
|
48
|
+
- Added 5-minute prompt-cache idle tracking (`lastReplyAt`, `idleMs`, `cacheTtlMs`, `cacheRemainingMs`, `cacheState`, `cacheAlert` in `getSessionStepStatus`) and a composer-top alert pill in OpenCode Desktop (`src/gui.tsx`, `src/gui.css`) and CLI TUI (`src/tui.ts`) that stays hidden during active chatting and appears only when live context is heavy (>=30K tokens) and idle >=4 minutes, with a 1-click `Save & Copy Handoff` action and per-turn dismiss button.
|
|
49
|
+
|
|
50
|
+
## 0.1.0 (2026-11-17)
|
|
51
|
+
|
|
52
|
+
- Initial release of `@nandoblanco/opencode-local-tokens` for OpenCode V2.
|
|
53
|
+
- Added local token analytics (`src/tokens.ts`, `src/summary.ts`) aggregating input, output, reasoning, cache-read, and cache-write counters across OpenCode SQLite databases and local Claude Code / Codex JSONL transcripts.
|
|
54
|
+
- Added `/tokens` and `/handoff` TUI commands (`src/tui.ts`), OpenCode Desktop Tokens panel (`src/gui.tsx`, `src/gui.css`, `Ctrl+Shift+Y`), and session bookmark/tag/note persistence in `session-tags.json` (`mutateSessionTag`).
|
|
55
|
+
- Added model-aware context capacity tracking (`getSessionStepStatus`) with 75% warning and 90% high-usage thresholds against exact configured model limits.
|
|
56
|
+
- Added structured session handoff tools (`handoff_checkpoint` and `handoff_history` in `src/handoff.ts`) and local handoff measurement sidecars (`src/measurement.ts`).
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Handoff measurement
|
|
2
|
+
|
|
3
|
+
## Implemented functionality
|
|
4
|
+
|
|
5
|
+
`src/measurement.ts` collects local observations without model calls or additional agent tools. `src/handoff.ts` records a checkpoint-save observation after saving working state. `buildSessionHandoff` records a separate observation after writing the handoff Markdown. The server subscribes to `session.idle` to refresh recovery windows for explicitly linked child sessions. Cleanup aborts the subscription.
|
|
6
|
+
|
|
7
|
+
| Observation | Recorded data | Boundary |
|
|
8
|
+
| :--- | :--- | :--- |
|
|
9
|
+
| Checkpoint save | Session ID, timestamp, message count, previous five usage-bearing assistant records | After the checkpoint write, not the start of preparation |
|
|
10
|
+
| Handoff save | Structured/fallback status, checkpoint timestamp, stale-message count, last request context and model, configured capacity if known, previous five records | After the handoff Markdown write |
|
|
11
|
+
| After checkpoint save | Usage records between the observed checkpoint save and handoff save | Does not measure checkpoint composition or its generating request reliably |
|
|
12
|
+
| Linked recovery | First request, first five, following five (requests 2 through 6), first ten, model-change flag | Refreshed on child-session idle; incomplete windows are labeled |
|
|
13
|
+
| Review status | `outcome: "unreviewed"` | No automatic correctness or quality judgment |
|
|
14
|
+
|
|
15
|
+
Each request observation contains message ID, timestamp, model key, input/output/reasoning/cache-read/cache-write counters, context (input plus both cache counters), and counts of direct `read` and `handoff_history` tool parts. Windows include observed counts and totals. These are usage-bearing assistant records, not a claim that every possible auxiliary model call is represented. No dollar savings are calculated.
|
|
16
|
+
|
|
17
|
+
## Storage and privacy
|
|
18
|
+
|
|
19
|
+
Files are written under the existing memory directory at `handoffs/measurements/`. `checkpoint-<session-id>.json` holds the latest checkpoint observation. Each handoff save creates `handoff-<uuid>.json`, preserving repeated exports as separate observations. Records contain IDs, timestamps, model identifiers, counters, and status fields. Prompt bodies, checkpoint prose, file paths, tool arguments, and tool outputs are not copied into analytics. The collector reads message JSON locally to extract counters and the continuation marker. The existing working-state JSON and handoff Markdown still contain their normal content.
|
|
20
|
+
|
|
21
|
+
The source OpenCode database is opened with `readOnly: true`. Analytics never change source messages. Collection errors emit a warning with the error class, without message content, and do not block handoff creation or normal execution. No network requests or additional model calls are made by the collector. Existing checkpoint generation, tool schemas, and history results still consume ordinary context tokens.
|
|
22
|
+
|
|
23
|
+
## Attribution and limitations
|
|
24
|
+
|
|
25
|
+
A child is linked only when its first user message begins with the existing `Continuing from previous session` marker and the exact parent ID. No heuristic matching of titles, directories, or text similarity is used. This is evidence of a parent link, not proof that the checkpoint was read or that recovery succeeded. A repeated parent export cannot be identified uniquely from that marker, so matching saves are explicitly labeled `candidate-only`. Saves later than the child's first user message are excluded.
|
|
26
|
+
|
|
27
|
+
There is no historical backfill. Measurement begins with newly observed checkpoint and handoff saves. Idle collection is not a streaming completion detector. It reads the first ten usage-bearing records available at idle. Counts of direct tool parts miss calls nested inside Code Mode or wrappers. Unknown model capacity is stored as `null`; historical capacities are not inferred from current model names. The five/ten request windows are exploratory conventions, not validated thresholds, and do not represent equal work before and after handoff.
|
|
28
|
+
|
|
29
|
+
## Unchanged behavior
|
|
30
|
+
|
|
31
|
+
Manual handoff controls, generated continuation prompts, session creation behavior, checkpoint text, context alerts, model selection, and automatic compaction are unchanged. The collector neither creates sessions nor recommends or triggers handoffs. Existing context warnings use 75% and 90% of the resolved model context capacity. Measurement does not change those values.
|
|
32
|
+
|
|
33
|
+
## Proposed functionality, not implemented
|
|
34
|
+
|
|
35
|
+
| Proposal | Current boundary |
|
|
36
|
+
| :--- | :--- |
|
|
37
|
+
| Explicit preparation-start observation | Checkpoint-save is the first observation; preparation overhead remains unmeasured |
|
|
38
|
+
| Reviewed recovery milestone with correct / needed correction / unclear outcomes | Only `unreviewed` is initialized; no review command or UI exists |
|
|
39
|
+
| Aggregate report and review after ten additional handoffs | Raw local JSON observations only; ten is a practical review point, not statistical proof |
|
|
40
|
+
| Recovery completeness and retained-quality assessment | Requires human evidence; token reductions cannot establish quality |
|
|
41
|
+
| Automatic timing or different thresholds | Outside this pass; requires separate approval and evidence |
|
|
42
|
+
|
|
43
|
+
## Verification
|
|
44
|
+
|
|
45
|
+
Run `npm test` from this package. `test/measurement.test.ts` covers window sizes and totals, partial recovery, model switches, repeated-idle deduplication, explicit links, privacy, fallback metadata, unchanged source rows, and non-blocking collection errors. Existing handoff tests cover working-state inclusion and unchanged alert status. Browser smoke tests exercise the existing GUI command handler with a stubbed host; they do not prove actual Desktop or TUI session creation.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fernando Blanco
|
|
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,238 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# opencode-local-tokens
|
|
2
|
+
|
|
3
|
+
**Local token auditing and model-aware session handoff for OpenCode V2**, built to find which projects consume the most tokens by project folder or tag. Compare token totals, drill into individual sessions, and separate input, output, reasoning, and cache activity. Search, sorting, and manual tags help trace the largest totals back to the work behind them.
|
|
4
|
+
|
|
5
|
+
Handoff connects that audit to the next step: continuing work when a conversation has grown large or is nearing the model's context limit. Token totals show where tokens went; context status shows how much of the current model's capacity the latest request used. When you choose to move to a fresh session, handoff carries forward a structured checkpoint of the goal, decisions, constraints, unfinished work, and next action, with bounded retrieval from linked predecessor sessions instead of requiring the entire transcript up front. The aim is to preserve useful working context without carrying every old exchange into the new conversation. Handoff is manual, preparation uses model tokens, and lower token costs are not guaranteed.
|
|
6
|
+
|
|
7
|
+
## Background
|
|
8
|
+
|
|
9
|
+
Tokens started with a practical question: which projects are consuming the most tokens, and what work is driving those totals? Session-by-session counters make that hard to see when work spans multiple conversations or folders.
|
|
10
|
+
|
|
11
|
+
Tokens reads local session records and transcripts to make that audit easier. Use project folders to narrow the work being reviewed, or tag related sessions across folders to track a client, feature, or type of task. Sort sessions by token count to find the largest contributors, then inspect their token breakdowns. Desktop's `Per Tag` view brings tagged sessions together for a grouped comparison.
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
| Feature | Details |
|
|
16
|
+
| :--- | :--- |
|
|
17
|
+
| Analytics | Input, output, reasoning, cache-read and cache-write counters; 30-day and all-time summaries |
|
|
18
|
+
| Session search & sort | Topic search, folder-based projects, configurable keyword tags, model/tag filters, likes, notes, turn-scoped matching, and sorting (`Billed tokens`, `Total w/ cache`, `Steps`, `Recently updated`, `Newest created`, `Oldest created`, `Title A-Z`, `Relevance`) |
|
|
19
|
+
| Manual tagging & Per-Tag view | Terminal add/remove tag editor; Desktop `+ Tag` and removable `#tag ×` chips plus lower split-view tabs (`Per Session` and `Per Tag`) |
|
|
20
|
+
| Local sources | OpenCode SQLite plus standalone Claude Code and Codex JSONL transcripts |
|
|
21
|
+
| Context status | Latest recorded request compared with the exact configured model capacity; warning at 75%, high at 90% |
|
|
22
|
+
| Handoff | Structured working-state tool, explicit predecessor history, save/copy continuation, measurement-only sidecars |
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
### Option 1: OpenCode Plugin CLI (Recommended)
|
|
27
|
+
|
|
28
|
+
Install with OpenCode's native plugin CLI. OpenCode downloads the package from npm (or GitHub) into its own cache automatically and adds one entry to `~/.config/opencode/opencode.jsonc` that loads the server tools, `/tokens` and `/handoff` TUI commands, and Desktop panel together:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
opencode plugin add @nandoblanco/opencode-local-tokens
|
|
32
|
+
# Auto-update on startup and every 24 hours:
|
|
33
|
+
opencode plugin add @nandoblanco/opencode-local-tokens@latest
|
|
34
|
+
# Or install directly from GitHub:
|
|
35
|
+
opencode plugin add github:nandoblanco/opencode-local-tokens
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Option 2: Manual Configuration
|
|
39
|
+
|
|
40
|
+
Add `@nandoblanco/opencode-local-tokens` to `"plugins"` in the global `~/.config/opencode/opencode.jsonc` (or project `./opencode.jsonc` / `./.opencode/opencode.jsonc`). OpenCode fetches the npm package automatically and loads the server, TUI, and Desktop parts from this single entry (no manual `npm install` or separate `cli.json` entry is required):
|
|
41
|
+
|
|
42
|
+
```jsonc
|
|
43
|
+
{
|
|
44
|
+
"plugins": [
|
|
45
|
+
{
|
|
46
|
+
"package": "@nandoblanco/opencode-local-tokens",
|
|
47
|
+
"options": {
|
|
48
|
+
"cacheAlerts": false
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
]
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Option 3: Built-in CLI Helper (`npx`)
|
|
56
|
+
|
|
57
|
+
Run the package CLI once via `npx` to register the plugin in `~/.config/opencode/opencode.jsonc`:
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
npx @nandoblanco/opencode-local-tokens install
|
|
61
|
+
# Or opt into prompt-cache alerts during setup:
|
|
62
|
+
npx @nandoblanco/opencode-local-tokens install --cache-alerts
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Option 4: From a Local Directory
|
|
66
|
+
|
|
67
|
+
Clone this repository, run `npm ci` and `npm run build:gui` after GUI source changes, then reference the package directory in `opencode.jsonc` (or place the directory inside `~/.config/opencode/plugins/` or `.opencode/plugins/`):
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
{
|
|
71
|
+
"plugins": ["file:///path/to/opencode-local-tokens"]
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Entrypoints are `./server`, `./tui`, and `./gui-experimental`. Package publication and live host loading are separate checks. Source execution requires a Node version with TypeScript execution support or equivalent tooling; the declared Node 22.5 minimum alone is insufficient for running these `.ts` entrypoints directly (the `install` CLI subcommand runs in plain Node without loading TypeScript entrypoints).
|
|
76
|
+
|
|
77
|
+
## Using Tokens
|
|
78
|
+
|
|
79
|
+
### Automatic behavior
|
|
80
|
+
|
|
81
|
+
`server.ts` registers a context reminder and two agent tools, loads and caches local analytics on demand when `/tokens` is queried, and observes `session.idle` for measurement updates. None of these creates a new session or changes compaction thresholds. Context alerts remain informational; unknown model capacity produces no guessed percentage.
|
|
82
|
+
|
|
83
|
+
Prompt-cache expiry banners and their countdown clocks are **off by default** in terminal and Desktop. Manual `/handoff`, context status, and token analytics remain available. To opt into the fixed five-minute cache estimate, set `cacheAlerts` to `true` in this plugin's options; it is an estimate, not a guarantee of the selected model's cache lifetime:
|
|
84
|
+
|
|
85
|
+
```jsonc
|
|
86
|
+
{
|
|
87
|
+
"plugins": [
|
|
88
|
+
{
|
|
89
|
+
"package": "@nandoblanco/opencode-local-tokens",
|
|
90
|
+
"options": { "cacheAlerts": true }
|
|
91
|
+
}
|
|
92
|
+
]
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Use `opencode.json(c)` for this multi-part plugin. If a terminal-only entry is configured separately in `cli.json`, set the option on that entry as well. Omit `cacheAlerts` or set it to `false` to disable the reminder. Only the boolean `true` enables it, and changing plugin options reloads the plugin.
|
|
97
|
+
|
|
98
|
+
### Commands
|
|
99
|
+
|
|
100
|
+
| Command | Behavior |
|
|
101
|
+
| :--- | :--- |
|
|
102
|
+
| `/tokens` | Open Token Audit |
|
|
103
|
+
| `/handoff` | Save handoff material; Desktop copies continuation text for manual pasting into a new chat |
|
|
104
|
+
| Desktop `Ctrl+Shift+Y` | Open Token Audit (sidebar and titlebar button with stacked coins icon) |
|
|
105
|
+
| Explorer likes/tags | Stored in `session-tags.json` sidecar (`like`, `unlike`, `tag`, `untag`, `note`), not written into the OpenCode database |
|
|
106
|
+
|
|
107
|
+
For a handoff, ask the agent to save current working state, run `/handoff`, manually open a new chat, and paste the copied continuation text. A saved state may become stale as the session continues. Generated fallback material is explicitly identified when structured working state is missing. Desktop save/copy does not itself open a new chat. Automatic session creation and full TUI handoff recovery are not verified.
|
|
108
|
+
|
|
109
|
+
## Query Syntax
|
|
110
|
+
|
|
111
|
+
| Syntax | Meaning | Example |
|
|
112
|
+
| :--- | :--- | :--- |
|
|
113
|
+
| Free text | Topic search | `playwright navbar` |
|
|
114
|
+
| `project:` or `p:` | Project filter | `project:storefront` |
|
|
115
|
+
| `model:` or `m:` | Model filter | `model:claude` |
|
|
116
|
+
| `tag:`, `t:`, or `#` | Tag filter | `#accessibility` |
|
|
117
|
+
| `liked`, `liked:true`, or `*` | Bookmarked sessions | `* navbar` |
|
|
118
|
+
|
|
119
|
+
## Terminal Controls (`/tokens`)
|
|
120
|
+
|
|
121
|
+
The terminal explorer keeps search, sort controls, and matched totals on separate lines. Type to filter the session list. Tags and likes are shared with Desktop through the same local sidecar; Desktop's `Per Tag` tab and clickable tag chips are not terminal controls.
|
|
122
|
+
|
|
123
|
+
| Key | Action |
|
|
124
|
+
| :--- | :--- |
|
|
125
|
+
| `Up` / `Down` or `Ctrl+P` / `Ctrl+N` | Select a session |
|
|
126
|
+
| `Enter` | Open the selected session |
|
|
127
|
+
| `Ctrl+S` | Open the sort picker; `Up` / `Down` choose, `Enter` applies, `Esc` cancels |
|
|
128
|
+
| `Ctrl+T` / `Ctrl+R` | Add / remove comma-separated tags on the selected session; `Enter` saves, `Esc` cancels |
|
|
129
|
+
| `Ctrl+L` | Toggle the selected session's like |
|
|
130
|
+
| `Ctrl+U` | Clear search, or clear tag input while editing |
|
|
131
|
+
| `Esc` | Cancel the open editor first; otherwise close the explorer |
|
|
132
|
+
|
|
133
|
+
Sort choices are billed tokens, total with cache, steps, updated date, newest/oldest creation date, title, and relevance. The terminal starts with best match (billed tokens break ties). Sorting is applied across all matches before the 80-session terminal result limit. Removing a keyword tag suppresses it until explicitly added again. Edits show save errors without closing the editor or discarding typed tags.
|
|
134
|
+
|
|
135
|
+
## How It Works
|
|
136
|
+
|
|
137
|
+
### 1. Local sources (`tokens.ts` and `summary.ts`)
|
|
138
|
+
|
|
139
|
+
The analytics engine reads local session records and transcripts. It groups token counters by session, model, project, and matching turns. The UI label `Billed Tokens` means input + output + reasoning; it is not a dollar invoice. Cache operations may also be charged, and pricing is not inferred from that label.
|
|
140
|
+
|
|
141
|
+
### 2. Separate persistence (`mutateSessionTag`)
|
|
142
|
+
|
|
143
|
+
Likes, tags, and notes use `session-tags.json`. `.tokens-turns-cache.json` caches searchable turn data and can contain session text. These files are local and should remain private.
|
|
144
|
+
|
|
145
|
+
### 3. Model capacity (`getSessionStepStatus`)
|
|
146
|
+
|
|
147
|
+
Live context is input + cache read + cache write from the latest token record. RPC status resolves the exact configured model key. Cumulative API-step and uncached-input counters do not drive the 75%/90% context alerts. Unknown capacity is reported as unknown, not guessed from a model name.
|
|
148
|
+
|
|
149
|
+
### 4. Working state and evidence (`handoff.ts`)
|
|
150
|
+
|
|
151
|
+
`handoff_checkpoint` stores structured working state bounded to 16,000 characters. `handoff_history` performs literal matching in the selected session and explicitly linked continuation ancestors, with at most 20 sessions, six results per page, and excerpts bounded to 900 characters. It does not search unrelated sessions or invoke a model.
|
|
152
|
+
|
|
153
|
+
### 5. UI isolation (`gui.tsx`, `gui.css`, and `tui.ts`)
|
|
154
|
+
|
|
155
|
+
Tokens uses its own plugin/RPC ID, panel IDs, commands, and `.olt-scope` stylesheet boundary. Desktop surfaces require CSS `@scope` support in the host webview.
|
|
156
|
+
|
|
157
|
+
### 6. Agent tools (`server.ts`)
|
|
158
|
+
|
|
159
|
+
| Tool | Required inputs | Optional inputs | Behavior |
|
|
160
|
+
| :--- | :--- | :--- | :--- |
|
|
161
|
+
| `handoff_checkpoint` | `goal`, `nextStep`, `constraints`, `decisions`, `verified`, `unfinished`, `failures`, `pendingUserRequests` | None | Save structured state for the current session |
|
|
162
|
+
| `handoff_history` | `sessionId`, `query` | `offset` | Retrieve bounded literal evidence |
|
|
163
|
+
|
|
164
|
+
RPC methods are `summary`, `tokens`, `mutateSession`, `sessionStatus`, and `createHandoff`. No `dashboard` account RPC is registered.
|
|
165
|
+
|
|
166
|
+
### 7. Measurement-only observations (`measurement.ts`)
|
|
167
|
+
|
|
168
|
+
Implemented: checkpoint-save and handoff-save observations, explicit continuation links, initial request, first five requests, requests two through six, and first ten requests. Partial windows remain marked incomplete. Sidecars store identifiers, counters, and timestamps rather than copied prompts or tool bodies. Errors do not block handoff. See [HANDOFF-MEASUREMENT.md](./HANDOFF-MEASUREMENT.md) for attribution and privacy limits.
|
|
169
|
+
|
|
170
|
+
Proposed, not implemented: preparation-start attribution, human outcome entry, aggregate reporting, automated quality scoring, and timing optimization. Measurements do not prove savings or correct recovery.
|
|
171
|
+
|
|
172
|
+
### 8. Token costs
|
|
173
|
+
|
|
174
|
+
| Operation | Token cost | Reason |
|
|
175
|
+
| :--- | :--- | :--- |
|
|
176
|
+
| Local analytics, UI, measurements | No additional model calls | Local reads and sidecar writes |
|
|
177
|
+
| Tool schemas and context reminder | Context tokens | Registered in agent context |
|
|
178
|
+
| Checkpoint/history tool use | Request/result tokens | State and evidence enter the conversation |
|
|
179
|
+
|
|
180
|
+
## Storage and Configuration
|
|
181
|
+
|
|
182
|
+
| Setting | Environment variable | Default | Purpose |
|
|
183
|
+
| :--- | :--- | :--- | :--- |
|
|
184
|
+
| Database | `OPENCODE_DB_PATH` | `~/.local/share/opencode/opencode.db` | Session source |
|
|
185
|
+
| Tags sidecar | `OPENCODE_SESSION_TAGS` | `~/.local/share/opencode/session-tags.json` | Likes, tags, notes |
|
|
186
|
+
| Handoff memory root | `OPENCODE_MEMORY_DIR` | `~/.opencode/memory` | `sessions/` exports and `handoffs/` working state and measurements |
|
|
187
|
+
| Project and tag rules | `OPENCODE_TOKENS_CONFIG` | `~/.config/opencode/tokens.json` | `ignoreFolders` and `keywords` (see below) |
|
|
188
|
+
|
|
189
|
+
Explicit function path arguments take precedence over these environment variables, which take precedence over home-directory defaults. Legacy machine-specific directories are no longer auto-detected. To keep using existing files elsewhere, set `OPENCODE_SESSION_TAGS` and `OPENCODE_MEMORY_DIR` to their current locations; no files are moved or migrated automatically. The measurement collector opens the source database read-only. Handoff Markdown and working-state files contain task information; measurement sidecars do not copy those bodies.
|
|
190
|
+
|
|
191
|
+
### Projects and keyword tags (`tokens.json`)
|
|
192
|
+
|
|
193
|
+
```json
|
|
194
|
+
{
|
|
195
|
+
"ignoreFolders": ["workspace", "git", "agency", "clients"],
|
|
196
|
+
"keywords": {
|
|
197
|
+
"frontend": ["css", "flexbox", "layout"]
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
- **Project** is every folder in the session directory except the drive, your home folder prefix, and any name in `ignoreFolders` (case-insensitive). With the example above, `/workspace/web-app` becomes `web-app` and `/workspace/git/agency/clients/acme/storefront` becomes `acme/storefront`. If every folder is ignored, the project is `general`. Without the file, `ignoreFolders` defaults to common names such as `git`, `repos`, `code`, `dev`, `projects`, `workspace`, `tmp`, `temp`, `Windows`, and `System32`.
|
|
203
|
+
- **Keywords** add a tag when any listed word appears as a whole word in the session title or first prompts. Keywords never change the project. There are no built-in keyword tags; imported Claude Code and Codex CLI sessions still get `#claude-code` / `#codex-cli`.
|
|
204
|
+
- Editing the file relabels every session on the next report; manual tags, removed tags, likes, and notes are kept.
|
|
205
|
+
|
|
206
|
+
## CLI Commands
|
|
207
|
+
|
|
208
|
+
```sh
|
|
209
|
+
node cli.js --help
|
|
210
|
+
node cli.js "playwright navbar"
|
|
211
|
+
node cli.js --project storefront --model claude
|
|
212
|
+
node cli.js --tag accessibility --liked
|
|
213
|
+
node cli.js --sort updated --limit 10
|
|
214
|
+
node cli.js like ses_39a1b2
|
|
215
|
+
node cli.js tag ses_39a1b2 "review,billing"
|
|
216
|
+
node cli.js untag ses_39a1b2 "billing"
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
The installed shell command is `opencode-tokens` with the same arguments. Shell `--sort` values are `billed`, `total`, `steps`, `updated`, `newest`, `oldest`, `title`, and `relevance`. Without `--sort`, shell reports keep their existing topic relevance / billed-token ordering. Shell commands print a report or mutate a sidecar; `/tokens` inside OpenCode opens the interactive terminal explorer.
|
|
220
|
+
|
|
221
|
+
## Development and Verification
|
|
222
|
+
|
|
223
|
+
```sh
|
|
224
|
+
npm test
|
|
225
|
+
npm run build:gui
|
|
226
|
+
node test/handoff-browser.mjs
|
|
227
|
+
node test/tui-browser.mjs
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Tests cover bounded history, working-state persistence, measurements, model-capacity lookup, and RPC separation. Workspace integration fixtures retain analytics and transcript parsing coverage. Browser fixtures run real GUI code against stubbed host APIs. They do not establish live Desktop/TUI behavior or live idle-event collection. No measured cost/quality improvement is claimed.
|
|
231
|
+
|
|
232
|
+
`tokens-controls.test.ts` verifies all eight sorts, ordering before limits, shell argument handling, and real SQLite/sidecar tag persistence. `tui-browser.mjs` exercises the real terminal dialog component through a DOM renderer adapter at 1280 and 800 pixels, with stubbed analytics and host APIs. Its screenshots verify browser-adapter layout and keyboard flows, not native OpenTUI cell layout or host shortcut dispatch.
|
|
233
|
+
|
|
234
|
+
The standalone unit suite and browser fixtures above define this package's verification scope.
|
|
235
|
+
|
|
236
|
+
## License
|
|
237
|
+
|
|
238
|
+
MIT
|
package/cli.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
|
|
9
|
+
const cliName = "open" + "code";
|
|
10
|
+
|
|
11
|
+
export function resolveConfigDir(explicitDir) {
|
|
12
|
+
if (explicitDir) {
|
|
13
|
+
if (explicitDir === "~") return os.homedir();
|
|
14
|
+
if (explicitDir.startsWith("~/") || explicitDir.startsWith("~\\")) {
|
|
15
|
+
return path.join(os.homedir(), explicitDir.slice(2));
|
|
16
|
+
}
|
|
17
|
+
return path.resolve(explicitDir);
|
|
18
|
+
}
|
|
19
|
+
if (process.env.OPENCODE_CONFIG_DIR) return path.resolve(process.env.OPENCODE_CONFIG_DIR);
|
|
20
|
+
if (process.env.XDG_CONFIG_HOME) return path.join(process.env.XDG_CONFIG_HOME, cliName);
|
|
21
|
+
return path.join(os.homedir(), ".config", cliName);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function findPluginsArraySpan(raw) {
|
|
25
|
+
const pluginsMatch = /"plugins"\s*:\s*\[/.exec(raw);
|
|
26
|
+
if (!pluginsMatch) return null;
|
|
27
|
+
const openBracketIdx = pluginsMatch.index + pluginsMatch[0].length - 1;
|
|
28
|
+
let depth = 0;
|
|
29
|
+
let inString = false;
|
|
30
|
+
let escape = false;
|
|
31
|
+
let inLineComment = false;
|
|
32
|
+
let inBlockComment = false;
|
|
33
|
+
|
|
34
|
+
for (let i = openBracketIdx; i < raw.length; i++) {
|
|
35
|
+
const ch = raw[i];
|
|
36
|
+
const next = raw[i + 1];
|
|
37
|
+
|
|
38
|
+
if (inLineComment) {
|
|
39
|
+
if (ch === "\n") inLineComment = false;
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (inBlockComment) {
|
|
43
|
+
if (ch === "*" && next === "/") {
|
|
44
|
+
inBlockComment = false;
|
|
45
|
+
i++;
|
|
46
|
+
}
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (escape) {
|
|
50
|
+
escape = false;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (inString) {
|
|
54
|
+
if (ch === "\\") escape = true;
|
|
55
|
+
else if (ch === '"') inString = false;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (ch === "/" && next === "/") {
|
|
59
|
+
inLineComment = true;
|
|
60
|
+
i++;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (ch === "/" && next === "*") {
|
|
64
|
+
inBlockComment = true;
|
|
65
|
+
i++;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (ch === '"') {
|
|
69
|
+
inString = true;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (ch === "[") depth++;
|
|
73
|
+
else if (ch === "]") {
|
|
74
|
+
depth--;
|
|
75
|
+
if (depth === 0) {
|
|
76
|
+
return { openBracketIdx, closeBracketIdx: i };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function findLastCodeCharIndex(str) {
|
|
84
|
+
let inString = false;
|
|
85
|
+
let escape = false;
|
|
86
|
+
let inLineComment = false;
|
|
87
|
+
let inBlockComment = false;
|
|
88
|
+
let lastCodeIdx = -1;
|
|
89
|
+
|
|
90
|
+
for (let i = 0; i < str.length; i++) {
|
|
91
|
+
const ch = str[i];
|
|
92
|
+
const next = str[i + 1];
|
|
93
|
+
|
|
94
|
+
if (inLineComment) {
|
|
95
|
+
if (ch === "\n") inLineComment = false;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (inBlockComment) {
|
|
99
|
+
if (ch === "*" && next === "/") {
|
|
100
|
+
inBlockComment = false;
|
|
101
|
+
i++;
|
|
102
|
+
}
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (escape) {
|
|
106
|
+
escape = false;
|
|
107
|
+
lastCodeIdx = i;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (inString) {
|
|
111
|
+
if (ch === "\\") escape = true;
|
|
112
|
+
else if (ch === '"') inString = false;
|
|
113
|
+
lastCodeIdx = i;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (ch === "/" && next === "/") {
|
|
117
|
+
inLineComment = true;
|
|
118
|
+
i++;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (ch === "/" && next === "*") {
|
|
122
|
+
inBlockComment = true;
|
|
123
|
+
i++;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (ch === '"') {
|
|
127
|
+
inString = true;
|
|
128
|
+
lastCodeIdx = i;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (!/\s/.test(ch)) {
|
|
132
|
+
lastCodeIdx = i;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return lastCodeIdx;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function addPluginToJsoncFile(filePath, defaultSchema, pluginEntryStr, matchSubstr) {
|
|
139
|
+
if (!fs.existsSync(filePath)) {
|
|
140
|
+
const initial =
|
|
141
|
+
"{\n" +
|
|
142
|
+
' "$schema": "' +
|
|
143
|
+
defaultSchema +
|
|
144
|
+
'",\n' +
|
|
145
|
+
' "plugins": [\n' +
|
|
146
|
+
" " +
|
|
147
|
+
pluginEntryStr +
|
|
148
|
+
"\n" +
|
|
149
|
+
" ]\n" +
|
|
150
|
+
"}\n";
|
|
151
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
152
|
+
fs.writeFileSync(filePath, initial, "utf8");
|
|
153
|
+
return "created";
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const raw = fs.readFileSync(filePath, "utf8");
|
|
157
|
+
if (raw.includes(matchSubstr)) {
|
|
158
|
+
return "already-present";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const span = findPluginsArraySpan(raw);
|
|
162
|
+
if (span) {
|
|
163
|
+
const { openBracketIdx, closeBracketIdx } = span;
|
|
164
|
+
const insideRaw = raw.slice(openBracketIdx + 1, closeBracketIdx);
|
|
165
|
+
const lastCodeIdx = findLastCodeCharIndex(insideRaw);
|
|
166
|
+
if (lastCodeIdx === -1) {
|
|
167
|
+
const updated =
|
|
168
|
+
raw.slice(0, openBracketIdx + 1) +
|
|
169
|
+
"\n " +
|
|
170
|
+
pluginEntryStr +
|
|
171
|
+
"\n " +
|
|
172
|
+
raw.slice(closeBracketIdx);
|
|
173
|
+
fs.writeFileSync(filePath, updated, "utf8");
|
|
174
|
+
return "updated";
|
|
175
|
+
}
|
|
176
|
+
const lastChar = insideRaw[lastCodeIdx];
|
|
177
|
+
const withComma =
|
|
178
|
+
lastChar === ","
|
|
179
|
+
? insideRaw.replace(/\s+$/, "")
|
|
180
|
+
: insideRaw.slice(0, lastCodeIdx + 1) + "," + insideRaw.slice(lastCodeIdx + 1).replace(/\s+$/, "");
|
|
181
|
+
const updated =
|
|
182
|
+
raw.slice(0, openBracketIdx + 1) +
|
|
183
|
+
withComma +
|
|
184
|
+
"\n " +
|
|
185
|
+
pluginEntryStr +
|
|
186
|
+
"\n " +
|
|
187
|
+
raw.slice(closeBracketIdx);
|
|
188
|
+
fs.writeFileSync(filePath, updated, "utf8");
|
|
189
|
+
return "updated";
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const lastBraceIdx = raw.lastIndexOf("}");
|
|
193
|
+
if (lastBraceIdx !== -1) {
|
|
194
|
+
const beforeRaw = raw.slice(0, lastBraceIdx);
|
|
195
|
+
const lastCodeIdx = findLastCodeCharIndex(beforeRaw);
|
|
196
|
+
const lastChar = lastCodeIdx !== -1 ? beforeRaw[lastCodeIdx] : "{";
|
|
197
|
+
const needsComma = lastChar !== "{" && lastChar !== ",";
|
|
198
|
+
const withComma = needsComma
|
|
199
|
+
? beforeRaw.slice(0, lastCodeIdx + 1) + "," + beforeRaw.slice(lastCodeIdx + 1).replace(/\s+$/, "")
|
|
200
|
+
: beforeRaw.replace(/\s+$/, "");
|
|
201
|
+
const updated =
|
|
202
|
+
withComma +
|
|
203
|
+
'\n "plugins": [\n ' +
|
|
204
|
+
pluginEntryStr +
|
|
205
|
+
"\n ]\n}\n";
|
|
206
|
+
fs.writeFileSync(filePath, updated, "utf8");
|
|
207
|
+
return "updated";
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return "skipped";
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export async function installPlugin(options) {
|
|
214
|
+
const opts = options || {};
|
|
215
|
+
const configDir = resolveConfigDir(opts.configDir);
|
|
216
|
+
fs.mkdirSync(configDir, { recursive: true });
|
|
217
|
+
|
|
218
|
+
const pkgName = "@nandoblanco/opencode-local-tokens";
|
|
219
|
+
const matchKey = "opencode-local-tokens";
|
|
220
|
+
const entryStr = opts.cacheAlerts === true
|
|
221
|
+
? JSON.stringify({ package: pkgName, options: { cacheAlerts: true } })
|
|
222
|
+
: JSON.stringify(pkgName);
|
|
223
|
+
|
|
224
|
+
const jsoncCandidate = path.join(configDir, cliName + ".jsonc");
|
|
225
|
+
const jsonCandidate = path.join(configDir, cliName + ".json");
|
|
226
|
+
const serverConfigFile = fs.existsSync(jsoncCandidate)
|
|
227
|
+
? jsoncCandidate
|
|
228
|
+
: fs.existsSync(jsonCandidate)
|
|
229
|
+
? jsonCandidate
|
|
230
|
+
: jsoncCandidate;
|
|
231
|
+
|
|
232
|
+
const serverStatus = addPluginToJsoncFile(
|
|
233
|
+
serverConfigFile,
|
|
234
|
+
"https://" + cliName + ".ai/config.json",
|
|
235
|
+
entryStr,
|
|
236
|
+
matchKey
|
|
237
|
+
);
|
|
238
|
+
|
|
239
|
+
return {
|
|
240
|
+
configDir,
|
|
241
|
+
serverConfigFile,
|
|
242
|
+
serverStatus,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const isDirectRun =
|
|
247
|
+
process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
|
|
248
|
+
if (isDirectRun) {
|
|
249
|
+
const args = process.argv.slice(2);
|
|
250
|
+
const cmd = args[0];
|
|
251
|
+
|
|
252
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
253
|
+
console.log(
|
|
254
|
+
"opencode-tokens install [--dir <config-dir>] [--cache-alerts]\n" +
|
|
255
|
+
"opencode-tokens [query] [--project name] [--model name] [--tag tag] [--liked] [--limit count] [--sort mode]\n" +
|
|
256
|
+
"Sort: billed, total, steps, updated, newest, oldest, title, relevance\n" +
|
|
257
|
+
"Commands: install, like <session>, unlike <session>, tag <session> <tags>, untag <session> <tags>, note <session> <text>\n" +
|
|
258
|
+
"Tags: comma-separated, e.g. review,billing\n" +
|
|
259
|
+
"In OpenCode: /tokens opens analytics (Ctrl+S sort, Ctrl+T add tags, Ctrl+R remove tags); /handoff creates a checkpoint for a fresh session."
|
|
260
|
+
);
|
|
261
|
+
} else if (cmd === "install" || cmd === "init" || cmd === "setup") {
|
|
262
|
+
let configDir;
|
|
263
|
+
let cacheAlerts = false;
|
|
264
|
+
for (let i = 1; i < args.length; i++) {
|
|
265
|
+
if ((args[i] === "--dir" || args[i] === "-d") && args[i + 1]) {
|
|
266
|
+
configDir = args[i + 1];
|
|
267
|
+
i++;
|
|
268
|
+
} else if (args[i] === "--cache-alerts") {
|
|
269
|
+
cacheAlerts = true;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
installPlugin({ configDir, cacheAlerts })
|
|
273
|
+
.then((res) => {
|
|
274
|
+
console.log("opencode-local-tokens installed:");
|
|
275
|
+
console.log(" Config file: " + res.serverConfigFile + " (" + res.serverStatus + ")");
|
|
276
|
+
})
|
|
277
|
+
.catch((err) => {
|
|
278
|
+
console.error("Install failed:", err);
|
|
279
|
+
process.exit(1);
|
|
280
|
+
});
|
|
281
|
+
} else {
|
|
282
|
+
import("./src/tokens.ts")
|
|
283
|
+
.then(({ runTokensCli }) => runTokensCli(args))
|
|
284
|
+
.catch((err) => {
|
|
285
|
+
console.error("Command failed:", err);
|
|
286
|
+
process.exit(1);
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|