@seaveyon/harness-switch 0.17.0 → 0.18.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
@@ -6,24 +6,32 @@ English | [简体中文](https://github.com/B1anker/harness-switch/blob/main/REA
6
6
 
7
7
  **harness-switch** is a Bun-powered web control plane for managing API profiles on an SSH or headless server. It switches API Base URL, API key, and model profiles for **Claude Code**, **Codex**, **Kimi Code**, **Pi**, and **DeepSeek Harness (DSH)**.
8
8
 
9
- It is a configuration manager, not an API proxy: it does not route or inspect model traffic.
9
+ It writes each tool's native configuration; it is not an API proxy and never routes model traffic. Profiles are encrypted at rest, writes are transactional, and every activation has a backup and an undo receipt.
10
10
 
11
11
  ## Install and run
12
12
 
13
- Requires [Bun](https://bun.sh) >= 1.2.
13
+ Requires [Bun](https://bun.sh) >= 1.2 as the runtime. Start it with your preferred package runner:
14
14
 
15
15
  ```bash
16
- bunx @seaveyon/harness-switch
16
+ bunx @seaveyon/harness-switch@latest
17
+ npx -y @seaveyon/harness-switch@latest
18
+ pnpm dlx @seaveyon/harness-switch@latest
17
19
  ```
18
20
 
19
- Or install it globally:
21
+ `pnpx @seaveyon/harness-switch@latest` is also supported where `pnpx` is available. Or install it globally:
20
22
 
21
23
  ```bash
22
24
  bun add -g @seaveyon/harness-switch
25
+ # npm install -g @seaveyon/harness-switch
26
+ # pnpm add -g @seaveyon/harness-switch
23
27
  harness-switch
24
28
  ```
25
29
 
26
- The server listens on `127.0.0.1:8787` by default. The first startup prints a randomly generated Web password in the terminal.
30
+ The command starts a background daemon on `127.0.0.1:8787`. Read the generated Web password with:
31
+
32
+ ```bash
33
+ cat ~/.harness-switch/web_password
34
+ ```
27
35
 
28
36
  For a remote SSH server, keep the server bound to loopback and use an SSH tunnel:
29
37
 
@@ -31,7 +39,7 @@ For a remote SSH server, keep the server bound to loopback and use an SSH tunnel
31
39
  ssh -N -L 8787:127.0.0.1:8787 user@your-server
32
40
  ```
33
41
 
34
- Then open <http://127.0.0.1:8787> in your local browser.
42
+ Then open <http://127.0.0.1:8787> locally. Use `harness-switch status`, `stop`, or `server` to inspect, stop, or run the service in the foreground.
35
43
 
36
44
  ### Interface language
37
45
 
@@ -165,15 +173,22 @@ Cross-user writes require access to the destination home. Managing both `root` a
165
173
 
166
174
  ### CLI automation
167
175
 
168
- The same business logic is available from the terminal without opening the browser or starting any listener: the CLI builds the same service graph in-process and reads/writes the same data directory, so it works even when the daemon is not running. Every command supports `--json` for scripting:
176
+ The CLI talks to the running local daemon and uses the same authenticated HTTP API as the Web UI. Start the daemon once before using API-backed commands. `help` and `version` work offline; data commands support `--json` (or `-j`) for scripting:
169
177
 
170
178
  ```bash
171
179
  harness-switch list # harnesses, active profile, profile counts
180
+ harness-switch profiles [claude] # secret-free profile list, optionally filtered
181
+ harness-switch create claude main \
182
+ --base-url https://api.example.com/v1 \
183
+ --model claude-sonnet-4-5 \
184
+ --api-key-env ANTHROPIC_TOKEN # safer than putting a key in shell history
172
185
  harness-switch providers # Provider Vault entries
173
186
  harness-switch doctor # read-only diagnostics
174
- harness-switch doctor --probe --harness claude
175
- harness-switch plan claude # drift inspection for a harness
187
+ harness-switch doctor --strict --harness claude # exit 1 if a check has error status
188
+ harness-switch plan claude main # exact native files activation would write
176
189
  harness-switch activate claude main --yes # activate a profile
190
+ harness-switch official claude --yes # return to the tool's built-in login
191
+ harness-switch delete claude old --yes # inactive profiles only
177
192
  harness-switch users # manageable local Unix users
178
193
  harness-switch list --user alice # inspect alice's independent store
179
194
  harness-switch activate codex main --user alice --yes
@@ -187,7 +202,9 @@ harness-switch operations # operation receipts, newest first
187
202
  harness-switch undo <operation-id> # revert one complete operation
188
203
  ```
189
204
 
190
- `plan <harness>` prints the drift inspection of the active profile (expected vs. current content per file); without an active profile it reports `status: unknown`. `activate` prompts for confirmation on a TTY and requires `--yes` in non-interactive terminals (CI). JSON output mirrors the HTTP API response shapes (`HarnessesResponse`, `ProvidersResponse`, `DoctorResponse`, `DriftSummary`, `ActivateResponse`), so scripts can reuse the same field names. `HSW_DATA_DIR` and `HSW_HOME_DIR` override where it reads state (defaults: `~/.harness-switch` and `$HOME`).
205
+ `plan <harness> <profile>` includes exact rendered content and therefore may include an API key. Mutating commands prompt on a TTY and require `--yes` in non-interactive terminals (CI). Prefer `--api-key-env VAR` to `--api-key VALUE` so credentials do not enter shell history or the process list. Run `harness-switch help` for the complete command reference. `HSW_URL` selects a non-default local endpoint; `HSW_DATA_DIR` tells the CLI where to find `web_password`.
206
+
207
+ JSON failures retain the HTTP status and stable server error code when available. Each CLI invocation logs out its temporary API session before exiting, so repeated automation does not grow the persisted Web session table.
191
208
 
192
209
  ## Security
193
210
 
@@ -207,6 +224,7 @@ This protects against accidental plaintext disclosure in profile storage, but do
207
224
  |---|---:|---|
208
225
  | `HOST` | `127.0.0.1` | Bind address. Keep the default when using SSH tunnelling. |
209
226
  | `PORT` | `8787` | Listening port. |
227
+ | `HSW_URL` | `http://127.0.0.1:$PORT` | Base URL used by API-backed CLI commands. |
210
228
  | `HSW_DATA_DIR` | `~/.harness-switch` | Control-plane and service-owner data directory; other users use `.harness-switch` in their own home. |
211
229
  | `HSW_HOME_DIR` | `$HOME` | Service owner's home override, mainly for tests and containers. |
212
230
  | `HSW_USERS` | auto-discovered | Comma-separated allowlist such as `root,alice`. The service owner is always manageable. |
@@ -239,6 +257,7 @@ The UI is a React SPA. Authentication uses an HttpOnly `hsw_session` cookie.
239
257
  | `DELETE` | `/api/harnesses/:id/profiles/:name` | Delete; `409` for the active profile |
240
258
  | `GET` | `/api/harnesses/:id/profiles/:name/preview` | The exact content that would be written |
241
259
  | `POST` | `/api/harnesses/:id/profiles/:name/activate` | Write the native config, then commit the switch |
260
+ | `POST` | `/api/harnesses/:id/official/activate` | Return a supported harness to its built-in account login |
242
261
  | `GET` | `/api/backups` | Snapshots, newest first |
243
262
  | `POST` | `/api/backups/:id/restore` | Restore a snapshot verbatim |
244
263
  | `POST` | `/api/transfer/export` | Create a passphrase-encrypted portable bundle |
@@ -260,7 +279,7 @@ The UI is a React SPA. Authentication uses an HttpOnly `hsw_session` cookie.
260
279
 
261
280
  Every POST/PATCH body is validated against a shared Zod schema (`packages/shared/src/schemas.ts`) that the server and the web client both build on. A malformed shape is rejected with a `400` naming the field *before* it reaches storage, instead of being persisted and only surfacing as a `500` on the next activation. Unknown fields are dropped rather than rejected, so an older client keeps working while nothing unrecognised enters the store.
262
281
 
263
- ## Background daemon (bunx / npx)
282
+ ## Background daemon (bunx / npx / pnpm)
264
283
 
265
284
  The published CLI runs as a background daemon by default: the command returns
266
285
  immediately, the server keeps running after the terminal is closed, and
@@ -274,15 +293,17 @@ bunx @seaveyon/harness-switch@latest server # run in the foreground instead
274
293
  bunx @seaveyon/harness-switch@latest list # CLI automation (see above)
275
294
  ```
276
295
 
277
- `npx -y @seaveyon/harness-switch@latest` works the same way. Append `@latest`
278
- so `bunx`/`npx` fetch the newest release before running.
296
+ Replace `bunx` with `npx -y`, `pnpm dlx`, or `pnpx` as preferred. Append `@latest`
297
+ so the package runner fetches the newest release before running. Bun remains the runtime used by the installed executable.
279
298
 
280
- The daemon writes its pid to `~/.harness-switch/daemon.pid` and its log to
299
+ The daemon writes its PID, instance identity, and listening address to `~/.harness-switch/daemon.pid` and its log to
281
300
  `~/.harness-switch/daemon.log` (a fresh log per start). The first run creates
282
301
  the web password in `~/.harness-switch/web_password` and prints it to the log.
283
302
  When a daemon is already running, a new invocation stops it before starting the
284
303
  new process, so the port never conflicts and the newest code wins.
285
304
 
305
+ Startup reports success only after the new process answers `/healthz`. `status` returns a non-zero exit code when the recorded daemon is not healthy. Before `stop` or an update sends a signal, the recorded instance identity is verified so a stale, reused PID cannot terminate an unrelated process.
306
+
286
307
  The dashboard polls the npm registry and shows a one-click **update button**
287
308
  next to the version badge when a newer release exists; it runs the same
288
309
  `bunx <package>@latest` restart under the hood and reloads the page once the
@@ -29962,7 +29962,10 @@ function createApp(services) {
29962
29962
  const environment = services.get(IEnvironmentService);
29963
29963
  const log = services.get(ILogService);
29964
29964
  app.use("*", createServiceMiddleware(services));
29965
- app.get("/healthz", (c) => c.json({ ok: true }));
29965
+ app.get("/healthz", (c) => c.json({
29966
+ ok: true,
29967
+ ...process.env.HSW_DAEMON_TOKEN ? { instance: process.env.HSW_DAEMON_TOKEN } : {}
29968
+ }));
29966
29969
  const api2 = new Hono2;
29967
29970
  api2.use("*", createOriginGuard());
29968
29971
  api2.get("/version", async (c) => c.json({ name: "harness-switch", version: await serverVersion() }));
@@ -30058,20 +30061,59 @@ function createServices() {
30058
30061
  }
30059
30062
 
30060
30063
  // src/cli/args.ts
30064
+ var VALUE_FLAGS = new Set([
30065
+ "api-key",
30066
+ "api-key-env",
30067
+ "base-url",
30068
+ "endpoint",
30069
+ "from",
30070
+ "harness",
30071
+ "model",
30072
+ "name",
30073
+ "notes",
30074
+ "provider",
30075
+ "to",
30076
+ "user"
30077
+ ]);
30078
+ var SHORT_FLAGS = {
30079
+ h: "help",
30080
+ j: "json",
30081
+ V: "version",
30082
+ y: "yes"
30083
+ };
30061
30084
  function parseArgs(argv) {
30062
30085
  const flags = {};
30063
30086
  const positional = [];
30064
- const valueFlags = new Set(["user", "from", "to", "harness"]);
30087
+ let optionsEnded = false;
30065
30088
  for (let index = 0;index < argv.length; index++) {
30066
30089
  const arg = argv[index];
30067
- if (arg.startsWith("--")) {
30090
+ if (optionsEnded) {
30091
+ positional.push(arg);
30092
+ } else if (arg === "--") {
30093
+ optionsEnded = true;
30094
+ } else if (/^-[^-]$/.test(arg)) {
30095
+ const name = SHORT_FLAGS[arg.slice(1)];
30096
+ if (!name)
30097
+ throw new CliError(`\u672A\u77E5\u9009\u9879\uFF1A${arg}`);
30098
+ flags[name] = true;
30099
+ } else if (arg.startsWith("--")) {
30068
30100
  const body = arg.slice(2);
30101
+ if (!body)
30102
+ throw new CliError("\u65E0\u6548\u9009\u9879\uFF1A--");
30069
30103
  const separator = body.indexOf("=");
30070
30104
  if (separator !== -1) {
30071
- flags[body.slice(0, separator)] = body.slice(separator + 1);
30105
+ const name = body.slice(0, separator);
30106
+ const value = body.slice(separator + 1);
30107
+ if (!VALUE_FLAGS.has(name))
30108
+ throw new CliError(`\u9009\u9879 --${name} \u4E0D\u63A5\u53D7\u503C`);
30109
+ if (!value)
30110
+ throw new CliError(`\u9009\u9879 --${name} \u9700\u8981\u4E00\u4E2A\u503C`);
30111
+ flags[name] = value;
30072
30112
  } else {
30073
30113
  const next = argv[index + 1];
30074
- if (valueFlags.has(body) && next && !next.startsWith("--")) {
30114
+ if (VALUE_FLAGS.has(body)) {
30115
+ if (!next || next.startsWith("-"))
30116
+ throw new CliError(`\u9009\u9879 --${body} \u9700\u8981\u4E00\u4E2A\u503C`);
30075
30117
  flags[body] = next;
30076
30118
  index++;
30077
30119
  } else {
@@ -30091,6 +30133,17 @@ function flagValue(flags, name, fallback = "") {
30091
30133
  function hasFlag(flags, name) {
30092
30134
  return flags[name] === true || typeof flags[name] === "string" && flags[name] !== "";
30093
30135
  }
30136
+ function validateFlags(flags, allowed) {
30137
+ const accepted = new Set(["json", "user", ...allowed]);
30138
+ const unknown3 = Object.keys(flags).find((name) => !accepted.has(name));
30139
+ if (unknown3)
30140
+ throw new CliError(`\u672A\u77E5\u9009\u9879\uFF1A--${unknown3}`);
30141
+ }
30142
+ function validatePositionals(positional, min, max, usage) {
30143
+ if (positional.length < min || positional.length > max) {
30144
+ throw new CliError(`\u7528\u6CD5\uFF1Aharness-switch ${usage}`);
30145
+ }
30146
+ }
30094
30147
  function requirePositional(positional, index, what) {
30095
30148
  const value = positional[index];
30096
30149
  if (!value) {
@@ -30100,9 +30153,15 @@ function requirePositional(positional, index, what) {
30100
30153
  }
30101
30154
 
30102
30155
  class CliError extends Error {
30103
- constructor(message) {
30156
+ status;
30157
+ code;
30158
+ params;
30159
+ constructor(message, options = {}) {
30104
30160
  super(message);
30105
30161
  this.name = "CliError";
30162
+ this.status = options.status;
30163
+ this.code = options.code;
30164
+ this.params = options.params;
30106
30165
  }
30107
30166
  }
30108
30167
 
@@ -30116,13 +30175,14 @@ import { join as join16 } from "path";
30116
30175
 
30117
30176
  // src/daemon.ts
30118
30177
  import { spawn as spawn2 } from "child_process";
30119
- import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
30178
+ import { randomBytes as randomBytes5 } from "crypto";
30179
+ import { closeSync, mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
30120
30180
  import { homedir as homedir3 } from "os";
30121
30181
  import { join as join15, resolve as resolve3 } from "path";
30122
30182
  var DEFAULT_HOST = "127.0.0.1";
30123
30183
  var DEFAULT_PORT = 8787;
30124
30184
  var STOP_TIMEOUT_MS = 5000;
30125
- var START_GRACE_MS = 500;
30185
+ var START_TIMEOUT_MS = 5000;
30126
30186
  function daemonDataDir() {
30127
30187
  return process.env.HSW_DATA_DIR || join15(homedir3(), ".harness-switch");
30128
30188
  }
@@ -30132,11 +30192,15 @@ function daemonPidFile() {
30132
30192
  function daemonLogFile() {
30133
30193
  return join15(daemonDataDir(), "daemon.log");
30134
30194
  }
30135
- function readPid() {
30195
+ function readRecord() {
30136
30196
  try {
30137
30197
  const raw2 = readFileSync3(daemonPidFile(), "utf8").trim();
30138
- const pid = Number(raw2);
30139
- return Number.isInteger(pid) && pid > 0 ? pid : null;
30198
+ if (/^\d+$/.test(raw2)) {
30199
+ const pid = Number(raw2);
30200
+ return Number.isInteger(pid) && pid > 0 ? { version: 0, pid } : null;
30201
+ }
30202
+ const value = JSON.parse(raw2);
30203
+ return value.version === 1 && Number.isInteger(value.pid) && value.pid > 0 && typeof value.token === "string" && typeof value.host === "string" && typeof value.port === "number" && typeof value.startedAt === "string" ? value : null;
30140
30204
  } catch {
30141
30205
  return null;
30142
30206
  }
@@ -30168,81 +30232,159 @@ async function killProcess(pid) {
30168
30232
  return waitForExit(pid, 3000);
30169
30233
  }
30170
30234
  async function stopDaemon() {
30171
- const pid = readPid();
30172
- if (pid === null) {
30235
+ const record2 = readRecord();
30236
+ if (record2 === null) {
30173
30237
  console.log("no harness-switch daemon pid file found");
30174
- return;
30238
+ return 0;
30175
30239
  }
30240
+ const { pid } = record2;
30176
30241
  if (!isAlive(pid)) {
30177
30242
  console.log(`daemon pid ${pid} is not running; removing stale pid file`);
30178
30243
  try {
30179
30244
  unlinkSync(daemonPidFile());
30180
30245
  } catch {}
30181
- return;
30246
+ return 0;
30247
+ }
30248
+ if (!await isOwnedDaemon(record2)) {
30249
+ console.error(`refusing to stop pid ${pid}: the pid file does not identify a running harness-switch daemon`);
30250
+ return 1;
30182
30251
  }
30183
30252
  console.log(`stopping harness-switch daemon (pid ${pid})...`);
30184
- await killProcess(pid);
30253
+ if (!await killProcess(pid)) {
30254
+ console.error(`failed to stop harness-switch daemon (pid ${pid}); pid file kept`);
30255
+ return 1;
30256
+ }
30185
30257
  try {
30186
30258
  unlinkSync(daemonPidFile());
30187
30259
  } catch {}
30188
30260
  console.log("stopped");
30261
+ return 0;
30189
30262
  }
30190
- function printStatus() {
30191
- const pid = readPid();
30192
- const host = process.env.HOST || DEFAULT_HOST;
30193
- const port = Number(process.env.PORT || DEFAULT_PORT);
30194
- const running = pid !== null && isAlive(pid);
30195
- console.log(`harness-switch daemon: ${running ? `running (pid ${pid})` : "not running"}`);
30196
- console.log(` url: http://${host}:${port}`);
30263
+ async function printStatus() {
30264
+ const record2 = readRecord();
30265
+ const host = record2?.version === 1 ? record2.host : process.env.HOST || DEFAULT_HOST;
30266
+ const port = record2?.version === 1 ? record2.port : Number(process.env.PORT || DEFAULT_PORT);
30267
+ const owned = record2 !== null && isAlive(record2.pid) && await isOwnedDaemon(record2);
30268
+ const running = owned && (record2.version === 0 || await checkHealth(record2));
30269
+ console.log(`harness-switch daemon: ${running ? `running (pid ${record2.pid})` : "not running"}`);
30270
+ console.log(` url: ${httpOrigin(host, port)}`);
30197
30271
  console.log(` log: ${daemonLogFile()}`);
30198
30272
  console.log(` password: ${join15(daemonDataDir(), "web_password")}`);
30199
30273
  console.log(` data: ${daemonDataDir()}`);
30274
+ return running ? 0 : 1;
30200
30275
  }
30201
30276
  async function daemonize() {
30202
- const previous = readPid();
30203
- if (previous !== null && isAlive(previous)) {
30204
- console.log(`restarting harness-switch daemon (previous pid ${previous})...`);
30205
- await killProcess(previous);
30277
+ const previous = readRecord();
30278
+ if (previous !== null && isAlive(previous.pid)) {
30279
+ if (!await isOwnedDaemon(previous)) {
30280
+ console.error(`refusing to replace unverified pid ${previous.pid}; remove ${daemonPidFile()} after checking it`);
30281
+ return 1;
30282
+ }
30283
+ console.log(`restarting harness-switch daemon (previous pid ${previous.pid})...`);
30284
+ if (!await killProcess(previous.pid)) {
30285
+ console.error(`failed to stop previous daemon (pid ${previous.pid})`);
30286
+ return 1;
30287
+ }
30206
30288
  }
30207
30289
  mkdirSync4(daemonDataDir(), { recursive: true, mode: 448 });
30208
30290
  const entry = resolve3(process.argv[1] ?? "harness-switch.js");
30209
30291
  const logPath = daemonLogFile();
30292
+ const host = process.env.HOST || DEFAULT_HOST;
30293
+ const port = Number(process.env.PORT || DEFAULT_PORT);
30294
+ const token = randomBytes5(24).toString("base64url");
30210
30295
  const logFd = openSync2(logPath, "w");
30211
30296
  const child = spawn2(process.execPath, [entry, "server"], {
30212
30297
  detached: true,
30213
30298
  stdio: ["ignore", logFd, logFd],
30214
- env: process.env
30299
+ env: { ...process.env, HSW_DAEMON_TOKEN: token }
30215
30300
  });
30301
+ closeSync(logFd);
30216
30302
  child.unref();
30217
- await Bun.sleep(START_GRACE_MS);
30218
- if (child.exitCode !== null || child.signalCode !== null) {
30219
- console.error(`daemon exited immediately (code ${child.exitCode}); tail of ${logPath}:`);
30303
+ const record2 = {
30304
+ version: 1,
30305
+ pid: child.pid,
30306
+ token,
30307
+ host,
30308
+ port,
30309
+ startedAt: new Date().toISOString()
30310
+ };
30311
+ writeFileSync2(daemonPidFile(), `${JSON.stringify(record2, null, 2)}
30312
+ `, { mode: 384 });
30313
+ if (!await waitForReady(record2, START_TIMEOUT_MS)) {
30314
+ if (isAlive(record2.pid))
30315
+ await killProcess(record2.pid);
30316
+ removeRecordIfMatches(token);
30317
+ console.error(`daemon failed its health check; tail of ${logPath}:`);
30220
30318
  try {
30221
- const tail = (await Bun.file(logPath).text()).split(`
30319
+ console.error((await Bun.file(logPath).text()).split(`
30222
30320
  `).slice(-15).join(`
30223
- `);
30224
- console.error(tail);
30321
+ `));
30225
30322
  } catch {}
30226
- process.exit(1);
30323
+ return 1;
30227
30324
  }
30228
- writeFileSync2(daemonPidFile(), `${child.pid}
30229
- `, { mode: 384 });
30230
- const host = process.env.HOST || DEFAULT_HOST;
30231
- const port = Number(process.env.PORT || DEFAULT_PORT);
30232
30325
  console.log(`harness-switch daemon started (pid ${child.pid})`);
30233
30326
  console.log(` url: http://${host}:${port}`);
30234
30327
  console.log(` log: ${logPath}`);
30235
30328
  console.log(" manage: harness-switch status | harness-switch stop");
30236
30329
  console.log(` password (first run): ${join15(daemonDataDir(), "web_password")}`);
30330
+ return 0;
30237
30331
  }
30238
- function usage() {
30239
- return [
30240
- "usage: harness-switch [server|daemon|status|stop]",
30241
- " harness-switch [list|providers|doctor|plan|activate|users|sync] [options]",
30242
- " harness-switch [scan|import|operations|undo] [options]",
30243
- " CLI commands run against the local data directory; add --json for machine output"
30244
- ].join(`
30245
- `);
30332
+ async function isOwnedDaemon(record2) {
30333
+ if (!isAlive(record2.pid))
30334
+ return false;
30335
+ if (record2.version === 0)
30336
+ return processLooksLikeHarnessSwitch(record2.pid);
30337
+ if (processHasToken(record2.pid, record2.token))
30338
+ return true;
30339
+ return checkHealth(record2);
30340
+ }
30341
+ function processHasToken(pid, token) {
30342
+ try {
30343
+ return readFileSync3(`/proc/${pid}/environ`, "utf8").split("\x00").includes(`HSW_DAEMON_TOKEN=${token}`);
30344
+ } catch {
30345
+ return false;
30346
+ }
30347
+ }
30348
+ function processLooksLikeHarnessSwitch(pid) {
30349
+ try {
30350
+ return readFileSync3(`/proc/${pid}/cmdline`, "utf8").includes("harness-switch");
30351
+ } catch {
30352
+ return false;
30353
+ }
30354
+ }
30355
+ async function waitForReady(record2, timeoutMs) {
30356
+ const deadline = Date.now() + timeoutMs;
30357
+ while (Date.now() < deadline) {
30358
+ if (!isAlive(record2.pid))
30359
+ return false;
30360
+ if (await checkHealth(record2))
30361
+ return true;
30362
+ await Bun.sleep(100);
30363
+ }
30364
+ return false;
30365
+ }
30366
+ async function checkHealth(record2) {
30367
+ try {
30368
+ const response = await fetch(`${httpOrigin(record2.host, record2.port)}/healthz`, {
30369
+ signal: AbortSignal.timeout(500)
30370
+ });
30371
+ const payload = await response.json();
30372
+ return response.ok && payload.ok === true && payload.instance === record2.token;
30373
+ } catch {
30374
+ return false;
30375
+ }
30376
+ }
30377
+ function httpOrigin(host, port) {
30378
+ const connectHost = host === "0.0.0.0" ? "127.0.0.1" : host === "::" ? "::1" : host;
30379
+ return `http://${connectHost.includes(":") ? `[${connectHost}]` : connectHost}:${port}`;
30380
+ }
30381
+ function removeRecordIfMatches(token) {
30382
+ const record2 = readRecord();
30383
+ if (record2?.version !== 1 || record2.token !== token)
30384
+ return;
30385
+ try {
30386
+ unlinkSync(daemonPidFile());
30387
+ } catch {}
30246
30388
  }
30247
30389
 
30248
30390
  // src/cli/client.ts
@@ -30263,16 +30405,31 @@ class CliClient {
30263
30405
  const setCookie2 = response.headers.get("set-cookie") ?? "";
30264
30406
  const match2 = /hsw_session=([^;]+)/.exec(setCookie2);
30265
30407
  if (!response.ok || !match2) {
30266
- throw new CliError(response.ok ? "\u767B\u5F55\u5931\u8D25\uFF1A\u670D\u52A1\u7AEF\u672A\u8FD4\u56DE\u4F1A\u8BDD" : `\u767B\u5F55\u5931\u8D25\uFF1A${await errorMessage(response)}`);
30408
+ if (response.ok)
30409
+ throw new CliError("\u767B\u5F55\u5931\u8D25\uFF1A\u670D\u52A1\u7AEF\u672A\u8FD4\u56DE\u4F1A\u8BDD");
30410
+ const error52 = await responseError(response);
30411
+ throw new CliError(`\u767B\u5F55\u5931\u8D25\uFF1A${error52.message}`, error52);
30267
30412
  }
30268
30413
  this.cookie = match2[1];
30269
30414
  }
30415
+ async logout() {
30416
+ if (!this.cookie)
30417
+ return;
30418
+ try {
30419
+ await this.request("POST", "/api/auth/logout");
30420
+ } finally {
30421
+ this.cookie = "";
30422
+ }
30423
+ }
30270
30424
  async get(path) {
30271
30425
  return this.request("GET", path);
30272
30426
  }
30273
30427
  async post(path, body) {
30274
30428
  return this.request("POST", path, body);
30275
30429
  }
30430
+ async delete(path) {
30431
+ return this.request("DELETE", path);
30432
+ }
30276
30433
  async request(method, path, body) {
30277
30434
  const response = await this.fetch(path, {
30278
30435
  method,
@@ -30284,8 +30441,11 @@ class CliClient {
30284
30441
  });
30285
30442
  const payload = await response.json().catch(() => null);
30286
30443
  if (!response.ok) {
30287
- const message = payload && typeof payload.error === "string" ? payload.error : `\u8BF7\u6C42\u5931\u8D25\uFF1AHTTP ${response.status}`;
30288
- throw new CliError(message);
30444
+ throw new CliError(payload && typeof payload.error === "string" ? payload.error : `\u8BF7\u6C42\u5931\u8D25\uFF1AHTTP ${response.status}`, {
30445
+ status: response.status,
30446
+ ...payload && typeof payload.code === "string" ? { code: payload.code } : {},
30447
+ ...payload && isMessageParams(payload.params) ? { params: payload.params } : {}
30448
+ });
30289
30449
  }
30290
30450
  return payload;
30291
30451
  }
@@ -30308,14 +30468,21 @@ function readWebPassword() {
30308
30468
  throw new CliError(`\u672A\u627E\u5230 ${file2}\u3002\u8BF7\u5148\u8FD0\u884C\u4E00\u6B21\u670D\u52A1\uFF08harness-switch daemon \u6216 server\uFF09\u751F\u6210\u5BC6\u7801\uFF0C\u518D\u4F7F\u7528 CLI\u3002`);
30309
30469
  }
30310
30470
  }
30311
- async function errorMessage(response) {
30471
+ async function responseError(response) {
30312
30472
  try {
30313
30473
  const payload = await response.json();
30314
- if (typeof payload.error === "string") {
30315
- return payload.error;
30316
- }
30317
- } catch {}
30318
- return `HTTP ${response.status}`;
30474
+ return {
30475
+ message: typeof payload.error === "string" ? payload.error : `HTTP ${response.status}`,
30476
+ status: response.status,
30477
+ ...typeof payload.code === "string" ? { code: payload.code } : {},
30478
+ ...isMessageParams(payload.params) ? { params: payload.params } : {}
30479
+ };
30480
+ } catch {
30481
+ return { message: `HTTP ${response.status}`, status: response.status };
30482
+ }
30483
+ }
30484
+ function isMessageParams(value) {
30485
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean");
30319
30486
  }
30320
30487
 
30321
30488
  // src/cli/output.ts
@@ -30340,6 +30507,16 @@ function printProvidersHuman(items) {
30340
30507
  console.log(`${entry.id.padEnd(24)} ${entry.name.padEnd(20)} ${configured.padEnd(9)} endpoints=${endpoints}`);
30341
30508
  }
30342
30509
  }
30510
+ function printProfilesHuman(items) {
30511
+ if (items.length === 0) {
30512
+ console.log("(no profiles)");
30513
+ return;
30514
+ }
30515
+ for (const profile of items) {
30516
+ const provider = profile.providerId ? `vault=${profile.providerId}` : "key=inline";
30517
+ console.log(`${profile.harness.padEnd(8)} ${profile.name.padEnd(20)} ${profile.model || "-"} ${provider}`);
30518
+ }
30519
+ }
30343
30520
  function printDoctorHuman(report) {
30344
30521
  console.log(`harness-switch doctor updateAvailable=${report.updatedAvailable}`);
30345
30522
  for (const item of report.items) {
@@ -30425,28 +30602,40 @@ function cliUsage() {
30425
30602
  "",
30426
30603
  "commands:",
30427
30604
  " list list harnesses, active profiles and live targets",
30605
+ " profiles [harness] list saved profiles without credential material",
30606
+ " create <harness> <name> create a profile from command-line options",
30607
+ " delete <harness> <profile> delete an inactive profile (confirmation required)",
30428
30608
  " providers list Provider Vault entries",
30429
- " doctor [--probe] [--harness H] run diagnostics (add --probe for /models checks)",
30609
+ " doctor [--probe] [--strict] run diagnostics; probe reports endpoint metadata only",
30430
30610
  " plan <harness> <profile> show the exact content activation would write",
30431
30611
  " activate <harness> <profile> activate a profile (add --yes to skip the prompt)",
30612
+ " official <harness> return a harness to its built-in login",
30432
30613
  " users list manageable local Unix users",
30433
30614
  " sync --from USER --to USER copy profiles and credentials between users",
30434
30615
  " scan find configuration the five tools already have",
30435
30616
  " import <id>... [--vault] save scanned configuration as profiles",
30436
30617
  " operations list operation receipts, newest first",
30437
30618
  " undo <operation-id> revert one complete operation",
30619
+ " version print the installed version",
30620
+ " help show this help",
30438
30621
  "",
30439
30622
  "options:",
30440
- " --json machine-readable JSON output",
30441
- " --yes skip confirmation for activate",
30442
- " --probe run the /models connectivity probe in doctor",
30623
+ " --json, -j machine-readable JSON output",
30624
+ " --yes, -y skip confirmation for activate, official and delete",
30625
+ " --probe show connectivity endpoint metadata (no network request yet)",
30443
30626
  " --harness H limit doctor to one harness",
30444
- " --user USER run list/providers/doctor/plan/activate for this Unix user",
30627
+ " --strict make doctor exit 1 when any check has error status",
30628
+ " --user USER run an API-backed command for this Unix user",
30445
30629
  " --overwrite overwrite same-name profiles during sync and import (default: skip)",
30446
30630
  " --copy-codex-auth copy the source user\u2019s Codex auth.json during sync",
30447
30631
  " --vault import extracts the credential into a Provider Vault entry",
30448
30632
  " --name NAME profile name for a single import (default: the provider id)",
30449
- " --api-key KEY credential for a provider whose key lives in the shell",
30633
+ " --api-key KEY inline credential for create/import (prefer --api-key-env)",
30634
+ " --api-key-env VAR read a create/import credential from an environment variable",
30635
+ " --base-url URL --model MODEL --notes TEXT profile fields used by create",
30636
+ " --provider ID [--endpoint KEY] create a profile backed by Provider Vault",
30637
+ " --help, -h show help without connecting to the service",
30638
+ " --version, -V print the installed version",
30450
30639
  "",
30451
30640
  "environment:",
30452
30641
  " HSW_URL base URL of the local service (default http://127.0.0.1:8787)",
@@ -30459,21 +30648,32 @@ function cliUsage() {
30459
30648
  // src/cli/commands.ts
30460
30649
  async function runCli(command, positional, flags) {
30461
30650
  const json2 = hasFlag(flags, "json") ? "json" : "human";
30651
+ try {
30652
+ validateCommand(command, positional, flags);
30653
+ } catch (error52) {
30654
+ return fail(error52, json2);
30655
+ }
30462
30656
  let client;
30463
30657
  try {
30464
30658
  client = new CliClient(resolveBaseUrl(), readWebPassword());
30465
30659
  await client.login();
30466
- const selectedUser = flagValue(flags, "user");
30467
- if (selectedUser) {
30468
- await selectUser(client, selectedUser);
30469
- }
30470
30660
  } catch (error52) {
30471
30661
  return fail(error52, json2);
30472
30662
  }
30473
30663
  try {
30664
+ const selectedUser = flagValue(flags, "user");
30665
+ if (selectedUser) {
30666
+ await selectUser(client, selectedUser);
30667
+ }
30474
30668
  switch (command) {
30475
30669
  case "list":
30476
30670
  return await cmdList(client, json2);
30671
+ case "profiles":
30672
+ return await cmdProfiles(client, positional, json2);
30673
+ case "create":
30674
+ return await cmdCreate(client, positional, flags, json2);
30675
+ case "delete":
30676
+ return await cmdDelete(client, positional, flags, json2);
30477
30677
  case "providers":
30478
30678
  return await cmdProviders(client, json2);
30479
30679
  case "doctor":
@@ -30482,6 +30682,8 @@ async function runCli(command, positional, flags) {
30482
30682
  return await cmdPlan(client, positional, json2);
30483
30683
  case "activate":
30484
30684
  return await cmdActivate(client, positional, flags, json2);
30685
+ case "official":
30686
+ return await cmdOfficial(client, positional, flags, json2);
30485
30687
  case "users":
30486
30688
  return await cmdUsers(client, json2);
30487
30689
  case "sync":
@@ -30500,8 +30702,61 @@ async function runCli(command, positional, flags) {
30500
30702
  }
30501
30703
  } catch (error52) {
30502
30704
  return fail(error52, json2);
30705
+ } finally {
30706
+ await client.logout().catch(() => {
30707
+ return;
30708
+ });
30503
30709
  }
30504
30710
  }
30711
+ function validateCommand(command, positional, flags) {
30712
+ const specs = {
30713
+ list: { min: 0, max: 0, usage: "list [options]" },
30714
+ profiles: { min: 0, max: 1, usage: "profiles [harness] [options]" },
30715
+ create: {
30716
+ flags: ["base-url", "model", "notes", "api-key", "api-key-env", "provider", "endpoint"],
30717
+ min: 2,
30718
+ max: 2,
30719
+ usage: "create <harness> <name> [options]"
30720
+ },
30721
+ delete: { flags: ["yes"], min: 2, max: 2, usage: "delete <harness> <profile> [--yes]" },
30722
+ providers: { min: 0, max: 0, usage: "providers [options]" },
30723
+ doctor: {
30724
+ flags: ["probe", "harness", "strict"],
30725
+ min: 0,
30726
+ max: 0,
30727
+ usage: "doctor [--probe] [--harness H] [--strict]"
30728
+ },
30729
+ plan: { min: 2, max: 2, usage: "plan <harness> <profile> [options]" },
30730
+ activate: {
30731
+ flags: ["yes"],
30732
+ min: 2,
30733
+ max: 2,
30734
+ usage: "activate <harness> <profile> [--yes]"
30735
+ },
30736
+ official: { flags: ["yes"], min: 1, max: 1, usage: "official <harness> [--yes]" },
30737
+ users: { min: 0, max: 0, usage: "users [options]" },
30738
+ sync: {
30739
+ flags: ["from", "to", "overwrite", "copy-codex-auth"],
30740
+ min: 0,
30741
+ max: 0,
30742
+ usage: "sync --from USER --to USER [options]"
30743
+ },
30744
+ scan: { min: 0, max: 0, usage: "scan [options]" },
30745
+ import: {
30746
+ flags: ["vault", "name", "api-key", "api-key-env", "overwrite"],
30747
+ min: 1,
30748
+ max: Number.POSITIVE_INFINITY,
30749
+ usage: "import <id>... [options]"
30750
+ },
30751
+ operations: { min: 0, max: 0, usage: "operations [options]" },
30752
+ undo: { min: 1, max: 1, usage: "undo <operation-id> [options]" }
30753
+ };
30754
+ const spec = specs[command];
30755
+ if (!spec)
30756
+ return;
30757
+ validateFlags(flags, spec.flags ?? []);
30758
+ validatePositionals(positional, spec.min, spec.max, spec.usage);
30759
+ }
30505
30760
  async function selectUser(client, username) {
30506
30761
  await client.post(`/api/users/${encodeURIComponent(username)}/select`);
30507
30762
  }
@@ -30547,6 +30802,47 @@ async function cmdList(client, json2) {
30547
30802
  }
30548
30803
  return 0;
30549
30804
  }
30805
+ async function cmdProfiles(client, positional, json2) {
30806
+ const harness = positional[0];
30807
+ const payload = await client.get(harness ? `/api/harnesses/${encodeURIComponent(harness)}` : "/api/harnesses");
30808
+ const items = "items" in payload ? payload.items.flatMap((item) => item.profiles) : payload.profiles;
30809
+ if (json2 === "json")
30810
+ printJson({ items });
30811
+ else
30812
+ printProfilesHuman(items);
30813
+ return 0;
30814
+ }
30815
+ async function cmdCreate(client, positional, flags, json2) {
30816
+ const harness = requirePositional(positional, 0, "harness");
30817
+ const name = requirePositional(positional, 1, "name");
30818
+ const apiKey = credentialFromFlags(flags);
30819
+ const payload = await client.post(`/api/harnesses/${encodeURIComponent(harness)}/profiles`, {
30820
+ name,
30821
+ baseUrl: flagValue(flags, "base-url"),
30822
+ model: flagValue(flags, "model"),
30823
+ notes: flagValue(flags, "notes"),
30824
+ ...apiKey ? { apiKey } : {},
30825
+ ...flagValue(flags, "provider") ? { providerId: flagValue(flags, "provider") } : {},
30826
+ ...flagValue(flags, "endpoint") ? { providerEndpoint: flagValue(flags, "endpoint") } : {}
30827
+ });
30828
+ if (json2 === "json")
30829
+ printJson(payload);
30830
+ else
30831
+ console.log(`\u5DF2\u521B\u5EFA ${payload.harness}/${payload.name}`);
30832
+ return 0;
30833
+ }
30834
+ async function cmdDelete(client, positional, flags, json2) {
30835
+ const harness = requirePositional(positional, 0, "harness");
30836
+ const profile = requirePositional(positional, 1, "profile");
30837
+ if (!await confirmMutation(`\u786E\u8BA4\u5220\u9664 ${harness}/${profile}\uFF1F[y/N] `, flags, json2))
30838
+ return 0;
30839
+ const payload = await client.delete(`/api/harnesses/${encodeURIComponent(harness)}/profiles/${encodeURIComponent(profile)}`);
30840
+ if (json2 === "json")
30841
+ printJson({ harness, profile, ...payload });
30842
+ else
30843
+ console.log(`\u5DF2\u5220\u9664 ${harness}/${profile}`);
30844
+ return 0;
30845
+ }
30550
30846
  async function cmdProviders(client, json2) {
30551
30847
  const payload = await client.get("/api/providers");
30552
30848
  if (json2 === "json") {
@@ -30572,7 +30868,7 @@ async function cmdDoctor(client, flags, json2) {
30572
30868
  } else {
30573
30869
  printDoctorHuman(payload);
30574
30870
  }
30575
- return 0;
30871
+ return hasFlag(flags, "strict") && payload.items.some((item) => item.checks.some((check2) => check2.status === "error")) ? 1 : 0;
30576
30872
  }
30577
30873
  async function cmdPlan(client, positional, json2) {
30578
30874
  const harness = requirePositional(positional, 0, "harness");
@@ -30589,24 +30885,12 @@ async function cmdActivate(client, positional, flags, json2) {
30589
30885
  const harness = requirePositional(positional, 0, "harness");
30590
30886
  const profile = requirePositional(positional, 1, "profile");
30591
30887
  if (!hasFlag(flags, "yes")) {
30592
- if (!stdin.isTTY) {
30593
- throw new CliError("\u975E\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u9700\u8981 --yes \u786E\u8BA4\u624D\u80FD\u6FC0\u6D3B");
30594
- }
30595
30888
  const preview = await client.get(`/api/harnesses/${encodeURIComponent(harness)}/profiles/${encodeURIComponent(profile)}/preview`);
30596
30889
  if (json2 === "human") {
30597
30890
  printPlanHuman(harness, profile, preview.targets);
30598
30891
  }
30599
- const readline = createInterface({ input: stdin, output: stdout });
30600
- const answer = (await readline.question(`\u786E\u8BA4\u6FC0\u6D3B ${harness}/${profile}\uFF1F[y/N] `)).trim().toLowerCase();
30601
- readline.close();
30602
- if (answer !== "y" && answer !== "yes") {
30603
- if (json2 === "json") {
30604
- printJson({ cancelled: true });
30605
- } else {
30606
- console.log("\u5DF2\u53D6\u6D88");
30607
- }
30892
+ if (!await confirmMutation(`\u786E\u8BA4\u6FC0\u6D3B ${harness}/${profile}\uFF1F[y/N] `, flags, json2))
30608
30893
  return 0;
30609
- }
30610
30894
  }
30611
30895
  const payload = await client.post(`/api/harnesses/${encodeURIComponent(harness)}/profiles/${encodeURIComponent(profile)}/activate`);
30612
30896
  if (json2 === "json") {
@@ -30616,6 +30900,17 @@ async function cmdActivate(client, positional, flags, json2) {
30616
30900
  }
30617
30901
  return 0;
30618
30902
  }
30903
+ async function cmdOfficial(client, positional, flags, json2) {
30904
+ const harness = requirePositional(positional, 0, "harness");
30905
+ if (!await confirmMutation(`\u786E\u8BA4\u8BA9 ${harness} \u6062\u590D\u5B98\u65B9\u767B\u5F55\uFF1F[y/N] `, flags, json2))
30906
+ return 0;
30907
+ const payload = await client.post(`/api/harnesses/${encodeURIComponent(harness)}/official/activate`);
30908
+ if (json2 === "json")
30909
+ printJson({ harness, official: true, ...payload });
30910
+ else
30911
+ printActivateHuman(harness, "official", payload);
30912
+ return 0;
30913
+ }
30619
30914
  async function cmdScan(client, json2) {
30620
30915
  const payload = await client.get("/api/scan");
30621
30916
  if (json2 === "json") {
@@ -30634,7 +30929,7 @@ async function cmdImport(client, positional, flags, json2) {
30634
30929
  if (name && positional.length > 1) {
30635
30930
  throw new CliError("--name \u53EA\u80FD\u7528\u4E8E\u5355\u6761\u5BFC\u5165");
30636
30931
  }
30637
- const apiKey = flagValue(flags, "api-key");
30932
+ const apiKey = credentialFromFlags(flags);
30638
30933
  const overwrite = hasFlag(flags, "overwrite");
30639
30934
  const selections = positional.map((id) => ({
30640
30935
  id,
@@ -30655,6 +30950,34 @@ async function cmdImport(client, positional, flags, json2) {
30655
30950
  }
30656
30951
  return payload.skipped > 0 && payload.imported === 0 ? 1 : 0;
30657
30952
  }
30953
+ function credentialFromFlags(flags) {
30954
+ const inline = flagValue(flags, "api-key");
30955
+ const envName = flagValue(flags, "api-key-env");
30956
+ if (inline && envName)
30957
+ throw new CliError("--api-key \u4E0E --api-key-env \u4E0D\u80FD\u540C\u65F6\u4F7F\u7528");
30958
+ if (!envName)
30959
+ return inline;
30960
+ const value = process.env[envName];
30961
+ if (!value)
30962
+ throw new CliError(`\u73AF\u5883\u53D8\u91CF ${envName} \u672A\u8BBE\u7F6E\u6216\u4E3A\u7A7A`);
30963
+ return value;
30964
+ }
30965
+ async function confirmMutation(prompt, flags, json2) {
30966
+ if (hasFlag(flags, "yes"))
30967
+ return true;
30968
+ if (!stdin.isTTY)
30969
+ throw new CliError("\u975E\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u9700\u8981 --yes \u786E\u8BA4\u6B64\u64CD\u4F5C");
30970
+ const readline = createInterface({ input: stdin, output: stdout });
30971
+ const answer = (await readline.question(prompt)).trim().toLowerCase();
30972
+ readline.close();
30973
+ if (answer === "y" || answer === "yes")
30974
+ return true;
30975
+ if (json2 === "json")
30976
+ printJson({ cancelled: true });
30977
+ else
30978
+ console.log("\u5DF2\u53D6\u6D88");
30979
+ return false;
30980
+ }
30658
30981
  async function cmdOperations(client, json2) {
30659
30982
  const payload = await client.get("/api/operations");
30660
30983
  if (json2 === "json") {
@@ -30678,7 +31001,15 @@ async function cmdUndo(client, positional, json2) {
30678
31001
  function fail(error52, json2) {
30679
31002
  const message = error52 instanceof Error ? error52.message : String(error52);
30680
31003
  if (json2 === "json") {
30681
- printJson({ error: { code: 1, message } });
31004
+ const cliError = error52 instanceof CliError ? error52 : undefined;
31005
+ printJson({
31006
+ error: {
31007
+ code: cliError?.code ?? 1,
31008
+ message,
31009
+ ...cliError?.status ? { status: cliError.status } : {},
31010
+ ...cliError?.params ? { params: cliError.params } : {}
31011
+ }
31012
+ });
30682
31013
  } else {
30683
31014
  console.error(`error: ${message}`);
30684
31015
  }
@@ -30704,19 +31035,36 @@ async function runServer() {
30704
31035
  log.info(`listening on http://${server.hostname}:${server.port}`);
30705
31036
  }
30706
31037
  var [command, ...rest] = process.argv.slice(2);
30707
- if (command === "server") {
31038
+ if (command === "help" || command === "--help" || command === "-h") {
31039
+ console.log(cliUsage());
31040
+ } else if (command === "version" || command === "--version" || command === "-V") {
31041
+ console.log(await serverVersion());
31042
+ } else if (rest.includes("--help") || rest.includes("-h")) {
31043
+ console.log(cliUsage());
31044
+ } else if (rest.includes("--version") || rest.includes("-V")) {
31045
+ console.log(await serverVersion());
31046
+ } else if (command === "server") {
30708
31047
  await runServer();
30709
31048
  } else if (command === "stop") {
30710
- await stopDaemon();
31049
+ process.exitCode = await stopDaemon();
30711
31050
  } else if (command === "status") {
30712
- printStatus();
30713
- } else if (command === "list" || command === "providers" || command === "doctor" || command === "plan" || command === "activate" || command === "users" || command === "sync" || command === "scan" || command === "import" || command === "operations" || command === "undo") {
30714
- const { flags, positional } = parseArgs(rest);
30715
- process.exitCode = await runCli(command, positional, flags);
31051
+ process.exitCode = await printStatus();
31052
+ } else if (command === "list" || command === "profiles" || command === "create" || command === "delete" || command === "providers" || command === "doctor" || command === "plan" || command === "activate" || command === "official" || command === "users" || command === "sync" || command === "scan" || command === "import" || command === "operations" || command === "undo") {
31053
+ try {
31054
+ const { flags, positional } = parseArgs(rest);
31055
+ process.exitCode = await runCli(command, positional, flags);
31056
+ } catch (error52) {
31057
+ const message = error52 instanceof Error ? error52.message : String(error52);
31058
+ if (rest.includes("--json") || rest.includes("-j"))
31059
+ printJson({ error: { code: 1, message } });
31060
+ else
31061
+ console.error(`error: ${message}`);
31062
+ process.exitCode = 1;
31063
+ }
30716
31064
  } else if (command === undefined || command === "daemon") {
30717
- await daemonize();
31065
+ process.exitCode = await daemonize();
30718
31066
  } else {
30719
31067
  console.error(`unknown command: ${command}`);
30720
- console.error(usage());
31068
+ console.error(cliUsage());
30721
31069
  process.exit(1);
30722
31070
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seaveyon/harness-switch",
3
- "version": "0.17.0",
3
+ "version": "0.18.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",