@k-electron/k-bench 0.0.0 → 0.1.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/LICENSE +21 -0
- package/README.md +69 -2
- package/dist/js/scripts/command-lib.js +56 -0
- package/dist/js/scripts/install-lib.js +187 -0
- package/dist/js/scripts/install.js +233 -0
- package/dist/js/scripts/k-bench.js +53 -0
- package/dist/js/scripts/status.js +178 -0
- package/dist/js/scripts/tailscale-serve.js +135 -0
- package/dist/js/scripts/uninstall.js +150 -0
- package/dist/js/src/server/access-guard.js +63 -0
- package/dist/js/src/server/app.js +122 -0
- package/dist/js/src/server/attachments.js +273 -0
- package/dist/js/src/server/config.js +42 -0
- package/dist/js/src/server/directories.js +34 -0
- package/dist/js/src/server/events.js +31 -0
- package/dist/js/src/server/main.js +42 -0
- package/dist/js/src/server/naming.js +9 -0
- package/dist/js/src/server/reconciler.js +41 -0
- package/dist/js/src/server/server.js +86 -0
- package/dist/js/src/server/service.js +217 -0
- package/dist/js/src/server/state-feed.js +115 -0
- package/dist/js/src/server/static.js +46 -0
- package/dist/js/src/server/store.js +127 -0
- package/dist/js/src/server/terminal.js +64 -0
- package/dist/js/src/server/tmux.js +294 -0
- package/dist/js/src/shared/terminal-protocol.js +67 -0
- package/dist/web/assets/index-BeaoLAfY.css +2 -0
- package/dist/web/assets/index-rujAJZxv.js +68 -0
- package/dist/web/index.html +13 -0
- package/package.json +91 -3
- package/scripts/fix-node-pty.mjs +21 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Karim Fatehi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,70 @@
|
|
|
1
|
-
#
|
|
1
|
+
# k-bench
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Persistent terminal Sessions on your Mac, organised into Workspaces, reachable from any browser on your tailnet.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
k-bench is macOS-only, and Tailscale is the only way in. It runs on your Mac as a background service and shows your terminals in a web page that only your own tailnet login can open.
|
|
8
|
+
|
|
9
|
+
## Why
|
|
10
|
+
|
|
11
|
+
You can reach Claude Code on your Mac from another device in a few ways, and each trades something away.
|
|
12
|
+
|
|
13
|
+
- **Claude Code's built-in remote mode.** [Remote Control](https://code.claude.com/docs/en/remote-control) shows a local Claude Code conversation in the Claude app or at claude.ai/code. It needs a claude.ai subscription (API keys are not supported), and some commands that only run in the terminal interface, such as `/plugin` and `/resume`, work only from the local terminal. You use Claude Code through a different interface from the one on your Mac.
|
|
14
|
+
- **Tools that wrap Claude Code in their own UI.** Tools in this category give you a purpose-built interface in place of the terminal. That can be easier to use on a phone, but the interface only shows what the tool chose to build: parts of Claude Code, such as the full TUI, your slash commands and hooks, can be missing or behave differently.
|
|
15
|
+
|
|
16
|
+
k-bench takes a third route. It gives you real Claude Code in a real terminal: persistent, and reachable from any browser on your tailnet. What runs in a Session is your own login shell with your own PATH and config, so Claude Code, its slash commands, its hooks and everything you have set up behave as they do in your local terminal.
|
|
17
|
+
|
|
18
|
+
It is not only for Claude Code. A Session is a shell, so it works for any terminal workload: a dev server, a test watcher, a deploy, an editor.
|
|
19
|
+
|
|
20
|
+
## What you get
|
|
21
|
+
|
|
22
|
+
- **Sessions that keep running** when you close the tab, lock your phone or lose your connection. Come back from any device and pick up where you left off.
|
|
23
|
+
- **Workspaces per project.** A Workspace points at a project folder on your Mac, and its Sessions start there.
|
|
24
|
+
- **Two Panes** side by side, for example Claude Code next to a dev server.
|
|
25
|
+
- **Bells.** When a Session's shell rings the terminal bell, its row in the sidebar shows a Bell until you look at it.
|
|
26
|
+
- **A phone layout** with a drawer for your Workspaces and a row of extra keys (Esc, Tab, Shift-Tab, Ctrl and the arrows) for the keys a phone keyboard lacks.
|
|
27
|
+
- **Access only for your tailnet login.** k-bench listens on localhost only and is published with `tailscale serve`. It admits only requests that carry your own tailnet login.
|
|
28
|
+
|
|
29
|
+

