@seaveyon/harness-switch 0.6.1 → 0.8.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 CHANGED
@@ -137,36 +137,36 @@ The UI is a React SPA. Authentication uses an HttpOnly `hsw_session` cookie.
137
137
  | `POST` | `/api/transfer/preview` | Decrypt and report profile counts and conflicts without writing |
138
138
  | `POST` | `/api/transfer/import` | Import with `skip` or `overwrite` conflict handling |
139
139
 
140
- ## systemd
140
+ ## Background daemon (bunx / npx)
141
141
 
142
- Create `/etc/systemd/system/harness-switch.service`:
142
+ The published CLI runs as a background daemon by default: the command returns
143
+ immediately, the server keeps running after the terminal is closed, and
144
+ re-running after a release restarts the daemon on the newest version.
143
145
 
144
- ```ini
145
- [Unit]
146
- Description=Harness Switch Web Control Plane
147
- After=network.target
146
+ ```bash
147
+ bunx @seaveyon/harness-switch@latest # start, or update + restart the daemon
148
+ bunx @seaveyon/harness-switch@latest status # pid, url, log path
149
+ bunx @seaveyon/harness-switch@latest stop # stop the daemon
150
+ bunx @seaveyon/harness-switch@latest server # run in the foreground instead
151
+ ```
152
+
153
+ `npx -y @seaveyon/harness-switch@latest` works the same way. Append `@latest`
154
+ so `bunx`/`npx` fetch the newest release before running.
155
+
156
+ The daemon writes its pid to `~/.harness-switch/daemon.pid` and its log to
157
+ `~/.harness-switch/daemon.log` (a fresh log per start). The first run creates
158
+ the web password in `~/.harness-switch/web_password` and prints it to the log.
159
+ When a daemon is already running, a new invocation stops it before starting the
160
+ new process, so the port never conflicts and the newest code wins.
161
+
162
+ Under systemd (or any supervisor), run the CLI in the foreground instead:
148
163
 
164
+ ```ini
149
165
  [Service]
150
166
  Type=simple
151
- User=ubuntu
152
- Environment=HOST=127.0.0.1
153
- Environment=PORT=8787
154
- ExecStart=/usr/bin/env harness-switch
167
+ ExecStart=/usr/local/bin/harness-switch server
155
168
  Restart=on-failure
156
169
  RestartSec=3
157
- NoNewPrivileges=true
158
- PrivateTmp=true
159
-
160
- [Install]
161
- WantedBy=multi-user.target
162
- ```
163
-
164
- Then run:
165
-
166
- ```bash
167
- sudo systemctl daemon-reload
168
- sudo systemctl enable --now harness-switch
169
- sudo journalctl -u harness-switch -f
170
170
  ```
171
171
 
172
172
  ## Development
@@ -206,7 +206,7 @@ bun run check
206
206
  bun run precommit
207
207
  ```
208
208
 
209
- Production build (frontend assets are copied into `apps/server/public`, then the CLI is bundled):
209
+ Production build (frontend assets are copied into `apps/server/public`, then the CLI is bundled). `bun run start` starts the daemon; use `bun run start:foreground` for the foreground server:
210
210
 
