@emesoft/tokenhub 0.9.2 → 0.9.4

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/README.md CHANGED
@@ -83,6 +83,10 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
83
83
  only in its fullscreen layout, so after installing the picker `connect` asks whether to turn that on
84
84
  (`"tui": "fullscreen"`, default no); in the classic layout the picker works from the keyboard and says
85
85
  `/tui fullscreen` turns the mouse on. `disconnect` leaves `tui` as it is.
86
+ The same install adds a second plugin, `tokenhub-usage` (`enabledPlugins["tokenhub-usage@tokenhub"]`): for an
87
+ **admin** device (`tokenhub connect --admin`), a bare `/usage` opens a panel above the prompt listing every pool
88
+ account with its 5h and weekly usage, status, resets and balance (Refresh re-reads it). Without an admin device it
89
+ says to run `tokenhub connect --admin`; `/usage <args>` and other hosts keep Claude Code's own `/usage`.
86
90
  - Asks whether to set up **TokenHub Remote**, unless you pass `--remote` or `--no-remote` (see [TokenHub Remote](#tokenhub-remote)).
87
91
  - Keeps every other setting, and saves the previous file as `settings.json.bak`.
88
92
 
@@ -6,6 +6,11 @@
6
6
  "name": "tokenhub-models",
7
7
  "source": "./plugins/tokenhub-models",
8
8
  "description": "A bare /model opens a TokenHub model picker above the prompt"
9
+ },
10
+ {
11
+ "name": "tokenhub-usage",
12
+ "source": "./plugins/tokenhub-usage",
13
+ "description": "A bare /usage opens the pool's account usage above the prompt for an admin device"
9
14
  }
10
15
  ]
