@seaveyon/harness-switch 0.12.0 → 0.14.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.
@@ -7014,7 +7014,7 @@ var require_public_api = __commonJS((exports) => {
7014
7014
  });
7015
7015
 
7016
7016
  // src/app.ts
7017
- import { existsSync as existsSync3 } from "fs";
7017
+ import { existsSync as existsSync4 } from "fs";
7018
7018
  import { join as join11 } from "path";
7019
7019
 
7020
7020
  // ../../node_modules/hono/dist/compose.js
@@ -9184,40 +9184,75 @@ class InstantiationService {
9184
9184
  import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
9185
9185
 
9186
9186
  // src/services/environment.ts
9187
+ import { AsyncLocalStorage } from "async_hooks";
9187
9188
  import { existsSync, mkdirSync } from "fs";
9188
- import { homedir } from "os";
9189
+ import { homedir, userInfo } from "os";
9189
9190
  import { join as join2 } from "path";
9190
9191
  var IEnvironmentService = createDecorator("environmentService");
9191
9192
 
9192
9193
  class EnvironmentService {
9193
9194
  host = process.env.HOST || "127.0.0.1";
9194
9195
  port = Number(process.env.PORT || 8787);
9195
- homeDir = process.env.HSW_HOME_DIR || homedir();
9196
- dataDir = process.env.HSW_DATA_DIR || join2(this.homeDir, ".harness-switch");
9197
9196
  publicDir = process.env.HSW_PUBLIC_DIR || resolvePublicDir();
9198
9197
  sessionTtlMs = resolveSessionTtlMs();
9199
9198
  cookieName = "hsw_session";
9200
- files = {
9201
- profiles: join2(this.dataDir, "profiles.json"),
9202
- active: join2(this.dataDir, "active.json"),
9203
- password: join2(this.dataDir, "web_password"),
9204
- key: join2(this.dataDir, "aes-256-gcm.key"),
9205
- env: join2(this.dataDir, "env.sh"),
9206
- sessions: join2(this.dataDir, "sessions.json"),
9207
- vault: join2(this.dataDir, "vault.json")
9208
- };
9209
- backupsDir = join2(this.dataDir, "backups");
9210
9199
  backupRetainCount = Math.max(1, Number(process.env.HSW_BACKUP_RETAIN || 10));
9211
- harnessHomes = {
9212
- claude: join2(this.homeDir, ".claude"),
9213
- codex: process.env.CODEX_HOME || join2(this.homeDir, ".codex"),
9214
- kimiCode: process.env.KIMI_CODE_HOME || join2(this.homeDir, ".kimi-code"),
9215
- piAgent: process.env.PI_CODING_AGENT_DIR || join2(this.homeDir, ".pi", "agent"),
9216
- dsh: process.env.DSH_HOME || join2(this.homeDir, ".dsh")
9200
+ defaultUser = resolveDefaultUser();
9201
+ managerDataDir = process.env.HSW_DATA_DIR || join2(this.defaultUser.homeDir, ".harness-switch");
9202
+ managerFiles = {
9203
+ password: join2(this.managerDataDir, "web_password"),
9204
+ sessions: join2(this.managerDataDir, "sessions.json")
9217
9205
  };
9206
+ userContext = new AsyncLocalStorage;
9207
+ get currentUser() {
9208
+ return this.userContext.getStore() ?? this.defaultUser;
9209
+ }
9210
+ get homeDir() {
9211
+ return this.currentUser.homeDir;
9212
+ }
9213
+ get dataDir() {
9214
+ return this.currentUser.username === this.defaultUser.username ? this.managerDataDir : join2(this.homeDir, ".harness-switch");
9215
+ }
9216
+ get files() {
9217
+ const dataDir = this.dataDir;
9218
+ return {
9219
+ profiles: join2(dataDir, "profiles.json"),
9220
+ active: join2(dataDir, "active.json"),
9221
+ password: join2(dataDir, "web_password"),
9222
+ key: join2(dataDir, "aes-256-gcm.key"),
9223
+ env: join2(dataDir, "env.sh"),
9224
+ sessions: join2(dataDir, "sessions.json"),
9225
+ vault: join2(dataDir, "vault.json")
9226
+ };
9227
+ }
9228
+ get backupsDir() {
9229
+ return join2(this.dataDir, "backups");
9230
+ }
9231
+ get harnessHomes() {
9232
+ const isDefault = this.currentUser.username === this.defaultUser.username;
9233
+ return {
9234
+ claude: join2(this.homeDir, ".claude"),
9235
+ codex: isDefault && process.env.CODEX_HOME ? process.env.CODEX_HOME : join2(this.homeDir, ".codex"),
9236
+ kimiCode: isDefault && process.env.KIMI_CODE_HOME ? process.env.KIMI_CODE_HOME : join2(this.homeDir, ".kimi-code"),
9237
+ piAgent: isDefault && process.env.PI_CODING_AGENT_DIR ? process.env.PI_CODING_AGENT_DIR : join2(this.homeDir, ".pi", "agent"),
9238
+ dsh: isDefault && process.env.DSH_HOME ? process.env.DSH_HOME : join2(this.homeDir, ".dsh")
9239
+ };
9240
+ }
9218
9241
  ensureDataDir() {
9219
9242
  mkdirSync(this.dataDir, { recursive: true, mode: 448 });
9220
9243
  }
9244
+ runAsUser(user, callback) {
9245
+ return this.userContext.run(user, callback);
9246
+ }
9247
+ }
9248
+ function resolveDefaultUser() {
9249
+ const info = userInfo();
9250
+ return {
9251
+ username: info.username,
9252
+ uid: info.uid,
9253
+ gid: info.gid,
9254
+ homeDir: process.env.HSW_HOME_DIR || homedir()
9255
+ };
9221
9256
  }
9222
9257
  function resolveSessionTtlMs() {
9223
9258
  const hours = Number(process.env.HSW_SESSION_TTL_HOURS || 24);
@@ -9236,6 +9271,7 @@ function resolvePublicDir() {
9236
9271
  import { randomBytes } from "crypto";
9237
9272
  import {
9238
9273
  chmodSync,
9274
+ chownSync,
9239
9275
  existsSync as existsSync2,
9240
9276
  mkdirSync as mkdirSync2,
9241
9277
  readdirSync,
@@ -9296,7 +9332,6 @@ class FileService {
9296
9332
  }
9297
9333
  }
9298
9334
  writeSecure(file, text) {
9299
- this.environment.ensureDataDir();
9300
9335
  this.write(file, text, 384);
9301
9336
  }
9302
9337
  writeUserFile(file, text) {
@@ -9314,7 +9349,22 @@ class FileService {
9314
9349
  `);
9315
9350
  }
9316
9351
  ensureDir(dir) {
9352
+ const missing = [];
9353
+ let cursor = dir;
9354
+ while (!existsSync2(cursor)) {
9355
+ missing.push(cursor);
9356
+ const parent = dirname2(cursor);
9357
+ if (parent === cursor)
9358
+ break;
9359
+ cursor = parent;
9360
+ }
9317
9361
  mkdirSync2(dir, { recursive: true, mode: 448 });
9362
+ for (const created of missing.toReversed()) {
9363
+ this.applyOwner(created, this.environment.currentUser.uid, this.environment.currentUser.gid);
9364
+ try {
9365
+ chmodSync(created, 448);
9366
+ } catch {}
9367
+ }
9318
9368
  }
9319
9369
  remove(file) {
9320
9370
  rmSync(file, { force: true, recursive: true });
@@ -9329,7 +9379,9 @@ class FileService {
9329
9379
  write(file, text, mode) {
9330
9380
  this.ensureDir(dirname2(file));
9331
9381
  const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
9382
+ const owner = this.ownerOf(file);
9332
9383
  writeFileSync(tmp, text, { encoding: "utf8", mode });
9384
+ this.applyOwner(tmp, owner.uid, owner.gid);
9333
9385
  renameSync(tmp, file);
9334
9386
  try {
9335
9387
  chmodSync(file, mode);
@@ -9342,6 +9394,27 @@ class FileService {
9342
9394
  return 384;
9343
9395
  }
9344
9396
  }
9397
+ ownerOf(file) {
9398
+ try {
9399
+ const stat2 = statSync(file);
9400
+ return { uid: stat2.uid, gid: stat2.gid };
9401
+ } catch {
9402
+ return { uid: this.environment.currentUser.uid, gid: this.environment.currentUser.gid };
9403
+ }
9404
+ }
9405
+ applyOwner(path, uid, gid) {
9406
+ if (process.platform === "win32")
9407
+ return;
9408
+ try {
9409
+ chownSync(path, uid, gid);
9410
+ } catch (error) {
9411
+ if (uid !== process.getuid?.() || gid !== process.getgid?.()) {
9412
+ throw new HttpError(403, `\u65E0\u6CD5\u628A ${path} \u7684\u6240\u6709\u6743\u8BBE\u7F6E\u4E3A ${this.environment.currentUser.username}\uFF0C\u8DE8\u7528\u6237\u7BA1\u7406\u9700\u8981\u4EE5 root \u8FD0\u884C`);
9413
+ }
9414
+ if (error.code !== "EPERM")
9415
+ throw error;
9416
+ }
9417
+ }
9345
9418
  }
9346
9419
  FileService = __decorateElement(_init, 0, "FileService", _dec, FileService);
9347
9420
  __runInitializers(_init, 1, FileService);
@@ -9456,7 +9529,7 @@ class AuthService {
9456
9529
  this.log = log;
9457
9530
  }
9458
9531
  ensurePassword() {
9459
- const file = this.environment.files.password;
9532
+ const file = this.environment.managerFiles.password;
9460
9533
  if (!this.files.exists(file)) {
9461
9534
  const password = this.crypto.randomPassword();
9462
9535
  this.files.writeSecure(file, `${password}
@@ -9472,7 +9545,8 @@ class AuthService {
9472
9545
  }
9473
9546
  const token = randomBytes3(32).toString("base64url");
9474
9547
  this.load().set(digest("session", token), {
9475
- expires: Date.now() + this.environment.sessionTtlMs
9548
+ expires: Date.now() + this.environment.sessionTtlMs,
9549
+ username: this.environment.defaultUser.username
9476
9550
  });
9477
9551
  this.persist();
9478
9552
  return token;
@@ -9497,13 +9571,29 @@ class AuthService {
9497
9571
  }
9498
9572
  return true;
9499
9573
  }
9574
+ userForToken(token) {
9575
+ if (!this.isAuthenticated(token) || !token) {
9576
+ return;
9577
+ }
9578
+ return this.load().get(digest("session", token))?.username;
9579
+ }
9580
+ selectUser(token, username) {
9581
+ if (!this.isAuthenticated(token) || !token) {
9582
+ return;
9583
+ }
9584
+ const session = this.load().get(digest("session", token));
9585
+ if (session) {
9586
+ session.username = username;
9587
+ this.persist();
9588
+ }
9589
+ }
9500
9590
  load() {
9501
9591
  const loaded = this.sessions;
9502
9592
  if (loaded) {
9503
9593
  return loaded;
9504
9594
  }
9505
9595
  this.fingerprint = digest("password", this.ensurePassword());
9506
- const store = this.files.readJson(this.environment.files.sessions, {
9596
+ const store = this.files.readJson(this.environment.managerFiles.sessions, {
9507
9597
  version: STORE_VERSION,
9508
9598
  password: this.fingerprint,
9509
9599
  sessions: {}
@@ -9513,7 +9603,10 @@ class AuthService {
9513
9603
  const now = Date.now();
9514
9604
  for (const [key, session] of Object.entries(store.sessions ?? {})) {
9515
9605
  if (typeof session?.expires === "number" && session.expires > now) {
9516
- sessions.set(key, { expires: session.expires });
9606
+ sessions.set(key, {
9607
+ expires: session.expires,
9608
+ username: typeof session.username === "string" ? session.username : this.environment.defaultUser.username
9609
+ });
9517
9610
  }
9518
9611
  }
9519
9612
  }
@@ -9528,7 +9621,7 @@ class AuthService {
9528
9621
  if (!sessions) {
9529
9622
  return;
9530
9623
  }
9531
- this.files.writeJson(this.environment.files.sessions, {
9624
+ this.files.writeJson(this.environment.managerFiles.sessions, {
9532
9625
  version: STORE_VERSION,
9533
9626
  password: this.fingerprint,
9534
9627
  sessions: Object.fromEntries(sessions)
@@ -9543,6 +9636,91 @@ function digest(kind, value) {
9543
9636
  return createHash("sha256").update(`${kind}:${value}`).digest("base64url");
9544
9637
  }
9545
9638
 
9639
+ // src/services/users.ts
9640
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
9641
+ var IUserService = createDecorator("userService");
9642
+ var _dec = [
9643
+ inject(IEnvironmentService)
9644
+ ];
9645
+ var _init = __decoratorStart(undefined);
9646
+
9647
+ class UserService {
9648
+ environment;
9649
+ constructor(environment) {
9650
+ this.environment = environment;
9651
+ }
9652
+ list() {
9653
+ const users = discoverUsers();
9654
+ const existing = users.find((user) => user.username === this.environment.defaultUser.username);
9655
+ if (existing) {
9656
+ Object.assign(existing, this.environment.defaultUser);
9657
+ } else {
9658
+ users.push(this.environment.defaultUser);
9659
+ }
9660
+ const allow = parseAllowList();
9661
+ return users.filter((user) => user.username === this.environment.defaultUser.username || !allow || allow.has(user.username)).toSorted((left, right) => {
9662
+ if (left.username === this.environment.defaultUser.username)
9663
+ return -1;
9664
+ if (right.username === this.environment.defaultUser.username)
9665
+ return 1;
9666
+ return left.uid - right.uid || left.username.localeCompare(right.username);
9667
+ });
9668
+ }
9669
+ require(username) {
9670
+ const normalized = String(username ?? "").trim();
9671
+ const user = this.list().find((candidate) => candidate.username === normalized);
9672
+ if (!user) {
9673
+ throw new HttpError(404, `\u672C\u5730\u7528\u6237 ${normalized || "(empty)"} \u4E0D\u5B58\u5728\u6216\u672A\u83B7\u51C6\u7BA1\u7406`);
9674
+ }
9675
+ return user;
9676
+ }
9677
+ }
9678
+ UserService = __decorateElement(_init, 0, "UserService", _dec, UserService);
9679
+ __runInitializers(_init, 1, UserService);
9680
+ __decoratorMetadata(_init, UserService);
9681
+ let _UserService = UserService;
9682
+ function discoverUsers() {
9683
+ if (process.platform === "win32") {
9684
+ return [];
9685
+ }
9686
+ let text = "";
9687
+ try {
9688
+ text = readFileSync2("/etc/passwd", "utf8");
9689
+ } catch {
9690
+ return [];
9691
+ }
9692
+ const uidMin = readUidMin();
9693
+ const users = [];
9694
+ for (const line of text.split(`
9695
+ `)) {
9696
+ if (!line || line.startsWith("#"))
9697
+ continue;
9698
+ const fields = line.split(":");
9699
+ if (fields.length < 7)
9700
+ continue;
9701
+ const [username, , uidText, gidText, , homeDir, shell] = fields;
9702
+ const uid = Number(uidText);
9703
+ const gid = Number(gidText);
9704
+ if (!username || !homeDir?.startsWith("/") || !Number.isInteger(uid) || !Number.isInteger(gid) || uid !== 0 && uid < uidMin || /(?:nologin|false)$/.test(shell ?? "") || !existsSync3(homeDir)) {
9705
+ continue;
9706
+ }
9707
+ users.push({ username, uid, gid, homeDir });
9708
+ }
9709
+ return users;
9710
+ }
9711
+ function readUidMin() {
9712
+ try {
9713
+ const match2 = /^\s*UID_MIN\s+(\d+)/m.exec(readFileSync2("/etc/login.defs", "utf8"));
9714
+ return match2 ? Number(match2[1]) : 1000;
9715
+ } catch {
9716
+ return 1000;
9717
+ }
9718
+ }
9719
+ function parseAllowList() {
9720
+ const value = process.env.HSW_USERS?.trim();
9721
+ return value ? new Set(value.split(",").map((item) => item.trim()).filter(Boolean)) : undefined;
9722
+ }
9723
+
9546
9724
  // src/http/middleware.ts
9547
9725
  function createServiceMiddleware(services) {
9548
9726
  return async (c, next) => {
@@ -9568,12 +9746,15 @@ function createOriginGuard() {
9568
9746
  function createAuthGuard(services) {
9569
9747
  const auth = services.get(IAuthService);
9570
9748
  const environment = services.get(IEnvironmentService);
9749
+ const users = services.get(IUserService);
9571
9750
  return async (c, next) => {
9572
9751
  const token = getCookie(c, environment.cookieName);
9573
9752
  if (!auth.isAuthenticated(token)) {
9574
9753
  throw new HttpError(401, "authentication required");
9575
9754
  }
9576
- await next();
9755
+ const username = auth.userForToken(token) ?? environment.defaultUser.username;
9756
+ const user = users.require(username);
9757
+ await environment.runAsUser(user, () => next());
9577
9758
  };
9578
9759
  }
9579
9760
 
@@ -9594,7 +9775,7 @@ function createAuthRoutes(services) {
9594
9775
  path: "/",
9595
9776
  maxAge: environment.sessionTtlMs / 1000
9596
9777
  });
9597
- return c.json({ authenticated: true });
9778
+ return c.json({ authenticated: true, currentUser: environment.defaultUser.username });
9598
9779
  });
9599
9780
  app.post("/logout", (c) => {
9600
9781
  auth.logout(getCookie(c, environment.cookieName));
@@ -9606,7 +9787,7 @@ function createAuthRoutes(services) {
9606
9787
  if (!auth.isAuthenticated(token)) {
9607
9788
  throw new HttpError(401, "authentication required");
9608
9789
  }
9609
- return c.json({ authenticated: true });
9790
+ return c.json({ authenticated: true, currentUser: auth.userForToken(token) });
9610
9791
  });
9611
9792
  return app;
9612
9793
  }
@@ -9820,6 +10001,9 @@ function compareVersions(a, b) {
9820
10001
  }
9821
10002
  async function checkForUpdate(force = false) {
9822
10003
  const current = await serverVersion();
10004
+ if (process.env.HSW_UPDATE_CHECK === "0") {
10005
+ return { current, latest: null, updateAvailable: false };
10006
+ }
9823
10007
  if (!force && cached2 && Date.now() - cached2.at < CACHE_TTL_MS) {
9824
10008
  return {
9825
10009
  current,
@@ -11029,11 +11213,31 @@ var BASE_URL_VAR = "ANTHROPIC_BASE_URL";
11029
11213
  var MODEL_VAR = "ANTHROPIC_MODEL";
11030
11214
  var AUTH_VARS = ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"];
11031
11215
  var MODEL_MAPPINGS = [
11032
- ["haikuModel", "ANTHROPIC_DEFAULT_HAIKU_MODEL"],
11033
- ["sonnetModel", "ANTHROPIC_DEFAULT_SONNET_MODEL"],
11034
- ["opusModel", "ANTHROPIC_DEFAULT_OPUS_MODEL"],
11035
- ["fableModel", "ANTHROPIC_DEFAULT_FABLE_MODEL"],
11036
- ["subagentModel", "CLAUDE_CODE_SUBAGENT_MODEL"]
11216
+ [
11217
+ "haikuModel",
11218
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
11219
+ "haikuModelName",
11220
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME"
11221
+ ],
11222
+ [
11223
+ "sonnetModel",
11224
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
11225
+ "sonnetModelName",
11226
+ "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME"
11227
+ ],
11228
+ [
11229
+ "opusModel",
11230
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
11231
+ "opusModelName",
11232
+ "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME"
11233
+ ],
11234
+ [
11235
+ "fableModel",
11236
+ "ANTHROPIC_DEFAULT_FABLE_MODEL",
11237
+ "fableModelName",
11238
+ "ANTHROPIC_DEFAULT_FABLE_MODEL_NAME"
11239
+ ],
11240
+ ["subagentModel", "CLAUDE_CODE_SUBAGENT_MODEL", undefined, undefined]
11037
11241
  ];
11038
11242
 
11039
11243
  class ClaudeAdapter {
@@ -11044,7 +11248,7 @@ class ClaudeAdapter {
11044
11248
  BASE_URL_VAR,
11045
11249
  ...AUTH_VARS,
11046
11250
  MODEL_VAR,
11047
- ...MODEL_MAPPINGS.map(([, envVar]) => envVar)
11251
+ ...MODEL_MAPPINGS.flatMap(([, envVar, , nameEnvVar]) => nameEnvVar ? [envVar, nameEnvVar] : [envVar])
11048
11252
  ];
11049
11253
  fields = [
11050
11254
  {
@@ -11053,6 +11257,7 @@ class ClaudeAdapter {
11053
11257
  kind: "select",
11054
11258
  defaultValue: "ANTHROPIC_AUTH_TOKEN",
11055
11259
  help: "\u7B2C\u4E09\u65B9\u4E2D\u8F6C\u901A\u5E38\u8981\u6C42 ANTHROPIC_AUTH_TOKEN\uFF1B\u5B98\u65B9 API key \u7528 ANTHROPIC_API_KEY\u3002",
11260
+ fullWidth: true,
11056
11261
  options: [
11057
11262
  { value: "ANTHROPIC_AUTH_TOKEN", label: "ANTHROPIC_AUTH_TOKEN\uFF08\u7B2C\u4E09\u65B9\u4E2D\u8F6C\uFF09" },
11058
11263
  { value: "ANTHROPIC_API_KEY", label: "ANTHROPIC_API_KEY\uFF08\u5B98\u65B9\uFF09" }
@@ -11062,23 +11267,47 @@ class ClaudeAdapter {
11062
11267
  key: "haikuModel",
11063
11268
  label: "Haiku \u6A21\u578B\u6620\u5C04",
11064
11269
  kind: "text",
11270
+ required: true,
11065
11271
  placeholder: "\u4F8B\u5982\uFF1Aglm-5-air",
11066
- help: "\u5199\u5165 ANTHROPIC_DEFAULT_HAIKU_MODEL\uFF1B\u7559\u7A7A\u4F7F\u7528\u56DE\u9000\u6A21\u578B\u6216 Claude Code \u9ED8\u8BA4\u503C\u3002"
11272
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_HAIKU_MODEL\u3002"
11273
+ },
11274
+ {
11275
+ key: "haikuModelName",
11276
+ label: "Haiku \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11277
+ kind: "text",
11278
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Haiku \u6A21\u578B ID",
11279
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11067
11280
  },
11068
11281
  {
11069
11282
  key: "sonnetModel",
11070
11283
  label: "Sonnet \u6A21\u578B\u6620\u5C04",
11071
11284
  kind: "text",
11285
+ required: true,
11072
11286
  placeholder: "\u4F8B\u5982\uFF1Aglm-5",
11073
11287
  help: "\u5199\u5165 ANTHROPIC_DEFAULT_SONNET_MODEL\u3002"
11074
11288
  },
11289
+ {
11290
+ key: "sonnetModelName",
11291
+ label: "Sonnet \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11292
+ kind: "text",
11293
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Sonnet \u6A21\u578B ID",
11294
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_SONNET_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11295
+ },
11075
11296
  {
11076
11297
  key: "opusModel",
11077
11298
  label: "Opus \u6A21\u578B\u6620\u5C04",
11078
11299
  kind: "text",
11300
+ required: true,
11079
11301
  placeholder: "\u4F8B\u5982\uFF1Aglm-5",
11080
11302
  help: "\u5199\u5165 ANTHROPIC_DEFAULT_OPUS_MODEL\u3002"
11081
11303
  },
11304
+ {
11305
+ key: "opusModelName",
11306
+ label: "Opus \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11307
+ kind: "text",
11308
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Opus \u6A21\u578B ID",
11309
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_OPUS_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11310
+ },
11082
11311
  {
11083
11312
  key: "fableModel",
11084
11313
  label: "Fable \u6A21\u578B\u6620\u5C04\uFF08\u53EF\u9009\uFF09",
@@ -11086,6 +11315,13 @@ class ClaudeAdapter {
11086
11315
  placeholder: "\u4F8B\u5982\uFF1Aglm-5",
11087
11316
  help: "\u5199\u5165 ANTHROPIC_DEFAULT_FABLE_MODEL\uFF1B\u7528\u4E8E\u652F\u6301 Fable \u6863\u4F4D\u7684\u65B0\u7248 Claude Code\u3002"
11088
11317
  },
11318
+ {
11319
+ key: "fableModelName",
11320
+ label: "Fable \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11321
+ kind: "text",
11322
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Fable \u6A21\u578B ID",
11323
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_FABLE_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11324
+ },
11089
11325
  {
11090
11326
  key: "subagentModel",
11091
11327
  label: "\u5B50\u4EE3\u7406\u6A21\u578B\uFF08\u53EF\u9009\uFF09",
@@ -11121,10 +11357,13 @@ API_TIMEOUT_MS=3000000`,
11121
11357
  if (profile.model) {
11122
11358
  vars[MODEL_VAR] = profile.model;
11123
11359
  }
11124
- for (const [field, envVar] of MODEL_MAPPINGS) {
11360
+ for (const [field, envVar, nameField, nameEnvVar] of MODEL_MAPPINGS) {
11125
11361
  if (profile.extras[field]) {
11126
11362
  vars[envVar] = profile.extras[field];
11127
11363
  }
11364
+ if (nameField && nameEnvVar && profile.extras[nameField]) {
11365
+ vars[nameEnvVar] = profile.extras[nameField];
11366
+ }
11128
11367
  }
11129
11368
  return vars;
11130
11369
  }
@@ -11144,13 +11383,21 @@ API_TIMEOUT_MS=3000000`,
11144
11383
  } else {
11145
11384
  delete env[MODEL_VAR];
11146
11385
  }
11147
- for (const [field, envVar] of MODEL_MAPPINGS) {
11386
+ for (const [field, envVar, nameField, nameEnvVar] of MODEL_MAPPINGS) {
11148
11387
  const value = profile.extras[field]?.trim();
11149
11388
  if (value) {
11150
11389
  env[envVar] = value;
11151
11390
  } else {
11152
11391
  delete env[envVar];
11153
11392
  }
11393
+ if (nameField && nameEnvVar) {
11394
+ const name = profile.extras[nameField]?.trim();
11395
+ if (name) {
11396
+ env[nameEnvVar] = name;
11397
+ } else {
11398
+ delete env[nameEnvVar];
11399
+ }
11400
+ }
11154
11401
  }
11155
11402
  for (const [key, value] of parseEnvLines(profile.extras.extraEnv)) {
11156
11403
  env[key] = value;
@@ -11165,8 +11412,10 @@ API_TIMEOUT_MS=3000000`,
11165
11412
  for (const authVar of AUTH_VARS) {
11166
11413
  delete env[authVar];
11167
11414
  }
11168
- for (const [, envVar] of MODEL_MAPPINGS) {
11415
+ for (const [, envVar, , nameEnvVar] of MODEL_MAPPINGS) {
11169
11416
  delete env[envVar];
11417
+ if (nameEnvVar)
11418
+ delete env[nameEnvVar];
11170
11419
  }
11171
11420
  for (const [key] of parseEnvLines(profile?.extras.extraEnv)) {
11172
11421
  delete env[key];
@@ -11187,7 +11436,10 @@ API_TIMEOUT_MS=3000000`,
11187
11436
  apiKey: apiKey || profile.apiKey,
11188
11437
  extras: {
11189
11438
  ...profile.extras,
11190
- ...Object.fromEntries(MODEL_MAPPINGS.map(([field, envVar]) => [field, readString(env, envVar)]))
11439
+ ...Object.fromEntries(MODEL_MAPPINGS.flatMap(([field, envVar, nameField, nameEnvVar]) => [
11440
+ [field, readString(env, envVar)],
11441
+ ...nameField && nameEnvVar ? [[nameField, readString(env, nameEnvVar)]] : []
11442
+ ]))
11191
11443
  }
11192
11444
  };
11193
11445
  }
@@ -11407,6 +11659,7 @@ class DshAdapter {
11407
11659
  environment;
11408
11660
  id = "dsh";
11409
11661
  mode = "additive";
11662
+ modelRequired = true;
11410
11663
  envVarNames = [];
11411
11664
  envNote = "API key \u5B89\u5168\u5199\u5165 DSH \u7684 .credentials.yaml\uFF0C\u5E76\u7531 settings.yaml \u5F15\u7528\u3002";
11412
11665
  fields = [
@@ -11613,6 +11866,7 @@ class KimiAdapter {
11613
11866
  environment;
11614
11867
  id = "kimi";
11615
11868
  mode = "additive";
11869
+ modelRequired = true;
11616
11870
  envVarNames = [];
11617
11871
  envNote = "Kimi Code \u4E0D\u4ECE shell \u8BFB\u53D6\u51ED\u636E\uFF0Cenv.sh \u5BF9\u5B83\u65E0\u6548\u3002";
11618
11872
  fields = [
@@ -11747,6 +12001,7 @@ class PiAdapter {
11747
12001
  environment;
11748
12002
  id = "pi";
11749
12003
  mode = "additive";
12004
+ modelRequired = true;
11750
12005
  envVarNames = [];
11751
12006
  envNote = "API key \u76F4\u63A5\u5199\u5165 models.json\uFF0C\u65E0\u9700\u73AF\u5883\u53D8\u91CF\uFF1B\u8FD0\u884C\u65F6\u4ECD\u53EF\u7528 --model \u8986\u76D6\u3002";
11752
12007
  fields = [
@@ -13151,6 +13406,7 @@ function createHarnessRoutes(services) {
13151
13406
  active: activation.getActive(id),
13152
13407
  profiles: profiles.list(id),
13153
13408
  fields: adapter.fields,
13409
+ modelRequired: adapter.modelRequired,
13154
13410
  targets: adapter.targets(),
13155
13411
  envVars: adapter.envVarNames,
13156
13412
  envNote: adapter.envNote,
@@ -13584,6 +13840,244 @@ function createUpdateRoutes(_services) {
13584
13840
  return api;
13585
13841
  }
13586
13842
 
13843
+ // src/services/user-sync.ts
13844
+ var IUserSyncService = createDecorator("userSyncService");
13845
+ var _dec = [
13846
+ inject(IEnvironmentService, IUserService, IFileService, ICryptoService)
13847
+ ];
13848
+ var _init = __decoratorStart(undefined);
13849
+
13850
+ class UserSyncService {
13851
+ environment;
13852
+ users;
13853
+ files;
13854
+ crypto;
13855
+ constructor(environment, users, files, crypto2) {
13856
+ this.environment = environment;
13857
+ this.users = users;
13858
+ this.files = files;
13859
+ this.crypto = crypto2;
13860
+ }
13861
+ preview(sourceUsername) {
13862
+ const target = this.environment.currentUser;
13863
+ const source = this.requireSource(sourceUsername, target);
13864
+ const portable = this.readPortable(source);
13865
+ const targetProfiles = this.readProfiles();
13866
+ const conflicts = [];
13867
+ let profileCount = 0;
13868
+ const referencedProviders = new Set;
13869
+ for (const [harness, profiles] of Object.entries(portable.profiles)) {
13870
+ for (const [name, profile] of Object.entries(profiles)) {
13871
+ profileCount++;
13872
+ if (targetProfiles[harness]?.[name]) {
13873
+ conflicts.push({ harness, name });
13874
+ }
13875
+ if (profile.provider_id)
13876
+ referencedProviders.add(profile.provider_id);
13877
+ }
13878
+ }
13879
+ return {
13880
+ sourceUser: source.username,
13881
+ targetUser: target.username,
13882
+ profileCount,
13883
+ providerCount: referencedProviders.size,
13884
+ conflicts
13885
+ };
13886
+ }
13887
+ sync(sourceUsername, conflictPolicy) {
13888
+ if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
13889
+ throw new HttpError(400, "invalid conflict policy");
13890
+ }
13891
+ const target = this.environment.currentUser;
13892
+ const source = this.requireSource(sourceUsername, target);
13893
+ const portable = this.readPortable(source);
13894
+ const profilesPath = this.environment.files.profiles;
13895
+ const vaultPath = this.environment.files.vault;
13896
+ const profileSnapshot = this.files.readOptional(profilesPath);
13897
+ const vaultSnapshot = this.files.readOptional(vaultPath);
13898
+ const targetProfiles = structuredClone(this.readProfiles());
13899
+ const targetVault = structuredClone(this.readVault());
13900
+ const active = this.files.readJson(this.environment.files.active, {});
13901
+ const warnings = [];
13902
+ let imported = 0;
13903
+ let overwritten = 0;
13904
+ let skipped = 0;
13905
+ const selected = [];
13906
+ for (const [harness, profiles] of Object.entries(portable.profiles)) {
13907
+ for (const [name, profile] of Object.entries(profiles)) {
13908
+ const exists = targetProfiles[harness]?.[name] !== undefined;
13909
+ if (exists && conflictPolicy === "skip") {
13910
+ skipped++;
13911
+ continue;
13912
+ }
13913
+ selected.push({ harness, name, profile });
13914
+ if (exists) {
13915
+ overwritten++;
13916
+ if (active[harness]?.name === name) {
13917
+ warnings.push(`${harness}/${name} \u5F53\u524D\u5904\u4E8E\u6FC0\u6D3B\u72B6\u6001\uFF1B\u5DF2\u66F4\u65B0\u914D\u7F6E\u5E93\u4F46\u672A\u6539\u5199\u539F\u751F\u6587\u4EF6\uFF0C\u8BF7\u624B\u52A8\u91CD\u65B0\u6FC0\u6D3B`);
13918
+ }
13919
+ } else
13920
+ imported++;
13921
+ }
13922
+ }
13923
+ const providerMap = new Map;
13924
+ for (const { profile } of selected) {
13925
+ const sourceId = profile.provider_id;
13926
+ if (!sourceId || providerMap.has(sourceId))
13927
+ continue;
13928
+ const provider = portable.providers[sourceId];
13929
+ if (!provider) {
13930
+ continue;
13931
+ }
13932
+ const targetId = this.availableProviderId(sourceId, source.username, targetVault);
13933
+ providerMap.set(sourceId, targetId);
13934
+ const { apiKey, ...storedProvider } = provider;
13935
+ targetVault.entries[targetId] = {
13936
+ ...storedProvider,
13937
+ id: targetId,
13938
+ api_key: this.crypto.encrypt(apiKey),
13939
+ created_at: new Date().toISOString(),
13940
+ updated_at: new Date().toISOString(),
13941
+ synced_from: { username: source.username, provider_id: sourceId }
13942
+ };
13943
+ }
13944
+ for (const { harness, name, profile } of selected) {
13945
+ targetProfiles[harness] ||= {};
13946
+ const mappedProvider = profile.provider_id ? providerMap.get(profile.provider_id) : undefined;
13947
+ const { apiKey, ...storedProfile } = profile;
13948
+ targetProfiles[harness][name] = {
13949
+ ...storedProfile,
13950
+ api_key: this.crypto.encrypt(apiKey),
13951
+ provider_id: mappedProvider,
13952
+ provider_endpoint: mappedProvider ? profile.provider_endpoint : undefined,
13953
+ updated_at: new Date().toISOString()
13954
+ };
13955
+ }
13956
+ try {
13957
+ this.files.writeJson(vaultPath, targetVault);
13958
+ this.files.writeJson(profilesPath, targetProfiles);
13959
+ } catch (error2) {
13960
+ this.restore(vaultPath, vaultSnapshot);
13961
+ this.restore(profilesPath, profileSnapshot);
13962
+ throw error2;
13963
+ }
13964
+ return {
13965
+ ok: true,
13966
+ sourceUser: source.username,
13967
+ targetUser: target.username,
13968
+ imported,
13969
+ overwritten,
13970
+ skipped,
13971
+ providersCopied: providerMap.size,
13972
+ warnings
13973
+ };
13974
+ }
13975
+ requireSource(sourceUsername, target) {
13976
+ const source = this.users.require(sourceUsername);
13977
+ if (source.username === target.username) {
13978
+ throw new HttpError(400, "\u6765\u6E90\u7528\u6237\u4E0D\u80FD\u4E0E\u5F53\u524D\u76EE\u6807\u7528\u6237\u76F8\u540C");
13979
+ }
13980
+ return source;
13981
+ }
13982
+ readPortable(source) {
13983
+ return this.environment.runAsUser(source, () => {
13984
+ const profiles = this.readProfiles();
13985
+ const vault = this.readVault();
13986
+ const portableProviders = {};
13987
+ for (const [id, entry] of Object.entries(vault.entries)) {
13988
+ portableProviders[id] = { ...entry, apiKey: this.crypto.decrypt(entry.api_key) };
13989
+ }
13990
+ const portableProfiles = {};
13991
+ for (const [harness, entries] of Object.entries(profiles)) {
13992
+ portableProfiles[harness] = {};
13993
+ for (const [name, profile] of Object.entries(entries)) {
13994
+ const providerKey = profile.provider_id ? portableProviders[profile.provider_id]?.apiKey : undefined;
13995
+ portableProfiles[harness][name] = {
13996
+ ...profile,
13997
+ apiKey: providerKey ?? this.crypto.decrypt(profile.api_key)
13998
+ };
13999
+ }
14000
+ }
14001
+ return { profiles: portableProfiles, providers: portableProviders };
14002
+ });
14003
+ }
14004
+ readProfiles() {
14005
+ return this.files.readJsonStrict(this.environment.files.profiles, {});
14006
+ }
14007
+ readVault() {
14008
+ return this.files.readJsonStrict(this.environment.files.vault, {
14009
+ version: 1,
14010
+ entries: {}
14011
+ });
14012
+ }
14013
+ availableProviderId(sourceId, sourceUsername, target) {
14014
+ const previous = Object.values(target.entries).find((entry) => entry.synced_from?.username === sourceUsername && entry.synced_from.provider_id === sourceId);
14015
+ if (previous)
14016
+ return previous.id;
14017
+ if (!target.entries[sourceId])
14018
+ return sourceId;
14019
+ const suffix = sourceUsername.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").slice(0, 24);
14020
+ const base = `${sourceId}-${suffix || "copy"}`.slice(0, 60);
14021
+ let candidate = base;
14022
+ let index = 2;
14023
+ while (target.entries[candidate]) {
14024
+ candidate = `${base}-${index}`.slice(0, 64);
14025
+ index++;
14026
+ }
14027
+ return candidate;
14028
+ }
14029
+ restore(path, snapshot) {
14030
+ try {
14031
+ if (snapshot === undefined)
14032
+ this.files.remove(path);
14033
+ else
14034
+ this.files.writeSecure(path, snapshot);
14035
+ } catch {}
14036
+ }
14037
+ }
14038
+ UserSyncService = __decorateElement(_init, 0, "UserSyncService", _dec, UserSyncService);
14039
+ __runInitializers(_init, 1, UserSyncService);
14040
+ __decoratorMetadata(_init, UserSyncService);
14041
+ let _UserSyncService = UserSyncService;
14042
+
14043
+ // src/http/routes/users.ts
14044
+ function createUserRoutes(services) {
14045
+ const app = new Hono2;
14046
+ const auth = services.get(IAuthService);
14047
+ const environment = services.get(IEnvironmentService);
14048
+ const users = services.get(IUserService);
14049
+ const sync = services.get(IUserSyncService);
14050
+ app.get("/", (c) => {
14051
+ const current = environment.currentUser.username;
14052
+ return c.json({
14053
+ currentUser: current,
14054
+ items: users.list().map((user) => ({ ...user, current: user.username === current }))
14055
+ });
14056
+ });
14057
+ app.post("/sync/preview", async (c) => {
14058
+ const body = await readBody4(c.req.json.bind(c.req));
14059
+ return c.json(sync.preview(String(body.sourceUser ?? "")));
14060
+ });
14061
+ app.post("/sync", async (c) => {
14062
+ const body = await readBody4(c.req.json.bind(c.req));
14063
+ return c.json(sync.sync(String(body.sourceUser ?? ""), body.conflictPolicy ?? "skip"));
14064
+ });
14065
+ app.post("/:username/select", (c) => {
14066
+ const user = users.require(decodeURIComponent(c.req.param("username")));
14067
+ const token = getCookie(c, environment.cookieName);
14068
+ if (!token)
14069
+ throw new HttpError(401, "authentication required");
14070
+ auth.selectUser(token, user.username);
14071
+ return c.json({ currentUser: user.username });
14072
+ });
14073
+ return app;
14074
+ }
14075
+ async function readBody4(read) {
14076
+ return read().catch(() => {
14077
+ throw new HttpError(400, "invalid json");
14078
+ });
14079
+ }
14080
+
13587
14081
  // src/app.ts
13588
14082
  function createApp(services) {
13589
14083
  const app = new Hono2;
@@ -13595,6 +14089,9 @@ function createApp(services) {
13595
14089
  api.use("*", createOriginGuard());
13596
14090
  api.get("/version", async (c) => c.json({ name: "harness-switch", version: await serverVersion() }));
13597
14091
  api.route("/auth", createAuthRoutes(services));
14092
+ api.use("/users/*", createAuthGuard(services));
14093
+ api.use("/users", createAuthGuard(services));
14094
+ api.route("/users", createUserRoutes(services));
13598
14095
  api.use("/harnesses/*", createAuthGuard(services));
13599
14096
  api.use("/harnesses", createAuthGuard(services));
13600
14097
  api.route("/harnesses", createHarnessRoutes(services));
@@ -13617,18 +14114,18 @@ function createApp(services) {
13617
14114
  api.route("/drift", createDriftRoutes(services));
13618
14115
  app.route("/api", api);
13619
14116
  const publicDir = environment.publicDir;
13620
- if (existsSync3(publicDir)) {
14117
+ if (existsSync4(publicDir)) {
13621
14118
  app.use("/assets/*", serveStatic2({ root: publicDir }));
13622
14119
  app.get("*", async (c, next) => {
13623
14120
  if (c.req.path.startsWith("/api") || c.req.path === "/healthz") {
13624
14121
  return next();
13625
14122
  }
13626
14123
  const assetPath = join11(publicDir, c.req.path.replace(/^\//, ""));
13627
- if (c.req.path !== "/" && existsSync3(assetPath)) {
14124
+ if (c.req.path !== "/" && existsSync4(assetPath)) {
13628
14125
  return serveStatic2({ root: publicDir })(c, next);
13629
14126
  }
13630
14127
  const index = join11(publicDir, "index.html");
13631
- if (existsSync3(index)) {
14128
+ if (existsSync4(index)) {
13632
14129
  c.header("Cache-Control", "no-store");
13633
14130
  return c.html(await Bun.file(index).text());
13634
14131
  }
@@ -13651,6 +14148,8 @@ function createServices() {
13651
14148
  const collection = new ServiceCollection;
13652
14149
  collection.set(ILogService, new SyncDescriptor(LogService));
13653
14150
  collection.set(IEnvironmentService, new SyncDescriptor(EnvironmentService));
14151
+ collection.set(IUserService, new SyncDescriptor(UserService));
14152
+ collection.set(IUserSyncService, new SyncDescriptor(UserSyncService));
13654
14153
  collection.set(IFileService, new SyncDescriptor(FileService));
13655
14154
  collection.set(ICryptoService, new SyncDescriptor(CryptoService));
13656
14155
  collection.set(IAuthService, new SyncDescriptor(AuthService));
@@ -13671,14 +14170,22 @@ function createServices() {
13671
14170
  function parseArgs(argv) {
13672
14171
  const flags = {};
13673
14172
  const positional = [];
13674
- for (const arg of argv) {
14173
+ const valueFlags = new Set(["user", "from", "to", "harness"]);
14174
+ for (let index = 0;index < argv.length; index++) {
14175
+ const arg = argv[index];
13675
14176
  if (arg.startsWith("--")) {
13676
14177
  const body = arg.slice(2);
13677
14178
  const separator = body.indexOf("=");
13678
14179
  if (separator !== -1) {
13679
14180
  flags[body.slice(0, separator)] = body.slice(separator + 1);
13680
14181
  } else {
13681
- flags[body] = true;
14182
+ const next = argv[index + 1];
14183
+ if (valueFlags.has(body) && next && !next.startsWith("--")) {
14184
+ flags[body] = next;
14185
+ index++;
14186
+ } else {
14187
+ flags[body] = true;
14188
+ }
13682
14189
  }
13683
14190
  } else {
13684
14191
  positional.push(arg);
@@ -13713,12 +14220,12 @@ import { stdin, stdout } from "process";
13713
14220
  import { createInterface } from "readline/promises";
13714
14221
 
13715
14222
  // src/cli/client.ts
13716
- import { readFileSync as readFileSync3 } from "fs";
14223
+ import { readFileSync as readFileSync4 } from "fs";
13717
14224
  import { join as join13 } from "path";
13718
14225
 
13719
14226
  // src/daemon.ts
13720
14227
  import { spawn as spawn2 } from "child_process";
13721
- import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
14228
+ import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
13722
14229
  import { homedir as homedir3 } from "os";
13723
14230
  import { join as join12, resolve } from "path";
13724
14231
  var DEFAULT_HOST = "127.0.0.1";
@@ -13736,7 +14243,7 @@ function daemonLogFile() {
13736
14243
  }
13737
14244
  function readPid() {
13738
14245
  try {
13739
- const raw2 = readFileSync2(daemonPidFile(), "utf8").trim();
14246
+ const raw2 = readFileSync3(daemonPidFile(), "utf8").trim();
13740
14247
  const pid = Number(raw2);
13741
14248
  return Number.isInteger(pid) && pid > 0 ? pid : null;
13742
14249
  } catch {
@@ -13904,7 +14411,7 @@ function resolveBaseUrl() {
13904
14411
  function readWebPassword() {
13905
14412
  const file = join13(daemonDataDir(), "web_password");
13906
14413
  try {
13907
- return readFileSync3(file, "utf8").trim();
14414
+ return readFileSync4(file, "utf8").trim();
13908
14415
  } catch {
13909
14416
  throw new CliError(`\u672A\u627E\u5230 ${file}\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`);
13910
14417
  }
@@ -13992,12 +14499,16 @@ function cliUsage() {
13992
14499
  " doctor [--probe] [--harness H] run diagnostics (add --probe for /models checks)",
13993
14500
  " plan <harness> <profile> show the exact content activation would write",
13994
14501
  " activate <harness> <profile> activate a profile (add --yes to skip the prompt)",
14502
+ " users list manageable local Unix users",
14503
+ " sync --from USER --to USER copy profiles and credentials between users",
13995
14504
  "",
13996
14505
  "options:",
13997
14506
  " --json machine-readable JSON output",
13998
14507
  " --yes skip confirmation for activate",
13999
14508
  " --probe run the /models connectivity probe in doctor",
14000
14509
  " --harness H limit doctor to one harness",
14510
+ " --user USER run list/providers/doctor/plan/activate for this Unix user",
14511
+ " --overwrite overwrite same-name profiles during sync (default: skip)",
14001
14512
  "",
14002
14513
  "environment:",
14003
14514
  " HSW_URL base URL of the local service (default http://127.0.0.1:8787)",
@@ -14014,6 +14525,10 @@ async function runCli(command, positional, flags) {
14014
14525
  try {
14015
14526
  client = new CliClient(resolveBaseUrl(), readWebPassword());
14016
14527
  await client.login();
14528
+ const selectedUser = flagValue(flags, "user");
14529
+ if (selectedUser) {
14530
+ await selectUser(client, selectedUser);
14531
+ }
14017
14532
  } catch (error2) {
14018
14533
  return fail(error2, json);
14019
14534
  }
@@ -14029,6 +14544,10 @@ async function runCli(command, positional, flags) {
14029
14544
  return await cmdPlan(client, positional, json);
14030
14545
  case "activate":
14031
14546
  return await cmdActivate(client, positional, flags, json);
14547
+ case "users":
14548
+ return await cmdUsers(client, json);
14549
+ case "sync":
14550
+ return await cmdSync(client, flags, json);
14032
14551
  default:
14033
14552
  console.error(cliUsage());
14034
14553
  throw new CliError(`unknown command: ${command}`);
@@ -14037,6 +14556,40 @@ async function runCli(command, positional, flags) {
14037
14556
  return fail(error2, json);
14038
14557
  }
14039
14558
  }
14559
+ async function selectUser(client, username) {
14560
+ await client.post(`/api/users/${encodeURIComponent(username)}/select`);
14561
+ }
14562
+ async function cmdUsers(client, json) {
14563
+ const payload = await client.get("/api/users");
14564
+ if (json === "json") {
14565
+ printJson(payload);
14566
+ } else {
14567
+ for (const user of payload.items) {
14568
+ console.log(`${user.current ? "*" : " "} ${user.username.padEnd(20)} ${user.homeDir}`);
14569
+ }
14570
+ }
14571
+ return 0;
14572
+ }
14573
+ async function cmdSync(client, flags, json) {
14574
+ const source = flagValue(flags, "from");
14575
+ const target = flagValue(flags, "to") || flagValue(flags, "user");
14576
+ if (!source || !target) {
14577
+ throw new CliError("sync \u9700\u8981 --from <\u6765\u6E90\u7528\u6237> \u548C --to <\u76EE\u6807\u7528\u6237>");
14578
+ }
14579
+ await selectUser(client, target);
14580
+ const conflictPolicy = hasFlag(flags, "overwrite") ? "overwrite" : "skip";
14581
+ const payload = await client.post("/api/users/sync", {
14582
+ sourceUser: source,
14583
+ conflictPolicy
14584
+ });
14585
+ if (json === "json") {
14586
+ printJson(payload);
14587
+ } else {
14588
+ console.log(`\u5DF2\u4ECE ${source} \u540C\u6B65\u5230 ${target}`);
14589
+ console.log(`\u65B0\u589E=${payload.imported} \u8986\u76D6=${payload.overwritten} \u8DF3\u8FC7=${payload.skipped} \u51ED\u636E=${payload.providersCopied}`);
14590
+ }
14591
+ return 0;
14592
+ }
14040
14593
  async function cmdList(client, json) {
14041
14594
  const payload = await client.get("/api/harnesses");
14042
14595
  if (json === "json") {
@@ -14149,7 +14702,7 @@ if (command === "server") {
14149
14702
  await stopDaemon();
14150
14703
  } else if (command === "status") {
14151
14704
  printStatus();
14152
- } else if (command === "list" || command === "providers" || command === "doctor" || command === "plan" || command === "activate") {
14705
+ } else if (command === "list" || command === "providers" || command === "doctor" || command === "plan" || command === "activate" || command === "users" || command === "sync") {
14153
14706
  const { flags, positional } = parseArgs(rest);
14154
14707
  process.exitCode = await runCli(command, positional, flags);
14155
14708
  } else if (command === undefined || command === "daemon") {