211
211
  ```bash
212
212
  bun run build
@@ -7015,7 +7015,7 @@ var require_public_api = __commonJS((exports) => {
7015
7015
 
7016
7016
  // src/app.ts
7017
7017
  import { existsSync as existsSync3 } from "fs";
7018
- import { join as join9 } from "path";
7018
+ import { join as join10 } from "path";
7019
7019
 
7020
7020
  // ../../node_modules/hono/dist/compose.js
7021
7021
  var compose = (middleware, onError, onNotFound) => {
@@ -12724,6 +12724,21 @@ async function readBody2(read) {
12724
12724
  });
12725
12725
  }
12726
12726
 
12727
+ // src/version.ts
12728
+ import { join as join9 } from "path";
12729
+ var cached;
12730
+ async function serverVersion() {
12731
+ if (cached)
12732
+ return cached;
12733
+ try {
12734
+ const pkg = JSON.parse(await Bun.file(join9(import.meta.dir, "../package.json")).text());
12735
+ cached = typeof pkg.version === "string" ? pkg.version : "0.0.0";
12736
+ } catch {
12737
+ cached = "0.0.0";
12738
+ }
12739
+ return cached;
12740
+ }
12741
+
12727
12742
  // src/app.ts
12728
12743
  function createApp(services) {
12729
12744
  const app = new Hono2;
@@ -12733,6 +12748,7 @@ function createApp(services) {
12733
12748
  app.get("/healthz", (c) => c.json({ ok: true }));
12734
12749
  const api = new Hono2;
12735
12750
  api.use("*", createOriginGuard());
12751
+ api.get("/version", async (c) => c.json({ name: "harness-switch", version: await serverVersion() }));
12736
12752
  api.route("/auth", createAuthRoutes(services));
12737
12753
  api.use("/harnesses/*", createAuthGuard(services));
12738
12754
  api.use("/harnesses", createAuthGuard(services));
@@ -12750,11 +12766,11 @@ function createApp(services) {
12750
12766
  if (c.req.path.startsWith("/api") || c.req.path === "/healthz") {
12751
12767
  return next();
12752
12768
  }
12753
- const assetPath = join9(publicDir, c.req.path.replace(/^\//, ""));
12769
+ const assetPath = join10(publicDir, c.req.path.replace(/^\//, ""));
12754
12770
  if (c.req.path !== "/" && existsSync3(assetPath)) {
12755
12771
  return serveStatic2({ root: publicDir })(c, next);
12756
12772
  }
12757
- const index = join9(publicDir, "index.html");
12773
+ const index = join10(publicDir, "index.html");
12758
12774
  if (existsSync3(index)) {
12759
12775
  c.header("Cache-Control", "no-store");
12760
12776
  return c.html(await Bun.file(index).text());
@@ -12791,18 +12807,159 @@ function createServices() {
12791
12807
  return new InstantiationService(collection);
12792
12808
  }
12793
12809
 
12810
+ // src/daemon.ts
12811
+ import { spawn } from "child_process";
12812
+ import { mkdirSync as mkdirSync3, openSync, readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
12813
+ import { homedir as homedir2 } from "os";
12814
+ import { join as join11, resolve } from "path";
12815
+ var DEFAULT_HOST = "127.0.0.1";
12816
+ var DEFAULT_PORT = 8787;
12817
+ var STOP_TIMEOUT_MS = 5000;
12818
+ var START_GRACE_MS = 500;
12819
+ function daemonDataDir() {
12820
+ return process.env.HSW_DATA_DIR || join11(homedir2(), ".harness-switch");
12821
+ }
12822
+ function daemonPidFile() {
12823
+ return join11(daemonDataDir(), "daemon.pid");
12824
+ }
12825
+ function daemonLogFile() {
12826
+ return join11(daemonDataDir(), "daemon.log");
12827
+ }
12828
+ function readPid() {
12829
+ try {
12830
+ const raw2 = readFileSync2(daemonPidFile(), "utf8").trim();
12831
+ const pid = Number(raw2);
12832
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
12833
+ } catch {
12834
+ return null;
12835
+ }
12836
+ }
12837
+ function isAlive(pid) {
12838
+ try {
12839
+ process.kill(pid, 0);
12840
+ return true;
12841
+ } catch {
12842
+ return false;
12843
+ }
12844
+ }
12845
+ async function waitForExit(pid, timeoutMs = STOP_TIMEOUT_MS) {
12846
+ const deadline = Date.now() + timeoutMs;
12847
+ while (Date.now() < deadline) {
12848
+ if (!isAlive(pid))
12849
+ return true;
12850
+ await Bun.sleep(100);
12851
+ }
12852
+ return !isAlive(pid);
12853
+ }
12854
+ async function killProcess(pid) {
12855
+ if (!isAlive(pid))
12856
+ return true;
12857
+ process.kill(pid, "SIGTERM");
12858
+ if (await waitForExit(pid))
12859
+ return true;
12860
+ process.kill(pid, "SIGKILL");
12861
+ return waitForExit(pid, 3000);
12862
+ }
12863
+ async function stopDaemon() {
12864
+ const pid = readPid();
12865
+ if (pid === null) {
12866
+ console.log("no harness-switch daemon pid file found");
12867
+ return;
12868
+ }
12869
+ if (!isAlive(pid)) {
12870
+ console.log(`daemon pid ${pid} is not running; removing stale pid file`);
12871
+ try {
12872
+ unlinkSync(daemonPidFile());
12873
+ } catch {}
12874
+ return;
12875
+ }
12876
+ console.log(`stopping harness-switch daemon (pid ${pid})...`);
12877
+ await killProcess(pid);
12878
+ try {
12879
+ unlinkSync(daemonPidFile());
12880
+ } catch {}
12881
+ console.log("stopped");
12882
+ }
12883
+ function printStatus() {
12884
+ const pid = readPid();
12885
+ const host = process.env.HOST || DEFAULT_HOST;
12886
+ const port = Number(process.env.PORT || DEFAULT_PORT);
12887
+ const running = pid !== null && isAlive(pid);
12888
+ console.log(`harness-switch daemon: ${running ? `running (pid ${pid})` : "not running"}`);
12889
+ console.log(` url: http://${host}:${port}`);
12890
+ console.log(` log: ${daemonLogFile()}`);
12891
+ console.log(` password: ${join11(daemonDataDir(), "web_password")}`);
12892
+ console.log(` data: ${daemonDataDir()}`);
12893
+ }
12894
+ async function daemonize() {
12895
+ const previous = readPid();
12896
+ if (previous !== null && isAlive(previous)) {
12897
+ console.log(`restarting harness-switch daemon (previous pid ${previous})...`);
12898
+ await killProcess(previous);
12899
+ }
12900
+ mkdirSync3(daemonDataDir(), { recursive: true, mode: 448 });
12901
+ const entry = resolve(process.argv[1] ?? "harness-switch.js");
12902
+ const logPath = daemonLogFile();
12903
+ const logFd = openSync(logPath, "w");
12904
+ const child = spawn(process.execPath, [entry, "server"], {
12905
+ detached: true,
12906
+ stdio: ["ignore", logFd, logFd],
12907
+ env: process.env
12908
+ });
12909
+ child.unref();
12910
+ await Bun.sleep(START_GRACE_MS);
12911
+ if (child.exitCode !== null || child.signalCode !== null) {
12912
+ console.error(`daemon exited immediately (code ${child.exitCode}); tail of ${logPath}:`);
12913
+ try {
12914
+ const tail = (await Bun.file(logPath).text()).split(`
12915
+ `).slice(-15).join(`
12916
+ `);
12917
+ console.error(tail);
12918
+ } catch {}
12919
+ process.exit(1);
12920
+ }
12921
+ writeFileSync2(daemonPidFile(), `${child.pid}
12922
+ `, { mode: 384 });
12923
+ const host = process.env.HOST || DEFAULT_HOST;
12924
+ const port = Number(process.env.PORT || DEFAULT_PORT);
12925
+ console.log(`harness-switch daemon started (pid ${child.pid})`);
12926
+ console.log(` url: http://${host}:${port}`);
12927
+ console.log(` log: ${logPath}`);
12928
+ console.log(" manage: harness-switch status | harness-switch stop");
12929
+ console.log(` password (first run): ${join11(daemonDataDir(), "web_password")}`);
12930
+ }
12931
+ function usage() {
12932
+ return "usage: harness-switch [server|daemon|status|stop]";
12933
+ }
12934
+
12794
12935
  // src/main.ts