11
16
  }
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "tokenhub-usage",
3
+ "version": "0.1.0",
4
+ "description": "A bare /usage opens the TokenHub pool's account usage above the prompt for an admin device when ANTHROPIC_BASE_URL points at TokenHub",
5
+ "author": { "name": "Emesoft" },
6
+ "license": "MIT",
7
+ "types": "./types/index.d.ts"
8
+ }
@@ -0,0 +1 @@
1
+ { "modules": ["./register.tsx"] }
@@ -0,0 +1,242 @@
1
+ import { atom, read, update } from 'claude-code'
2
+ import type { EngineInterface, Register } from 'claude-code'
3
+ import type { UsageReport, UsageRow } from '../types/index'
4
+
5
+ const SELF = 'tokenhub-usage'
6
+ const isOpen = atom({ plugin: 'tokenhub-usage', key: 'isOpen' } as const, false)
7
+ // Where the panel is: `loading` before the first answer, then `ok`, `nolink` (no admin device on this machine),
8
+ // `invalid` (the pool refused the token) or `offline` (no answer, or an answer that is not a report).
9
+ const phase = atom({ plugin: 'tokenhub-usage', key: 'phase' } as const, 'loading')
10
+ // The last report the pool answered, kept for the session so a failed refresh still shows the rows.
11
+ const report = atom({ plugin: 'tokenhub-usage', key: 'report' } as const, null)
12
+ // A line under the header: a refresh under way, or a limit the pool answered.
13
+ const note = atom({ plugin: 'tokenhub-usage', key: 'note' } as const, '')
14
+ const busy = atom({ plugin: 'tokenhub-usage', key: 'busy' } as const, false)
15
+ const OVERLAY_PATH = '/admin/api/overlay'
16
+ const REFRESH_PATH = '/admin/api/overlay/refresh'
17
+ /** How long a call waits for the pool before the panel says it did not answer. */
18
+ const FETCH_TIMEOUT_MS = 3000
19
+ const BAR_CELLS = 8
20
+ /** TokenHub hosts: `<slug>.aimpact.io.vn`, or a local gateway on 8787-8789. */
21
+ function isTokenHub(base: string | undefined): boolean {
22
+ if (!base) return false
23
+ try {
24
+ const url = new URL(base)
25
+ return url.hostname.endsWith('.aimpact.io.vn') ||
26
+ ((url.hostname === 'localhost' || url.hostname === '127.0.0.1') && ['8787', '8788', '8789'].includes(url.port))
27
+ } catch {
28
+ return false
29
+ }
30
+ }
31
+ /**
32
+ * Reads the admin device `tokenhub connect --admin` stored: `admin.json` under `$TOKENHUB_CONFIG_DIR`, else under
33
+ * `~/.tokenhub`. It reports no reason for a failed read, so no text of the file can reach a toast.
34
+ * @returns The pool address and token, or null when the file is missing or unusable.
35
+ */
36
+ async function readAdmin($: EngineInterface): Promise<{ baseUrl: string; token: string } | null> {
37
+ try {
38
+ const config = await $.env.get('TOKENHUB_CONFIG_DIR')
39
+ const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
40
+ const dir = config || (home ? `${home.replace(/[\\/]+$/, '')}/.tokenhub` : '')
41
+ if (!dir) return null
42
+ const body = JSON.parse(await $.fs.read(`${dir.replace(/[\\/]+$/, '')}/admin.json`)) as { baseUrl?: unknown; token?: unknown }
43
+ return typeof body?.baseUrl === 'string' && typeof body?.token === 'string' && body.baseUrl && body.token
44
+ ? { baseUrl: body.baseUrl.replace(/\/+$/, ''), token: body.token }
45
+ : null
46
+ } catch {
47
+ return null
48
+ }
49
+ }
50
+ const pct = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? Math.max(0, Math.min(100, Math.round(v))) : null)
51
+ const iso = (v: unknown): string | null => (typeof v === 'string' && v ? v : null)
52
+ /** @returns The report of an answer when it has the expected shape, else null. */
53
+ function parseReport(text: string): UsageReport | null {
54
+ let body: unknown
55
+ try {
56
+ body = JSON.parse(text)
57
+ } catch {
58
+ return null
59
+ }
60
+ const accounts = (body as { accounts?: unknown })?.accounts
61
+ if (!Array.isArray(accounts)) return null
62
+ const rows: UsageRow[] = []
63
+ for (const a of accounts) {
64
+ if (typeof a?.name !== 'string') continue
65
+ const b = a.balance
66
+ rows.push({
67
+ name: a.name,
68
+ provider: typeof a.provider === 'string' ? a.provider : '',
69
+ status: typeof a.status === 'string' ? a.status : 'ok',
70
+ used5h: pct(a.used_5h),
71
+ usedWeekly: pct(a.used_weekly),
72
+ resets5hAt: iso(a.resets_5h_at),
73
+ resetsWeeklyAt: iso(a.resets_weekly_at),
74
+ balance: b && typeof b.amount === 'number' && typeof b.currency === 'string'
75
+ ? { amount: b.amount, currency: b.currency, low: b.low === true }
76
+ : null,
77
+ })
78
+ }
79
+ const flight = (body as { in_flight?: unknown }).in_flight
80
+ const at = (body as { updated_at?: unknown }).updated_at
81
+ return { rows, inFlight: typeof flight === 'number' ? flight : 0, updatedAt: typeof at === 'string' ? at : '' }
82
+ }
83
+ /** One call to the pool, bearing the admin token; null when it failed or took longer than `FETCH_TIMEOUT_MS`. */
84
+ async function call($: EngineInterface, url: string, token: string, method?: string) {
85
+ const stop = new AbortController()
86
+ // A sleep that cannot run (refused, or cut short by the abort below) never counts as a timeout.
87
+ const timeout = $.clock.sleep(FETCH_TIMEOUT_MS, { signal: stop.signal }).then(() => null, () => new Promise<null>(() => {}))
88
+ const answer = await Promise.race([
89
+ $.http.fetch(url, { method, headers: { authorization: `Bearer ${token}` } }).catch(() => null),
90
+ timeout,
91
+ ])
92
+ stop.abort()
93
+ return answer
94
+ }
95
+ /**
96
+ * Reads the pool's usage (after a refresh when asked) and stores it; never throws, and never writes the token to
97
+ * the panel, a toast or an error text.
98
+ */
99
+ async function loadUsage($: EngineInterface, refresh: boolean): Promise<void> {
100
+ if (await read($, busy).catch(() => false)) return
101
+ await update($, busy, () => true).catch(() => undefined)
102
+ try {
103
+ const admin = await readAdmin($)
104
+ if (!admin) {
105
+ await update($, phase, () => 'nolink')
106
+ return
107
+ }
108
+ let hint = ''
109
+ if (refresh) {
110
+ await update($, note, () => 'refreshing...')
111
+ const pushed = await call($, `${admin.baseUrl}${REFRESH_PATH}`, admin.token, 'POST')
112
+ if (pushed?.status === 429) hint = 'refresh limited, try again shortly'
113
+ }
114
+ const answer = await call($, `${admin.baseUrl}${OVERLAY_PATH}`, admin.token)
115
+ if (answer?.status === 401) {
116
+ await update($, report, () => null)
117
+ await update($, phase, () => 'invalid')
118
+ await update($, note, () => '')
119
+ return
120
+ }
121
+ if (answer?.status === 429) hint = 'too many requests, try again shortly'
122
+ const parsed = answer?.ok ? parseReport(answer.text) : null
123
+ if (parsed) await update($, report, () => parsed)
124
+ await update($, phase, () => (parsed ? 'ok' : 'offline'))
125
+ await update($, note, () => hint)
126
+ } catch {
127
+ await update($, phase, () => 'offline').catch(() => undefined)
128
+ await update($, note, () => '').catch(() => undefined)
129
+ } finally {
130
+ await update($, busy, () => false).catch(() => undefined)
131
+ }
132
+ }
133
+ /** @returns A remaining time as `3d 4h`, `2h 10m` or `45m`; empty when unknown or already past. */
134
+ function untilLabel(at: string | null, now: number): string {
135
+ const ms = at ? Date.parse(at) - now : NaN
136
+ if (!Number.isFinite(ms) || ms <= 0) return ''
137
+ const minutes = Math.floor(ms / 60_000)
138
+ const days = Math.floor(minutes / 1440)
139
+ const hours = Math.floor((minutes % 1440) / 60)
140
+ if (days > 0) return `${days}d ${hours}h`
141
+ return hours > 0 ? `${hours}h ${minutes % 60}m` : `${minutes}m`
142
+ }
143
+ /** @returns A used share as a text bar of `BAR_CELLS`, then its percent; dashes when never reported. */
144
+ function barLabel(used: number | null): string {
145
+ if (used === null) return `${'-'.repeat(BAR_CELLS)} --%`
146
+ const filled = Math.round((used / 100) * BAR_CELLS)
147
+ return `${'█'.repeat(filled)}${'░'.repeat(BAR_CELLS - filled)} ${String(used).padStart(3)}%`
148
+ }
149
+ const usedColor = (used: number | null) => (used !== null && used >= 90 ? 'error' : used !== null && used >= 70 ? 'warning' : undefined)
150
+ const statusColor = (status: string) => (status === 'ok' ? 'success' : status === 'limited' ? 'warning' : status === 'offline' ? 'error' : 'inactive')
151
+ /** @returns `hh:mm` of an ISO instant in local time; empty when it is not one. */
152
+ function clockLabel(at: string): string {
153
+ const d = new Date(at)
154
+ return Number.isNaN(d.getTime()) ? '' : `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
155
+ }
156
+ const MESSAGES: Record<string, string> = {
157
+ nolink: 'Pool usage needs an admin device: run `tokenhub connect --admin`',
158
+ invalid: 'Admin device token invalid or revoked; run `tokenhub connect --admin` again',
159
+ offline: 'TokenHub did not answer',
160
+ }
161
+ export const register: Register = on => {
162
+ on('command.run', { command: 'usage' }, async ($, e, next) => {
163
+ // `/usage <args>`, our own runs and non-TokenHub sessions keep the built-in command.
164
+ if ((e.args ?? '').trim() !== '') return next(e)
165
+ if (e.origin?.kind === 'plugin' && e.origin.name === SELF) return next(e)
166
+ try {
167
+ if (!isTokenHub(await $.env.get('ANTHROPIC_BASE_URL'))) return next(e)
168
+ await update($, isOpen, () => true)
169
+ await update($, note, () => '')
170
+ if ((await read($, report)) === null) await update($, phase, () => 'loading')
171
+ } catch (err) {
172
+ $.ui.toast(`tokenhub-usage: ${String(err)}`)
173
+ return next(e) // never block /usage on a failure of ours
174
+ }
175
+ void loadUsage($, false)
176
+ return { text: 'TokenHub pool usage opened above the prompt.' }
177
+ })
178
+ // Enter on an empty prompt closes the panel; a typed prompt closes it and is sent as usual.
179
+ on('prompt.submit', async ($, e, next) => {
180
+ let open = false
181
+ try {
182
+ open = await read($, isOpen)
183
+ } catch {
184
+ return next(e)
185
+ }
186
+ if (open) await update($, isOpen, () => false).catch(() => undefined)
187
+ if (open && e.text.trim() === '') return { drop: 'Usage closed.' }
188
+ return next(e)
189
+ })
190
+ // Anything typed while the panel is open closes it, as its hint says; the text stays in the prompt.
191
+ on('prompt.edit', async ($, e, next) => {
192
+ if (e.inputText && (await read($, isOpen).catch(() => false))) await update($, isOpen, () => false).catch(() => undefined)
193
+ return next(e)
194
+ })
195
+ on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
196
+ if (e.props.hasSurvey || !(await read($, isOpen))) return next(e)
197
+ if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e)
198
+ const { Box, Text, Button } = $.ui.resolve(e)
199
+ const state = await read($, phase)
200
+ const data = await read($, report)
201
+ const hint = await read($, note)
202
+ const now = await $.clock.now()
203
+ const close = () => void update($, isOpen, () => false)
204
+ const header = data
205
+ ? `Pool usage · TokenHub · ${data.rows.length} account${data.rows.length === 1 ? '' : 's'} · in flight ${data.inFlight}` +
206
+ (clockLabel(data.updatedAt) ? ` · updated ${clockLabel(data.updatedAt)}` : '')
207
+ : 'Pool usage · TokenHub'
208
+ const problem = MESSAGES[state]
209
+ return (
210
+ <Box flexDirection="column" borderStyle="round" paddingX={1}>
211
+ <Box flexDirection="row">
212
+ <Text bold>{header} </Text>
213
+ {state === 'ok' || state === 'offline' ? <Button key="refresh" plain dimColor onPress={() => void loadUsage($, true)}>Refresh</Button> : ''}
214
+ {state === 'ok' || state === 'offline' ? <Text> </Text> : ''}
215
+ <Button key="builtin" plain dimColor onPress={() => { close(); void $.command.run({ command: 'usage' }) }}>Built-in /usage</Button>
216
+ <Text> </Text>
217
+ <Button key="close" plain dimColor onPress={close}>Close</Button>
218
+ </Box>
219
+ {state === 'loading' ? <Text dimColor>Loading pool usage...</Text> : ''}
220
+ {problem ? <Text color={state === 'offline' ? 'warning' : 'error'}>{problem}</Text> : ''}
221
+ {hint ? <Text dimColor>{hint}</Text> : ''}
222
+ {data && state !== 'nolink' && state !== 'invalid'
223
+ ? data.rows.map((row, i) => (
224
+ <Box key={`row${i}`} flexDirection="row">
225
+ <Box width={20}><Text wrap="truncate">{row.name}</Text></Box>
226
+ <Box width={13}><Text wrap="truncate" dimColor>{row.provider}</Text></Box>
227
+ <Box width={10}><Text color={statusColor(row.status)}>{row.status}</Text></Box>
228
+ <Box width={22}><Text wrap="truncate" color={usedColor(row.used5h)}>{`5h ${barLabel(row.used5h)}`}</Text></Box>
229
+ <Box width={9}><Text wrap="truncate" dimColor>{untilLabel(row.resets5hAt, now)}</Text></Box>
230
+ <Box width={22}><Text wrap="truncate" color={usedColor(row.usedWeekly)}>{`wk ${barLabel(row.usedWeekly)}`}</Text></Box>
231
+ <Box width={9}><Text wrap="truncate" dimColor>{untilLabel(row.resetsWeeklyAt, now)}</Text></Box>
232
+ <Text color={row.balance?.low ? 'warning' : undefined}>
233
+ {row.balance ? `${row.balance.currency} ${row.balance.amount.toFixed(2)}${row.balance.low ? ' low' : ''}` : ''}
234
+ </Text>
235
+ </Box>
236
+ ))
237
+ : ''}
238
+ <Text dimColor>Type to close · Enter closes</Text>
239
+ </Box>
240
+ )
241
+ })
242
+ }
@@ -0,0 +1,24 @@
1
+ export type UsageRow = {
2
+ name: string
3
+ provider: string
4
+ status: string
5
+ used5h: number | null
6
+ usedWeekly: number | null
7
+ resets5hAt: string | null
8
+ resetsWeeklyAt: string | null
9
+ balance: { amount: number; currency: string; low: boolean } | null
10
+ }
11
+ export type UsageReport = { rows: UsageRow[]; inFlight: number; updatedAt: string }
12
+ declare module 'claude-code' {
13
+ interface PluginState {
14
+ 'tokenhub-usage': {
15
+ isOpen: boolean
16
+ /** `loading` before the first answer, then `ok`, `nolink` (no admin device), `invalid` (token refused) or `offline`. */
17
+ phase: string
18
+ report: UsageReport | null
19
+ /** A short line under the header: a refresh in progress or a limit the pool answered. */
20
+ note: string
21
+ busy: boolean
22
+ }
23
+ }
24
+ }
@@ -1,5 +1,5 @@
1
1
  import { hostname } from "node:os";
2
- import { appDataCacheDir, appDataDir, fetchModels, isInstalled, writeDesktopConfig } from "./desktop.js";
2
+ import { appDataDir, fetchModels, isInstalled, writeDesktopConfig } from "./desktop.js";
3
3
  import { openBrowser, pairDevice, resolvePoolUrl } from "./pair.js";
4
4
 
5
5
  /**
@@ -37,7 +37,7 @@ export async function runDesktop({
37
37
  return 1;
38
38
  }
39
39
  // Judged before the write, which creates the folder.
40
- const installed = isInstalled(dir, platform === "win32" ? appDataCacheDir(env, home) : null);
40
+ const installed = isInstalled(dir);
41
41
  let pool;
42
42
  try {
43
43
  pool = resolvePoolUrl(poolUrl);
package/lib/desktop.js CHANGED
@@ -1,4 +1,5 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
3
  import { homedir } from "node:os";
3
4
  import { join } from "node:path";
4
5
 
@@ -11,20 +12,25 @@ import { join } from "node:path";
11
12
  export const APP_FOLDER = "Claude-3p";
12
13
  /** Name of the configuration this writes and applies. */
13
14
  export const CONFIG_NAME = "TokenHub";
15
+ /** Desktop loads a configuration only when its id has this shape (a UUID) and ignores any other id (#829). */
16
+ const ID_SHAPE = /^[a-f0-9-]{36}$/;
17
+ /** The id releases before #829 wrote, which Desktop never loaded. */
18
+ const LEGACY_ID = "tokenhub";
14
19
  /** Effort levels Desktop knows, lowest first. */
15
20
  const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
16
21
  /** Families Desktop recognises in `anthropicFamilyTier`. */
17
22
  const TIERS = ["sonnet", "opus", "haiku", "fable", "mythos"];
18
23
 
19
24
  /**
20
- * Where Claude Desktop keeps its 3p data per platform.
25
+ * Where Claude Desktop keeps its 3p data per platform. On Windows that is Local app data, not Roaming: Desktop 5.x
26
+ * reads its 3p config from `%LOCALAPPDATA%` (#829).
21
27
  * @param {string} [platform] Node platform name.
22
- * @param {Record<string, string | undefined>} [env] Environment to read APPDATA / XDG_CONFIG_HOME from.
28
+ * @param {Record<string, string | undefined>} [env] Environment to read LOCALAPPDATA / XDG_CONFIG_HOME from.
23
29
  * @param {string} [home] Home directory used when the variable is unset.
24
30
  * @returns {string | null} Absolute folder, or null on a platform Desktop does not ship for.
25
31
  */
26
32
  export function appDataDir(platform = process.platform, env = process.env, home = homedir()) {
27
- if (platform === "win32") return join(env.APPDATA || join(home, "AppData", "Roaming"), APP_FOLDER);
33
+ if (platform === "win32") return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), APP_FOLDER);
28
34
  if (platform === "darwin") return join(home, "Library", "Application Support", APP_FOLDER);
29
35
  if (platform === "linux") return join(env.XDG_CONFIG_HOME || join(home, ".config"), APP_FOLDER);
30
36
  return null;
@@ -42,15 +48,15 @@ export function configLibraryDir(base) {
42
48
 
43
49
  /**
44
50
  * The configuration id this machine already uses for TokenHub, so a second run updates that record rather than
45
- * adding another. Falls back to a stable new id derived from the name, which is all Desktop needs.
51
+ * adding another. Falls back to a new UUID, the only id shape Desktop loads.
46
52
  * @param {string} dir Config library folder.
47
53
  * @returns {string} Configuration id.
48
54
  */
49
55
  export function configId(dir) {
50
56
  const meta = readJson(join(dir, "_meta.json"));
51
57
  const entries = Array.isArray(meta?.entries) ? meta.entries : [];
52
- const found = entries.find((entry) => entry?.name === CONFIG_NAME && typeof entry.id === "string");
53
- return found ? found.id : "tokenhub";
58
+ const found = entries.find((entry) => entry?.name === CONFIG_NAME && ID_SHAPE.test(String(entry.id)));
59
+ return found ? found.id : randomUUID();
54
60
  }
55
61
 
56
62
  /**
@@ -97,13 +103,14 @@ export function buildConfig({ baseUrl, key, models, effort = "medium" }) {
97
103
  }
98
104
 
99
105
  /**
100
- * Merge the configuration into `_meta.json` and make it the applied one.
106
+ * Merge the configuration into `_meta.json` and make it the applied one, dropping the entry an older release wrote
107
+ * under the id Desktop ignores.
101
108
  * @param {unknown} meta Existing `_meta.json` (null when absent).
102
109
  * @param {string} id Configuration id.
103
110
  * @returns {Record<string, unknown>} New `_meta.json`.
104
111
  */
105
112
  export function mergeMeta(meta, id) {
106
- const entries = Array.isArray(meta?.entries) ? meta.entries.filter((entry) => entry?.id !== id) : [];
113
+ const entries = Array.isArray(meta?.entries) ? meta.entries.filter((entry) => entry?.id !== id && entry?.id !== LEGACY_ID) : [];
107
114
  return { ...meta, appliedId: id, entries: [...entries, { id, name: CONFIG_NAME }] };
108
115
  }
109
116
 
@@ -156,29 +163,17 @@ export function writeDesktopConfig({ dir, baseUrl, key, models, effort }) {
156
163
  writeFileSync(configPath, `${JSON.stringify(buildConfig({ baseUrl, key, models, effort }), null, 2)}\n`);
157
164
  writeFileSync(metaPath, `${JSON.stringify(mergeMeta(readJson(metaPath), id), null, 2)}\n`);
158
165
  writeFileSync(desktopConfigPath, `${JSON.stringify(mergeDesktopConfig(readJson(desktopConfigPath)), null, 2)}\n`);
166
+ rmSync(join(library, `${LEGACY_ID}.json`), { force: true });
159
167
  return { configPath, metaPath, desktopConfigPath, models: models.length };
160
168
  }
161
169
 
162
170
  /**
163
- * Where Claude Desktop keeps its caches, storage and logs on Windows, beside the folder `appDataDir` returns: Desktop
164
- * splits its app data across Roaming (config) and Local (everything else), and either can exist first.
165
- * @param {Record<string, string | undefined>} [env] Environment to read LOCALAPPDATA from.
166
- * @param {string} [home] Home directory used when the variable is unset.
167
- * @returns {string | null} Absolute folder, or null on a platform Desktop does not split.
168
- */
169
- export function appDataCacheDir(env = process.env, home = homedir()) {
170
- return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), APP_FOLDER);
171
- }
172
-
173
- /**
174
- * Whether Desktop is installed here, judged by its app-data folders: the one it reads config from, or the one it keeps
175
- * caches in. Desktop creates one before the other, so either proves an install (#790).
176
- * @param {string | null} dir Config folder from `appDataDir`.
177
- * @param {string | null} [cacheDir] Cache folder from `appDataCacheDir`.
178
- * @returns {boolean} True when either exists.
171
+ * Whether Desktop is installed here, judged by its 3p app-data folder.
172
+ * @param {string | null} dir Folder from `appDataDir`.
173
+ * @returns {boolean} True when it exists.
179
174
  */
180
- export function isInstalled(dir, cacheDir = null) {
181
- return [dir, cacheDir].some((folder) => Boolean(folder) && existsSync(folder));
175
+ export function isInstalled(dir) {
176
+ return Boolean(dir) && existsSync(dir);
182
177
  }
183
178
 
184
179
  /**
@@ -1,5 +1,6 @@
1
1
  export const MARKETPLACE: string;
2
2
  export const PLUGIN_KEY: string;
3
+ export const USAGE_PLUGIN_KEY: string;
3
4
  export function modelPickerDir(env?: Record<string, string | undefined>, home?: string): string;
4
5
  export function mergeModelPicker(settings: Record<string, any>, dir: string): Record<string, any>;
5
6
  export function removeModelPicker(settings: Record<string, any>): Record<string, any>;
@@ -8,9 +8,12 @@ import { readSettings, writeSettings } from "./settings.js";
8
8
  // The Claude Code mod that turns a bare `/model` into a TokenHub model picker ships inside this package as a
9
9
  // local plugin marketplace (`claude-plugin/`). Installing copies it to a stable folder (the npx cache moves) and
10
10
  // registers it in settings.json: `extraKnownMarketplaces.tokenhub` (a directory source) and
11
- // `enabledPlugins["tokenhub-models@tokenhub"]`. Claude Code loads it on its next start.
11
+ // `enabledPlugins["tokenhub-models@tokenhub"]`. Claude Code loads it on its next start. The marketplace's second
12
+ // plugin, `tokenhub-usage` (a bare `/usage` shows the pool's accounts to an admin device, #821), is installed and
13
+ // enabled with it.
12
14
  export const MARKETPLACE = "tokenhub";
13
15
  export const PLUGIN_KEY = "tokenhub-models@tokenhub";
16
+ export const USAGE_PLUGIN_KEY = "tokenhub-usage@tokenhub";
14
17
  const BUNDLED = fileURLToPath(new URL("../claude-plugin", import.meta.url));
15
18
  /** What is copied: the marketplace manifest and the plugin's runtime files, never its tests. */
16
19
  const PARTS = [
@@ -18,6 +21,9 @@ const PARTS = [
18
21
  join("plugins", "tokenhub-models", ".claude-plugin"),
19
22
  join("plugins", "tokenhub-models", "hooks"),
20
23
  join("plugins", "tokenhub-models", "types"),
24
+ join("plugins", "tokenhub-usage", ".claude-plugin"),
25
+ join("plugins", "tokenhub-usage", "hooks"),
26
+ join("plugins", "tokenhub-usage", "types"),
21
27
  ];
22
28
 
23
29
  /**
@@ -42,7 +48,7 @@ export function mergeModelPicker(settings, dir) {
42
48
  return {
43
49
  ...settings,
44
50
  extraKnownMarketplaces: { ...markets, [MARKETPLACE]: { source: { source: "directory", path: dir } } },
45
- enabledPlugins: { ...enabled, [PLUGIN_KEY]: true },
51
+ enabledPlugins: { ...enabled, [PLUGIN_KEY]: true, [USAGE_PLUGIN_KEY]: true },
46
52
  };
47
53
  }
48
54
 
@@ -53,7 +59,11 @@ export function mergeModelPicker(settings, dir) {
53
59
  */
54
60
  export function removeModelPicker(settings) {
55
61
  const next = { ...settings };
56
- for (const [field, key] of [["extraKnownMarketplaces", MARKETPLACE], ["enabledPlugins", PLUGIN_KEY]]) {
62
+ for (const [field, key] of [
63
+ ["extraKnownMarketplaces", MARKETPLACE],
64
+ ["enabledPlugins", PLUGIN_KEY],
65
+ ["enabledPlugins", USAGE_PLUGIN_KEY],
66
+ ]) {
57
67
  if (!isPlainObject(next[field]) || !(key in next[field])) continue;
58
68
  const { [key]: _gone, ...rest } = next[field];
59
69
  if (Object.keys(rest).length > 0) next[field] = rest;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emesoft/tokenhub",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "description": "Connect Claude Code to a TokenHub pool in one command, and track your spend from the terminal",
5
5
  "keywords": [
6
6
  "claude",
@@ -26,6 +26,9 @@
26
26
  "claude-plugin/plugins/tokenhub-models/.claude-plugin",
27
27
  "claude-plugin/plugins/tokenhub-models/hooks",
28
28
  "claude-plugin/plugins/tokenhub-models/types",
29
+ "claude-plugin/plugins/tokenhub-usage/.claude-plugin",
30
+ "claude-plugin/plugins/tokenhub-usage/hooks",
31
+ "claude-plugin/plugins/tokenhub-usage/types",
29
32
  "README.md",
30
33
  "LICENSE"
31
34
  ],