@emesoft/tokenhub 0.8.10 → 0.8.12
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 +5 -1
- package/bin/tokenhub.js +22 -1
- package/claude-plugin/plugins/tokenhub-models/.claude-plugin/plugin.json +1 -1
- package/claude-plugin/plugins/tokenhub-models/hooks/register.tsx +2 -0
- package/lib/desktop-connect.d.ts +13 -0
- package/lib/desktop-connect.js +69 -0
- package/lib/desktop.d.ts +28 -0
- package/lib/desktop.js +188 -0
- package/lib/model-picker.d.ts +3 -1
- package/lib/model-picker.js +28 -6
- package/lib/pair.d.ts +11 -1
- package/lib/pair.js +100 -75
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -41,6 +41,7 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
41
41
|
| Command | What it does |
|
|
42
42
|
| --- | --- |
|
|
43
43
|
| `tokenhub connect [tenant]` | Pair this machine with your tenant (`acme` = `https://acme.aimpact.io.vn`, or a full URL). Asks for it when left out. |
|
|
44
|
+
| `tokenhub desktop [tenant]` | The same pairing, for Claude Desktop: writes its third-party inference config and turns that mode on. Restart the app afterwards. |
|
|
44
45
|
| `tokenhub usage [--json]` | Today's and this week's spend against your limits, your credit and pool health. |
|
|
45
46
|
| `tokenhub dashboard` | Live full-screen view of spend and your recent requests. |
|
|
46
47
|
| `tokenhub overlay <tenant>` | Install the TokenHub desktop overlay (Windows). |
|
|
@@ -73,7 +74,10 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
73
74
|
`,` / `.` or a click for effort (hover highlights), and `[` or a click for **1M**: each model shows its context window, and with 1M on, a model whose window is 1M is picked as `<id>[1m]` so Claude Code compacts at 1M instead of 200K (only for models whose window TokenHub knows to be 1M). `/model <id>` and other hosts keep Claude Code's own picker. The list is read from your tenant
|
|
74
75
|
(`/member/api/models`: the providers your key may use, with a skeleton while it loads); when the pool does not
|
|
75
76
|
answer within a few seconds it falls back to a built-in list, marked "offline list". The plugin relies on Claude
|
|
76
|
-
Code's early-access plugin hooks, which can change between Claude Code releases.
|
|
77
|
+
Code's early-access plugin hooks, which can change between Claude Code releases. Claude Code reports the mouse
|
|
78
|
+
only in its fullscreen layout, so after installing the picker `connect` asks whether to turn that on
|
|
79
|
+
(`"tui": "fullscreen"`, default no); in the classic layout the picker works from the keyboard and says
|
|
80
|
+
`/tui fullscreen` turns the mouse on. `disconnect` leaves `tui` as it is.
|
|
77
81
|
- Keeps every other setting, and saves the previous file as `settings.json.bak`.
|
|
78
82
|
|
|
79
83
|
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.
|
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 { runDesktop } from "../lib/desktop-connect.js";
|
|
6
7
|
import { modelPickerDir, uninstallModelPicker } from "../lib/model-picker.js";
|
|
7
8
|
import { runOverlayInstall } from "../lib/overlay.js";
|
|
8
9
|
import { promptTenant, runConnect, TENANT_DOMAIN } from "../lib/pair.js";
|
|
@@ -16,12 +17,15 @@ Usage:
|
|
|
16
17
|
Pair this machine and write ~/.claude/settings.json, including the status line
|
|
17
18
|
(today's spend under the prompt) unless --no-statusline. Then offers to install the
|
|
18
19
|
TokenHub model picker (a bare /model in Claude Code lists TokenHub models) unless
|
|
19
|
-
--no-model-picker
|
|
20
|
+
--no-model-picker, and then Claude Code's fullscreen layout, the only one that gives
|
|
21
|
+
the picker the mouse (default no).
|
|
20
22
|
tenant is your tenant name (acme = https://acme.${TENANT_DOMAIN}) or a full URL;
|
|
21
23
|
it is asked for when left out
|
|
22
24
|
tokenhub connect [tenant] --admin
|
|
23
25
|
Pair this machine as an admin device (for the desktop overlay's pool view): the admin
|
|
24
26
|
confirms in the console, the token is saved to ~/.tokenhub/admin.json
|
|
27
|
+
tokenhub desktop [tenant] Pair this machine and point Claude Desktop at the pool: writes its third-party
|
|
28
|
+
inference config (gateway address, key, models) and turns on the 3p mode it needs
|
|
25
29
|
tokenhub overlay <tenant> Download and install the TokenHub desktop overlay (Windows)
|
|
26
30
|
tokenhub usage [--json] Show today's and this week's spend, credit and pool health
|
|
27
31
|
tokenhub dashboard [--interval <sec>] [--once]
|
|
@@ -80,6 +84,23 @@ async function main(argv) {
|
|
|
80
84
|
modelPicker: !flags.includes("--no-model-picker"),
|
|
81
85
|
});
|
|
82
86
|
}
|
|
87
|
+
if (command === "desktop") {
|
|
88
|
+
if (isInteractive()) {
|
|
89
|
+
await showBanner({ showActions: false });
|
|
90
|
+
}
|
|
91
|
+
const controller = new AbortController();
|
|
92
|
+
process.once("SIGINT", () => controller.abort());
|
|
93
|
+
let poolUrl = arg;
|
|
94
|
+
if (!poolUrl) {
|
|
95
|
+
try {
|
|
96
|
+
poolUrl = await promptTenant();
|
|
97
|
+
} catch (error) {
|
|
98
|
+
console.error(`Error: ${error.message}`);
|
|
99
|
+
return 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return runDesktop({ poolUrl, signal: controller.signal });
|
|
103
|
+
}
|
|
83
104
|
if (command === "overlay") {
|
|
84
105
|
return runOverlayInstall({ poolUrl: arg });
|
|
85
106
|
}
|
|
@@ -240,6 +240,8 @@ export const register: Register = on => {
|
|
|
240
240
|
</Box>
|
|
241
241
|
<Client key="picker" module="./picker.tsx"
|
|
242
242
|
props={{ groups, loading: groups.length === 0, current, cursor, effort, efforts: EFFORTS, use1m: await read($, use1m) }} />
|
|
243
|
+
{/* Claude Code reports the mouse only in its fullscreen layout (#766); say so where it says it is not. */}
|
|
244
|
+
{e.viewport?.isFullscreen === false ? <Text dimColor>Mouse needs Claude Code's fullscreen layout: /tui fullscreen</Text> : ''}
|
|
243
245
|
</Box>
|
|
244
246
|
)
|
|
245
247
|
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function runDesktop(options: {
|
|
2
|
+
/** Tenant slug (`acme`) or pool URL as typed by the user. */
|
|
3
|
+
poolUrl: string | undefined;
|
|
4
|
+
log?: (line: string) => void;
|
|
5
|
+
open?: (url: string) => void;
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
deviceName?: string;
|
|
8
|
+
intervalOverrideMs?: number;
|
|
9
|
+
platform?: string;
|
|
10
|
+
env?: Record<string, string | undefined>;
|
|
11
|
+
home?: string;
|
|
12
|
+
fetchImpl?: typeof fetch;
|
|
13
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { appDataDir, fetchModels, isInstalled, writeDesktopConfig } from "./desktop.js";
|
|
3
|
+
import { pairDevice, resolvePoolUrl } from "./pair.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Pair this machine and configure Claude Desktop's third-party inference so the app points at the pool: the models
|
|
7
|
+
* from `/v1/models`, the gateway key, and the `3p` deployment mode that makes Desktop read them.
|
|
8
|
+
*
|
|
9
|
+
* @param {object} options
|
|
10
|
+
* @param {string} options.poolUrl Tenant slug or pool URL as typed by the user (see `resolvePoolUrl`).
|
|
11
|
+
* @param {(line: string) => void} [options.log] Output sink.
|
|
12
|
+
* @param {(url: string) => void} [options.open] Browser opener.
|
|
13
|
+
* @param {AbortSignal} [options.signal] Aborts the flow (Ctrl+C).
|
|
14
|
+
* @param {string} [options.deviceName] Name shown on the confirmation page.
|
|
15
|
+
* @param {number} [options.intervalOverrideMs] Poll interval override (tests).
|
|
16
|
+
* @param {string} [options.platform] Node platform name.
|
|
17
|
+
* @param {Record<string, string | undefined>} [options.env] Environment read for the app-data folder.
|
|
18
|
+
* @param {string} [options.home] Home directory (tests).
|
|
19
|
+
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
20
|
+
* @returns {Promise<number>} Process exit code.
|
|
21
|
+
*/
|
|
22
|
+
export async function runDesktop({
|
|
23
|
+
poolUrl,
|
|
24
|
+
log = console.log,
|
|
25
|
+
open,
|
|
26
|
+
signal,
|
|
27
|
+
deviceName = hostname(),
|
|
28
|
+
intervalOverrideMs,
|
|
29
|
+
platform = process.platform,
|
|
30
|
+
env = process.env,
|
|
31
|
+
home,
|
|
32
|
+
fetchImpl = fetch,
|
|
33
|
+
}) {
|
|
34
|
+
const dir = appDataDir(platform, env, home);
|
|
35
|
+
if (!dir) {
|
|
36
|
+
log("Claude Desktop does not run on this system.");
|
|
37
|
+
return 1;
|
|
38
|
+
}
|
|
39
|
+
// Judged before the write, which creates the folder.
|
|
40
|
+
const installed = isInstalled(dir);
|
|
41
|
+
let pool;
|
|
42
|
+
try {
|
|
43
|
+
pool = resolvePoolUrl(poolUrl);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
log(`Error: ${error.message}`);
|
|
46
|
+
return 1;
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
const paired = await pairDevice({ pool, deviceName, log, open, signal, intervalOverrideMs, fetchImpl });
|
|
50
|
+
if (!paired.ok) return paired.code;
|
|
51
|
+
const models = await fetchModels(paired.baseUrl, paired.key, fetchImpl);
|
|
52
|
+
const written = writeDesktopConfig({ dir, baseUrl: paired.baseUrl, key: paired.key, models });
|
|
53
|
+
log("");
|
|
54
|
+
log(`Claude Desktop is set up: ${written.models} models from ${paired.baseUrl}`);
|
|
55
|
+
if (!installed) {
|
|
56
|
+
log(`The folder ${dir} did not exist yet, so install and open Claude Desktop once to pick the setup up.`);
|
|
57
|
+
}
|
|
58
|
+
log("Restart Claude Desktop and pick a model in the prompt box. You are on the pool.");
|
|
59
|
+
return 0;
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (signal?.aborted) {
|
|
62
|
+
log("Cancelled.");
|
|
63
|
+
return 130;
|
|
64
|
+
}
|
|
65
|
+
log(`Error: ${error.message}`);
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
package/lib/desktop.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const APP_FOLDER: string;
|
|
2
|
+
export const CONFIG_NAME: string;
|
|
3
|
+
export function appDataDir(platform?: string, env?: Record<string, string | undefined>, home?: string): string | null;
|
|
4
|
+
export function configLibraryDir(base: string): string;
|
|
5
|
+
export function configId(dir: string): string;
|
|
6
|
+
export function modelEntry(row: { id: string; display_name?: string; anthropic_family_tier?: string; max_input_tokens?: number }): Record<string, unknown>;
|
|
7
|
+
export function buildConfig(options: {
|
|
8
|
+
baseUrl: string;
|
|
9
|
+
key: string;
|
|
10
|
+
models: Array<{ id: string; display_name?: string; anthropic_family_tier?: string; max_input_tokens?: number }>;
|
|
11
|
+
effort?: string;
|
|
12
|
+
}): Record<string, unknown>;
|
|
13
|
+
export function mergeMeta(meta: unknown, id: string): Record<string, unknown>;
|
|
14
|
+
export function mergeDesktopConfig(config: unknown): Record<string, unknown>;
|
|
15
|
+
export function readJson(file: string): any;
|
|
16
|
+
export function writeDesktopConfig(options: {
|
|
17
|
+
dir: string;
|
|
18
|
+
baseUrl: string;
|
|
19
|
+
key: string;
|
|
20
|
+
models: Array<{ id: string; display_name?: string; anthropic_family_tier?: string; max_input_tokens?: number }>;
|
|
21
|
+
effort?: string;
|
|
22
|
+
}): { configPath: string; metaPath: string; desktopConfigPath: string; models: number };
|
|
23
|
+
export function isInstalled(dir: string | null): boolean;
|
|
24
|
+
export function fetchModels(
|
|
25
|
+
baseUrl: string,
|
|
26
|
+
key: string,
|
|
27
|
+
fetchImpl?: typeof fetch,
|
|
28
|
+
): Promise<Array<{ id: string; display_name?: string; anthropic_family_tier?: string; max_input_tokens?: number }>>;
|
package/lib/desktop.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
// Claude Desktop's third-party inference setup ("Configure third-party inference", reached from Developer mode) keeps
|
|
6
|
+
// one JSON record per named configuration under `<app data>/Claude-3p/configLibrary/`, plus `_meta.json` naming the
|
|
7
|
+
// applied one, and a `claude_desktop_config.json` beside them holding `"deploymentMode": "3p"`. Writing those three is
|
|
8
|
+
// what the form does by hand, so a newcomer only has to run one command. Desktop seals a plaintext API key itself on
|
|
9
|
+
// load (`__sealed__:v1:` through the OS keystore), so nothing here has to reproduce that.
|
|
10
|
+
/** Folder name Desktop uses for the 3p install (the stable consumer build is `Claude`, the 3p one `Claude-3p`). */
|
|
11
|
+
export const APP_FOLDER = "Claude-3p";
|
|
12
|
+
/** Name of the configuration this writes and applies. */
|
|
13
|
+
export const CONFIG_NAME = "TokenHub";
|
|
14
|
+
/** Effort levels Desktop knows, lowest first. */
|
|
15
|
+
const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
16
|
+
/** Families Desktop recognises in `anthropicFamilyTier`. */
|
|
17
|
+
const TIERS = ["sonnet", "opus", "haiku", "fable", "mythos"];
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Where Claude Desktop keeps its 3p data per platform.
|
|
21
|
+
* @param {string} [platform] Node platform name.
|
|
22
|
+
* @param {Record<string, string | undefined>} [env] Environment to read APPDATA / XDG_CONFIG_HOME from.
|
|
23
|
+
* @param {string} [home] Home directory used when the variable is unset.
|
|
24
|
+
* @returns {string | null} Absolute folder, or null on a platform Desktop does not ship for.
|
|
25
|
+
*/
|
|
26
|
+
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);
|
|
28
|
+
if (platform === "darwin") return join(home, "Library", "Application Support", APP_FOLDER);
|
|
29
|
+
if (platform === "linux") return join(env.XDG_CONFIG_HOME || join(home, ".config"), APP_FOLDER);
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The folder the config library lives in, on either layout Desktop has shipped: the 3p build's own app-data folder
|
|
35
|
+
* (`<app data>/Claude-3p/configLibrary`) and the classic build's (`<app data>/Claude/configLibrary`).
|
|
36
|
+
* @param {string | null} base Folder from `appDataDir`.
|
|
37
|
+
* @returns {string} Absolute folder (may not exist yet).
|
|
38
|
+
*/
|
|
39
|
+
export function configLibraryDir(base) {
|
|
40
|
+
return join(base, "configLibrary");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 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.
|
|
46
|
+
* @param {string} dir Config library folder.
|
|
47
|
+
* @returns {string} Configuration id.
|
|
48
|
+
*/
|
|
49
|
+
export function configId(dir) {
|
|
50
|
+
const meta = readJson(join(dir, "_meta.json"));
|
|
51
|
+
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";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Read one of Desktop's model rows (as `/v1/models` returns them) as the config library's shape.
|
|
58
|
+
*
|
|
59
|
+
* @param {{ id: string, display_name?: string, anthropic_family_tier?: string, max_input_tokens?: number }} row Model row.
|
|
60
|
+
* @returns {Record<string, unknown>} Config-library model entry.
|
|
61
|
+
*/
|
|
62
|
+
export function modelEntry(row) {
|
|
63
|
+
const tier = String(row.anthropic_family_tier ?? "").toLowerCase();
|
|
64
|
+
return {
|
|
65
|
+
name: row.id,
|
|
66
|
+
...(row.display_name && { labelOverride: row.display_name }),
|
|
67
|
+
...(TIERS.includes(tier) && { anthropicFamilyTier: tier }),
|
|
68
|
+
...(typeof row.max_input_tokens === "number" && row.max_input_tokens >= 1_000_000 && { supports1m: true }),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Build the configuration record: the gateway address and key, the models, and a default model.
|
|
74
|
+
*
|
|
75
|
+
* @param {object} options
|
|
76
|
+
* @param {string} options.baseUrl Gateway address (no trailing slash).
|
|
77
|
+
* @param {string} options.key Gateway key.
|
|
78
|
+
* @param {Array<{ id: string, display_name?: string, anthropic_family_tier?: string, max_input_tokens?: number }>} options.models Models from `/v1/models`.
|
|
79
|
+
* @param {string} [options.effort] Default effort; `medium` when Desktop's own value is not one it knows.
|
|
80
|
+
* @returns {Record<string, unknown>} The `configLibrary/<id>.json` body.
|
|
81
|
+
*/
|
|
82
|
+
export function buildConfig({ baseUrl, key, models, effort = "medium" }) {
|
|
83
|
+
const list = models.map(modelEntry);
|
|
84
|
+
const defaultModel = list.find((entry) => entry.anthropicFamilyTier === "sonnet") ?? list[0];
|
|
85
|
+
return {
|
|
86
|
+
inferenceGatewayBaseUrl: baseUrl,
|
|
87
|
+
inferenceGatewayAutoModeServerChecks: true,
|
|
88
|
+
inferenceGatewayApiKey: key,
|
|
89
|
+
inferenceModels: list,
|
|
90
|
+
defaultModel: defaultModel ? defaultModel.name : undefined,
|
|
91
|
+
defaultModelEffort: EFFORTS.includes(effort) ? effort : "medium",
|
|
92
|
+
alwaysStartWithDefaultModel: true,
|
|
93
|
+
inferenceModelPricingEnabled: true,
|
|
94
|
+
inferenceProvider: "gateway",
|
|
95
|
+
inferenceCredentialKind: "static",
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Merge the configuration into `_meta.json` and make it the applied one.
|
|
101
|
+
* @param {unknown} meta Existing `_meta.json` (null when absent).
|
|
102
|
+
* @param {string} id Configuration id.
|
|
103
|
+
* @returns {Record<string, unknown>} New `_meta.json`.
|
|
104
|
+
*/
|
|
105
|
+
export function mergeMeta(meta, id) {
|
|
106
|
+
const entries = Array.isArray(meta?.entries) ? meta.entries.filter((entry) => entry?.id !== id) : [];
|
|
107
|
+
return { ...meta, appliedId: id, entries: [...entries, { id, name: CONFIG_NAME }] };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Turn on the mode that makes Desktop read the config library.
|
|
112
|
+
* @param {unknown} config Existing `claude_desktop_config.json` (null when absent).
|
|
113
|
+
* @returns {Record<string, unknown>} New `claude_desktop_config.json`.
|
|
114
|
+
*/
|
|
115
|
+
export function mergeDesktopConfig(config) {
|
|
116
|
+
return { ...(isPlainObject(config) ? config : {}), deploymentMode: "3p" };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Read a JSON file, tolerating a missing or unreadable one.
|
|
121
|
+
* @param {string} file Path.
|
|
122
|
+
* @returns {any} Parsed value, or null.
|
|
123
|
+
*/
|
|
124
|
+
export function readJson(file) {
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
127
|
+
} catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @returns Whether a value is a plain object. */
|
|
133
|
+
function isPlainObject(value) {
|
|
134
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Write Claude Desktop's third-party inference setup: the applied configuration, `_meta.json` naming it, and
|
|
139
|
+
* `deploymentMode: "3p"` in `claude_desktop_config.json`. Existing preferences are preserved.
|
|
140
|
+
*
|
|
141
|
+
* @param {object} options
|
|
142
|
+
* @param {string} options.dir The `Claude-3p` folder from `appDataDir` (created when missing).
|
|
143
|
+
* @param {string} options.baseUrl Gateway address.
|
|
144
|
+
* @param {string} options.key Gateway key.
|
|
145
|
+
* @param {Array<{ id: string, display_name?: string }>} options.models Models from `/v1/models`.
|
|
146
|
+
* @param {string} [options.effort] Default effort.
|
|
147
|
+
* @returns {{ configPath: string, metaPath: string, desktopConfigPath: string, models: number }} Files written.
|
|
148
|
+
*/
|
|
149
|
+
export function writeDesktopConfig({ dir, baseUrl, key, models, effort }) {
|
|
150
|
+
const library = configLibraryDir(dir);
|
|
151
|
+
mkdirSync(library, { recursive: true });
|
|
152
|
+
const id = configId(library);
|
|
153
|
+
const configPath = join(library, `${id}.json`);
|
|
154
|
+
const metaPath = join(library, "_meta.json");
|
|
155
|
+
const desktopConfigPath = join(dir, "claude_desktop_config.json");
|
|
156
|
+
writeFileSync(configPath, `${JSON.stringify(buildConfig({ baseUrl, key, models, effort }), null, 2)}\n`);
|
|
157
|
+
writeFileSync(metaPath, `${JSON.stringify(mergeMeta(readJson(metaPath), id), null, 2)}\n`);
|
|
158
|
+
writeFileSync(desktopConfigPath, `${JSON.stringify(mergeDesktopConfig(readJson(desktopConfigPath)), null, 2)}\n`);
|
|
159
|
+
return { configPath, metaPath, desktopConfigPath, models: models.length };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Whether Desktop is installed here, judged by its app-data folder (Desktop creates it on first run).
|
|
164
|
+
* @param {string | null} dir Folder from `appDataDir`.
|
|
165
|
+
* @returns {boolean} True when it exists.
|
|
166
|
+
*/
|
|
167
|
+
export function isInstalled(dir) {
|
|
168
|
+
return Boolean(dir) && existsSync(dir);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Fetch the models the key may use from the pool.
|
|
173
|
+
* @param {string} baseUrl Gateway address.
|
|
174
|
+
* @param {string} key Gateway key.
|
|
175
|
+
* @param {typeof fetch} [fetchImpl] `fetch` override for tests.
|
|
176
|
+
* @returns {Promise<Array<{ id: string, display_name?: string, anthropic_family_tier?: string, max_input_tokens?: number }>>} Model rows.
|
|
177
|
+
* @throws {Error} When the pool answers anything but a model list.
|
|
178
|
+
*/
|
|
179
|
+
export async function fetchModels(baseUrl, key, fetchImpl = fetch) {
|
|
180
|
+
const res = await fetchImpl(`${baseUrl}/v1/models?limit=1000`, {
|
|
181
|
+
headers: { "x-api-key": key, "anthropic-version": "2023-06-01" },
|
|
182
|
+
signal: AbortSignal.timeout(15_000),
|
|
183
|
+
});
|
|
184
|
+
if (!res.ok) throw new Error(`The pool answered ${res.status} for its model list. Is it up to date?`);
|
|
185
|
+
const body = await res.json().catch(() => null);
|
|
186
|
+
if (!Array.isArray(body?.data)) throw new Error("The pool's model list was not the shape expected. Is it up to date?");
|
|
187
|
+
return body.data;
|
|
188
|
+
}
|
package/lib/model-picker.d.ts
CHANGED
|
@@ -7,5 +7,7 @@ export function installModelPicker(settingsFile: string, dir: string, source?: s
|
|
|
7
7
|
export function uninstallModelPicker(settingsFile: string, dir: string): boolean;
|
|
8
8
|
export function askYesNo(
|
|
9
9
|
question: string,
|
|
10
|
-
io?: { input?: NodeJS.ReadableStream & { isTTY?: boolean }; output?: NodeJS.WritableStream },
|
|
10
|
+
io?: { input?: NodeJS.ReadableStream & { isTTY?: boolean }; output?: NodeJS.WritableStream; defaultYes?: boolean },
|
|
11
11
|
): Promise<boolean>;
|
|
12
|
+
export function enableFullscreen(settingsFile: string): boolean;
|
|
13
|
+
export function layoutUnset(settingsFile: string): boolean;
|
package/lib/model-picker.js
CHANGED
|
@@ -106,22 +106,44 @@ export function uninstallModelPicker(settingsFile, dir) {
|
|
|
106
106
|
}
|
|
107
107
|
|
|
108
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).
|
|
109
|
+
* Ask a yes/no question on the terminal; Enter alone answers the default (yes unless `defaultYes` is false).
|
|
110
|
+
* @param {string} question The question, without the `(Y/n)` / `(y/N)` suffix.
|
|
111
|
+
* @param {{ input?: NodeJS.ReadableStream & { isTTY?: boolean }, output?: NodeJS.WritableStream, defaultYes?: boolean }} [io] Streams (tests) and the default answer.
|
|
112
112
|
* @returns {Promise<boolean>} The answer; false when there is no terminal to ask on.
|
|
113
113
|
*/
|
|
114
|
-
export async function askYesNo(question, { input = process.stdin, output = process.stdout } = {}) {
|
|
114
|
+
export async function askYesNo(question, { input = process.stdin, output = process.stdout, defaultYes = true } = {}) {
|
|
115
115
|
if (!input.isTTY) return false;
|
|
116
116
|
const rl = createInterface({ input, output });
|
|
117
117
|
try {
|
|
118
|
-
const answer = (await rl.question(`${question} (Y/n) `)).trim().toLowerCase();
|
|
119
|
-
return answer === ""
|
|
118
|
+
const answer = (await rl.question(`${question} ${defaultYes ? "(Y/n)" : "(y/N)"} `)).trim().toLowerCase();
|
|
119
|
+
return answer === "" ? defaultYes : answer === "y" || answer === "yes";
|
|
120
120
|
} finally {
|
|
121
121
|
rl.close();
|
|
122
122
|
}
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
/**
|
|
126
|
+
* Turn on Claude Code's fullscreen layout (`"tui": "fullscreen"`), the only one that reports the mouse to the picker
|
|
127
|
+
* (#766). A `tui` the user already chose is left alone.
|
|
128
|
+
* @param {string} settingsFile Path of settings.json.
|
|
129
|
+
* @returns {boolean} True when it was written, false when `tui` was already set.
|
|
130
|
+
* @throws {Error} When the existing file is invalid JSON (left untouched).
|
|
131
|
+
*/
|
|
132
|
+
export function enableFullscreen(settingsFile) {
|
|
133
|
+
const { settings } = readSettings(settingsFile);
|
|
134
|
+
if (settings.tui !== undefined) return false;
|
|
135
|
+
writeSettings(settingsFile, { ...settings, tui: "fullscreen" });
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {string} settingsFile Path of settings.json.
|
|
141
|
+
* @returns {boolean} Whether the user has not chosen a Claude Code layout (`tui`) yet.
|
|
142
|
+
*/
|
|
143
|
+
export function layoutUnset(settingsFile) {
|
|
144
|
+
return readSettings(settingsFile).settings.tui === undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
125
147
|
/**
|
|
126
148
|
* @param {unknown} value Value to test.
|
|
127
149
|
* @returns {value is Record<string, any>} True for non-null, non-array objects.
|
package/lib/pair.d.ts
CHANGED
|
@@ -14,6 +14,16 @@ export function promptTenant(options?: {
|
|
|
14
14
|
tenantList?: Array<{ slug: string; name: string }>;
|
|
15
15
|
}): Promise<string>;
|
|
16
16
|
export function openBrowser(url: string, platform?: string): void;
|
|
17
|
+
export function pairDevice(options: {
|
|
18
|
+
pool: string;
|
|
19
|
+
admin?: boolean;
|
|
20
|
+
deviceName: string;
|
|
21
|
+
log: (line: string) => void;
|
|
22
|
+
open: (url: string) => void;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
intervalOverrideMs?: number;
|
|
25
|
+
fetchImpl?: typeof fetch;
|
|
26
|
+
}): Promise<{ ok: true; key: string; baseUrl: string; kind?: string } | { ok: false; code: number }>;
|
|
17
27
|
export function runConnect(options: {
|
|
18
28
|
/** Tenant slug (`acme`) or pool URL; required. */
|
|
19
29
|
poolUrl: string | undefined;
|
|
@@ -34,5 +44,5 @@ export function runConnect(options: {
|
|
|
34
44
|
/** Where the picker is installed; `modelPickerDir()` by default. */
|
|
35
45
|
modelPickerDir?: string;
|
|
36
46
|
/** Yes/no prompt; answers false without a terminal. */
|
|
37
|
-
ask?: (question: string) => Promise<boolean>;
|
|
47
|
+
ask?: (question: string, defaultYes?: boolean) => Promise<boolean>;
|
|
38
48
|
}): Promise<number>;
|
package/lib/pair.js
CHANGED
|
@@ -3,7 +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
|
+
import { askYesNo, enableFullscreen, installModelPicker, layoutUnset, modelPickerDir } from "./model-picker.js";
|
|
7
7
|
import { connectSettings, normalizeUrl, overridingEnvVars, readSettings } from "./settings.js";
|
|
8
8
|
|
|
9
9
|
const MAX_WAIT_MS = 15 * 60 * 1000;
|
|
@@ -202,10 +202,11 @@ function sleep(ms, signal) {
|
|
|
202
202
|
* @param {string} url Endpoint URL.
|
|
203
203
|
* @param {object} body JSON payload.
|
|
204
204
|
* @param {AbortSignal} [signal] Cancels the request.
|
|
205
|
+
* @param {typeof fetch} [fetchImpl] `fetch` override for tests.
|
|
205
206
|
* @returns {Promise<{ status: number, body: any }>} HTTP status and parsed JSON (null when not JSON).
|
|
206
207
|
*/
|
|
207
|
-
async function postJson(url, body, signal) {
|
|
208
|
-
const res = await
|
|
208
|
+
async function postJson(url, body, signal, fetchImpl = fetch) {
|
|
209
|
+
const res = await fetchImpl(url, {
|
|
209
210
|
method: "POST",
|
|
210
211
|
headers: { "content-type": "application/json" },
|
|
211
212
|
body: JSON.stringify(body),
|
|
@@ -214,6 +215,69 @@ async function postJson(url, body, signal) {
|
|
|
214
215
|
return { status: res.status, body: await res.json().catch(() => null) };
|
|
215
216
|
}
|
|
216
217
|
|
|
218
|
+
/**
|
|
219
|
+
* Pair this machine and wait for the approval, printing the code and opening the browser.
|
|
220
|
+
*
|
|
221
|
+
* @param {object} options
|
|
222
|
+
* @param {string} options.pool Pool address from `resolvePoolUrl`.
|
|
223
|
+
* @param {boolean} [options.admin] Ask the pool for an admin device token instead of a Claude Code key.
|
|
224
|
+
* @param {string} options.deviceName Name shown on the confirmation page.
|
|
225
|
+
* @param {(line: string) => void} options.log Output sink.
|
|
226
|
+
* @param {(url: string) => void} options.open Browser opener.
|
|
227
|
+
* @param {AbortSignal} [options.signal] Aborts the flow (Ctrl+C).
|
|
228
|
+
* @param {number} [options.intervalOverrideMs] Poll interval override (tests).
|
|
229
|
+
* @param {typeof fetch} [options.fetchImpl] `fetch` override for tests.
|
|
230
|
+
* @returns {Promise<{ ok: true, key: string, baseUrl: string, kind?: string } | { ok: false, code: number }>} The issued
|
|
231
|
+
* credential and the address to use it against, or the exit code to report (cancelled, denied, expired, timed out).
|
|
232
|
+
*/
|
|
233
|
+
export async function pairDevice({ pool, admin = false, deviceName, log, open, signal, intervalOverrideMs, fetchImpl = fetch }) {
|
|
234
|
+
const start = await postJson(`${pool}/pair/start`, admin ? { deviceName, kind: "admin" } : { deviceName }, signal, fetchImpl);
|
|
235
|
+
if (start.status === 429) {
|
|
236
|
+
log("Too many pairing attempts. Wait a few minutes and try again.");
|
|
237
|
+
return { ok: false, code: 1 };
|
|
238
|
+
}
|
|
239
|
+
if (start.status !== 200 || !start.body?.deviceCode) {
|
|
240
|
+
log(`Error: the pool rejected the pairing request (HTTP ${start.status}).`);
|
|
241
|
+
return { ok: false, code: 1 };
|
|
242
|
+
}
|
|
243
|
+
const { deviceCode, userCode, verifyUrl: rawVerifyUrl, interval, expiresIn } = start.body;
|
|
244
|
+
const verifyUrl = pool.startsWith("https://") && String(rawVerifyUrl || "").startsWith("http://")
|
|
245
|
+
? rawVerifyUrl.replace(/^http:\/\//, "https://")
|
|
246
|
+
: rawVerifyUrl;
|
|
247
|
+
log("");
|
|
248
|
+
log(` Your code: ${userCode}`);
|
|
249
|
+
log("");
|
|
250
|
+
log(`Confirm it at: ${verifyUrl}${admin ? " (sign in as the admin)" : ""}`);
|
|
251
|
+
log("Opening your browser. Waiting for approval (Ctrl+C to cancel)...");
|
|
252
|
+
open(verifyUrl);
|
|
253
|
+
const intervalMs = intervalOverrideMs ?? Math.max(1, Number(interval) || 3) * 1000;
|
|
254
|
+
const deadline = Date.now() + Math.min(MAX_WAIT_MS, (Number(expiresIn) || 600) * 1000 + intervalMs);
|
|
255
|
+
while (Date.now() < deadline) {
|
|
256
|
+
await sleep(intervalMs, signal);
|
|
257
|
+
if (signal?.aborted) {
|
|
258
|
+
log("Cancelled.");
|
|
259
|
+
return { ok: false, code: 130 };
|
|
260
|
+
}
|
|
261
|
+
const poll = await postJson(`${pool}/pair/poll`, { deviceCode }, signal, fetchImpl);
|
|
262
|
+
if (poll.status === 429) continue;
|
|
263
|
+
const status = poll.body?.status;
|
|
264
|
+
const baseUrl = pool.startsWith("https://") && String(poll.body?.baseUrl || "").startsWith("http://")
|
|
265
|
+
? poll.body.baseUrl.replace(/^http:\/\//, "https://")
|
|
266
|
+
: poll.body?.baseUrl || pool;
|
|
267
|
+
if (status === "approved") return { ok: true, key: poll.body.key, baseUrl, kind: poll.body.kind };
|
|
268
|
+
if (status === "denied") {
|
|
269
|
+
log("The request was denied.");
|
|
270
|
+
return { ok: false, code: 1 };
|
|
271
|
+
}
|
|
272
|
+
if (status === "expired") {
|
|
273
|
+
log("The code expired. Run the command again.");
|
|
274
|
+
return { ok: false, code: 1 };
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
log("Timed out waiting for approval. Run the command again.");
|
|
278
|
+
return { ok: false, code: 1 };
|
|
279
|
+
}
|
|
280
|
+
|
|
217
281
|
/**
|
|
218
282
|
* Run the pairing flow and write the issued key into settings.json.
|
|
219
283
|
* @param {object} options
|
|
@@ -230,7 +294,7 @@ async function postJson(url, body, signal) {
|
|
|
230
294
|
* @param {string} [options.adminFile] Path from `adminConfigPath`; required with `admin`.
|
|
231
295
|
* @param {boolean} [options.modelPicker] Offer to install the Claude Code model picker after pairing (default true).
|
|
232
296
|
* @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.
|
|
297
|
+
* @param {(question: string, defaultYes?: boolean) => Promise<boolean>} [options.ask] Yes/no prompt (tests); false without a terminal.
|
|
234
298
|
* @returns {Promise<number>} Process exit code.
|
|
235
299
|
*/
|
|
236
300
|
export async function runConnect({
|
|
@@ -247,7 +311,7 @@ export async function runConnect({
|
|
|
247
311
|
adminFile,
|
|
248
312
|
modelPicker = true,
|
|
249
313
|
modelPickerDir: pickerDir = modelPickerDir(),
|
|
250
|
-
ask = askYesNo,
|
|
314
|
+
ask = (question, defaultYes = true) => askYesNo(question, { defaultYes }),
|
|
251
315
|
}) {
|
|
252
316
|
let pool;
|
|
253
317
|
try {
|
|
@@ -258,81 +322,42 @@ export async function runConnect({
|
|
|
258
322
|
return 1;
|
|
259
323
|
}
|
|
260
324
|
try {
|
|
261
|
-
const
|
|
262
|
-
if (
|
|
263
|
-
|
|
264
|
-
|
|
325
|
+
const paired = await pairDevice({ pool, admin, deviceName, log, open, signal, intervalOverrideMs });
|
|
326
|
+
if (!paired.ok) return paired.code;
|
|
327
|
+
const { baseUrl } = paired;
|
|
328
|
+
if (admin) {
|
|
329
|
+
if (paired.kind !== "admin") {
|
|
330
|
+
log("Error: the pool did not issue an admin device token. Update the pool, then run the command again.");
|
|
331
|
+
return 1;
|
|
332
|
+
}
|
|
333
|
+
writeAdminConfig(adminFile, baseUrl, paired.key);
|
|
334
|
+
log(`Admin device paired. Token saved to ${adminFile}`);
|
|
335
|
+
log(`Revoke it any time on the pool's admin Devices page (${baseUrl}/admin/pair).`);
|
|
336
|
+
return 0;
|
|
265
337
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
338
|
+
const statusResult = connectSettings(settingsFile, baseUrl, paired.key, { statusLine });
|
|
339
|
+
log(`Connected. Claude Code settings updated: ${settingsFile}`);
|
|
340
|
+
if (statusResult === "installed") log("Status line added: today's spend and credit show under the Claude Code prompt.");
|
|
341
|
+
if (statusResult === "updated") log("Status line refreshed with your new key.");
|
|
342
|
+
if (statusResult === "kept") log("Your existing statusLine was left as is. The setup guide on the pool site has the TokenHub one if you want it.");
|
|
343
|
+
const overriding = overridingEnvVars(env);
|
|
344
|
+
if (overriding.length > 0) {
|
|
345
|
+
log(`Warning: ${overriding.join(", ")} set in your shell overrides settings.json. Unset it to use the pool.`);
|
|
269
346
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
log("Opening your browser. Waiting for approval (Ctrl+C to cancel)...");
|
|
279
|
-
open(verifyUrl);
|
|
280
|
-
|
|
281
|
-
const intervalMs = intervalOverrideMs ?? Math.max(1, Number(interval) || 3) * 1000;
|
|
282
|
-
const deadline = Date.now() + Math.min(MAX_WAIT_MS, (Number(expiresIn) || 600) * 1000 + intervalMs);
|
|
283
|
-
while (Date.now() < deadline) {
|
|
284
|
-
await sleep(intervalMs, signal);
|
|
285
|
-
if (signal?.aborted) {
|
|
286
|
-
log("Cancelled.");
|
|
287
|
-
return 130;
|
|
288
|
-
}
|
|
289
|
-
const poll = await postJson(`${pool}/pair/poll`, { deviceCode }, signal);
|
|
290
|
-
if (poll.status === 429) continue;
|
|
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;
|
|
295
|
-
if (status === "approved" && admin) {
|
|
296
|
-
if (poll.body.kind !== "admin") {
|
|
297
|
-
log("Error: the pool did not issue an admin device token. Update the pool, then run the command again.");
|
|
298
|
-
return 1;
|
|
347
|
+
if (modelPicker && (await ask("Install the TokenHub model picker for Claude Code (/model lists TokenHub models)?"))) {
|
|
348
|
+
try {
|
|
349
|
+
installModelPicker(settingsFile, pickerDir);
|
|
350
|
+
log("Model picker installed. Restart Claude Code, then type /model to pick a TokenHub model.");
|
|
351
|
+
// Claude Code reports the mouse only in its fullscreen layout (#766): offer it, never force it.
|
|
352
|
+
if (layoutUnset(settingsFile) && (await ask("Turn on Claude Code's fullscreen layout so the picker takes the mouse?", false))) {
|
|
353
|
+
enableFullscreen(settingsFile);
|
|
354
|
+
log('Fullscreen layout on ("tui": "fullscreen"). Switch back any time with /tui default.');
|
|
299
355
|
}
|
|
300
|
-
|
|
301
|
-
log(`
|
|
302
|
-
log(`Revoke it any time on the pool's admin Devices page (${baseUrl}/admin/pair).`);
|
|
303
|
-
return 0;
|
|
304
|
-
}
|
|
305
|
-
if (status === "approved") {
|
|
306
|
-
const statusResult = connectSettings(settingsFile, baseUrl, poll.body.key, { statusLine });
|
|
307
|
-
log(`Connected. Claude Code settings updated: ${settingsFile}`);
|
|
308
|
-
if (statusResult === "installed") log("Status line added: today's spend and credit show under the Claude Code prompt.");
|
|
309
|
-
if (statusResult === "updated") log("Status line refreshed with your new key.");
|
|
310
|
-
if (statusResult === "kept") log("Your existing statusLine was left as is. The setup guide on the pool site has the TokenHub one if you want it.");
|
|
311
|
-
const overriding = overridingEnvVars(env);
|
|
312
|
-
if (overriding.length > 0) {
|
|
313
|
-
log(`Warning: ${overriding.join(", ")} set in your shell overrides settings.json. Unset it to use the pool.`);
|
|
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
|
-
}
|
|
323
|
-
return 0;
|
|
324
|
-
}
|
|
325
|
-
if (status === "denied") {
|
|
326
|
-
log("The request was denied.");
|
|
327
|
-
return 1;
|
|
328
|
-
}
|
|
329
|
-
if (status === "expired") {
|
|
330
|
-
log("The code expired. Run the command again.");
|
|
331
|
-
return 1;
|
|
356
|
+
} catch (error) {
|
|
357
|
+
log(`Model picker not installed: ${error.message}`);
|
|
332
358
|
}
|
|
333
359
|
}
|
|
334
|
-
|
|
335
|
-
return 1;
|
|
360
|
+
return 0;
|
|
336
361
|
} catch (error) {
|
|
337
362
|
if (signal?.aborted) {
|
|
338
363
|
log("Cancelled.");
|