12795
- var services = createServices();
12796
- var environment = services.get(IEnvironmentService);
12797
- var log = services.get(ILogService);
12798
- var auth = services.get(IAuthService);
12799
- environment.ensureDataDir();
12800
- auth.ensurePassword();
12801
- var app = createApp(services);
12802
- var server = Bun.serve({
12803
- hostname: environment.host,
12804
- port: environment.port,
12805
- fetch: app.fetch
12806
- });
12807
- log.info(`data directory: ${environment.dataDir}`);
12808
- log.info(`listening on http://${server.hostname}:${server.port}`);
12936
+ async function runServer() {
12937
+ const services = createServices();
12938
+ const environment = services.get(IEnvironmentService);
12939
+ const log = services.get(ILogService);
12940
+ const auth = services.get(IAuthService);
12941
+ environment.ensureDataDir();
12942
+ auth.ensurePassword();
12943
+ const app = createApp(services);
12944
+ const server = Bun.serve({
12945
+ hostname: environment.host,
12946
+ port: environment.port,
12947
+ fetch: app.fetch
12948
+ });
12949
+ log.info(`data directory: ${environment.dataDir}`);
12950
+ log.info(`listening on http://${server.hostname}:${server.port}`);
12951
+ }
12952
+ var command = process.argv[2];
12953
+ if (command === "server") {
12954
+ await runServer();
12955
+ } else if (command === "stop") {
12956
+ await stopDaemon();
12957
+ } else if (command === "status") {
12958
+ printStatus();
12959
+ } else if (command === undefined || command === "daemon") {
12960
+ await daemonize();
12961
+ } else {
12962
+ console.error(`unknown command: ${command}`);
12963
+ console.error(usage());
12964
+ process.exit(1);
12965
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seaveyon/harness-switch",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "A secure web control plane that switches API providers for Claude Code, Codex, Kimi Code, Pi and DeepSeek Harness by writing their native config files on SSH servers.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -29,8 +29,9 @@
29
29
  "LICENSE"
30
30
  ],
31
31
  "scripts": {
32
- "dev": "bun --hot src/main.ts",
32
+ "dev": "bun --hot src/main.ts server",
33
33
  "start": "bun dist/harness-switch.js",
34
+ "start:foreground": "bun dist/harness-switch.js server",
34
35
  "build": "bun build src/main.ts --outfile dist/harness-switch.js --target bun && bun ../../scripts/postbuild.ts",
35
36
  "test": "bun test test"
36
37
  },