@emesoft/tokenhub 0.8.11 → 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 +1 -0
- package/bin/tokenhub.js +20 -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/pair.d.ts +10 -0
- package/lib/pair.js +97 -77
- 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). |
|
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";
|
|
@@ -23,6 +24,8 @@ Usage:
|
|
|
23
24
|
tokenhub connect [tenant] --admin
|
|
24
25
|
Pair this machine as an admin device (for the desktop overlay's pool view): the admin
|
|
25
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
|
|
26
29
|
tokenhub overlay <tenant> Download and install the TokenHub desktop overlay (Windows)
|
|
27
30
|
tokenhub usage [--json] Show today's and this week's spend, credit and pool health
|
|
28
31
|
tokenhub dashboard [--interval <sec>] [--once]
|
|
@@ -81,6 +84,23 @@ async function main(argv) {
|
|
|
81
84
|
modelPicker: !flags.includes("--no-model-picker"),
|
|
82
85
|
});
|
|
83
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
|
+
}
|
|
84
104
|
if (command === "overlay") {
|
|
85
105
|
return runOverlayInstall({ poolUrl: arg });
|
|
86
106
|
}
|
|
@@ -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/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;
|
package/lib/pair.js
CHANGED
|
@@ -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
|
|
@@ -258,86 +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
|
-
// Claude Code reports the mouse only in its fullscreen layout (#766): offer it, never force it.
|
|
320
|
-
if (layoutUnset(settingsFile) && (await ask("Turn on Claude Code's fullscreen layout so the picker takes the mouse?", false))) {
|
|
321
|
-
enableFullscreen(settingsFile);
|
|
322
|
-
log('Fullscreen layout on ("tui": "fullscreen"). Switch back any time with /tui default.');
|
|
323
|
-
}
|
|
324
|
-
} catch (error) {
|
|
325
|
-
log(`Model picker not installed: ${error.message}`);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
return 0;
|
|
329
|
-
}
|
|
330
|
-
if (status === "denied") {
|
|
331
|
-
log("The request was denied.");
|
|
332
|
-
return 1;
|
|
333
|
-
}
|
|
334
|
-
if (status === "expired") {
|
|
335
|
-
log("The code expired. Run the command again.");
|
|
336
|
-
return 1;
|
|
356
|
+
} catch (error) {
|
|
357
|
+
log(`Model picker not installed: ${error.message}`);
|
|
337
358
|
}
|
|
338
359
|
}
|
|
339
|
-
|
|
340
|
-
return 1;
|
|
360
|
+
return 0;
|
|
341
361
|
} catch (error) {
|
|
342
362
|
if (signal?.aborted) {
|
|
343
363
|
log("Cancelled.");
|