|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
**You need:**
|
|
34
|
+
|
|
35
|
+
- A Mac (k-bench is macOS-only).
|
|
36
|
+
- [Node](https://nodejs.org/) 26 or later.
|
|
37
|
+
- tmux (`brew install tmux`).
|
|
38
|
+
- [Tailscale](https://tailscale.com/download), signed in, with HTTPS certificates turned on for your tailnet. [Setup](docs/guide/setup.md#1-set-up-tailscale) has the steps.
|
|
39
|
+
|
|
40
|
+
**Then:**
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
npm i -g @k-electron/k-bench
|
|
44
|
+
k-bench install
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`k-bench install` finds your tailnet login by itself, starts k-bench as a background service that starts when you log in, publishes it with `tailscale serve`, and prints the URL it is now reachable at. Open that URL from any device signed in to your tailnet with the same login. To see what the install would do first, run `k-bench install --dry-run`: it changes nothing.
|
|
48
|
+
|
|
49
|
+
Something not working? Run `k-bench status`: it checks each part and says how to fix what fails.
|
|
50
|
+
|
|
51
|
+
## Guide
|
|
52
|
+
|
|
53
|
+
- [The guide](docs/guide/README.md), with
|
|
54
|
+
- [Setup](docs/guide/setup.md): Tailscale, installing, updating, uninstalling.
|
|
55
|
+
- [Using k-bench](docs/guide/using-k-bench.md): Workspaces, Sessions, Panes, Bells, scrolling and copying, the phone layout.
|
|
56
|
+
- [Using k-bench with Claude Code](docs/guide/claude-code.md): making Claude Code ring the Bell, and working with several conversations.
|
|
57
|
+
- [Troubleshooting](docs/guide/troubleshooting.md): start from `k-bench status`.
|
|
58
|
+
- [CHANGELOG](CHANGELOG.md): what changed in each version.
|
|
59
|
+
|
|
60
|
+
## Security
|
|
61
|
+
|
|
62
|
+
k-bench is a remote shell: anyone who can open it can run commands on your Mac as you. It is built so that only you can. It listens on `127.0.0.1` only, `tailscale serve` is the only way in, and the server refuses any request that does not carry your own tailnet login, or that comes from a web page on another site. There is no password, no LAN mode and no other tunnel. [Access](docs/internals/access.md) has the details, and [SECURITY.md](SECURITY.md) says how to report a vulnerability privately.
|
|
63
|
+
|
|
64
|
+
## Contributing
|
|
65
|
+
|
|
66
|
+
Issues and pull requests are welcome. [CONTRIBUTING](CONTRIBUTING.md) covers setup, the checks and the pull request flow. [Internals](docs/internals/README.md) explains how k-bench works inside, [GLOSSARY.md](GLOSSARY.md) holds the vocabulary and [docs/adr/](docs/adr/) the design decisions.
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// What the `k-bench` commands (install, uninstall, status) share: where the Installed
|
|
2
|
+
// instance keeps its files, how they talk to launchd, and how they report what they do.
|
|
3
|
+
// Unlike `install-lib.ts`, which is pure, this reads HOME and PATH and runs programs.
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { delimiter, join } from "node:path";
|
|
7
|
+
/** The LaunchAgent's label, as `k-bench install` loads it. */
|
|
8
|
+
export const LAUNCH_AGENT_LABEL = "com.k-bench.server";
|
|
9
|
+
/** The file in the app folder that records what was installed (read by the server). */
|
|
10
|
+
export const BUILD_INFO_FILE = "build-info.json";
|
|
11
|
+
const LOG_FILE_UNDER_HOME = join("Library", "Logs", "k-bench", "k-bench.log");
|
|
12
|
+
/** The log file's place for a message to the owner: `~` stands for their home folder. */
|
|
13
|
+
export const LOG_HINT = `~/${LOG_FILE_UNDER_HOME}`;
|
|
14
|
+
/** The Installed instance's log file; the folder holding it is the logs `--purge` deletes. */
|
|
15
|
+
export function logPath() {
|
|
16
|
+
return join(homedir(), LOG_FILE_UNDER_HOME);
|
|
17
|
+
}
|
|
18
|
+
export function launchAgentPlistPath() {
|
|
19
|
+
return join(homedir(), "Library", "LaunchAgents", `${LAUNCH_AGENT_LABEL}.plist`);
|
|
20
|
+
}
|
|
21
|
+
/** The app folder inside the Installed instance's data folder. */
|
|
22
|
+
export function appDirIn(dataDir) {
|
|
23
|
+
return join(dataDir, "app");
|
|
24
|
+
}
|
|
25
|
+
/** The launchd domain of the logged-in user's GUI session. */
|
|
26
|
+
export function launchdDomain() {
|
|
27
|
+
return `gui/${process.getuid?.() ?? 501}`;
|
|
28
|
+
}
|
|
29
|
+
/** The directories on PATH. */
|
|
30
|
+
export function pathDirs(env = process.env) {
|
|
31
|
+
return (env.PATH ?? "").split(delimiter).filter(Boolean);
|
|
32
|
+
}
|
|
33
|
+
/** Whether a program ran and exited 0; its output is discarded. */
|
|
34
|
+
export function succeeds(command, args) {
|
|
35
|
+
return spawnSync(command, args, { stdio: "ignore" }).status === 0;
|
|
36
|
+
}
|
|
37
|
+
/** Whether launchd has the LaunchAgent loaded. */
|
|
38
|
+
export function launchAgentLoaded() {
|
|
39
|
+
return succeeds("launchctl", ["print", `${launchdDomain()}/${LAUNCH_AGENT_LABEL}`]);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* How a command reports. `step` announces what it is about to do (prefixed `would:` in a
|
|
43
|
+
* dry run) and does it unless this is a dry run.
|
|
44
|
+
*/
|
|
45
|
+
export function reporter(dryRun) {
|
|
46
|
+
return {
|
|
47
|
+
say(line) {
|
|
48
|
+
console.log(line);
|
|
49
|
+
},
|
|
50
|
+
async step(description, action) {
|
|
51
|
+
console.log(`${dryRun ? "would: " : ""}${description}`);
|
|
52
|
+
if (!dryRun)
|
|
53
|
+
await action();
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// The pure parts of the install: nothing in here talks to launchd or Tailscale. Every path
|
|
2
|
+
// and command is an argument, so `test/install.test.ts` can check them in temporary folders.
|
|
3
|
+
import { accessSync, constants, cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
/** Where the Tailscale macOS app keeps its command-line tool. */
|
|
6
|
+
export const TAILSCALE_APP_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
|
|
7
|
+
function isExecutableFile(path) {
|
|
8
|
+
try {
|
|
9
|
+
if (!statSync(path).isFile())
|
|
10
|
+
return false;
|
|
11
|
+
accessSync(path, constants.X_OK);
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** The first executable file called `name` in `dirs`, like `which`. */
|
|
19
|
+
export function findExecutable(name, dirs) {
|
|
20
|
+
for (const dir of dirs) {
|
|
21
|
+
const candidate = join(dir, name);
|
|
22
|
+
if (isExecutableFile(candidate))
|
|
23
|
+
return candidate;
|
|
24
|
+
}
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
/** `tailscale` from PATH, else the CLI inside Tailscale.app, else undefined. */
|
|
28
|
+
export function resolveTailscaleCli(options) {
|
|
29
|
+
const onPath = findExecutable("tailscale", options.pathDirs);
|
|
30
|
+
if (onPath)
|
|
31
|
+
return onPath;
|
|
32
|
+
const app = options.appBundleCli ?? TAILSCALE_APP_CLI;
|
|
33
|
+
return isExecutableFile(app) ? app : undefined;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* What to tell the owner when the running Node is older than the package's `engines.node`
|
|
37
|
+
* (a `>=<major>` range), which npm only warns about. Undefined when it is new enough.
|
|
38
|
+
*/
|
|
39
|
+
export function nodeVersionProblem(running, engines) {
|
|
40
|
+
const required = Number(/\d+/.exec(engines ?? "")?.[0]);
|
|
41
|
+
if (!Number.isInteger(required) || Number(running.split(".")[0]) >= required) {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
return `Node ${running} is too old: k-bench needs Node ${required} or later. Install a current Node (for example \`brew install node\`), then run \`k-bench install\` again.`;
|
|
45
|
+
}
|
|
46
|
+
/** Reads the output of `tailscale status --json`. */
|
|
47
|
+
export function parseTailscaleStatus(json) {
|
|
48
|
+
const status = JSON.parse(json);
|
|
49
|
+
const userId = status.Self?.UserID;
|
|
50
|
+
const login = userId === undefined ? undefined : status.User?.[String(userId)]?.LoginName;
|
|
51
|
+
if (!login) {
|
|
52
|
+
throw new Error("Could not read your tailnet login from `tailscale status --json`. Is Tailscale running and logged in?");
|
|
53
|
+
}
|
|
54
|
+
return { login, dnsName: (status.Self?.DNSName ?? "").replace(/\.$/, "") };
|
|
55
|
+
}
|
|
56
|
+
function xml(text) {
|
|
57
|
+
return text
|
|
58
|
+
.replaceAll("&", "&")
|
|
59
|
+
.replaceAll("<", "<")
|
|
60
|
+
.replaceAll(">", ">")
|
|
61
|
+
.replaceAll('"', """)
|
|
62
|
+
.replaceAll("'", "'");
|
|
63
|
+
}
|
|
64
|
+
/** The compiled server, relative to the app folder (and to the package root). */
|
|
65
|
+
export const SERVER_ENTRY = "dist/js/src/server/main.js";
|
|
66
|
+
/**
|
|
67
|
+
* The LaunchAgent for the Installed instance.
|
|
68
|
+
* - `RunAtLoad` and `KeepAlive`: starts at login and after a crash.
|
|
69
|
+
* - `AbandonProcessGroup`: when launchd stops the server it must not kill the rest of the
|
|
70
|
+
* job's process group, which is where tmux (and so every Session) may live (ADR-0001).
|
|
71
|
+
*/
|
|
72
|
+
export function buildLaunchAgentPlist(options) {
|
|
73
|
+
const env = Object.entries(options.env)
|
|
74
|
+
.map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`)
|
|
75
|
+
.join("\n");
|
|
76
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
77
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
78
|
+
<plist version="1.0">
|
|
79
|
+
<dict>
|
|
80
|
+
<key>Label</key>
|
|
81
|
+
<string>${xml(options.label)}</string>
|
|
82
|
+
<key>ProgramArguments</key>
|
|
83
|
+
<array>
|
|
84
|
+
<string>${xml(options.nodePath)}</string>
|
|
85
|
+
<string>${xml(join(options.appDir, SERVER_ENTRY))}</string>
|
|
86
|
+
</array>
|
|
87
|
+
<key>WorkingDirectory</key>
|
|
88
|
+
<string>${xml(options.appDir)}</string>
|
|
89
|
+
<key>EnvironmentVariables</key>
|
|
90
|
+
<dict>
|
|
91
|
+
${env}
|
|
92
|
+
</dict>
|
|
93
|
+
<key>RunAtLoad</key>
|
|
94
|
+
<true/>
|
|
95
|
+
<key>KeepAlive</key>
|
|
96
|
+
<true/>
|
|
97
|
+
<key>AbandonProcessGroup</key>
|
|
98
|
+
<true/>
|
|
99
|
+
<key>StandardOutPath</key>
|
|
100
|
+
<string>${xml(options.logPath)}</string>
|
|
101
|
+
<key>StandardErrorPath</key>
|
|
102
|
+
<string>${xml(options.logPath)}</string>
|
|
103
|
+
</dict>
|
|
104
|
+
</plist>
|
|
105
|
+
`;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* What the installed app copies from the package: the compiled server (with the modules it
|
|
109
|
+
* shares with the browser), the built front end, and the script that restores node-pty's
|
|
110
|
+
* spawn-helper execute bit. Its package.json is generated: see `appManifest`.
|
|
111
|
+
*/
|
|
112
|
+
const APP_FILES = ["dist/js/src", "dist/web", "scripts/fix-node-pty.mjs"];
|
|
113
|
+
/** The nearest folder at or above `start` that holds a package.json. */
|
|
114
|
+
export function findPackageRoot(start) {
|
|
115
|
+
for (let dir = start;; dir = dirname(dir)) {
|
|
116
|
+
if (existsSync(join(dir, "package.json")))
|
|
117
|
+
return dir;
|
|
118
|
+
if (dirname(dir) === dir)
|
|
119
|
+
throw new Error(`no package.json at or above ${start}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The installed app's package.json: only what its dependencies and `engines` need, so that
|
|
124
|
+
* installing them in the app folder runs none of the package's own scripts.
|
|
125
|
+
*/
|
|
126
|
+
export function appManifest(pkg) {
|
|
127
|
+
return {
|
|
128
|
+
name: "k-bench-app",
|
|
129
|
+
private: true,
|
|
130
|
+
version: pkg.version,
|
|
131
|
+
type: "module",
|
|
132
|
+
engines: pkg.engines,
|
|
133
|
+
dependencies: pkg.dependencies,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Copies the app files from the package (the npm package, or a built checkout) into a fresh
|
|
138
|
+
* `stagingDir` (replacing any leftovers), with `manifest` as its package.json.
|
|
139
|
+
*/
|
|
140
|
+
export function stageApp(options) {
|
|
141
|
+
for (const built of ["dist/web/index.html", SERVER_ENTRY]) {
|
|
142
|
+
if (!existsSync(join(options.packageDir, built))) {
|
|
143
|
+
throw new Error(`${built} has not been built: run \`pnpm build\` first.`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
rmSync(options.stagingDir, { recursive: true, force: true });
|
|
147
|
+
for (const file of APP_FILES) {
|
|
148
|
+
const target = join(options.stagingDir, file);
|
|
149
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
150
|
+
cpSync(join(options.packageDir, file), target, { recursive: true });
|
|
151
|
+
}
|
|
152
|
+
writeFileSync(join(options.stagingDir, "package.json"), `${JSON.stringify(options.manifest, null, 2)}\n`);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Makes the staged copy the app. Two renames, so a running server never sees a half-written
|
|
156
|
+
* app folder; the previous app is deleted afterwards. Only the two app folders are touched.
|
|
157
|
+
*/
|
|
158
|
+
export function swapInStagedApp(options) {
|
|
159
|
+
const previous = `${options.appDir}.previous`;
|
|
160
|
+
rmSync(previous, { recursive: true, force: true });
|
|
161
|
+
if (existsSync(options.appDir))
|
|
162
|
+
renameSync(options.appDir, previous);
|
|
163
|
+
renameSync(options.stagingDir, options.appDir);
|
|
164
|
+
rmSync(previous, { recursive: true, force: true });
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Reasons the native node-pty build under `appDir/node_modules` would not work. pnpm
|
|
168
|
+
* installs its `spawn-helper` without the execute bit, which makes every pty.spawn fail.
|
|
169
|
+
*/
|
|
170
|
+
export function nodePtyProblems(appDir) {
|
|
171
|
+
const root = join(appDir, "node_modules/node-pty");
|
|
172
|
+
if (!existsSync(root))
|
|
173
|
+
return [`node-pty is not installed in ${appDir}/node_modules`];
|
|
174
|
+
const problems = [];
|
|
175
|
+
const prebuilds = join(root, "prebuilds");
|
|
176
|
+
const platforms = existsSync(prebuilds) ? readdirSync(prebuilds) : [];
|
|
177
|
+
if (platforms.length === 0 && !existsSync(join(root, "build/Release/pty.node"))) {
|
|
178
|
+
problems.push("node-pty has no native build (prebuilds/ or build/Release/pty.node)");
|
|
179
|
+
}
|
|
180
|
+
for (const platform of platforms) {
|
|
181
|
+
const helper = join(prebuilds, platform, "spawn-helper");
|
|
182
|
+
if (existsSync(helper) && !isExecutableFile(helper)) {
|
|
183
|
+
problems.push(`${helper} is not executable`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return problems;
|
|
187
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
// `k-bench install`: installs k-bench as the Installed instance (ADR-0001, ADR-0003), from
|
|
2
|
+
// the npm package or, as `pnpm install-app`, from a checkout. Safe to re-run: it updates the
|
|
3
|
+
// app in place, and running Sessions live in tmux, outside this server's process group, so
|
|
4
|
+
// they carry on. `--dry-run` prints the plan and changes nothing; `--login <login>` skips
|
|
5
|
+
// reading it from Tailscale. It publishes on HTTPS port 443, or `--https-port <n>`, and
|
|
6
|
+
// refuses (before changing anything) when that port already serves something other than
|
|
7
|
+
// k-bench, unless `--force`.
|
|
8
|
+
import { execFileSync } from "node:child_process";
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync, } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { delimiter, dirname, join } from "node:path";
|
|
12
|
+
import { parseArgs } from "node:util";
|
|
13
|
+
import { resolveConfig } from "../src/server/config.js";
|
|
14
|
+
import { appDirIn, BUILD_INFO_FILE, LAUNCH_AGENT_LABEL, launchAgentPlistPath, launchdDomain, logPath, pathDirs as pathDirsOf, reporter, succeeds, } from "./command-lib.js";
|
|
15
|
+
import { appManifest, buildLaunchAgentPlist, findExecutable, findPackageRoot, nodePtyProblems, nodeVersionProblem, parseTailscaleStatus, resolveTailscaleCli, stageApp, swapInStagedApp, } from "./install-lib.js";
|
|
16
|
+
import { DEFAULT_HTTPS_PORT, portUse, readServeConfig, serveOffArgs, serveUrl, } from "./tailscale-serve.js";
|
|
17
|
+
export async function install(argv) {
|
|
18
|
+
const { values: flags } = parseArgs({
|
|
19
|
+
args: argv,
|
|
20
|
+
options: {
|
|
21
|
+
"dry-run": { type: "boolean", default: false },
|
|
22
|
+
login: { type: "string" },
|
|
23
|
+
"https-port": { type: "string", default: String(DEFAULT_HTTPS_PORT) },
|
|
24
|
+
force: { type: "boolean", default: false },
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
const dryRun = flags["dry-run"];
|
|
28
|
+
const httpsPortText = flags["https-port"];
|
|
29
|
+
const httpsPort = Number(httpsPortText);
|
|
30
|
+
function fail(message) {
|
|
31
|
+
console.error(`k-bench install: ${message}`);
|
|
32
|
+
process.exit(1);
|
|
33
|
+
}
|
|
34
|
+
// The npm package, or the checkout: where the files to install come from. Its `engines`
|
|
35
|
+
// are checked before anything else, in a dry run too, because npm only warns about them.
|
|
36
|
+
const packageDir = findPackageRoot(import.meta.dirname);
|
|
37
|
+
const pkg = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
|
|
38
|
+
const nodeProblem = nodeVersionProblem(process.versions.node, pkg.engines?.node);
|
|
39
|
+
if (nodeProblem)
|
|
40
|
+
fail(nodeProblem);
|
|
41
|
+
if (!/^\d+$/.test(httpsPortText) || httpsPort < 1 || httpsPort > 65535) {
|
|
42
|
+
fail(`--https-port needs a port number from 1 to 65535, not "${httpsPortText}".`);
|
|
43
|
+
}
|
|
44
|
+
const { say, step } = reporter(dryRun);
|
|
45
|
+
// Explicit env: the install must never pick up a K_BENCH_* override from the shell.
|
|
46
|
+
const config = resolveConfig({ K_BENCH_INSTANCE: "installed" });
|
|
47
|
+
// A checkout has the TypeScript source (the package ships only compiled JavaScript), and
|
|
48
|
+
// so can be built and asked for its git commit.
|
|
49
|
+
const fromCheckout = existsSync(join(packageDir, "src/server/main.ts"));
|
|
50
|
+
const appDir = appDirIn(config.dataDir);
|
|
51
|
+
const stagingDir = join(config.dataDir, "app.staging");
|
|
52
|
+
const logFile = logPath();
|
|
53
|
+
const plistPath = launchAgentPlistPath();
|
|
54
|
+
const domain = launchdDomain();
|
|
55
|
+
// Prerequisites. These are read-only checks, so they run in a dry run too.
|
|
56
|
+
const pathDirs = pathDirsOf();
|
|
57
|
+
const tmux = findExecutable("tmux", pathDirs);
|
|
58
|
+
if (!tmux)
|
|
59
|
+
fail("tmux not found. Install it with `brew install tmux`.");
|
|
60
|
+
const tailscale = resolveTailscaleCli({ pathDirs });
|
|
61
|
+
if (!tailscale) {
|
|
62
|
+
fail("the Tailscale CLI was not found on PATH or inside /Applications/Tailscale.app.");
|
|
63
|
+
}
|
|
64
|
+
// Read before anything is done: if the port is taken by someone else's setup, the install
|
|
65
|
+
// stops here, having changed nothing.
|
|
66
|
+
let serveConfig;
|
|
67
|
+
try {
|
|
68
|
+
serveConfig = readServeConfig(tailscale);
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
fail(error.message);
|
|
72
|
+
}
|
|
73
|
+
const occupant = portUse(serveConfig, httpsPort, config.port);
|
|
74
|
+
if (occupant.kind === "other" && !flags.force) {
|
|
75
|
+
const what = occupant.entry.targets.map((target) => ` ${target.description}`);
|
|
76
|
+
fail(`HTTPS port ${httpsPort} already serves something other than k-bench:\n${what.join("\n")}\n` +
|
|
77
|
+
"Nothing was changed. Publish k-bench on another port with `--https-port <n>` " +
|
|
78
|
+
`(for example \`--https-port 8443\`), or replace what is on port ${httpsPort} with \`--force\`.`);
|
|
79
|
+
}
|
|
80
|
+
function resolveNodePath() {
|
|
81
|
+
// Prefer the stable name on PATH (e.g. /opt/homebrew/bin/node) over the versioned Cellar
|
|
82
|
+
// path, so a `brew upgrade node` doesn't break the agent, when it is the running Node.
|
|
83
|
+
const onPath = findExecutable("node", pathDirs);
|
|
84
|
+
if (onPath && realpathSync(onPath) === realpathSync(process.execPath))
|
|
85
|
+
return onPath;
|
|
86
|
+
return process.execPath;
|
|
87
|
+
}
|
|
88
|
+
const nodePath = resolveNodePath();
|
|
89
|
+
function agentPath() {
|
|
90
|
+
const dirs = [
|
|
91
|
+
dirname(nodePath),
|
|
92
|
+
dirname(tmux),
|
|
93
|
+
"/opt/homebrew/bin",
|
|
94
|
+
"/opt/homebrew/sbin",
|
|
95
|
+
"/usr/local/bin",
|
|
96
|
+
"/usr/bin",
|
|
97
|
+
"/bin",
|
|
98
|
+
"/usr/sbin",
|
|
99
|
+
"/sbin",
|
|
100
|
+
];
|
|
101
|
+
return [...new Set(dirs)].join(delimiter);
|
|
102
|
+
}
|
|
103
|
+
const launchctl = (args) => succeeds("launchctl", args);
|
|
104
|
+
async function waitFor(what, check) {
|
|
105
|
+
for (let attempt = 0; attempt < 40; attempt++) {
|
|
106
|
+
if (await check())
|
|
107
|
+
return;
|
|
108
|
+
await new Promise((done) => setTimeout(done, 500));
|
|
109
|
+
}
|
|
110
|
+
fail(`timed out waiting for ${what}`);
|
|
111
|
+
}
|
|
112
|
+
say(dryRun ? "k-bench install: dry run, nothing will be changed.\n" : "k-bench install\n");
|
|
113
|
+
say(` version ${pkg.version}${fromCheckout ? " (checkout)" : ""}`);
|
|
114
|
+
say(` node ${nodePath}`);
|
|
115
|
+
say(` tmux ${tmux}`);
|
|
116
|
+
say(` tailscale ${tailscale}`);
|
|
117
|
+
say(` app ${appDir}`);
|
|
118
|
+
say(` data ${config.dataDir} (tmux socket "${config.tmuxSocket}", port ${config.port})`);
|
|
119
|
+
say(` agent ${plistPath}`);
|
|
120
|
+
say(` log ${logFile}\n`);
|
|
121
|
+
// The login the server admits, and the name the URL is built from. A dry run only looks,
|
|
122
|
+
// so it carries on with placeholders when Tailscale can't say.
|
|
123
|
+
let identity = {
|
|
124
|
+
login: flags.login ?? "<your login, read from `tailscale status --json`>",
|
|
125
|
+
dnsName: "<this machine's tailnet name>",
|
|
126
|
+
};
|
|
127
|
+
try {
|
|
128
|
+
const status = parseTailscaleStatus(execFileSync(tailscale, ["status", "--json"], { encoding: "utf8" }));
|
|
129
|
+
identity = { login: flags.login ?? status.login, dnsName: status.dnsName };
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
if (!dryRun)
|
|
133
|
+
fail(error.message);
|
|
134
|
+
}
|
|
135
|
+
say(`allowed login: ${identity.login}\n`);
|
|
136
|
+
if (fromCheckout) {
|
|
137
|
+
await step("build the server and the front end (pnpm build)", () => {
|
|
138
|
+
execFileSync("pnpm", ["build"], { cwd: packageDir, stdio: "inherit" });
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
await step(`copy the server and built assets into ${stagingDir}`, () => stageApp({ packageDir, stagingDir, manifest: appManifest(pkg) }));
|
|
142
|
+
await step(fromCheckout
|
|
143
|
+
? `record the installed version and commit in ${BUILD_INFO_FILE}`
|
|
144
|
+
: `record the installed version in ${BUILD_INFO_FILE}`, () => {
|
|
145
|
+
const git = (args) => execFileSync("git", args, { cwd: packageDir, encoding: "utf8" }).trim();
|
|
146
|
+
const buildInfo = {
|
|
147
|
+
version: pkg.version,
|
|
148
|
+
...(fromCheckout && {
|
|
149
|
+
commit: git(["rev-parse", "HEAD"]),
|
|
150
|
+
// Uncommitted changes were installed too, so the commit alone doesn't describe it.
|
|
151
|
+
dirty: git(["status", "--porcelain"]) !== "",
|
|
152
|
+
}),
|
|
153
|
+
installedAt: new Date().toISOString(),
|
|
154
|
+
};
|
|
155
|
+
writeFileSync(join(stagingDir, BUILD_INFO_FILE), `${JSON.stringify(buildInfo, null, 2)}\n`);
|
|
156
|
+
});
|
|
157
|
+
await step("install production dependencies there (npm install --omit=dev)", () => {
|
|
158
|
+
const npm = findExecutable("npm", pathDirs);
|
|
159
|
+
if (!npm)
|
|
160
|
+
fail("npm not found on PATH. It comes with Node.");
|
|
161
|
+
// Not inside pnpm's or npm's own run: their npm_* variables would change what npm does.
|
|
162
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("npm_")));
|
|
163
|
+
execFileSync(npm, ["install", "--omit=dev", "--no-audit", "--no-fund"], {
|
|
164
|
+
cwd: stagingDir,
|
|
165
|
+
stdio: "inherit",
|
|
166
|
+
env,
|
|
167
|
+
});
|
|
168
|
+
execFileSync(process.execPath, ["scripts/fix-node-pty.mjs"], {
|
|
169
|
+
cwd: stagingDir,
|
|
170
|
+
stdio: "inherit",
|
|
171
|
+
});
|
|
172
|
+
const problems = nodePtyProblems(stagingDir);
|
|
173
|
+
if (problems.length > 0)
|
|
174
|
+
fail(`node-pty is not usable:\n ${problems.join("\n ")}`);
|
|
175
|
+
});
|
|
176
|
+
// The old server stops before its folder is replaced: otherwise it would keep running from
|
|
177
|
+
// a deleted directory, and KeepAlive could restart it against a half-swapped tree. Stopping
|
|
178
|
+
// the agent leaves tmux, and so every Session, running (AbandonProcessGroup, ADR-0001).
|
|
179
|
+
await step(`stop the running LaunchAgent (launchctl bootout, ${domain}), if loaded`, async () => {
|
|
180
|
+
if (launchctl(["print", `${domain}/${LAUNCH_AGENT_LABEL}`])) {
|
|
181
|
+
launchctl(["bootout", `${domain}/${LAUNCH_AGENT_LABEL}`]);
|
|
182
|
+
await waitFor("launchd to unload the old agent", () => !launchctl(["print", `${domain}/${LAUNCH_AGENT_LABEL}`]));
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
await step(`swap the staged copy in as ${appDir}`, () => swapInStagedApp({ appDir, stagingDir }));
|
|
186
|
+
await step(`write the LaunchAgent ${plistPath}`, () => {
|
|
187
|
+
mkdirSync(dirname(plistPath), { recursive: true });
|
|
188
|
+
mkdirSync(dirname(logFile), { recursive: true });
|
|
189
|
+
writeFileSync(plistPath, buildLaunchAgentPlist({
|
|
190
|
+
label: LAUNCH_AGENT_LABEL,
|
|
191
|
+
nodePath,
|
|
192
|
+
appDir,
|
|
193
|
+
logPath: logFile,
|
|
194
|
+
env: {
|
|
195
|
+
K_BENCH_INSTANCE: "installed",
|
|
196
|
+
K_BENCH_ALLOWED_LOGIN: identity.login,
|
|
197
|
+
PATH: agentPath(),
|
|
198
|
+
HOME: homedir(),
|
|
199
|
+
},
|
|
200
|
+
}));
|
|
201
|
+
});
|
|
202
|
+
await step(`load the LaunchAgent (launchctl bootstrap, ${domain}) and wait for it to answer`, async () => {
|
|
203
|
+
execFileSync("launchctl", ["bootstrap", domain, plistPath], { stdio: "inherit" });
|
|
204
|
+
// Up and guarded: without a Tailscale-User-Login header the server answers 403.
|
|
205
|
+
await waitFor("k-bench to answer on 127.0.0.1", async () => {
|
|
206
|
+
try {
|
|
207
|
+
return ((await fetch(`http://127.0.0.1:${config.port}/api/state`)).status === 403);
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
if (occupant.kind === "other") {
|
|
215
|
+
const offArgs = serveOffArgs(occupant.entry);
|
|
216
|
+
await step(`remove what is on port ${httpsPort} (--force): ${tailscale} ${offArgs.join(" ")}`, () => {
|
|
217
|
+
execFileSync(tailscale, offArgs, { stdio: "inherit" });
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
const serveArgs = [
|
|
221
|
+
"serve",
|
|
222
|
+
"--bg",
|
|
223
|
+
`--https=${httpsPort}`,
|
|
224
|
+
`http://127.0.0.1:${config.port}`,
|
|
225
|
+
];
|
|
226
|
+
await step(`publish on the tailnet: ${tailscale} ${serveArgs.join(" ")}`, () => {
|
|
227
|
+
execFileSync(tailscale, serveArgs, { stdio: "inherit" });
|
|
228
|
+
});
|
|
229
|
+
const url = serveUrl(identity.dnsName, httpsPort);
|
|
230
|
+
say(dryRun
|
|
231
|
+
? `\nDry run finished: nothing was changed. k-bench would be reachable at ${url}`
|
|
232
|
+
: `\nInstalled. Open ${url} from a device on your tailnet.`);
|
|
233
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The `k-bench` command (the package's `bin`). From a checkout, `pnpm install-app` runs it
|
|
3
|
+
// as `node scripts/k-bench.ts install`; in the npm package it is compiled to JavaScript.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { install } from "./install.js";
|
|
7
|
+
import { findPackageRoot } from "./install-lib.js";
|
|
8
|
+
import { status } from "./status.js";
|
|
9
|
+
import { DEFAULT_HTTPS_PORT } from "./tailscale-serve.js";
|
|
10
|
+
import { uninstall } from "./uninstall.js";
|
|
11
|
+
const USAGE = `Usage: k-bench <command> [options]
|
|
12
|
+
|
|
13
|
+
Commands:
|
|
14
|
+
install [--dry-run] [--login <login>] [--https-port <n>] [--force]
|
|
15
|
+
install or update k-bench as a background service, published on
|
|
16
|
+
HTTPS port ${DEFAULT_HTTPS_PORT} unless --https-port says otherwise; --force replaces
|
|
17
|
+
whatever else is on that port
|
|
18
|
+
uninstall [--dry-run] [--purge]
|
|
19
|
+
stop and remove the service, its tailscale serve entry and the app
|
|
20
|
+
folder, keeping your data and running Sessions; --purge also deletes
|
|
21
|
+
the data and ends every Session
|
|
22
|
+
status check that k-bench is set up and healthy: each check passes or
|
|
23
|
+
fails with a fix, and the exit status is non-zero when one fails
|
|
24
|
+
|
|
25
|
+
Options:
|
|
26
|
+
--help, -h show this help
|
|
27
|
+
--version, -v show the version
|
|
28
|
+
`;
|
|
29
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
30
|
+
if (command === "--version" || command === "-v") {
|
|
31
|
+
const root = findPackageRoot(import.meta.dirname);
|
|
32
|
+
console.log(JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version);
|
|
33
|
+
}
|
|
34
|
+
else if (command === "--help" || command === "-h") {
|
|
35
|
+
console.log(USAGE);
|
|
36
|
+
}
|
|
37
|
+
else if (command === undefined) {
|
|
38
|
+
console.error(USAGE);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
}
|
|
41
|
+
else if (command === "install") {
|
|
42
|
+
await install(rest);
|
|
43
|
+
}
|
|
44
|
+
else if (command === "uninstall") {
|
|
45
|
+
await uninstall(rest);
|
|
46
|
+
}
|
|
47
|
+
else if (command === "status") {
|
|
48
|
+
await status(rest);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
console.error(`k-bench: unknown command "${command}"\n\n${USAGE}`);
|
|
52
|
+
process.exit(1);
|
|
53
|
+
}
|