@emesoft/tokenhub 0.8.4 → 0.8.6
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 +9 -1
- package/bin/tokenhub.js +10 -4
- package/claude-plugin/.claude-plugin/marketplace.json +11 -0
- package/claude-plugin/plugins/tokenhub-models/.claude-plugin/plugin.json +8 -0
- package/claude-plugin/plugins/tokenhub-models/hooks/catalog.ts +40 -0
- package/claude-plugin/plugins/tokenhub-models/hooks/hooks.json +1 -0
- package/claude-plugin/plugins/tokenhub-models/hooks/picker.tsx +62 -0
- package/claude-plugin/plugins/tokenhub-models/hooks/register.tsx +158 -0
- package/claude-plugin/plugins/tokenhub-models/types/index.d.ts +6 -0
- package/lib/model-picker.d.ts +11 -0
- package/lib/model-picker.js +131 -0
- package/lib/pair.d.ts +6 -0
- package/lib/pair.js +25 -4
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -52,6 +52,7 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
52
52
|
| Option | Applies to | Effect |
|
|
53
53
|
| --- | --- | --- |
|
|
54
54
|
| `--no-statusline` | `connect` | Don't add the spend status line to Claude Code. |
|
|
55
|
+
| `--no-model-picker` | `connect` | Don't offer to install the TokenHub model picker. |
|
|
55
56
|
| `--admin` | `connect`, `disconnect` | Pair (or forget) this machine as an admin device. See [For admins](#for-admins). |
|
|
56
57
|
| `--json` | `usage` | Print the raw report. |
|
|
57
58
|
| `--interval <sec>` | `dashboard` | Refresh rate in seconds (default 3, minimum 2). |
|
|
@@ -65,9 +66,16 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
65
66
|
|
|
66
67
|
- Sets `env.ANTHROPIC_BASE_URL` and `env.ANTHROPIC_AUTH_TOKEN` to the pool and a new key for this machine.
|
|
67
68
|
- Adds a `statusLine` showing today's spend and credit, unless you already have one or pass `--no-statusline`.
|
|
69
|
+
- Asks whether to install the **TokenHub model picker**, unless you pass `--no-model-picker` or there is no terminal
|
|
70
|
+
to ask on. On yes it copies a Claude Code plugin to `~/.tokenhub/claude-plugin` and registers it as
|
|
71
|
+
`extraKnownMarketplaces.tokenhub` and `enabledPlugins["tokenhub-models@tokenhub"]`. After a restart, a bare `/model`
|
|
72
|
+
opens a picker of TokenHub models above the prompt: providers side by side, ↑/↓ and Enter or `1`–`9` to pick,
|
|
73
|
+
`,` / `.` for effort. `/model <id>` and other hosts keep Claude Code's own picker. The list is fixed in the plugin and
|
|
74
|
+
does not follow what your key may use; the plugin relies on Claude Code's early-access plugin hooks, which can change
|
|
75
|
+
between Claude Code releases.
|
|
68
76
|
- Keeps every other setting, and saves the previous file as `settings.json.bak`.
|
|
69
77
|
|
|
70
|
-
Each machine gets its own key, which you can revoke from the pool's **Keys** page. `disconnect` removes exactly these entries and nothing else.
|
|
78
|
+
Each machine gets its own key, which you can revoke from the pool's **Keys** page. `disconnect` removes exactly these entries (and the model picker's copy) and nothing else.
|
|
71
79
|
|
|
72
80
|
> If `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_API_KEY` is set in your shell, it takes precedence over `settings.json`. `connect` warns you when it finds one.
|
|
73
81
|
|
package/bin/tokenhub.js
CHANGED
|
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
|
|
|
3
3
|
import { adminConfigPath, removeAdminConfig } from "../lib/admin.js";
|
|
4
4
|
import { isInteractive, showBanner } from "../lib/banner.js";
|
|
5
5
|
import { parseDashboardArgs, runDashboard } from "../lib/dashboard.js";
|
|
6
|
+
import { modelPickerDir, uninstallModelPicker } from "../lib/model-picker.js";
|
|
6
7
|
import { runOverlayInstall } from "../lib/overlay.js";
|
|
7
8
|
import { promptTenant, runConnect, TENANT_DOMAIN } from "../lib/pair.js";
|
|
8
9
|
import { disconnectSettings, readSettings, settingsPath } from "../lib/settings.js";
|
|
@@ -11,9 +12,11 @@ import { fetchUsage, formatUsage, resolveCredentials } from "../lib/usage.js";
|
|
|
11
12
|
const HELP = `tokenhub - pair Claude Code with your TokenHub tenant
|
|
12
13
|
|
|
13
14
|
Usage:
|
|
14
|
-
tokenhub connect [tenant] [--no-statusline]
|
|
15
|
+
tokenhub connect [tenant] [--no-statusline] [--no-model-picker]
|
|
15
16
|
Pair this machine and write ~/.claude/settings.json, including the status line
|
|
16
|
-
(today's spend under the prompt) unless --no-statusline.
|
|
17
|
+
(today's spend under the prompt) unless --no-statusline. Then offers to install the
|
|
18
|
+
TokenHub model picker (a bare /model in Claude Code lists TokenHub models) unless
|
|
19
|
+
--no-model-picker.
|
|
17
20
|
tenant is your tenant name (acme = https://acme.${TENANT_DOMAIN}) or a full URL;
|
|
18
21
|
it is asked for when left out
|
|
19
22
|
tokenhub connect [tenant] --admin
|
|
@@ -23,7 +26,7 @@ Usage:
|
|
|
23
26
|
tokenhub usage [--json] Show today's and this week's spend, credit and pool health
|
|
24
27
|
tokenhub dashboard [--interval <sec>] [--once]
|
|
25
28
|
Live full-screen view of spend, pool health and recent requests (q quits)
|
|
26
|
-
tokenhub disconnect Remove the pool entries
|
|
29
|
+
tokenhub disconnect Remove the pool entries, the status line and the model picker from settings.json
|
|
27
30
|
tokenhub disconnect --admin Forget the admin device token on this machine (revoke it on the pool's admin Devices page)
|
|
28
31
|
tokenhub banner Display the TokenHub welcome banner
|
|
29
32
|
tokenhub --help | --version
|
|
@@ -74,6 +77,7 @@ async function main(argv) {
|
|
|
74
77
|
statusLine: !flags.includes("--no-statusline"),
|
|
75
78
|
admin: flags.includes("--admin"),
|
|
76
79
|
adminFile: adminConfigPath(),
|
|
80
|
+
modelPicker: !flags.includes("--no-model-picker"),
|
|
77
81
|
});
|
|
78
82
|
}
|
|
79
83
|
if (command === "overlay") {
|
|
@@ -115,7 +119,9 @@ async function main(argv) {
|
|
|
115
119
|
console.log(removeAdminConfig(adminFile) ? `Admin device forgotten. Removed ${adminFile}` : `Nothing to remove at ${adminFile}`);
|
|
116
120
|
return 0;
|
|
117
121
|
}
|
|
118
|
-
|
|
122
|
+
const pool = disconnectSettings(file);
|
|
123
|
+
const picker = uninstallModelPicker(file, modelPickerDir());
|
|
124
|
+
console.log(pool || picker ? `Disconnected. Updated ${file}` : `Nothing to remove in ${file}`);
|
|
119
125
|
return 0;
|
|
120
126
|
} catch (error) {
|
|
121
127
|
console.error(`Error: ${error.message}`);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "tokenhub-models",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A bare /model opens a TokenHub model picker above the prompt when ANTHROPIC_BASE_URL points at TokenHub",
|
|
5
|
+
"author": { "name": "Emesoft" },
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"types": "./types/index.d.ts"
|
|
8
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Spike: a static copy of the gateway's declared catalogs (src/model-catalog.ts) with the
|
|
2
|
+
// provider prefixes of ADR-0045. Antigravity has no prefix, so it is left out.
|
|
3
|
+
export type Model = { id: string; name: string }
|
|
4
|
+
export type Group = { provider: string; models: Model[] }
|
|
5
|
+
|
|
6
|
+
export const GROUPS: Group[] = [
|
|
7
|
+
{
|
|
8
|
+
provider: 'Claude Code',
|
|
9
|
+
models: [
|
|
10
|
+
{ id: 'cc/claude-fable-5-1', name: 'Fable 5.1' },
|
|
11
|
+
{ id: 'cc/claude-opus-5-5', name: 'Opus 5.5' },
|
|
12
|
+
{ id: 'cc/claude-opus-5', name: 'Opus 5' },
|
|
13
|
+
{ id: 'cc/claude-sonnet-5-5', name: 'Sonnet 5.5' },
|
|
14
|
+
{ id: 'cc/claude-sonnet-5', name: 'Sonnet 5' },
|
|
15
|
+
{ id: 'cc/claude-haiku-4-5', name: 'Haiku 4.5' },
|
|
16
|
+
],
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
provider: 'Codex',
|
|
20
|
+
models: [
|
|
21
|
+
{ id: 'cx/gpt-6.1-sol', name: 'GPT 6.1 Sol' },
|
|
22
|
+
{ id: 'cx/gpt-6.1-terra', name: 'GPT 6.1 Terra' },
|
|
23
|
+
{ id: 'cx/gpt-6-astra', name: 'GPT 6.0 Astra' },
|
|
24
|
+
{ id: 'cx/gpt-6-sol', name: 'GPT 6.0 Sol' },
|
|
25
|
+
{ id: 'cx/gpt-6-luna', name: 'GPT 6.0 Luna' },
|
|
26
|
+
{ id: 'cx/gpt-5.6-sol', name: 'GPT 5.6 Sol' },
|
|
27
|
+
{ id: 'cx/gpt-5.6-terra', name: 'GPT 5.6 Terra' },
|
|
28
|
+
{ id: 'cx/gpt-5.6-luna', name: 'GPT 5.6 Luna' },
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
provider: 'DeepSeek',
|
|
33
|
+
models: [
|
|
34
|
+
{ id: 'deepseek/deepseek-v4-pro', name: 'DeepSeek V4 Pro' },
|
|
35
|
+
{ id: 'deepseek/deepseek-flash', name: 'DeepSeek Flash' },
|
|
36
|
+
],
|
|
37
|
+
},
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
export const EFFORTS: string[] = ['low', 'medium', 'high', 'xhigh', 'max']
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "modules": ["./register.tsx"] }
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { ClientModule } from 'claude-code'
|
|
2
|
+
|
|
3
|
+
// The picker's drawing: provider columns side by side, the cursor and effort handed in as
|
|
4
|
+
// props (the hooks module owns them). While it has the focus, up/down post a move, left/right
|
|
5
|
+
// or ,/. an effort step, Enter a pick; the hooks module answers with the next props.
|
|
6
|
+
type Props = {
|
|
7
|
+
groups: { provider: string; models: { id: string; name: string }[] }[]
|
|
8
|
+
current: string
|
|
9
|
+
cursor: number
|
|
10
|
+
effort: string
|
|
11
|
+
efforts: string[]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const matches = (id: string, current: string) => id === current || id.endsWith('/' + current)
|
|
15
|
+
|
|
16
|
+
const Picker: ClientModule<Props> = (props, s) => {
|
|
17
|
+
const { Box, Text } = s.elements
|
|
18
|
+
const flat = props.groups.flatMap(g => g.models)
|
|
19
|
+
s.onKey(k => {
|
|
20
|
+
if (k.key === 'down') s.post({ move: 1 })
|
|
21
|
+
else if (k.key === 'up') s.post({ move: -1 })
|
|
22
|
+
else if (k.key === 'right' || k.key === '.') s.post({ effort: 1 })
|
|
23
|
+
else if (k.key === 'left' || k.key === ',') s.post({ effort: -1 })
|
|
24
|
+
else if (k.key === 'return') s.post({ pick: true })
|
|
25
|
+
})
|
|
26
|
+
const colWidth = Math.max(20, Math.floor((s.columns || 90) / Math.max(1, props.groups.length)))
|
|
27
|
+
let i = 0
|
|
28
|
+
return (
|
|
29
|
+
<Box flexDirection="column">
|
|
30
|
+
<Box flexDirection="row">
|
|
31
|
+
{props.groups.map(g => (
|
|
32
|
+
<Box flexDirection="column" width={colWidth}>
|
|
33
|
+
<Text bold>{g.provider}</Text>
|
|
34
|
+
{g.models.map(m => {
|
|
35
|
+
const at = i++
|
|
36
|
+
const isCursor = at === props.cursor
|
|
37
|
+
const isCurrent = matches(m.id, props.current)
|
|
38
|
+
const digit = at < 9 ? `${at + 1}.` : ' '
|
|
39
|
+
return (
|
|
40
|
+
<Text wrap="truncate" color={isCursor ? 'suggestion' : undefined} dimColor={!isCursor && !isCurrent}>
|
|
41
|
+
{isCursor ? '› ' : ' '}{digit} {m.name}{isCurrent ? ' ✔' : ''}
|
|
42
|
+
</Text>
|
|
43
|
+
)
|
|
44
|
+
})}
|
|
45
|
+
</Box>
|
|
46
|
+
))}
|
|
47
|
+
</Box>
|
|
48
|
+
<Box marginTop={1}>
|
|
49
|
+
<Text>
|
|
50
|
+
<Text color="warning">● </Text>
|
|
51
|
+
{'Effort: '}
|
|
52
|
+
{props.efforts.map(e => (e === props.effort ? `[${e}]` : e)).join(' ')}
|
|
53
|
+
<Text dimColor> , / . to adjust</Text>
|
|
54
|
+
</Text>
|
|
55
|
+
</Box>
|
|
56
|
+
<Text dimColor>
|
|
57
|
+
{flat[props.cursor]?.id ?? ''} · ↑/↓ select · Enter or 1-9 picks · type anything to close
|
|
58
|
+
</Text>
|
|
59
|
+
</Box>
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
export default Picker
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { atom, read, update } from 'claude-code'
|
|
2
|
+
import type { EngineInterface, Register } from 'claude-code'
|
|
3
|
+
import { EFFORTS, GROUPS } from './catalog'
|
|
4
|
+
|
|
5
|
+
const SELF = 'tokenhub-models'
|
|
6
|
+
const isOpen = atom({ plugin: 'tokenhub-models', key: 'isOpen' } as const, false)
|
|
7
|
+
// The picker's cursor (index over every model) and effort; null until moved.
|
|
8
|
+
const cursorAt = atom({ plugin: 'tokenhub-models', key: 'cursor' } as const, null)
|
|
9
|
+
const effortPick = atom({ plugin: 'tokenhub-models', key: 'effort' } as const, null)
|
|
10
|
+
|
|
11
|
+
const FLAT = GROUPS.flatMap(g => g.models)
|
|
12
|
+
const matches = (id: string, current: string) => id === current || id.endsWith('/' + current)
|
|
13
|
+
|
|
14
|
+
/** TokenHub hosts: `<slug>.aimpact.io.vn`, or a local gateway on 8787-8789. */
|
|
15
|
+
function isTokenHub(base: string | undefined): boolean {
|
|
16
|
+
if (!base) return false
|
|
17
|
+
try {
|
|
18
|
+
const url = new URL(base)
|
|
19
|
+
return url.hostname.endsWith('.aimpact.io.vn') ||
|
|
20
|
+
((url.hostname === 'localhost' || url.hostname === '127.0.0.1') && ['8787', '8788', '8789'].includes(url.port))
|
|
21
|
+
} catch {
|
|
22
|
+
return false
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function savedEffort($: EngineInterface): Promise<string> {
|
|
27
|
+
return String((await $.settings.read({ key: 'effortLevel' })) ?? 'high')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function stepEffort($: EngineInterface, by: number) {
|
|
31
|
+
const now = (await read($, effortPick)) ?? (await savedEffort($))
|
|
32
|
+
const i = Math.max(0, EFFORTS.indexOf(now))
|
|
33
|
+
const next = EFFORTS[Math.min(EFFORTS.length - 1, Math.max(0, i + by))] ?? now
|
|
34
|
+
await update($, effortPick, () => next)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Closes the picker and switches: `/effort` first when it changed, then `/model`. */
|
|
38
|
+
async function pick($: EngineInterface, index: number) {
|
|
39
|
+
const model = FLAT[index]
|
|
40
|
+
if (!model) return
|
|
41
|
+
await update($, isOpen, () => false)
|
|
42
|
+
const saved = await savedEffort($)
|
|
43
|
+
const effort = (await read($, effortPick)) ?? saved
|
|
44
|
+
if (effort !== saved) void $.command.run({ command: 'effort', args: effort })
|
|
45
|
+
void $.command.run({ command: 'model', args: model.id })
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function cursorOf($: EngineInterface): Promise<number> {
|
|
49
|
+
const at = await read($, cursorAt)
|
|
50
|
+
if (at !== null) return at
|
|
51
|
+
const current = await $.session.model()
|
|
52
|
+
return Math.max(0, FLAT.findIndex(m => matches(m.id, current)))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const register: Register = on => {
|
|
56
|
+
on('command.run', { command: 'model' }, async ($, e, next) => {
|
|
57
|
+
// `/model <id>`, our own runs and non-TokenHub sessions keep the built-in command.
|
|
58
|
+
if ((e.args ?? '').trim() !== '') return next(e)
|
|
59
|
+
if (e.origin?.kind === 'plugin' && e.origin.name === SELF) return next(e)
|
|
60
|
+
try {
|
|
61
|
+
if (!isTokenHub(await $.env.get('ANTHROPIC_BASE_URL'))) return next(e)
|
|
62
|
+
await update($, isOpen, () => true)
|
|
63
|
+
} catch (err) {
|
|
64
|
+
$.ui.toast(`tokenhub-models: ${String(err)}`)
|
|
65
|
+
return next(e) // never block /model on a failure of ours
|
|
66
|
+
}
|
|
67
|
+
// Start from the current model and the saved effort; a failed reset is not fatal.
|
|
68
|
+
await update($, cursorAt, () => null).catch(err => $.ui.toast(`tokenhub-models cursor: ${String(err)}`))
|
|
69
|
+
await update($, effortPick, () => null).catch(err => $.ui.toast(`tokenhub-models effort: ${String(err)}`))
|
|
70
|
+
return { text: 'TokenHub model picker opened above the prompt.' }
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
// Enter on an empty prompt picks the model under the cursor; a typed prompt closes the picker.
|
|
74
|
+
on('prompt.submit', async ($, e, next) => {
|
|
75
|
+
let open = false
|
|
76
|
+
try {
|
|
77
|
+
open = await read($, isOpen)
|
|
78
|
+
} catch {
|
|
79
|
+
return next(e)
|
|
80
|
+
}
|
|
81
|
+
if (open && e.text.trim() === '') {
|
|
82
|
+
await pick($, await cursorOf($)).catch(() => undefined)
|
|
83
|
+
return { drop: 'Model picked.' }
|
|
84
|
+
}
|
|
85
|
+
if (open) await update($, isOpen, () => false).catch(() => undefined)
|
|
86
|
+
return next(e)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
// While the picker is open and the prompt is empty, the prompt drives it: up/down move the
|
|
90
|
+
// cursor, `,` / `.` step the effort, 1-9 pick a model. Anything else types as usual.
|
|
91
|
+
on('prompt.edit', async ($, e, next) => {
|
|
92
|
+
const arrow = e.key?.key === 'up' || e.key?.key === 'down' ? e.key.key : undefined
|
|
93
|
+
if (arrow && e.text === '') {
|
|
94
|
+
let open = false
|
|
95
|
+
try {
|
|
96
|
+
open = await read($, isOpen)
|
|
97
|
+
} catch {
|
|
98
|
+
return next(e)
|
|
99
|
+
}
|
|
100
|
+
if (!open) return next(e)
|
|
101
|
+
const r = await next(e)
|
|
102
|
+
const at = await cursorOf($)
|
|
103
|
+
const by = arrow === 'down' ? 1 : -1
|
|
104
|
+
await update($, cursorAt, () => (at + by + FLAT.length) % FLAT.length).catch(() => undefined)
|
|
105
|
+
return { ...r, text: '', cursor: 0 }
|
|
106
|
+
}
|
|
107
|
+
const typed = e.inputText
|
|
108
|
+
if (e.text !== '' || !(typed === ',' || typed === '.' || /^[1-9]$/.test(typed))) return next(e)
|
|
109
|
+
let open = false
|
|
110
|
+
try {
|
|
111
|
+
open = await read($, isOpen)
|
|
112
|
+
} catch {
|
|
113
|
+
return next(e)
|
|
114
|
+
}
|
|
115
|
+
if (!open) return next(e)
|
|
116
|
+
const r = await next(e)
|
|
117
|
+
if (typed === ',' || typed === '.') await stepEffort($, typed === '.' ? 1 : -1).catch(() => undefined)
|
|
118
|
+
else await pick($, Number(typed) - 1).catch(() => undefined)
|
|
119
|
+
return { ...r, text: '', cursor: 0 }
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
|
|
123
|
+
if (e.props.hasSurvey || !(await read($, isOpen))) return next(e)
|
|
124
|
+
if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e)
|
|
125
|
+
const { Box, Text, Button, Client } = $.ui.resolve(e)
|
|
126
|
+
const current = await $.session.model()
|
|
127
|
+
const effort = (await read($, effortPick)) ?? (await savedEffort($))
|
|
128
|
+
const cursor = await cursorOf($)
|
|
129
|
+
const close = () => void update($, isOpen, () => false)
|
|
130
|
+
return (
|
|
131
|
+
<Box flexDirection="column" borderStyle="round" paddingX={1}>
|
|
132
|
+
<Box flexDirection="row">
|
|
133
|
+
<Text bold>Select model </Text>
|
|
134
|
+
<Text dimColor>TokenHub · current {current} </Text>
|
|
135
|
+
<Button key="builtin" plain dimColor onPress={() => { close(); void $.command.run({ command: 'model' }) }}>Built-in picker</Button>
|
|
136
|
+
<Text> </Text>
|
|
137
|
+
<Button key="cancel" plain dimColor onPress={close}>Cancel</Button>
|
|
138
|
+
</Box>
|
|
139
|
+
<Client key="picker" module="./picker.tsx"
|
|
140
|
+
props={{ groups: GROUPS, current, cursor, effort, efforts: EFFORTS }} />
|
|
141
|
+
</Box>
|
|
142
|
+
)
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
on('ui.message', async ($, e, next) => {
|
|
146
|
+
if (e.element !== 'picker') return next(e)
|
|
147
|
+
const data = e.data as { move?: number; effort?: number; pick?: boolean }
|
|
148
|
+
if (data.move) {
|
|
149
|
+
const at = await cursorOf($)
|
|
150
|
+
await update($, cursorAt, () => (at + data.move! + FLAT.length) % FLAT.length)
|
|
151
|
+
} else if (data.effort) {
|
|
152
|
+
await stepEffort($, data.effort)
|
|
153
|
+
} else if (data.pick) {
|
|
154
|
+
await pick($, await cursorOf($))
|
|
155
|
+
}
|
|
156
|
+
return {}
|
|
157
|
+
})
|
|
158
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const MARKETPLACE: string;
|
|
2
|
+
export const PLUGIN_KEY: string;
|
|
3
|
+
export function modelPickerDir(env?: Record<string, string | undefined>, home?: string): string;
|
|
4
|
+
export function mergeModelPicker(settings: Record<string, any>, dir: string): Record<string, any>;
|
|
5
|
+
export function removeModelPicker(settings: Record<string, any>): Record<string, any>;
|
|
6
|
+
export function installModelPicker(settingsFile: string, dir: string, source?: string): void;
|
|
7
|
+
export function uninstallModelPicker(settingsFile: string, dir: string): boolean;
|
|
8
|
+
export function askYesNo(
|
|
9
|
+
question: string,
|
|
10
|
+
io?: { input?: NodeJS.ReadableStream & { isTTY?: boolean }; output?: NodeJS.WritableStream },
|
|
11
|
+
): Promise<boolean>;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { readSettings, writeSettings } from "./settings.js";
|
|
7
|
+
|
|
8
|
+
// The Claude Code mod that turns a bare `/model` into a TokenHub model picker ships inside this package as a
|
|
9
|
+
// local plugin marketplace (`claude-plugin/`). Installing copies it to a stable folder (the npx cache moves) and
|
|
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.
|
|
12
|
+
export const MARKETPLACE = "tokenhub";
|
|
13
|
+
export const PLUGIN_KEY = "tokenhub-models@tokenhub";
|
|
14
|
+
const BUNDLED = fileURLToPath(new URL("../claude-plugin", import.meta.url));
|
|
15
|
+
/** What is copied: the marketplace manifest and the plugin's runtime files, never its tests. */
|
|
16
|
+
const PARTS = [
|
|
17
|
+
".claude-plugin",
|
|
18
|
+
join("plugins", "tokenhub-models", ".claude-plugin"),
|
|
19
|
+
join("plugins", "tokenhub-models", "hooks"),
|
|
20
|
+
join("plugins", "tokenhub-models", "types"),
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Where the picker is installed: beside the CLI's other state.
|
|
25
|
+
* @param {Record<string, string | undefined>} [env] Environment to read TOKENHUB_CONFIG_DIR from.
|
|
26
|
+
* @param {string} [home] Home directory used when TOKENHUB_CONFIG_DIR is unset.
|
|
27
|
+
* @returns {string} Absolute path of the marketplace folder.
|
|
28
|
+
*/
|
|
29
|
+
export function modelPickerDir(env = process.env, home = homedir()) {
|
|
30
|
+
return join(env.TOKENHUB_CONFIG_DIR || join(home, ".tokenhub"), "claude-plugin");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Return a copy of the settings with the picker's marketplace registered and its plugin enabled.
|
|
35
|
+
* @param {Record<string, any>} settings Existing settings object.
|
|
36
|
+
* @param {string} dir Absolute path of the installed marketplace folder.
|
|
37
|
+
* @returns {Record<string, any>} New settings; all other keys are preserved.
|
|
38
|
+
*/
|
|
39
|
+
export function mergeModelPicker(settings, dir) {
|
|
40
|
+
const markets = isPlainObject(settings.extraKnownMarketplaces) ? settings.extraKnownMarketplaces : {};
|
|
41
|
+
const enabled = isPlainObject(settings.enabledPlugins) ? settings.enabledPlugins : {};
|
|
42
|
+
return {
|
|
43
|
+
...settings,
|
|
44
|
+
extraKnownMarketplaces: { ...markets, [MARKETPLACE]: { source: { source: "directory", path: dir } } },
|
|
45
|
+
enabledPlugins: { ...enabled, [PLUGIN_KEY]: true },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Return a copy of the settings without the picker's entries; an object left empty is dropped.
|
|
51
|
+
* @param {Record<string, any>} settings Existing settings object.
|
|
52
|
+
* @returns {Record<string, any>} New settings.
|
|
53
|
+
*/
|
|
54
|
+
export function removeModelPicker(settings) {
|
|
55
|
+
const next = { ...settings };
|
|
56
|
+
for (const [field, key] of [["extraKnownMarketplaces", MARKETPLACE], ["enabledPlugins", PLUGIN_KEY]]) {
|
|
57
|
+
if (!isPlainObject(next[field]) || !(key in next[field])) continue;
|
|
58
|
+
const { [key]: _gone, ...rest } = next[field];
|
|
59
|
+
if (Object.keys(rest).length > 0) next[field] = rest;
|
|
60
|
+
else delete next[field];
|
|
61
|
+
}
|
|
62
|
+
return next;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Copy the bundled picker to `dir` (replacing an older copy) and register it in the settings file.
|
|
67
|
+
* @param {string} settingsFile Path of settings.json.
|
|
68
|
+
* @param {string} dir Destination from `modelPickerDir`.
|
|
69
|
+
* @param {string} [source] Bundled marketplace folder (tests).
|
|
70
|
+
* @returns {void}
|
|
71
|
+
* @throws {Error} When the settings file is invalid JSON (left untouched) or the copy fails.
|
|
72
|
+
*/
|
|
73
|
+
export function installModelPicker(settingsFile, dir, source = BUNDLED) {
|
|
74
|
+
const { settings } = readSettings(settingsFile);
|
|
75
|
+
rmSync(dir, { recursive: true, force: true });
|
|
76
|
+
for (const part of PARTS) {
|
|
77
|
+
const from = join(source, part);
|
|
78
|
+
if (!existsSync(from)) throw new Error(`The model picker is missing from this package (${part}).`);
|
|
79
|
+
mkdirSync(dirname(join(dir, part)), { recursive: true });
|
|
80
|
+
cpSync(from, join(dir, part), { recursive: true });
|
|
81
|
+
}
|
|
82
|
+
writeSettings(settingsFile, mergeModelPicker(settings, dir));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Unregister the picker from the settings file and delete its installed copy.
|
|
87
|
+
* @param {string} settingsFile Path of settings.json.
|
|
88
|
+
* @param {string} dir Folder from `modelPickerDir`.
|
|
89
|
+
* @returns {boolean} True when anything was removed.
|
|
90
|
+
*/
|
|
91
|
+
export function uninstallModelPicker(settingsFile, dir) {
|
|
92
|
+
let changed = false;
|
|
93
|
+
const { exists, settings } = readSettings(settingsFile);
|
|
94
|
+
if (exists) {
|
|
95
|
+
const next = removeModelPicker(settings);
|
|
96
|
+
if (JSON.stringify(next) !== JSON.stringify(settings)) {
|
|
97
|
+
writeSettings(settingsFile, next);
|
|
98
|
+
changed = true;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (existsSync(dir)) {
|
|
102
|
+
rmSync(dir, { recursive: true, force: true });
|
|
103
|
+
changed = true;
|
|
104
|
+
}
|
|
105
|
+
return changed;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Ask a yes/no question on the terminal; Enter alone answers yes.
|
|
110
|
+
* @param {string} question The question, without the `(Y/n)` suffix.
|
|
111
|
+
* @param {{ input?: NodeJS.ReadableStream & { isTTY?: boolean }, output?: NodeJS.WritableStream }} [io] Streams (tests).
|
|
112
|
+
* @returns {Promise<boolean>} The answer; false when there is no terminal to ask on.
|
|
113
|
+
*/
|
|
114
|
+
export async function askYesNo(question, { input = process.stdin, output = process.stdout } = {}) {
|
|
115
|
+
if (!input.isTTY) return false;
|
|
116
|
+
const rl = createInterface({ input, output });
|
|
117
|
+
try {
|
|
118
|
+
const answer = (await rl.question(`${question} (Y/n) `)).trim().toLowerCase();
|
|
119
|
+
return answer === "" || answer === "y" || answer === "yes";
|
|
120
|
+
} finally {
|
|
121
|
+
rl.close();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* @param {unknown} value Value to test.
|
|
127
|
+
* @returns {value is Record<string, any>} True for non-null, non-array objects.
|
|
128
|
+
*/
|
|
129
|
+
function isPlainObject(value) {
|
|
130
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
131
|
+
}
|
package/lib/pair.d.ts
CHANGED
|
@@ -29,4 +29,10 @@ export function runConnect(options: {
|
|
|
29
29
|
admin?: boolean;
|
|
30
30
|
/** Where the admin device token is stored; required with `admin`. */
|
|
31
31
|
adminFile?: string;
|
|
32
|
+
/** Offer to install the Claude Code model picker after pairing (default true). */
|
|
33
|
+
modelPicker?: boolean;
|
|
34
|
+
/** Where the picker is installed; `modelPickerDir()` by default. */
|
|
35
|
+
modelPickerDir?: string;
|
|
36
|
+
/** Yes/no prompt; answers false without a terminal. */
|
|
37
|
+
ask?: (question: string) => Promise<boolean>;
|
|
32
38
|
}): Promise<number>;
|
package/lib/pair.js
CHANGED
|
@@ -3,6 +3,7 @@ import { hostname } from "node:os";
|
|
|
3
3
|
import { emitKeypressEvents } from "node:readline";
|
|
4
4
|
import { createInterface } from "node:readline/promises";
|
|
5
5
|
import { writeAdminConfig } from "./admin.js";
|
|
6
|
+
import { askYesNo, installModelPicker, modelPickerDir } from "./model-picker.js";
|
|
6
7
|
import { connectSettings, normalizeUrl, overridingEnvVars, readSettings } from "./settings.js";
|
|
7
8
|
|
|
8
9
|
const MAX_WAIT_MS = 15 * 60 * 1000;
|
|
@@ -227,6 +228,9 @@ async function postJson(url, body, signal) {
|
|
|
227
228
|
* @param {boolean} [options.statusLine] Also install the TokenHub status line (default true).
|
|
228
229
|
* @param {boolean} [options.admin] Pair as an admin device: the admin approves in the console and the token is stored in `adminFile` (for the desktop overlay), leaving Claude Code's settings alone.
|
|
229
230
|
* @param {string} [options.adminFile] Path from `adminConfigPath`; required with `admin`.
|
|
231
|
+
* @param {boolean} [options.modelPicker] Offer to install the Claude Code model picker after pairing (default true).
|
|
232
|
+
* @param {string} [options.modelPickerDir] Where the picker is installed (`modelPickerDir()` by default).
|
|
233
|
+
* @param {(question: string) => Promise<boolean>} [options.ask] Yes/no prompt (tests); false without a terminal.
|
|
230
234
|
* @returns {Promise<number>} Process exit code.
|
|
231
235
|
*/
|
|
232
236
|
export async function runConnect({
|
|
@@ -241,6 +245,9 @@ export async function runConnect({
|
|
|
241
245
|
statusLine = true,
|
|
242
246
|
admin = false,
|
|
243
247
|
adminFile,
|
|
248
|
+
modelPicker = true,
|
|
249
|
+
modelPickerDir: pickerDir = modelPickerDir(),
|
|
250
|
+
ask = askYesNo,
|
|
244
251
|
}) {
|
|
245
252
|
let pool;
|
|
246
253
|
try {
|
|
@@ -260,7 +267,10 @@ export async function runConnect({
|
|
|
260
267
|
log(`Error: the pool rejected the pairing request (HTTP ${start.status}).`);
|
|
261
268
|
return 1;
|
|
262
269
|
}
|
|
263
|
-
const { deviceCode, userCode, verifyUrl, interval, expiresIn } = start.body;
|
|
270
|
+
const { deviceCode, userCode, verifyUrl: rawVerifyUrl, interval, expiresIn } = start.body;
|
|
271
|
+
const verifyUrl = pool.startsWith("https://") && String(rawVerifyUrl || "").startsWith("http://")
|
|
272
|
+
? rawVerifyUrl.replace(/^http:\/\//, "https://")
|
|
273
|
+
: rawVerifyUrl;
|
|
264
274
|
log("");
|
|
265
275
|
log(` Your code: ${userCode}`);
|
|
266
276
|
log("");
|
|
@@ -279,18 +289,21 @@ export async function runConnect({
|
|
|
279
289
|
const poll = await postJson(`${pool}/pair/poll`, { deviceCode }, signal);
|
|
280
290
|
if (poll.status === 429) continue;
|
|
281
291
|
const status = poll.body?.status;
|
|
292
|
+
const baseUrl = pool.startsWith("https://") && String(poll.body?.baseUrl || "").startsWith("http://")
|
|
293
|
+
? poll.body.baseUrl.replace(/^http:\/\//, "https://")
|
|
294
|
+
: poll.body?.baseUrl || pool;
|
|
282
295
|
if (status === "approved" && admin) {
|
|
283
296
|
if (poll.body.kind !== "admin") {
|
|
284
297
|
log("Error: the pool did not issue an admin device token. Update the pool, then run the command again.");
|
|
285
298
|
return 1;
|
|
286
299
|
}
|
|
287
|
-
writeAdminConfig(adminFile,
|
|
300
|
+
writeAdminConfig(adminFile, baseUrl, poll.body.key);
|
|
288
301
|
log(`Admin device paired. Token saved to ${adminFile}`);
|
|
289
|
-
log(`Revoke it any time on the pool's admin Devices page (${
|
|
302
|
+
log(`Revoke it any time on the pool's admin Devices page (${baseUrl}/admin/pair).`);
|
|
290
303
|
return 0;
|
|
291
304
|
}
|
|
292
305
|
if (status === "approved") {
|
|
293
|
-
const statusResult = connectSettings(settingsFile,
|
|
306
|
+
const statusResult = connectSettings(settingsFile, baseUrl, poll.body.key, { statusLine });
|
|
294
307
|
log(`Connected. Claude Code settings updated: ${settingsFile}`);
|
|
295
308
|
if (statusResult === "installed") log("Status line added: today's spend and credit show under the Claude Code prompt.");
|
|
296
309
|
if (statusResult === "updated") log("Status line refreshed with your new key.");
|
|
@@ -299,6 +312,14 @@ export async function runConnect({
|
|
|
299
312
|
if (overriding.length > 0) {
|
|
300
313
|
log(`Warning: ${overriding.join(", ")} set in your shell overrides settings.json. Unset it to use the pool.`);
|
|
301
314
|
}
|
|
315
|
+
if (modelPicker && (await ask("Install the TokenHub model picker for Claude Code (/model lists TokenHub models)?"))) {
|
|
316
|
+
try {
|
|
317
|
+
installModelPicker(settingsFile, pickerDir);
|
|
318
|
+
log("Model picker installed. Restart Claude Code, then type /model to pick a TokenHub model.");
|
|
319
|
+
} catch (error) {
|
|
320
|
+
log(`Model picker not installed: ${error.message}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
302
323
|
return 0;
|
|
303
324
|
}
|
|
304
325
|
if (status === "denied") {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@emesoft/tokenhub",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.6",
|
|
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",
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
"files": [
|
|
23
23
|
"bin",
|
|
24
24
|
"lib",
|
|
25
|
+
"claude-plugin/.claude-plugin",
|
|
26
|
+
"claude-plugin/plugins/tokenhub-models/.claude-plugin",
|
|
27
|
+
"claude-plugin/plugins/tokenhub-models/hooks",
|
|
28
|
+
"claude-plugin/plugins/tokenhub-models/types",
|
|
25
29
|
"README.md",
|
|
26
30
|
"LICENSE"
|
|
27
31
|
],
|