@emesoft/tokenhub 0.9.2 → 0.9.3

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,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.3",
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
  ],