@emesoft/tokenhub 0.8.13 → 0.9.0
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 +13 -1
- package/bin/tokenhub.js +44 -5
- package/lib/claude-shim.d.ts +37 -0
- package/lib/claude-shim.js +284 -0
- package/lib/desktop-connect.js +2 -2
- package/lib/desktop.d.ts +2 -1
- package/lib/desktop.js +18 -5
- package/lib/pair.d.ts +6 -0
- package/lib/pair.js +14 -1
- package/lib/remote-download.d.ts +29 -0
- package/lib/remote-download.js +242 -0
- package/lib/remote-install.d.ts +85 -0
- package/lib/remote-install.js +582 -0
- package/lib/remote-paths.d.ts +7 -0
- package/lib/remote-paths.js +72 -0
- package/lib/remote-shim.d.ts +8 -0
- package/lib/remote-shim.js +124 -0
- package/lib/remote-text.d.ts +4 -0
- package/lib/remote-text.js +143 -0
- package/lib/remote.d.ts +33 -0
- package/lib/remote.js +201 -0
- package/lib/run.d.ts +8 -0
- package/lib/run.js +16 -0
- package/lib/user-path.d.ts +20 -0
- package/lib/user-path.js +227 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -45,7 +45,8 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
45
45
|
| `tokenhub usage [--json]` | Today's and this week's spend against your limits, your credit and pool health. |
|
|
46
46
|
| `tokenhub dashboard` | Live full-screen view of spend and your recent requests. |
|
|
47
47
|
| `tokenhub overlay <tenant>` | Install the TokenHub desktop overlay (Windows). |
|
|
48
|
-
| `tokenhub
|
|
48
|
+
| `tokenhub remote status` | TokenHub Remote: installed version, whether its daemon runs, the relay it is set up for, the `claude` launcher and your Remote page. |
|
|
49
|
+
| `tokenhub disconnect` | Undo `connect`, including TokenHub Remote. |
|
|
49
50
|
| `tokenhub --help` / `--version` | Help and version. |
|
|
50
51
|
|
|
51
52
|
### Options
|
|
@@ -54,6 +55,8 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
54
55
|
| --- | --- | --- |
|
|
55
56
|
| `--no-statusline` | `connect` | Don't add the spend status line to Claude Code. |
|
|
56
57
|
| `--no-model-picker` | `connect` | Don't offer to install the TokenHub model picker. |
|
|
58
|
+
| `--remote` / `--no-remote` | `connect` | Set up TokenHub Remote without asking / skip its question. |
|
|
59
|
+
| `--force` | `disconnect` | Stop the Remote daemon even while it hosts Claude sessions (they end). |
|
|
57
60
|
| `--admin` | `connect`, `disconnect` | Pair (or forget) this machine as an admin device. See [For admins](#for-admins). |
|
|
58
61
|
| `--json` | `usage` | Print the raw report. |
|
|
59
62
|
| `--interval <sec>` | `dashboard` | Refresh rate in seconds (default 3, minimum 2). |
|
|
@@ -78,6 +81,7 @@ Prefer not to install? Use `npx @emesoft/tokenhub connect <your tenant name>` in
|
|
|
78
81
|
only in its fullscreen layout, so after installing the picker `connect` asks whether to turn that on
|
|
79
82
|
(`"tui": "fullscreen"`, default no); in the classic layout the picker works from the keyboard and says
|
|
80
83
|
`/tui fullscreen` turns the mouse on. `disconnect` leaves `tui` as it is.
|
|
84
|
+
- Asks whether to set up **TokenHub Remote**, unless you pass `--remote` or `--no-remote` (see [TokenHub Remote](#tokenhub-remote)).
|
|
81
85
|
- Keeps every other setting, and saves the previous file as `settings.json.bak`.
|
|
82
86
|
|
|
83
87
|
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.
|
|
@@ -98,6 +102,14 @@ Each machine gets its own key, which you can revoke from the pool's **Keys** pag
|
|
|
98
102
|
|
|
99
103
|
<sub>Screenshots use sample data.</sub>
|
|
100
104
|
|
|
105
|
+
## TokenHub Remote
|
|
106
|
+
Drive the Claude Code session on your computer from your phone, while the terminal keeps working (Windows and macOS). `connect` asks "Use Claude from your phone (TokenHub Remote)?" (English or Vietnamese by your system language, or `TOKENHUB_LANG=vi`); the default is no. On yes it:
|
|
107
|
+
1. downloads the Remote daemon from your pool (`/downloads/remote/`), checks its SHA-256 and installs it in `~/.tokenhub/remote/<version>`;
|
|
108
|
+
2. pairs this computer for Remote: one more approval in the browser (revoke it any time on `https://<tenant>.aimpact.io.vn/member/remote`), and saves the token where the daemon reads it (`relay.json`, readable by you only);
|
|
109
|
+
3. adds the `/tf-remote` command and its hooks to Claude Code's settings (a backup `settings.json.tf-remote.bak-<time>` is made and the change is printed);
|
|
110
|
+
4. asks whether to make `claude` start through Remote: it puts a small launcher in `~/.tokenhub/bin` first on your PATH (Windows: your user `Path`; macOS: a marked block in `~/.zprofile`, and `~/.bash_profile` if you have one). `claude mcp`, `claude -p`, `--version`, `--help` and piped input or output run Claude Code untouched. Say no and start Claude with the `tfc` program that `connect` prints.
|
|
111
|
+
Then open a **new** terminal, run `claude`, type `/tf-remote` and scan the QR code with your phone. Run `connect` again to update the daemon (your token is kept unless you revoked it). `tokenhub remote status` shows what is installed; `tokenhub disconnect` stops the daemon, revokes the token, and removes the launcher, the PATH entry, the hooks and `/tf-remote`, touching only what `connect` wrote (it refuses while Remote hosts open Claude sessions; `--force` ends them).
|
|
112
|
+
|
|
101
113
|
## For admins
|
|
102
114
|
|
|
103
115
|
`tokenhub connect --admin` pairs this machine as an **admin device** for the desktop overlay's pool view:
|
package/bin/tokenhub.js
CHANGED
|
@@ -1,24 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
3
4
|
import { adminConfigPath, removeAdminConfig } from "../lib/admin.js";
|
|
4
5
|
import { isInteractive, showBanner } from "../lib/banner.js";
|
|
5
6
|
import { parseDashboardArgs, runDashboard } from "../lib/dashboard.js";
|
|
6
7
|
import { runDesktop } from "../lib/desktop-connect.js";
|
|
7
8
|
import { modelPickerDir, uninstallModelPicker } from "../lib/model-picker.js";
|
|
8
9
|
import { runOverlayInstall } from "../lib/overlay.js";
|
|
9
|
-
import { openBrowser, promptTenant, runConnect, TENANT_DOMAIN } from "../lib/pair.js";
|
|
10
|
+
import { openBrowser, promptTenant, resolvePoolUrl, runConnect, TENANT_DOMAIN } from "../lib/pair.js";
|
|
11
|
+
import { pairRemote, remoteDevConfigPath, writeRemoteDevConfig } from "../lib/remote.js";
|
|
12
|
+
import { disconnectRemote, remoteStatus } from "../lib/remote-install.js";
|
|
13
|
+
import { detectLang } from "../lib/remote-text.js";
|
|
10
14
|
import { disconnectSettings, readSettings, settingsPath } from "../lib/settings.js";
|
|
11
15
|
import { fetchUsage, formatUsage, resolveCredentials } from "../lib/usage.js";
|
|
12
16
|
|
|
13
17
|
const HELP = `tokenhub - pair Claude Code with your TokenHub tenant
|
|
14
18
|
|
|
15
19
|
Usage:
|
|
16
|
-
tokenhub connect [tenant] [--no-statusline] [--no-model-picker]
|
|
20
|
+
tokenhub connect [tenant] [--no-statusline] [--no-model-picker] [--remote | --no-remote]
|
|
17
21
|
Pair this machine and write ~/.claude/settings.json, including the status line
|
|
18
22
|
(today's spend under the prompt) unless --no-statusline. Then offers to install the
|
|
19
23
|
TokenHub model picker (a bare /model in Claude Code lists TokenHub models) unless
|
|
20
24
|
--no-model-picker, and then Claude Code's fullscreen layout, the only one that gives
|
|
21
|
-
the picker the mouse (default no).
|
|
25
|
+
the picker the mouse (default no). Finally asks "Use Claude from your phone (TokenHub
|
|
26
|
+
Remote)?" (default no; --remote says yes, --no-remote skips the question): it downloads
|
|
27
|
+
the daemon, pairs this computer (one more approval in the browser), adds the /tf-remote
|
|
28
|
+
command to Claude Code and, if you agree, a launcher that makes claude use it, first on your PATH
|
|
22
29
|
tenant is your tenant name (acme = https://acme.${TENANT_DOMAIN}) or a full URL;
|
|
23
30
|
it is asked for when left out
|
|
24
31
|
tokenhub connect [tenant] --admin
|
|
@@ -30,8 +37,12 @@ Usage:
|
|
|
30
37
|
tokenhub usage [--json] Show today's and this week's spend, credit and pool health
|
|
31
38
|
tokenhub dashboard [--interval <sec>] [--once]
|
|
32
39
|
Live full-screen view of spend, pool health and recent requests (q quits)
|
|
33
|
-
tokenhub disconnect
|
|
40
|
+
tokenhub disconnect [--force]
|
|
41
|
+
Remove the pool entries, the status line and the model picker from settings.json, and
|
|
42
|
+
TokenHub Remote if it was set up (daemon, launcher, PATH entry, hooks, token). Refuses
|
|
43
|
+
while Remote hosts Claude sessions, unless --force stops them
|
|
34
44
|
tokenhub disconnect --admin Forget the admin device token on this machine (revoke it on the pool's admin Devices page)
|
|
45
|
+
tokenhub remote status TokenHub Remote: installed version, daemon, relay configuration, launcher, your page
|
|
35
46
|
tokenhub banner Display the TokenHub welcome banner
|
|
36
47
|
tokenhub --help | --version
|
|
37
48
|
`;
|
|
@@ -82,6 +93,7 @@ async function main(argv) {
|
|
|
82
93
|
admin: flags.includes("--admin"),
|
|
83
94
|
adminFile: adminConfigPath(),
|
|
84
95
|
modelPicker: !flags.includes("--no-model-picker"),
|
|
96
|
+
remote: flags.includes("--remote") ? true : flags.includes("--no-remote") ? false : undefined,
|
|
85
97
|
});
|
|
86
98
|
}
|
|
87
99
|
if (command === "desktop") {
|
|
@@ -101,6 +113,31 @@ async function main(argv) {
|
|
|
101
113
|
}
|
|
102
114
|
return runDesktop({ poolUrl, open: openBrowser, signal: controller.signal });
|
|
103
115
|
}
|
|
116
|
+
if (command === "remote") {
|
|
117
|
+
const [sub, tenant] = rest.filter((item) => !item.startsWith("--"));
|
|
118
|
+
if (sub === "status") return remoteStatus({ settingsFile: file, home: homedir() });
|
|
119
|
+
// `remote pair --dev` is a hidden development command (not in HELP): it parks a token in a temp file, no installation.
|
|
120
|
+
if (sub !== "pair" || !flags.includes("--dev")) {
|
|
121
|
+
console.error("Usage: tokenhub remote status (set TokenHub Remote up with `tokenhub connect --remote`)");
|
|
122
|
+
return 1;
|
|
123
|
+
}
|
|
124
|
+
const controller = new AbortController();
|
|
125
|
+
process.once("SIGINT", () => controller.abort());
|
|
126
|
+
try {
|
|
127
|
+
const pool = resolvePoolUrl(tenant ?? (await promptTenant()));
|
|
128
|
+
const paired = await pairRemote({ pool, log: console.log, open: openBrowser, signal: controller.signal });
|
|
129
|
+
if (!paired.ok) return paired.code;
|
|
130
|
+
const devFile = remoteDevConfigPath();
|
|
131
|
+
writeRemoteDevConfig(devFile, paired.baseUrl, paired.token);
|
|
132
|
+
console.log("Computer paired for TokenHub Remote.");
|
|
133
|
+
console.log(`The daemon config is not written yet (its location comes from the daemon). For development the token is saved to ${devFile}`);
|
|
134
|
+
console.log(`Revoke it any time on ${paired.baseUrl}/member/remote`);
|
|
135
|
+
return 0;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
console.error(controller.signal.aborted ? "Cancelled." : `Error: ${error.message}`);
|
|
138
|
+
return controller.signal.aborted ? 130 : 1;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
104
141
|
if (command === "overlay") {
|
|
105
142
|
return runOverlayInstall({ poolUrl: arg });
|
|
106
143
|
}
|
|
@@ -140,9 +177,11 @@ async function main(argv) {
|
|
|
140
177
|
console.log(removeAdminConfig(adminFile) ? `Admin device forgotten. Removed ${adminFile}` : `Nothing to remove at ${adminFile}`);
|
|
141
178
|
return 0;
|
|
142
179
|
}
|
|
180
|
+
const remote = await disconnectRemote({ settingsFile: file, force: flags.includes("--force"), home: homedir(), lang: detectLang() });
|
|
181
|
+
if (remote.blocked) return 1;
|
|
143
182
|
const pool = disconnectSettings(file);
|
|
144
183
|
const picker = uninstallModelPicker(file, modelPickerDir());
|
|
145
|
-
console.log(pool || picker ? `Disconnected. Updated ${file}` : `Nothing to remove in ${file}`);
|
|
184
|
+
console.log(pool || picker || remote.found ? `Disconnected. Updated ${file}` : `Nothing to remove in ${file}`);
|
|
146
185
|
return 0;
|
|
147
186
|
} catch (error) {
|
|
148
187
|
console.error(`Error: ${error.message}`);
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const SHIM_MARKER: string;
|
|
2
|
+
export const BYPASS_SUBCOMMANDS: Set<string>;
|
|
3
|
+
export const BYPASS_FLAGS: Set<string>;
|
|
4
|
+
export function detectLang(env?: Record<string, string | undefined>): "en" | "vi";
|
|
5
|
+
export function decide(args: string[], tty: { stdinTTY: boolean; stdoutTTY: boolean }): { route: "real" | "hosted"; reason: string };
|
|
6
|
+
export function normalizeDir(dir: string, platform?: string): string;
|
|
7
|
+
export function findOnPath(
|
|
8
|
+
names: string[],
|
|
9
|
+
pathValue: string,
|
|
10
|
+
options?: { exclude?: string[]; platform?: string; exists?: (file: string) => boolean },
|
|
11
|
+
): string | undefined;
|
|
12
|
+
export function findRealClaude(options: {
|
|
13
|
+
pathValue: string;
|
|
14
|
+
shimDirs: string[];
|
|
15
|
+
env?: Record<string, string | undefined>;
|
|
16
|
+
platform?: string;
|
|
17
|
+
home?: string;
|
|
18
|
+
exists?: (file: string) => boolean;
|
|
19
|
+
}): string | undefined;
|
|
20
|
+
export function hostedEnv(
|
|
21
|
+
env: Record<string, string | undefined>,
|
|
22
|
+
options: { shimDirs: string[]; real: string; configDir?: string; platform?: string; exists?: (file: string) => boolean },
|
|
23
|
+
): Record<string, string | undefined>;
|
|
24
|
+
export function remoteConfigDir(shimDir: string, platform?: string): string;
|
|
25
|
+
export function findTfc(shimDir: string, platform?: string): string | undefined;
|
|
26
|
+
export function quoteForCmd(arg: string): string;
|
|
27
|
+
export function launch(file: string, args: string[], env: Record<string, string | undefined>, platform?: string): Promise<number>;
|
|
28
|
+
export function runShim(options: {
|
|
29
|
+
args: string[];
|
|
30
|
+
shimDir: string;
|
|
31
|
+
env?: Record<string, string | undefined>;
|
|
32
|
+
platform?: string;
|
|
33
|
+
home?: string;
|
|
34
|
+
stdinTTY?: boolean;
|
|
35
|
+
stdoutTTY?: boolean;
|
|
36
|
+
start?: typeof launch;
|
|
37
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// tokenhub-remote-shim: the `claude` that `tokenhub connect` puts first on PATH (TokenHub Remote, ADR-0058).
|
|
2
|
+
//
|
|
3
|
+
// This one file is both a module (the CLI imports its pure functions) and, copied to `~/.tokenhub/bin/claude-shim.mjs`, the program
|
|
4
|
+
// the `claude` / `claude.cmd` wrappers run. It imports only Node's own modules for that reason: nothing else is beside the copy.
|
|
5
|
+
//
|
|
6
|
+
// `claude <args>` runs `tfc -- <args>` (the terminal client of the session host, which hosts the real claude in a pseudo-terminal so
|
|
7
|
+
// a phone can drive the same session) except where hosting would only get in the way: Claude's own subcommands, `-v`, `-h`, `-p`,
|
|
8
|
+
// and any call whose stdin or stdout is not a terminal go straight to the real claude. The shim never calls itself: the real claude
|
|
9
|
+
// is looked up on PATH without the shim's own folder, and `tfc` gets a PATH without it too.
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
12
|
+
import { constants as osConstants, homedir } from "node:os";
|
|
13
|
+
import { dirname as hostDirname, posix, resolve, win32 } from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
|
|
16
|
+
/** @param {string} platform Node platform name. @returns {typeof posix} The path functions of that system (so a Windows path is handled as one on any host). */
|
|
17
|
+
function pathFor(platform) {
|
|
18
|
+
return platform === "win32" ? win32 : posix;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Marker every file the installer writes carries, so uninstall removes only files it wrote. */
|
|
22
|
+
export const SHIM_MARKER = "tokenhub-remote-shim";
|
|
23
|
+
/** The first argument of these is a Claude Code subcommand: never hosted. */
|
|
24
|
+
export const BYPASS_SUBCOMMANDS = new Set(["mcp", "config", "update", "doctor", "install", "plugin", "plugins", "agents", "auth", "setup-token", "migrate-installer", "login", "logout"]);
|
|
25
|
+
/** Flags that make a run non-interactive or informational: never hosted. */
|
|
26
|
+
export const BYPASS_FLAGS = new Set(["-v", "--version", "-h", "--help", "-p", "--print"]);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Language of the messages: Vietnamese when `TOKENHUB_LANG`, `LC_ALL`, `LC_MESSAGES`, `LANG` or the system locale says `vi`.
|
|
30
|
+
*
|
|
31
|
+
* @param {Record<string, string | undefined>} [env] Environment to read the variables from.
|
|
32
|
+
* @returns {"en" | "vi"} The language.
|
|
33
|
+
*/
|
|
34
|
+
export function detectLang(env = process.env) {
|
|
35
|
+
let locale = env.TOKENHUB_LANG || env.LC_ALL || env.LC_MESSAGES || env.LANG || "";
|
|
36
|
+
if (!locale) {
|
|
37
|
+
try {
|
|
38
|
+
locale = Intl.DateTimeFormat().resolvedOptions().locale;
|
|
39
|
+
} catch {
|
|
40
|
+
locale = "";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return /^vi/i.test(locale) ? "vi" : "en";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Decide where a `claude` call goes.
|
|
48
|
+
*
|
|
49
|
+
* @param {string[]} args The arguments the user typed.
|
|
50
|
+
* @param {{ stdinTTY: boolean, stdoutTTY: boolean }} tty Whether stdin and stdout are terminals (a redirect is not one).
|
|
51
|
+
* @returns {{ route: "real" | "hosted", reason: string }} `real` runs the real claude untouched; `hosted` runs it through `tfc`.
|
|
52
|
+
*/
|
|
53
|
+
export function decide(args, { stdinTTY, stdoutTTY }) {
|
|
54
|
+
if (!stdinTTY || !stdoutTTY) return { route: "real", reason: "redirected" };
|
|
55
|
+
if (args.length > 0 && BYPASS_SUBCOMMANDS.has(args[0])) return { route: "real", reason: "subcommand" };
|
|
56
|
+
// What follows `--` is the prompt, not options.
|
|
57
|
+
const end = args.indexOf("--");
|
|
58
|
+
const options = end === -1 ? args : args.slice(0, end);
|
|
59
|
+
if (options.some((arg) => BYPASS_FLAGS.has(arg))) return { route: "real", reason: "flag" };
|
|
60
|
+
return { route: "hosted", reason: "interactive" };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Compare two folders the way the OS would: absolute, no trailing separator, case-insensitive on Windows.
|
|
65
|
+
*
|
|
66
|
+
* @param {string} dir A folder path.
|
|
67
|
+
* @param {string} [platform] Node platform name.
|
|
68
|
+
* @returns {string} A string that is equal for equal folders.
|
|
69
|
+
*/
|
|
70
|
+
export function normalizeDir(dir, platform = process.platform) {
|
|
71
|
+
const full = pathFor(platform).resolve(String(dir));
|
|
72
|
+
return platform === "win32" ? full.toLowerCase() : full;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The first file called one of `names` in a folder of `pathValue`, skipping the excluded folders.
|
|
77
|
+
*
|
|
78
|
+
* @param {string[]} names File names to look for, in order of preference, in each folder.
|
|
79
|
+
* @param {string} pathValue A PATH value.
|
|
80
|
+
* @param {object} [options]
|
|
81
|
+
* @param {string[]} [options.exclude] Folders never to return a file from (the shim's own).
|
|
82
|
+
* @param {string} [options.platform] Node platform name.
|
|
83
|
+
* @param {(file: string) => boolean} [options.exists] File check (tests replace it).
|
|
84
|
+
* @returns {string | undefined} The file's path.
|
|
85
|
+
*/
|
|
86
|
+
export function findOnPath(names, pathValue, { exclude = [], platform = process.platform, exists = existsSync } = {}) {
|
|
87
|
+
const { delimiter, join } = pathFor(platform);
|
|
88
|
+
const skip = new Set(exclude.map((dir) => normalizeDir(dir, platform)));
|
|
89
|
+
for (const raw of String(pathValue ?? "").split(delimiter)) {
|
|
90
|
+
const dir = raw.trim().replace(/^"(.*)"$/, "$1");
|
|
91
|
+
if (!dir || skip.has(normalizeDir(dir, platform))) continue;
|
|
92
|
+
for (const name of names) {
|
|
93
|
+
const file = join(dir, name);
|
|
94
|
+
if (exists(file)) return file;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @param {string} platform Node platform name. @returns {string[]} File names a real claude can have, preferred first. */
|
|
101
|
+
function claudeNames(platform) {
|
|
102
|
+
return platform === "win32" ? ["claude.exe", "claude.cmd"] : ["claude"];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Find the real Claude Code: `TF_CLAUDE` when it names a file, else the first `claude` on PATH outside the shim's folder, else the
|
|
107
|
+
* places the installers use.
|
|
108
|
+
*
|
|
109
|
+
* @param {object} options
|
|
110
|
+
* @param {string} options.pathValue PATH to search.
|
|
111
|
+
* @param {string[]} options.shimDirs The shim's folder; nothing in it is returned.
|
|
112
|
+
* @param {Record<string, string | undefined>} [options.env] Environment (for `TF_CLAUDE`).
|
|
113
|
+
* @param {string} [options.platform] Node platform name.
|
|
114
|
+
* @param {string} [options.home] Home folder for the installers' usual places.
|
|
115
|
+
* @param {(file: string) => boolean} [options.exists] File check (tests replace it).
|
|
116
|
+
* @returns {string | undefined} The path, or undefined when there is none.
|
|
117
|
+
*/
|
|
118
|
+
export function findRealClaude({ pathValue, shimDirs, env = {}, platform = process.platform, home = homedir(), exists = existsSync }) {
|
|
119
|
+
const { dirname, join } = pathFor(platform);
|
|
120
|
+
const skip = new Set(shimDirs.map((dir) => normalizeDir(dir, platform)));
|
|
121
|
+
const outside = (file) => !skip.has(normalizeDir(dirname(file), platform));
|
|
122
|
+
if (env.TF_CLAUDE && exists(env.TF_CLAUDE) && outside(env.TF_CLAUDE)) return env.TF_CLAUDE;
|
|
123
|
+
const onPath = findOnPath(claudeNames(platform), pathValue, { exclude: shimDirs, platform, exists });
|
|
124
|
+
if (onPath) return onPath;
|
|
125
|
+
const usual =
|
|
126
|
+
platform === "win32"
|
|
127
|
+
? [join(home, ".local", "bin", "claude.exe")]
|
|
128
|
+
: [join(home, ".local", "bin", "claude"), join(home, ".claude", "local", "claude"), "/opt/homebrew/bin/claude", "/usr/local/bin/claude"];
|
|
129
|
+
return usual.find((file) => exists(file) && outside(file));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The environment `tfc` runs in, and so the hosted claude: PATH without the shim's folder, `TF_CLAUDE` naming the real claude,
|
|
134
|
+
* and, when the daemon would not find that claude by its own PATH lookup (it looks for `claude.exe` on Windows, `claude` elsewhere),
|
|
135
|
+
* the real claude's folder in front.
|
|
136
|
+
*
|
|
137
|
+
* @param {Record<string, string | undefined>} env The environment the shim runs in.
|
|
138
|
+
* @param {object} options
|
|
139
|
+
* @param {string[]} options.shimDirs The shim's folder.
|
|
140
|
+
* @param {string} options.real Path of the real claude.
|
|
141
|
+
* @param {string} [options.configDir] TokenHub Remote's own config folder, set as `TFR_CONFIG_DIR`: where `tfc` looks for `host.json` and `relay.json`
|
|
142
|
+
* (so it never touches TicketFlow's folder) and, passed on by the daemon, where the hook script of the hosted session finds `remote.key`.
|
|
143
|
+
* @param {string} [options.platform] Node platform name.
|
|
144
|
+
* @param {(file: string) => boolean} [options.exists] File check (tests replace it).
|
|
145
|
+
* @returns {Record<string, string | undefined>} A new environment; `env` is not changed.
|
|
146
|
+
*/
|
|
147
|
+
export function hostedEnv(env, { shimDirs, real, configDir, platform = process.platform, exists = existsSync }) {
|
|
148
|
+
const { delimiter, dirname } = pathFor(platform);
|
|
149
|
+
const key = Object.keys(env).find((name) => name.toUpperCase() === "PATH") ?? "PATH";
|
|
150
|
+
const skip = new Set(shimDirs.map((dir) => normalizeDir(dir, platform)));
|
|
151
|
+
const kept = String(env[key] ?? "")
|
|
152
|
+
.split(delimiter)
|
|
153
|
+
.filter((dir) => dir && !skip.has(normalizeDir(dir.trim().replace(/^"(.*)"$/, "$1"), platform)));
|
|
154
|
+
const names = platform === "win32" ? ["claude.exe"] : ["claude"];
|
|
155
|
+
const found = findOnPath(names, kept.join(delimiter), { platform, exists });
|
|
156
|
+
const path = found && normalizeDir(found, platform) === normalizeDir(real, platform) ? kept : [dirname(real), ...kept];
|
|
157
|
+
return { ...env, [key]: path.join(delimiter), TF_CLAUDE: real, ...(configDir ? { TFR_CONFIG_DIR: configDir } : {}) };
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Where TokenHub Remote's config folder is: `<tokenhub dir>/remote/config`, beside the shim's folder (same rule as `appConfigDir` in
|
|
161
|
+
* `remote-paths.js`, which the CLI uses; the shim has no imports besides Node's).
|
|
162
|
+
*
|
|
163
|
+
* @param {string} shimDir The shim's folder (`~/.tokenhub/bin`).
|
|
164
|
+
* @param {string} [platform] Node platform name.
|
|
165
|
+
* @returns {string} The path (not created).
|
|
166
|
+
*/
|
|
167
|
+
export function remoteConfigDir(shimDir, platform = process.platform) {
|
|
168
|
+
return pathFor(platform).join(shimDir, "..", "remote", "config");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Where `tfc` is: the folder `current.json` (written by `tokenhub connect`) names, next to the shim's folder.
|
|
173
|
+
*
|
|
174
|
+
* @param {string} shimDir The shim's folder (`~/.tokenhub/bin`).
|
|
175
|
+
* @param {string} [platform] Node platform name.
|
|
176
|
+
* @returns {string | undefined} The path of `tfc`, or undefined when Remote is not installed (or half removed).
|
|
177
|
+
*/
|
|
178
|
+
export function findTfc(shimDir, platform = process.platform) {
|
|
179
|
+
const { join } = pathFor(platform);
|
|
180
|
+
try {
|
|
181
|
+
const pointer = JSON.parse(readFileSync(join(shimDir, "..", "remote", "current.json"), "utf8"));
|
|
182
|
+
const file = join(String(pointer.dir), platform === "win32" ? "tfc.exe" : "tfc");
|
|
183
|
+
return existsSync(file) ? file : undefined;
|
|
184
|
+
} catch {
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Quote one argument for `cmd.exe`.
|
|
191
|
+
*
|
|
192
|
+
* @param {string} arg The argument.
|
|
193
|
+
* @returns {string} The argument as it is written on a cmd command line.
|
|
194
|
+
*/
|
|
195
|
+
export function quoteForCmd(arg) {
|
|
196
|
+
return /^[A-Za-z0-9_\-.:\\/]+$/.test(arg) ? arg : `"${arg.replace(/"/g, '""')}"`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Run a program with this terminal's stdio and wait for it.
|
|
201
|
+
*
|
|
202
|
+
* @param {string} file The program (an `.exe`, a script, or on Windows a `.cmd`).
|
|
203
|
+
* @param {string[]} args Its arguments.
|
|
204
|
+
* @param {Record<string, string | undefined>} env Its environment.
|
|
205
|
+
* @param {string} [platform] Node platform name.
|
|
206
|
+
* @returns {Promise<number>} Its exit code (128 + signal number when a signal ended it; 127 when it could not start).
|
|
207
|
+
* @sideEffect While it runs, SIGINT is ignored here (Ctrl+C belongs to the program) and SIGTERM and SIGHUP are passed on.
|
|
208
|
+
*/
|
|
209
|
+
export function launch(file, args, env, platform = process.platform) {
|
|
210
|
+
return new Promise((done) => {
|
|
211
|
+
const viaCmd = platform === "win32" && /\.(cmd|bat)$/i.test(file);
|
|
212
|
+
const child = viaCmd
|
|
213
|
+
? spawn(env.ComSpec || "cmd.exe", ["/d", "/s", "/c", `"${[file, ...args].map(quoteForCmd).join(" ")}"`], { stdio: "inherit", env, windowsVerbatimArguments: true })
|
|
214
|
+
: spawn(file, args, { stdio: "inherit", env });
|
|
215
|
+
const forward = (signal) => () => child.kill(signal);
|
|
216
|
+
const handlers = [["SIGINT", () => {}], ["SIGTERM", forward("SIGTERM")], ["SIGHUP", forward("SIGHUP")]];
|
|
217
|
+
for (const [signal, handler] of handlers) process.on(signal, handler);
|
|
218
|
+
const finish = (code) => {
|
|
219
|
+
for (const [signal, handler] of handlers) process.off(signal, handler);
|
|
220
|
+
done(code);
|
|
221
|
+
};
|
|
222
|
+
child.on("error", (error) => {
|
|
223
|
+
console.error(`tokenhub: could not start ${file}: ${error.message}`);
|
|
224
|
+
finish(127);
|
|
225
|
+
});
|
|
226
|
+
child.on("exit", (code, signal) => finish(code ?? 128 + (osConstants.signals[signal] ?? 1)));
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** What the shim says when something is missing. */
|
|
231
|
+
const MESSAGES = {
|
|
232
|
+
en: {
|
|
233
|
+
noClaude: "tokenhub: Claude Code was not found. Install it, or run `tokenhub disconnect` to remove this shim.",
|
|
234
|
+
cmdOnly: "tokenhub: TokenHub Remote needs the native claude.exe, and this Claude Code is a .cmd script. Running it without Remote.",
|
|
235
|
+
},
|
|
236
|
+
vi: {
|
|
237
|
+
noClaude: "tokenhub: không tìm thấy Claude Code. Hãy cài nó, hoặc chạy `tokenhub disconnect` để gỡ shim này.",
|
|
238
|
+
cmdOnly: "tokenhub: TokenHub Remote cần claude.exe bản gốc, còn Claude Code này là script .cmd. Đang chạy không có Remote.",
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* What `claude` does: pick the route, then run it.
|
|
244
|
+
*
|
|
245
|
+
* @param {object} options
|
|
246
|
+
* @param {string[]} options.args The user's arguments.
|
|
247
|
+
* @param {string} options.shimDir The folder the wrapper lives in.
|
|
248
|
+
* @param {Record<string, string | undefined>} [options.env] Environment.
|
|
249
|
+
* @param {string} [options.platform] Node platform name.
|
|
250
|
+
* @param {boolean} [options.stdinTTY] Whether stdin is a terminal.
|
|
251
|
+
* @param {boolean} [options.stdoutTTY] Whether stdout is a terminal.
|
|
252
|
+
* @param {string} [options.home] Home folder for the places the installers use.
|
|
253
|
+
* @param {typeof launch} [options.start] Starts a program (tests replace it).
|
|
254
|
+
* @returns {Promise<number>} The exit code to exit with.
|
|
255
|
+
*/
|
|
256
|
+
export async function runShim({ args, shimDir, env = process.env, platform = process.platform, home = homedir(), stdinTTY = Boolean(process.stdin.isTTY), stdoutTTY = Boolean(process.stdout.isTTY), start = launch }) {
|
|
257
|
+
const text = MESSAGES[detectLang(env)];
|
|
258
|
+
const shimDirs = [shimDir];
|
|
259
|
+
const real = findRealClaude({ pathValue: env.PATH ?? env.Path ?? "", shimDirs, env, platform, home });
|
|
260
|
+
if (!real) {
|
|
261
|
+
console.error(text.noClaude);
|
|
262
|
+
return 127;
|
|
263
|
+
}
|
|
264
|
+
const { route } = decide(args, { stdinTTY, stdoutTTY });
|
|
265
|
+
const tfc = route === "hosted" ? findTfc(shimDir, platform) : undefined;
|
|
266
|
+
if (!tfc) return start(real, args, env, platform);
|
|
267
|
+
if (platform === "win32" && !/\.exe$/i.test(real)) {
|
|
268
|
+
console.error(text.cmdOnly);
|
|
269
|
+
return start(real, args, env, platform);
|
|
270
|
+
}
|
|
271
|
+
// `--` so tfc hands every argument to claude, even one it would take for its own (`ls`, `attach`).
|
|
272
|
+
return start(tfc, ["--", ...args], hostedEnv(env, { shimDirs, real, configDir: remoteConfigDir(shimDir, platform), platform }), platform);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Run when started as the program (not when the CLI or a test imports it).
|
|
276
|
+
if (process.argv[1]) {
|
|
277
|
+
let isMain = false;
|
|
278
|
+
try {
|
|
279
|
+
isMain = realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url));
|
|
280
|
+
} catch {
|
|
281
|
+
isMain = false;
|
|
282
|
+
}
|
|
283
|
+
if (isMain) process.exitCode = await runShim({ args: process.argv.slice(2), shimDir: hostDirname(fileURLToPath(import.meta.url)) });
|
|
284
|
+
}
|
package/lib/desktop-connect.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { hostname } from "node:os";
|
|
2
|
-
import { appDataDir, fetchModels, isInstalled, writeDesktopConfig } from "./desktop.js";
|
|
2
|
+
import { appDataCacheDir, appDataDir, fetchModels, isInstalled, writeDesktopConfig } from "./desktop.js";
|
|
3
3
|
import { openBrowser, pairDevice, resolvePoolUrl } from "./pair.js";
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -37,7 +37,7 @@ export async function runDesktop({
|
|
|
37
37
|
return 1;
|
|
38
38
|
}
|
|
39
39
|
// Judged before the write, which creates the folder.
|
|
40
|
-
const installed = isInstalled(dir);
|
|
40
|
+
const installed = isInstalled(dir, platform === "win32" ? appDataCacheDir(env, home) : null);
|
|
41
41
|
let pool;
|
|
42
42
|
try {
|
|
43
43
|
pool = resolvePoolUrl(poolUrl);
|
package/lib/desktop.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export const APP_FOLDER: string;
|
|
2
2
|
export const CONFIG_NAME: string;
|
|
3
3
|
export function appDataDir(platform?: string, env?: Record<string, string | undefined>, home?: string): string | null;
|
|
4
|
+
export function appDataCacheDir(env?: Record<string, string | undefined>, home?: string): string | null;
|
|
4
5
|
export function configLibraryDir(base: string): string;
|
|
5
6
|
export function configId(dir: string): string;
|
|
6
7
|
export function modelEntry(row: { id: string; display_name?: string; anthropic_family_tier?: string; max_input_tokens?: number }): Record<string, unknown>;
|
|
@@ -20,7 +21,7 @@ export function writeDesktopConfig(options: {
|
|
|
20
21
|
models: Array<{ id: string; display_name?: string; anthropic_family_tier?: string; max_input_tokens?: number }>;
|
|
21
22
|
effort?: string;
|
|
22
23
|
}): { configPath: string; metaPath: string; desktopConfigPath: string; models: number };
|
|
23
|
-
export function isInstalled(dir: string | null): boolean;
|
|
24
|
+
export function isInstalled(dir: string | null, cacheDir?: string | null): boolean;
|
|
24
25
|
export function fetchModels(
|
|
25
26
|
baseUrl: string,
|
|
26
27
|
key: string,
|
package/lib/desktop.js
CHANGED
|
@@ -160,12 +160,25 @@ export function writeDesktopConfig({ dir, baseUrl, key, models, effort }) {
|
|
|
160
160
|
}
|
|
161
161
|
|
|
162
162
|
/**
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
* @
|
|
163
|
+
* Where Claude Desktop keeps its caches, storage and logs on Windows, beside the folder `appDataDir` returns: Desktop
|
|
164
|
+
* splits its app data across Roaming (config) and Local (everything else), and either can exist first.
|
|
165
|
+
* @param {Record<string, string | undefined>} [env] Environment to read LOCALAPPDATA from.
|
|
166
|
+
* @param {string} [home] Home directory used when the variable is unset.
|
|
167
|
+
* @returns {string | null} Absolute folder, or null on a platform Desktop does not split.
|
|
168
|
+
*/
|
|
169
|
+
export function appDataCacheDir(env = process.env, home = homedir()) {
|
|
170
|
+
return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), APP_FOLDER);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Whether Desktop is installed here, judged by its app-data folders: the one it reads config from, or the one it keeps
|
|
175
|
+
* caches in. Desktop creates one before the other, so either proves an install (#790).
|
|
176
|
+
* @param {string | null} dir Config folder from `appDataDir`.
|
|
177
|
+
* @param {string | null} [cacheDir] Cache folder from `appDataCacheDir`.
|
|
178
|
+
* @returns {boolean} True when either exists.
|
|
166
179
|
*/
|
|
167
|
-
export function isInstalled(dir) {
|
|
168
|
-
return Boolean(
|
|
180
|
+
export function isInstalled(dir, cacheDir = null) {
|
|
181
|
+
return [dir, cacheDir].some((folder) => Boolean(folder) && existsSync(folder));
|
|
169
182
|
}
|
|
170
183
|
|
|
171
184
|
/**
|
package/lib/pair.d.ts
CHANGED
|
@@ -43,6 +43,12 @@ export function runConnect(options: {
|
|
|
43
43
|
modelPicker?: boolean;
|
|
44
44
|
/** Where the picker is installed; `modelPickerDir()` by default. */
|
|
45
45
|
modelPickerDir?: string;
|
|
46
|
+
/** `true` installs TokenHub Remote (--remote), `false` skips it (--no-remote); left out, the question is asked (default no). */
|
|
47
|
+
remote?: boolean;
|
|
48
|
+
/** The Remote installer; tests replace it. */
|
|
49
|
+
installRemoteFn?: typeof import("./remote-install.js").installRemote;
|
|
50
|
+
/** Home directory the Remote installer uses. */
|
|
51
|
+
home?: string;
|
|
46
52
|
/** Yes/no prompt; answers false without a terminal. */
|
|
47
53
|
ask?: (question: string, defaultYes?: boolean) => Promise<boolean>;
|
|
48
54
|
}): Promise<number>;
|
package/lib/pair.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { hostname } from "node:os";
|
|
2
|
+
import { homedir, 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
6
|
import { askYesNo, enableFullscreen, installModelPicker, layoutUnset, modelPickerDir } from "./model-picker.js";
|
|
7
|
+
import { installRemote } from "./remote-install.js";
|
|
8
|
+
import { detectLang, text } from "./remote-text.js";
|
|
7
9
|
import { connectSettings, normalizeUrl, overridingEnvVars, readSettings } from "./settings.js";
|
|
8
10
|
|
|
9
11
|
const MAX_WAIT_MS = 15 * 60 * 1000;
|
|
@@ -294,6 +296,9 @@ export async function pairDevice({ pool, admin = false, deviceName, log, open, s
|
|
|
294
296
|
* @param {string} [options.adminFile] Path from `adminConfigPath`; required with `admin`.
|
|
295
297
|
* @param {boolean} [options.modelPicker] Offer to install the Claude Code model picker after pairing (default true).
|
|
296
298
|
* @param {string} [options.modelPickerDir] Where the picker is installed (`modelPickerDir()` by default).
|
|
299
|
+
* @param {boolean} [options.remote] `true` (--remote) installs TokenHub Remote, `false` (--no-remote) skips it; left out, it is asked (default no).
|
|
300
|
+
* @param {typeof installRemote} [options.installRemoteFn] The Remote installer (tests replace it).
|
|
301
|
+
* @param {string} [options.home] Home directory the Remote installer uses.
|
|
297
302
|
* @param {(question: string, defaultYes?: boolean) => Promise<boolean>} [options.ask] Yes/no prompt (tests); false without a terminal.
|
|
298
303
|
* @returns {Promise<number>} Process exit code.
|
|
299
304
|
*/
|
|
@@ -311,6 +316,9 @@ export async function runConnect({
|
|
|
311
316
|
adminFile,
|
|
312
317
|
modelPicker = true,
|
|
313
318
|
modelPickerDir: pickerDir = modelPickerDir(),
|
|
319
|
+
remote,
|
|
320
|
+
installRemoteFn = installRemote,
|
|
321
|
+
home = homedir(),
|
|
314
322
|
ask = (question, defaultYes = true) => askYesNo(question, { defaultYes }),
|
|
315
323
|
}) {
|
|
316
324
|
let pool;
|
|
@@ -357,6 +365,11 @@ export async function runConnect({
|
|
|
357
365
|
log(`Model picker not installed: ${error.message}`);
|
|
358
366
|
}
|
|
359
367
|
}
|
|
368
|
+
const lang = detectLang(env);
|
|
369
|
+
if (remote ?? (await ask(text(lang).askRemote, false))) {
|
|
370
|
+
const installed = await installRemoteFn({ pool, baseUrl, settingsFile, lang, log, open, signal, ask, deviceName, intervalOverrideMs, env, home });
|
|
371
|
+
if (!installed.ok) return installed.code;
|
|
372
|
+
}
|
|
360
373
|
return 0;
|
|
361
374
|
} catch (error) {
|
|
362
375
|
if (signal?.aborted) {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Runner } from "./run.js";
|
|
2
|
+
export const REMOTE_DOWNLOADS: string;
|
|
3
|
+
export const HOOK_FILE: string;
|
|
4
|
+
export interface ManifestFile {
|
|
5
|
+
name: string;
|
|
6
|
+
sha256: string;
|
|
7
|
+
size?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface Manifest {
|
|
10
|
+
version: string;
|
|
11
|
+
platforms: Record<string, ManifestFile[]>;
|
|
12
|
+
}
|
|
13
|
+
export function sha256Hex(bytes: Buffer | Uint8Array | string): string;
|
|
14
|
+
export function parseManifest(json: unknown): Manifest;
|
|
15
|
+
export function pickPlatform(manifest: Manifest, platform: string, arch: string): { key: string; files: ManifestFile[] };
|
|
16
|
+
export function compareVersions(a: string, b: string): number;
|
|
17
|
+
export function readCurrent(root: string): { version: string; dir: string } | undefined;
|
|
18
|
+
export function fetchManifest(pool: string, options?: { fetchImpl?: typeof fetch; signal?: AbortSignal }): Promise<Manifest>;
|
|
19
|
+
export function downloadRemote(options: {
|
|
20
|
+
pool: string;
|
|
21
|
+
root: string;
|
|
22
|
+
platform?: string;
|
|
23
|
+
arch?: string;
|
|
24
|
+
log?: (line: string) => void;
|
|
25
|
+
fetchImpl?: typeof fetch;
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
run?: Runner;
|
|
28
|
+
manifest?: Manifest;
|
|
29
|
+
}): Promise<{ version: string; dir: string; action: "installed" | "updated" | "repaired" | "kept"; previous?: string; platformKey: string }>;
|