@emesoft/tokenhub 0.9.1 → 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
@@ -56,6 +56,8 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
56
56
  | `--no-statusline` | `connect` | Don't add the spend status line to Claude Code. |
57
57
  | `--no-model-picker` | `connect` | Don't offer to install the TokenHub model picker. |
58
58
  | `--remote` / `--no-remote` | `connect` | Set up TokenHub Remote without asking / skip its question. |
59
+ | `--plain` | `connect` | One plain line per finished step instead of the progress bar (also used without a terminal or with `NO_COLOR`). |
60
+ | `--verbose` | `connect` | Also print what is otherwise only kept in `~/.tokenhub/remote/install.log` (download sizes, backup paths, the settings diff, PATH details). |
59
61
  | `--force` | `disconnect` | Stop the Remote daemon even while it hosts Claude sessions (they end). |
60
62
  | `--admin` | `connect`, `disconnect` | Pair (or forget) this machine as an admin device. See [For admins](#for-admins). |
61
63
  | `--json` | `usage` | Print the raw report. |
@@ -81,6 +83,10 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
81
83
  only in its fullscreen layout, so after installing the picker `connect` asks whether to turn that on
82
84
  (`"tui": "fullscreen"`, default no); in the classic layout the picker works from the keyboard and says
83
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`.
84
90
  - Asks whether to set up **TokenHub Remote**, unless you pass `--remote` or `--no-remote` (see [TokenHub Remote](#tokenhub-remote)).
85
91
  - Keeps every other setting, and saves the previous file as `settings.json.bak`.
86
92
 
package/bin/tokenhub.js CHANGED
@@ -17,7 +17,7 @@ import { fetchUsage, formatUsage, resolveCredentials } from "../lib/usage.js";
17
17
  const HELP = `tokenhub - pair Claude Code with your TokenHub tenant
18
18
 
19
19
  Usage:
20
- tokenhub connect [tenant] [--no-statusline] [--no-model-picker] [--remote | --no-remote]
20
+ tokenhub connect [tenant] [--no-statusline] [--no-model-picker] [--remote | --no-remote] [--plain] [--verbose]
21
21
  Pair this machine and write ~/.claude/settings.json, including the status line
22
22
  (today's spend under the prompt) unless --no-statusline. Then offers to install the
23
23
  TokenHub model picker (a bare /model in Claude Code lists TokenHub models) unless
@@ -27,7 +27,9 @@ Usage:
27
27
  the daemon, pairs this computer (one more approval in the browser), adds the /tf-remote
28
28
  command to Claude Code and, if you agree, a launcher that makes claude use it, first on your PATH
29
29
  tenant is your tenant name (acme = https://acme.${TENANT_DOMAIN}) or a full URL;
30
- it is asked for when left out
30
+ it is asked for when left out. One progress bar shows the steps; --plain prints one
31
+ line per finished step instead (also used without a terminal or with NO_COLOR) and
32
+ --verbose prints what is otherwise only kept in ~/.tokenhub/remote/install.log
31
33
  tokenhub connect [tenant] --admin
32
34
  Pair this machine as an admin device (for the desktop overlay's pool view): the admin
33
35
  confirms in the console, the token is saved to ~/.tokenhub/admin.json
@@ -94,6 +96,8 @@ async function main(argv) {
94
96
  adminFile: adminConfigPath(),
95
97
  modelPicker: !flags.includes("--no-model-picker"),
96
98
  remote: flags.includes("--remote") ? true : flags.includes("--no-remote") ? false : undefined,
99
+ plain: flags.includes("--plain"),
100
+ verbose: flags.includes("--verbose"),
97
101
  });
98
102
  }
99
103
  if (command === "desktop") {
@@ -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
+ }
@@ -0,0 +1,2 @@
1
+ export function installLogPath(root: string): string;
2
+ export function openInstallLog(options: { file: string; title?: string; now?: () => Date }): { file: string; write(line: string): void };
@@ -0,0 +1,46 @@
1
+ import { appendFileSync, mkdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ /**
5
+ * Where the installer's log goes: `<remote dir>/install.log`.
6
+ * @param {string} root The Remote folder (`remoteDir()`).
7
+ * @returns {string} Absolute path.
8
+ */
9
+ export function installLogPath(root) {
10
+ return join(root, "install.log");
11
+ }
12
+ /**
13
+ * The installer's log: a file that every run appends to, each run under a header with its time. It holds what a quiet install
14
+ * does not print (download sizes, backup paths, the settings diff, the hook script's output, PATH and launcher details) and what
15
+ * it printed. Writing never throws: a log that cannot be written must not stop an install.
16
+ *
17
+ * @param {object} options
18
+ * @param {string} options.file Path of the log (created with its folder).
19
+ * @param {string} [options.title] What the run is, for the header (`tokenhub connect --remote`).
20
+ * @param {() => Date} [options.now] Clock (tests).
21
+ * @returns {{ file: string, write: (line: string) => void }} The log. The header is written with the first line.
22
+ */
23
+ export function openInstallLog({ file, title = "tokenhub connect", now = () => new Date() }) {
24
+ let started = false;
25
+ let broken = false;
26
+ /** @param {string} text Text to append. */
27
+ const append = (text) => {
28
+ if (broken) return;
29
+ try {
30
+ mkdirSync(dirname(file), { recursive: true });
31
+ appendFileSync(file, text);
32
+ } catch {
33
+ broken = true;
34
+ }
35
+ };
36
+ return {
37
+ file,
38
+ write(line) {
39
+ if (!started) {
40
+ started = true;
41
+ append(`\n=== ${now().toISOString()} ${title} ===\n`);
42
+ }
43
+ append(`${line}\n`);
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,27 @@
1
+ import type { Progress, ProgressStream } from "./progress.js";
2
+
3
+ export interface InstallUi {
4
+ readonly progress: Progress;
5
+ /** Path of the log once `useLog` has been called. */
6
+ readonly logFile: string | undefined;
7
+ useLog(file: string, title?: string): void;
8
+ say(line: string): void;
9
+ detail(line: string): void;
10
+ ask(question: (text: string, defaultYes?: boolean) => Promise<boolean>): (text: string, defaultYes?: boolean) => Promise<boolean>;
11
+ begin(label: string): void;
12
+ update(change: { label?: string; within?: number }): void;
13
+ complete(text: string): void;
14
+ addSteps(count: number): void;
15
+ finish(label: string): void;
16
+ close(): void;
17
+ }
18
+ export interface InstallUiOptions {
19
+ log?: (line: string) => void;
20
+ stream?: ProgressStream;
21
+ env?: Record<string, string | undefined>;
22
+ plain?: boolean;
23
+ verbose?: boolean;
24
+ total?: number;
25
+ now?: () => Date;
26
+ }
27
+ export function createInstallUi(options?: InstallUiOptions): InstallUi;
@@ -0,0 +1,66 @@
1
+ import { openInstallLog } from "./install-log.js";
2
+ import { createProgress } from "./progress.js";
3
+
4
+ /**
5
+ * What `tokenhub connect` shows while it works: the progress bar, plain lines for what the user must read, and a log file for the rest.
6
+ *
7
+ * - `say(line)` is for what the user must read or act on (a code, a question's text, a warning, an error): the bar is paused first,
8
+ * so the line is printed plainly below it and the bar is drawn again on a fresh line by the next step.
9
+ * - `detail(line)` is for what a quiet install keeps to itself (sizes, paths, diffs, hook output): it goes to the log file, and is printed
10
+ * only with `verbose` (which also turns the bar into plain step lines, so the output reads in order).
11
+ * - `ask(fn)` wraps a yes/no prompt so the bar is paused before it is shown.
12
+ * - the step methods (`begin`, `update`, `complete`, `finish`, `addSteps`) drive the bar.
13
+ *
14
+ * @param {object} options
15
+ * @param {(line: string) => void} [options.log] Where plain lines go (console.log).
16
+ * @param {import("./progress.js").ProgressStream} [options.stream] Where the bar is drawn (stdout).
17
+ * @param {Record<string, string | undefined>} [options.env] Environment (NO_COLOR, TERM, CI).
18
+ * @param {boolean} [options.plain] `--plain`: plain step lines, no bar.
19
+ * @param {boolean} [options.verbose] `--verbose`: print the details too (and no bar).
20
+ * @param {number} [options.total] Steps in all.
21
+ * @param {() => Date} [options.now] Clock for the log's headers (tests).
22
+ * @returns {InstallUi} The interface.
23
+ */
24
+ export function createInstallUi({ log = console.log, stream = process.stdout, env = process.env, plain = false, verbose = false, total = 1, now } = {}) {
25
+ const progress = createProgress({ stream, log, env, plain: plain || verbose, total });
26
+ /** @type {{ file: string, write: (line: string) => void } | undefined} */
27
+ let logFile;
28
+ return {
29
+ progress,
30
+ get logFile() {
31
+ return logFile?.file;
32
+ },
33
+ useLog(file, title) {
34
+ logFile = openInstallLog({ file, title, now });
35
+ },
36
+ say(line) {
37
+ progress.pause();
38
+ logFile?.write(line);
39
+ log(line);
40
+ },
41
+ detail(line) {
42
+ logFile?.write(line);
43
+ if (verbose) {
44
+ progress.pause();
45
+ log(` ${line}`);
46
+ }
47
+ },
48
+ ask(question) {
49
+ return async (text, defaultYes) => {
50
+ progress.pause();
51
+ const answer = await question(text, defaultYes);
52
+ logFile?.write(`? ${text} ${answer ? "yes" : "no"}`);
53
+ return answer;
54
+ };
55
+ },
56
+ begin: (label) => progress.begin(label),
57
+ update: (change) => progress.update(change),
58
+ complete(text) {
59
+ logFile?.write(`step ${progress.done + 1}/${progress.total}: ${text}`);
60
+ progress.complete(text);
61
+ },
62
+ addSteps: (count) => progress.setTotal(progress.total + count),
63
+ finish: (label) => progress.finish(label),
64
+ close: () => progress.close(),
65
+ };
66
+ }
@@ -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/lib/pair.d.ts CHANGED
@@ -51,4 +51,10 @@ export function runConnect(options: {
51
51
  home?: string;
52
52
  /** Yes/no prompt; answers false without a terminal. */
53
53
  ask?: (question: string, defaultYes?: boolean) => Promise<boolean>;
54
+ /** One plain line per finished step instead of the progress bar (--plain). */
55
+ plain?: boolean;
56
+ /** Also print what is otherwise only in the install log; plain lines, no bar (--verbose). */
57
+ verbose?: boolean;
58
+ /** Where the progress bar is drawn; stdout by default. */
59
+ stream?: import("./progress.js").ProgressStream;
54
60
  }): Promise<number>;