@seaveyon/harness-switch 0.6.0 → 0.7.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
@@ -189,11 +189,12 @@ bun run dev:server
189
189
  bun run dev:web
190
190
  ```
191
191
 
192
- Linting and formatting are split: **Oxlint** for diagnostics, **Biome** for format and import organization.
192
+ Quality gates are three-layered: **tsc** for type checking, **Oxlint** for diagnostics, **Biome** for format and import organization. `bun run check` runs all three.
193
193
 
194
194
  ```bash
195
195
  bun run lint
196
196
  bun run lint:fix
197
+ bun run typecheck
197
198
  bun run format
198
199
  bun run format:check
199
200
  bun run check
@@ -205,7 +206,7 @@ bun run check
205
206
  bun run precommit
206
207
  ```
207
208
 
208
- 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:
209
210
 
210
211
  ```bash
211
212
  bun run build
@@ -217,7 +218,7 @@ The web dev server listens on `http://127.0.0.1:5173` and proxies `/api` to the
217
218
 
218
219
  ## Release
219
220
 
220
- Pushes to `main` run [semantic-release](https://semantic-release.gitbook.io/). It reads conventional commits, bumps `@seaveyon/harness-switch`, tags `v*`, and publishes to npm via Trusted Publishing.
221
+ Pushes to `main` run [semantic-release](https://semantic-release.gitbook.io/). It reads conventional commits, bumps `@seaveyon/harness-switch`, tags `v*`, and publishes to npm via Trusted Publishing. The tarball is published to the npm registry **before** the `v*` tag and GitHub release are created, so a failed registry publish never leaves a tag without a matching npm version, and a re-run skips versions that are already on the registry.
221
222
 
222
223
  | Commit | Version bump |
223
224
  |---|---|
@@ -9244,7 +9244,7 @@ import {
9244
9244
  statSync,
9245
9245
  writeFileSync
9246
9246
  } from "fs";
9247
- import { dirname as dirname2 } from "path";
9247
+ import { basename, dirname as dirname2 } from "path";
9248
9248
  var IFileService = createDecorator("fileService");
9249
9249
  var _dec = [
9250
9250
  inject(IEnvironmentService)
@@ -9265,8 +9265,33 @@ class FileService {
9265
9265
  readOptional(file) {
9266
9266
  try {
9267
9267
  return readFileSync(file, "utf8");
9268
+ } catch (error) {
9269
+ if (error.code === "ENOENT") {
9270
+ return;
9271
+ }
9272
+ throw error;
9273
+ }
9274
+ }
9275
+ readJsonStrict(file, fallback) {
9276
+ if (!existsSync2(file)) {
9277
+ return fallback;
9278
+ }
9279
+ let text;
9280
+ try {
9281
+ text = this.readText(file);
9268
9282
  } catch {
9269
- return;
9283
+ throw new HttpError(500, `\u6570\u636E\u5B58\u50A8\u4E0D\u53EF\u8BFB\uFF1A${file}`);
9284
+ }
9285
+ try {
9286
+ return JSON.parse(text);
9287
+ } catch {
9288
+ const quarantine = `${file}.corrupt-${Date.now()}`;
9289
+ try {
9290
+ renameSync(file, quarantine);
9291
+ } catch {
9292
+ throw new HttpError(500, `\u6570\u636E\u5B58\u50A8\u635F\u574F\u4E14\u65E0\u6CD5\u9694\u79BB\uFF1A${file}`);
9293
+ }
9294
+ throw new HttpError(500, `\u6570\u636E\u5B58\u50A8\u5DF2\u635F\u574F\uFF0C\u539F\u6587\u4EF6\u5DF2\u9694\u79BB\u4E3A ${basename(quarantine)}\uFF0C\u8BF7\u4ECE\u5907\u4EFD\u6062\u590D\u540E\u518D\u7EE7\u7EED`);
9270
9295
  }
9271
9296
  }
9272
9297
  writeSecure(file, text) {
@@ -9586,7 +9611,7 @@ function createAuthRoutes(services) {
9586
9611
  }
9587
9612
 
9588
9613
  // src/services/backup.ts
9589
- import { basename, join as join3 } from "path";
9614
+ import { basename as basename2, join as join3 } from "path";
9590
9615
  var IBackupService = createDecorator("backupService");
9591
9616
  var MANIFEST = "manifest.json";
9592
9617
  var _dec = [
@@ -9612,7 +9637,7 @@ class BackupService {
9612
9637
  if (snapshot.content === undefined) {
9613
9638
  return { path: snapshot.path, existed: false };
9614
9639
  }
9615
- const name = `${index}-${basename(snapshot.path)}`;
9640
+ const name = `${index}-${basename2(snapshot.path)}`;
9616
9641
  this.files.writeSecure(join3(dir, name), snapshot.content);
9617
9642
  return { path: snapshot.path, existed: true, stored: name };
9618
9643
  });
@@ -12043,7 +12068,7 @@ class ProfileService {
12043
12068
  this.files.writeJson(this.environment.files.profiles, store);
12044
12069
  }
12045
12070
  read() {
12046
- return this.files.readJson(this.environment.files.profiles, {});
12071
+ return this.files.readJsonStrict(this.environment.files.profiles, {});
12047
12072
  }
12048
12073
  toPublic(harness, name, profile) {
12049
12074
  return {
@@ -12216,14 +12241,10 @@ class ActivationService {
12216
12241
  if (!adapter.revoke) {
12217
12242
  return;
12218
12243
  }
12219
- try {
12220
- const profile = this.profiles.decrypt(harness, name);
12221
- const targets = adapter.targets();
12222
- const rendered = adapter.revoke(profile, this.readCurrent(targets));
12223
- this.liveWrite.apply(harness, name, this.toWrites(targets, rendered));
12224
- } catch (error) {
12225
- this.log.error(`failed to revoke ${harness}/${name} from live config`, error);
12226
- }
12244
+ const profile = this.profiles.decrypt(harness, name);
12245
+ const targets = adapter.targets();
12246
+ const rendered = adapter.revoke(profile, this.readCurrent(targets));
12247
+ this.liveWrite.apply(harness, name, this.toWrites(targets, rendered));
12227
12248
  }
12228
12249
  backfillPrevious(adapter, previous, nextName, warnings) {
12229
12250
  if (!adapter.backfill || !previous || previous.official || previous.name === nextName) {
@@ -12275,7 +12296,7 @@ class ActivationService {
12275
12296
  return current;
12276
12297
  }
12277
12298
  read() {
12278
- return this.files.readJson(this.environment.files.active, {});
12299
+ return this.files.readJsonStrict(this.environment.files.active, {});
12279
12300
  }
12280
12301
  writeEnv(active) {
12281
12302
  const lines = [
@@ -12334,6 +12355,8 @@ function createHarnessRoutes(services) {
12334
12355
  const activation = services.get(IActivationService);
12335
12356
  const adapters = services.get(IAdapterRegistry);
12336
12357
  const environment = services.get(IEnvironmentService);
12358
+ const files = services.get(IFileService);
12359
+ const log = services.get(ILogService);
12337
12360
  function summary(id) {
12338
12361
  const adapter = adapters.get(id);
12339
12362
  return {
@@ -12372,18 +12395,36 @@ function createHarnessRoutes(services) {
12372
12395
  const harnessId = harnesses.require(c.req.param("harnessId"));
12373
12396
  const name = decodeURIComponent(c.req.param("name"));
12374
12397
  const body = await readBody(c.req.json.bind(c.req));
12375
- const profile = profiles.upsert(harnessId, {
12376
- name: String(body.name ?? name),
12377
- sourceName: name,
12378
- baseUrl: body.baseUrl,
12379
- apiKey: body.apiKey,
12380
- model: body.model,
12381
- notes: body.notes,
12382
- extras: body.extras,
12383
- overrides: body.overrides
12384
- }, false);
12385
- activation.reconcileProfileUpdate(harnessId, name, profile.name);
12386
- return c.json(profile);
12398
+ const wasActive = activation.getActive(harnessId)?.name === name;
12399
+ const snapshot = files.readOptional(environment.files.profiles);
12400
+ let persisted = false;
12401
+ try {
12402
+ const profile = profiles.upsert(harnessId, {
12403
+ name: String(body.name ?? name),
12404
+ sourceName: name,
12405
+ baseUrl: body.baseUrl,
12406
+ apiKey: body.apiKey,
12407
+ model: body.model,
12408
+ notes: body.notes,
12409
+ extras: body.extras,
12410
+ overrides: body.overrides
12411
+ }, false);
12412
+ persisted = true;
12413
+ activation.reconcileProfileUpdate(harnessId, name, profile.name);
12414
+ return c.json(profile);
12415
+ } catch (error) {
12416
+ if (persisted) {
12417
+ restoreProfileStore(files, environment.files.profiles, snapshot);
12418
+ if (wasActive) {
12419
+ try {
12420
+ activation.activate(harnessId, name);
12421
+ } catch (rollbackError) {
12422
+ log.error(`edit rollback: failed to re-activate ${harnessId}/${name}`, rollbackError);
12423
+ }
12424
+ }
12425
+ }
12426
+ throw error;
12427
+ }
12387
12428
  });
12388
12429
  app.delete("/:harnessId/profiles/:name", (c) => {
12389
12430
  const harnessId = harnesses.require(c.req.param("harnessId"));
@@ -12415,6 +12456,13 @@ async function readBody(read) {
12415
12456
  throw new HttpError(400, "invalid json");
12416
12457
  });
12417
12458
  }
12459
+ function restoreProfileStore(files, path, snapshot) {
12460
+ if (snapshot === undefined) {
12461
+ files.remove(path);
12462
+ return;
12463
+ }
12464
+ files.writeSecure(path, snapshot);
12465
+ }
12418
12466
 
12419
12467
  // src/services/transfer.ts
12420
12468
  import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4, scryptSync } from "crypto";
@@ -12580,7 +12628,7 @@ class TransferService {
12580
12628
  };
12581
12629
  }
12582
12630
  readStore() {
12583
- return this.files.readJson(this.environment.files.profiles, {});
12631
+ return this.files.readJsonStrict(this.environment.files.profiles, {});
12584
12632
  }
12585
12633
  assertPassphrase(passphrase) {
12586
12634
  if (passphrase.length < 8) {
@@ -12743,18 +12791,159 @@ function createServices() {
12743
12791
  return new InstantiationService(collection);
12744
12792
  }
12745
12793
 
12794
+ // src/daemon.ts
12795
+ import { spawn } from "child_process";
12796
+ import { mkdirSync as mkdirSync3, openSync, readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
12797
+ import { homedir as homedir2 } from "os";
12798
+ import { join as join10, resolve } from "path";
12799
+ var DEFAULT_HOST = "127.0.0.1";
12800
+ var DEFAULT_PORT = 8787;
12801
+ var STOP_TIMEOUT_MS = 5000;
12802
+ var START_GRACE_MS = 500;
12803
+ function daemonDataDir() {
12804
+ return process.env.HSW_DATA_DIR || join10(homedir2(), ".harness-switch");
12805
+ }
12806
+ function daemonPidFile() {
12807
+ return join10(daemonDataDir(), "daemon.pid");
12808
+ }
12809
+ function daemonLogFile() {
12810
+ return join10(daemonDataDir(), "daemon.log");
12811
+ }
12812
+ function readPid() {
12813
+ try {
12814
+ const raw2 = readFileSync2(daemonPidFile(), "utf8").trim();
12815
+ const pid = Number(raw2);
12816
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
12817
+ } catch {
12818
+ return null;
12819
+ }
12820
+ }
12821
+ function isAlive(pid) {
12822
+ try {
12823
+ process.kill(pid, 0);
12824
+ return true;
12825
+ } catch {
12826
+ return false;
12827
+ }
12828
+ }
12829
+ async function waitForExit(pid, timeoutMs = STOP_TIMEOUT_MS) {
12830
+ const deadline = Date.now() + timeoutMs;
12831
+ while (Date.now() < deadline) {
12832
+ if (!isAlive(pid))
12833
+ return true;
12834
+ await Bun.sleep(100);
12835
+ }
12836
+ return !isAlive(pid);
12837
+ }
12838
+ async function killProcess(pid) {
12839
+ if (!isAlive(pid))
12840
+ return true;
12841
+ process.kill(pid, "SIGTERM");
12842
+ if (await waitForExit(pid))
12843
+ return true;
12844
+ process.kill(pid, "SIGKILL");
12845
+ return waitForExit(pid, 3000);
12846
+ }
12847
+ async function stopDaemon() {
12848
+ const pid = readPid();
12849
+ if (pid === null) {
12850
+ console.log("no harness-switch daemon pid file found");
12851
+ return;
12852
+ }
12853
+ if (!isAlive(pid)) {
12854
+ console.log(`daemon pid ${pid} is not running; removing stale pid file`);
12855
+ try {
12856
+ unlinkSync(daemonPidFile());
12857
+ } catch {}
12858
+ return;
12859
+ }
12860
+ console.log(`stopping harness-switch daemon (pid ${pid})...`);
12861
+ await killProcess(pid);
12862
+ try {
12863
+ unlinkSync(daemonPidFile());
12864
+ } catch {}
12865
+ console.log("stopped");
12866
+ }
12867
+ function printStatus() {
12868
+ const pid = readPid();
12869
+ const host = process.env.HOST || DEFAULT_HOST;
12870
+ const port = Number(process.env.PORT || DEFAULT_PORT);
12871
+ const running = pid !== null && isAlive(pid);
12872
+ console.log(`harness-switch daemon: ${running ? `running (pid ${pid})` : "not running"}`);
12873
+ console.log(` url: http://${host}:${port}`);
12874
+ console.log(` log: ${daemonLogFile()}`);
12875
+ console.log(` password: ${join10(daemonDataDir(), "web_password")}`);
12876
+ console.log(` data: ${daemonDataDir()}`);
12877
+ }
12878
+ async function daemonize() {
12879
+ const previous = readPid();
12880
+ if (previous !== null && isAlive(previous)) {
12881
+ console.log(`restarting harness-switch daemon (previous pid ${previous})...`);
12882
+ await killProcess(previous);
12883
+ }
12884
+ mkdirSync3(daemonDataDir(), { recursive: true, mode: 448 });
12885
+ const entry = resolve(process.argv[1] ?? "harness-switch.js");
12886
+ const logPath = daemonLogFile();
12887
+ const logFd = openSync(logPath, "w");
12888
+ const child = spawn(process.execPath, [entry, "server"], {
12889
+ detached: true,
12890
+ stdio: ["ignore", logFd, logFd],
12891
+ env: process.env
12892
+ });
12893
+ child.unref();
12894
+ await Bun.sleep(START_GRACE_MS);
12895
+ if (child.exitCode !== null || child.signalCode !== null) {
12896
+ console.error(`daemon exited immediately (code ${child.exitCode}); tail of ${logPath}:`);
12897
+ try {
12898
+ const tail = (await Bun.file(logPath).text()).split(`
12899
+ `).slice(-15).join(`
12900
+ `);
12901
+ console.error(tail);
12902
+ } catch {}
12903
+ process.exit(1);
12904
+ }
12905
+ writeFileSync2(daemonPidFile(), `${child.pid}
12906
+ `, { mode: 384 });
12907
+ const host = process.env.HOST || DEFAULT_HOST;
12908
+ const port = Number(process.env.PORT || DEFAULT_PORT);
12909
+ console.log(`harness-switch daemon started (pid ${child.pid})`);
12910
+ console.log(` url: http://${host}:${port}`);
12911
+ console.log(` log: ${logPath}`);
12912
+ console.log(" manage: harness-switch status | harness-switch stop");
12913
+ console.log(` password (first run): ${join10(daemonDataDir(), "web_password")}`);
12914
+ }
12915
+ function usage() {
12916
+ return "usage: harness-switch [server|daemon|status|stop]";
12917
+ }
12918
+
12746
12919
  // src/main.ts
12747
- var services = createServices();
12748
- var environment = services.get(IEnvironmentService);
12749
- var log = services.get(ILogService);
12750
- var auth = services.get(IAuthService);
12751
- environment.ensureDataDir();
12752
- auth.ensurePassword();
12753
- var app = createApp(services);
12754
- var server = Bun.serve({
12755
- hostname: environment.host,
12756
- port: environment.port,
12757
- fetch: app.fetch
12758
- });
12759
- log.info(`data directory: ${environment.dataDir}`);
12760
- log.info(`listening on http://${server.hostname}:${server.port}`);
12920
+ async function runServer() {
12921
+ const services = createServices();
12922
+ const environment = services.get(IEnvironmentService);
12923
+ const log = services.get(ILogService);
12924
+ const auth = services.get(IAuthService);
12925
+ environment.ensureDataDir();
12926
+ auth.ensurePassword();
12927
+ const app = createApp(services);
12928
+ const server = Bun.serve({
12929
+ hostname: environment.host,
12930
+ port: environment.port,
12931
+ fetch: app.fetch
12932
+ });
12933
+ log.info(`data directory: ${environment.dataDir}`);
12934
+ log.info(`listening on http://${server.hostname}:${server.port}`);
12935
+ }
12936
+ var command = process.argv[2];
12937
+ if (command === "server") {
12938
+ await runServer();
12939
+ } else if (command === "stop") {
12940
+ await stopDaemon();
12941
+ } else if (command === "status") {
12942
+ printStatus();
12943
+ } else if (command === undefined || command === "daemon") {
12944
+ await daemonize();
12945
+ } else {
12946
+ console.error(`unknown command: ${command}`);
12947
+ console.error(usage());
12948
+ process.exit(1);
12949
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seaveyon/harness-switch",
3
- "version": "0.6.0",
3
+ "version": "0.7.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
  },
@@ -1 +1 @@
1
- "use strict";(self.webpackChunk_seaveyon_harness_switch_web=self.webpackChunk_seaveyon_harness_switch_web||[]).push([["4952"],{1419(e,n,l){l.r(n),l.d(n,{PierreFileDiff:()=>s});var t=l(1085),o=l(8437),r={themeType:"dark",theme:"pierre-dark",diffStyle:"unified",overflow:"wrap",expandUnchanged:!0,stickyHeader:!0};function s(e){var n=e.file,l=n.path,s=null===n.currentContent?null:{name:l,contents:n.currentContent},i=null===n.content?null:{name:l,contents:n.content};return null===s&&null===i?(0,t.jsx)("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"两侧都不存在"}):null===s?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:null,newFile:i,options:r}):null===i?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:null,options:r}):(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:i,options:r})}}}]);
1
+ "use strict";(self.webpackChunk_seaveyon_harness_switch_web=self.webpackChunk_seaveyon_harness_switch_web||[]).push([["4952"],{1419(e,n,l){l.r(n),l.d(n,{PierreFileDiff:()=>s});var t=l(1085),o=l(8437),r={themeType:"dark",theme:"pierre-dark",diffStyle:"unified",overflow:"wrap",expandUnchanged:!0,stickyHeader:!0};function s(e){var n=e.file,l=n.path,s=null===n.currentContent?null:{name:l,contents:n.currentContent},i=null===n.content?null:{name:l,contents:n.content};return null!==s&&null!==i?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:i,options:r}):null!==s?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:s,newFile:null,options:r}):null!==i?(0,t.jsx)(o.T,{disableWorkerPool:!0,oldFile:null,newFile:i,options:r}):(0,t.jsx)("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"两侧都不存在"})}}}]);