@seaveyon/harness-switch 0.13.0 → 0.15.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.
@@ -7015,7 +7015,7 @@ var require_public_api = __commonJS((exports) => {
7015
7015
 
7016
7016
  // src/app.ts
7017
7017
  import { existsSync as existsSync4 } from "fs";
7018
- import { join as join11 } from "path";
7018
+ import { join as join12 } from "path";
7019
7019
 
7020
7020
  // ../../node_modules/hono/dist/compose.js
7021
7021
  var compose = (middleware, onError, onNotFound) => {
@@ -9337,6 +9337,12 @@ class FileService {
9337
9337
  writeUserFile(file, text) {
9338
9338
  this.write(file, text, this.modeOf(file));
9339
9339
  }
9340
+ writeUserSecretFile(file, text) {
9341
+ this.write(file, text, 384, {
9342
+ uid: this.environment.currentUser.uid,
9343
+ gid: this.environment.currentUser.gid
9344
+ });
9345
+ }
9340
9346
  readJson(file, fallback) {
9341
9347
  try {
9342
9348
  return JSON.parse(this.readText(file));
@@ -9376,10 +9382,9 @@ class FileService {
9376
9382
  return [];
9377
9383
  }
9378
9384
  }
9379
- write(file, text, mode) {
9385
+ write(file, text, mode, owner = this.ownerOf(file)) {
9380
9386
  this.ensureDir(dirname2(file));
9381
9387
  const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
9382
- const owner = this.ownerOf(file);
9383
9388
  writeFileSync(tmp, text, { encoding: "utf8", mode });
9384
9389
  this.applyOwner(tmp, owner.uid, owner.gid);
9385
9390
  renameSync(tmp, file);
@@ -10001,6 +10006,9 @@ function compareVersions(a, b) {
10001
10006
  }
10002
10007
  async function checkForUpdate(force = false) {
10003
10008
  const current = await serverVersion();
10009
+ if (process.env.HSW_UPDATE_CHECK === "0") {
10010
+ return { current, latest: null, updateAvailable: false };
10011
+ }
10004
10012
  if (!force && cached2 && Date.now() - cached2.at < CACHE_TTL_MS) {
10005
10013
  return {
10006
10014
  current,
@@ -11209,13 +11217,51 @@ var SETTINGS = "settings";
11209
11217
  var BASE_URL_VAR = "ANTHROPIC_BASE_URL";
11210
11218
  var MODEL_VAR = "ANTHROPIC_MODEL";
11211
11219
  var AUTH_VARS = ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"];
11220
+ var ONE_M_SUFFIX = "[1m]";
11212
11221
  var MODEL_MAPPINGS = [
11213
- ["haikuModel", "ANTHROPIC_DEFAULT_HAIKU_MODEL"],
11214
- ["sonnetModel", "ANTHROPIC_DEFAULT_SONNET_MODEL"],
11215
- ["opusModel", "ANTHROPIC_DEFAULT_OPUS_MODEL"],
11216
- ["fableModel", "ANTHROPIC_DEFAULT_FABLE_MODEL"],
11217
- ["subagentModel", "CLAUDE_CODE_SUBAGENT_MODEL"]
11222
+ {
11223
+ field: "haikuModel",
11224
+ envVar: "ANTHROPIC_DEFAULT_HAIKU_MODEL",
11225
+ nameField: "haikuModelName",
11226
+ nameEnvVar: "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME"
11227
+ },
11228
+ {
11229
+ field: "sonnetModel",
11230
+ envVar: "ANTHROPIC_DEFAULT_SONNET_MODEL",
11231
+ nameField: "sonnetModelName",
11232
+ nameEnvVar: "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME",
11233
+ oneMField: "sonnetModel1m"
11234
+ },
11235
+ {
11236
+ field: "opusModel",
11237
+ envVar: "ANTHROPIC_DEFAULT_OPUS_MODEL",
11238
+ nameField: "opusModelName",
11239
+ nameEnvVar: "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME",
11240
+ oneMField: "opusModel1m"
11241
+ },
11242
+ {
11243
+ field: "fableModel",
11244
+ envVar: "ANTHROPIC_DEFAULT_FABLE_MODEL",
11245
+ nameField: "fableModelName",
11246
+ nameEnvVar: "ANTHROPIC_DEFAULT_FABLE_MODEL_NAME",
11247
+ oneMField: "fableModel1m"
11248
+ },
11249
+ { field: "subagentModel", envVar: "CLAUDE_CODE_SUBAGENT_MODEL", oneMField: "subagentModel1m" }
11250
+ ];
11251
+ var ONE_M_OPTIONS = [
11252
+ { value: "false", label: "\u5173\u95ED" },
11253
+ { value: "true", label: "\u5F00\u542F" }
11218
11254
  ];
11255
+ function oneMField(role, key) {
11256
+ return {
11257
+ key,
11258
+ label: `${role} \u58F0\u660E\u652F\u6301 1M`,
11259
+ kind: "select",
11260
+ defaultValue: "false",
11261
+ options: ONE_M_OPTIONS,
11262
+ help: "\u5728\u6A21\u578B ID \u672B\u5C3E\u8FFD\u52A0 [1m]\uFF0C\u5411 Claude Code \u58F0\u660E 1M \u4E0A\u4E0B\u6587\uFF1BClaude Code \u8BF7\u6C42\u4E0A\u6E38\u524D\u4F1A\u53BB\u6389\u8BE5\u540E\u7F00\u3002\u4EC5\u5728\u8BE5\u6A21\u578B\u786E\u5B9E\u652F\u6301 1M \u65F6\u5F00\u542F\u3002"
11263
+ };
11264
+ }
11219
11265
 
11220
11266
  class ClaudeAdapter {
11221
11267
  environment;
@@ -11225,7 +11271,7 @@ class ClaudeAdapter {
11225
11271
  BASE_URL_VAR,
11226
11272
  ...AUTH_VARS,
11227
11273
  MODEL_VAR,
11228
- ...MODEL_MAPPINGS.map(([, envVar]) => envVar)
11274
+ ...MODEL_MAPPINGS.flatMap(({ envVar, nameEnvVar }) => nameEnvVar ? [envVar, nameEnvVar] : [envVar])
11229
11275
  ];
11230
11276
  fields = [
11231
11277
  {
@@ -11234,6 +11280,7 @@ class ClaudeAdapter {
11234
11280
  kind: "select",
11235
11281
  defaultValue: "ANTHROPIC_AUTH_TOKEN",
11236
11282
  help: "\u7B2C\u4E09\u65B9\u4E2D\u8F6C\u901A\u5E38\u8981\u6C42 ANTHROPIC_AUTH_TOKEN\uFF1B\u5B98\u65B9 API key \u7528 ANTHROPIC_API_KEY\u3002",
11283
+ fullWidth: true,
11237
11284
  options: [
11238
11285
  { value: "ANTHROPIC_AUTH_TOKEN", label: "ANTHROPIC_AUTH_TOKEN\uFF08\u7B2C\u4E09\u65B9\u4E2D\u8F6C\uFF09" },
11239
11286
  { value: "ANTHROPIC_API_KEY", label: "ANTHROPIC_API_KEY\uFF08\u5B98\u65B9\uFF09" }
@@ -11243,23 +11290,49 @@ class ClaudeAdapter {
11243
11290
  key: "haikuModel",
11244
11291
  label: "Haiku \u6A21\u578B\u6620\u5C04",
11245
11292
  kind: "text",
11293
+ required: true,
11246
11294
  placeholder: "\u4F8B\u5982\uFF1Aglm-5-air",
11247
- help: "\u5199\u5165 ANTHROPIC_DEFAULT_HAIKU_MODEL\uFF1B\u7559\u7A7A\u4F7F\u7528\u56DE\u9000\u6A21\u578B\u6216 Claude Code \u9ED8\u8BA4\u503C\u3002"
11295
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_HAIKU_MODEL\u3002"
11296
+ },
11297
+ {
11298
+ key: "haikuModelName",
11299
+ label: "Haiku \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11300
+ kind: "text",
11301
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Haiku \u6A21\u578B ID",
11302
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11248
11303
  },
11249
11304
  {
11250
11305
  key: "sonnetModel",
11251
11306
  label: "Sonnet \u6A21\u578B\u6620\u5C04",
11252
11307
  kind: "text",
11308
+ required: true,
11253
11309
  placeholder: "\u4F8B\u5982\uFF1Aglm-5",
11254
11310
  help: "\u5199\u5165 ANTHROPIC_DEFAULT_SONNET_MODEL\u3002"
11255
11311
  },
11312
+ {
11313
+ key: "sonnetModelName",
11314
+ label: "Sonnet \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11315
+ kind: "text",
11316
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Sonnet \u6A21\u578B ID",
11317
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_SONNET_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11318
+ },
11319
+ oneMField("Sonnet", "sonnetModel1m"),
11256
11320
  {
11257
11321
  key: "opusModel",
11258
11322
  label: "Opus \u6A21\u578B\u6620\u5C04",
11259
11323
  kind: "text",
11324
+ required: true,
11260
11325
  placeholder: "\u4F8B\u5982\uFF1Aglm-5",
11261
11326
  help: "\u5199\u5165 ANTHROPIC_DEFAULT_OPUS_MODEL\u3002"
11262
11327
  },
11328
+ {
11329
+ key: "opusModelName",
11330
+ label: "Opus \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11331
+ kind: "text",
11332
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Opus \u6A21\u578B ID",
11333
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_OPUS_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11334
+ },
11335
+ oneMField("Opus", "opusModel1m"),
11263
11336
  {
11264
11337
  key: "fableModel",
11265
11338
  label: "Fable \u6A21\u578B\u6620\u5C04\uFF08\u53EF\u9009\uFF09",
@@ -11267,6 +11340,14 @@ class ClaudeAdapter {
11267
11340
  placeholder: "\u4F8B\u5982\uFF1Aglm-5",
11268
11341
  help: "\u5199\u5165 ANTHROPIC_DEFAULT_FABLE_MODEL\uFF1B\u7528\u4E8E\u652F\u6301 Fable \u6863\u4F4D\u7684\u65B0\u7248 Claude Code\u3002"
11269
11342
  },
11343
+ {
11344
+ key: "fableModelName",
11345
+ label: "Fable \u663E\u793A\u540D\u79F0\uFF08\u9009\u586B\uFF09",
11346
+ kind: "text",
11347
+ placeholder: "\u7559\u7A7A\u5219\u4F7F\u7528 Fable \u6A21\u578B ID",
11348
+ help: "\u5199\u5165 ANTHROPIC_DEFAULT_FABLE_MODEL_NAME\uFF1B\u7559\u7A7A\u65F6 Claude Code \u9ED8\u8BA4\u663E\u793A\u5BF9\u5E94\u6A21\u578B ID\u3002"
11349
+ },
11350
+ oneMField("Fable", "fableModel1m"),
11270
11351
  {
11271
11352
  key: "subagentModel",
11272
11353
  label: "\u5B50\u4EE3\u7406\u6A21\u578B\uFF08\u53EF\u9009\uFF09",
@@ -11274,6 +11355,7 @@ class ClaudeAdapter {
11274
11355
  placeholder: "\u4F8B\u5982\uFF1Aglm-5-air",
11275
11356
  help: "\u5199\u5165 CLAUDE_CODE_SUBAGENT_MODEL\uFF0C\u53EF\u8BA9\u5B50\u4EE3\u7406\u4F7F\u7528\u66F4\u5FEB\u6216\u6210\u672C\u66F4\u4F4E\u7684\u6A21\u578B\u3002"
11276
11357
  },
11358
+ oneMField("\u5B50\u4EE3\u7406", "subagentModel1m"),
11277
11359
  {
11278
11360
  key: "extraEnv",
11279
11361
  label: "\u8FFD\u52A0\u73AF\u5883\u53D8\u91CF\uFF08\u53EF\u9009\uFF09",
@@ -11302,9 +11384,12 @@ API_TIMEOUT_MS=3000000`,
11302
11384
  if (profile.model) {
11303
11385
  vars[MODEL_VAR] = profile.model;
11304
11386
  }
11305
- for (const [field, envVar] of MODEL_MAPPINGS) {
11387
+ for (const { field, envVar, nameField, nameEnvVar, oneMField: flagField } of MODEL_MAPPINGS) {
11306
11388
  if (profile.extras[field]) {
11307
- vars[envVar] = profile.extras[field];
11389
+ vars[envVar] = withOneM(profile.extras[field], profile.extras[flagField ?? ""]);
11390
+ }
11391
+ if (nameField && nameEnvVar && profile.extras[nameField]) {
11392
+ vars[nameEnvVar] = profile.extras[nameField];
11308
11393
  }
11309
11394
  }
11310
11395
  return vars;
@@ -11325,13 +11410,21 @@ API_TIMEOUT_MS=3000000`,
11325
11410
  } else {
11326
11411
  delete env[MODEL_VAR];
11327
11412
  }
11328
- for (const [field, envVar] of MODEL_MAPPINGS) {
11413
+ for (const { field, envVar, nameField, nameEnvVar, oneMField: flagField } of MODEL_MAPPINGS) {
11329
11414
  const value = profile.extras[field]?.trim();
11330
11415
  if (value) {
11331
- env[envVar] = value;
11416
+ env[envVar] = withOneM(value, profile.extras[flagField ?? ""]);
11332
11417
  } else {
11333
11418
  delete env[envVar];
11334
11419
  }
11420
+ if (nameField && nameEnvVar) {
11421
+ const name = profile.extras[nameField]?.trim();
11422
+ if (name) {
11423
+ env[nameEnvVar] = name;
11424
+ } else {
11425
+ delete env[nameEnvVar];
11426
+ }
11427
+ }
11335
11428
  }
11336
11429
  for (const [key, value] of parseEnvLines(profile.extras.extraEnv)) {
11337
11430
  env[key] = value;
@@ -11346,8 +11439,10 @@ API_TIMEOUT_MS=3000000`,
11346
11439
  for (const authVar of AUTH_VARS) {
11347
11440
  delete env[authVar];
11348
11441
  }
11349
- for (const [, envVar] of MODEL_MAPPINGS) {
11442
+ for (const { envVar, nameEnvVar } of MODEL_MAPPINGS) {
11350
11443
  delete env[envVar];
11444
+ if (nameEnvVar)
11445
+ delete env[nameEnvVar];
11351
11446
  }
11352
11447
  for (const [key] of parseEnvLines(profile?.extras.extraEnv)) {
11353
11448
  delete env[key];
@@ -11368,7 +11463,14 @@ API_TIMEOUT_MS=3000000`,
11368
11463
  apiKey: apiKey || profile.apiKey,
11369
11464
  extras: {
11370
11465
  ...profile.extras,
11371
- ...Object.fromEntries(MODEL_MAPPINGS.map(([field, envVar]) => [field, readString(env, envVar)]))
11466
+ ...Object.fromEntries(MODEL_MAPPINGS.flatMap(({ field, envVar, nameField, nameEnvVar, oneMField: flagField }) => {
11467
+ const value = readString(env, envVar);
11468
+ return [
11469
+ [field, withoutOneM(value)],
11470
+ ...nameField && nameEnvVar ? [[nameField, readString(env, nameEnvVar)]] : [],
11471
+ ...flagField ? [[flagField, value.endsWith(ONE_M_SUFFIX) ? "true" : "false"]] : []
11472
+ ];
11473
+ }))
11372
11474
  }
11373
11475
  };
11374
11476
  }
@@ -11377,6 +11479,13 @@ API_TIMEOUT_MS=3000000`,
11377
11479
  return AUTH_VARS.includes(configured) ? configured : AUTH_VARS[0];
11378
11480
  }
11379
11481
  }
11482
+ function withOneM(value, enabled) {
11483
+ const model = withoutOneM(value.trim());
11484
+ return enabled === "true" && model ? `${model}${ONE_M_SUFFIX}` : model;
11485
+ }
11486
+ function withoutOneM(value) {
11487
+ return value.endsWith(ONE_M_SUFFIX) ? value.slice(0, -ONE_M_SUFFIX.length) : value;
11488
+ }
11380
11489
  function safeParse(text) {
11381
11490
  try {
11382
11491
  return parseJsonObject(text);
@@ -11588,6 +11697,7 @@ class DshAdapter {
11588
11697
  environment;
11589
11698
  id = "dsh";
11590
11699
  mode = "additive";
11700
+ modelRequired = true;
11591
11701
  envVarNames = [];
11592
11702
  envNote = "API key \u5B89\u5168\u5199\u5165 DSH \u7684 .credentials.yaml\uFF0C\u5E76\u7531 settings.yaml \u5F15\u7528\u3002";
11593
11703
  fields = [
@@ -11794,6 +11904,7 @@ class KimiAdapter {
11794
11904
  environment;
11795
11905
  id = "kimi";
11796
11906
  mode = "additive";
11907
+ modelRequired = true;
11797
11908
  envVarNames = [];
11798
11909
  envNote = "Kimi Code \u4E0D\u4ECE shell \u8BFB\u53D6\u51ED\u636E\uFF0Cenv.sh \u5BF9\u5B83\u65E0\u6548\u3002";
11799
11910
  fields = [
@@ -11928,6 +12039,7 @@ class PiAdapter {
11928
12039
  environment;
11929
12040
  id = "pi";
11930
12041
  mode = "additive";
12042
+ modelRequired = true;
11931
12043
  envVarNames = [];
11932
12044
  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";
11933
12045
  fields = [
@@ -12157,8 +12269,13 @@ class LiveWriteService {
12157
12269
  this.log = log;
12158
12270
  }
12159
12271
  apply(harness, profile, writes) {
12160
- if (writes.length === 0) {
12272
+ this.transaction(harness, profile, writes, () => {
12161
12273
  return;
12274
+ });
12275
+ }
12276
+ transaction(harness, profile, writes, operation) {
12277
+ if (writes.length === 0) {
12278
+ return operation();
12162
12279
  }
12163
12280
  for (const write2 of writes) {
12164
12281
  assertParsable(write2.format, write2.path, write2.content);
@@ -12171,22 +12288,34 @@ class LiveWriteService {
12171
12288
  const written = [];
12172
12289
  try {
12173
12290
  for (const [index, write2] of writes.entries()) {
12174
- this.files.writeUserFile(write2.path, write2.content);
12175
- written.push(snapshots[index]);
12291
+ this.write(write2);
12292
+ written.push({ snapshot: snapshots[index], secret: write2.secret === true });
12176
12293
  }
12294
+ return operation();
12177
12295
  } catch (error) {
12178
12296
  this.rollback(written);
12179
12297
  throw error;
12180
12298
  }
12181
12299
  }
12300
+ write(write2) {
12301
+ if (write2.secret) {
12302
+ this.files.writeUserSecretFile(write2.path, write2.content);
12303
+ return;
12304
+ }
12305
+ this.files.writeUserFile(write2.path, write2.content);
12306
+ }
12182
12307
  rollback(written) {
12183
- for (const snapshot of written.toReversed()) {
12308
+ for (const { snapshot, secret } of written.toReversed()) {
12184
12309
  try {
12185
12310
  if (snapshot.content === undefined) {
12186
12311
  this.files.remove(snapshot.path);
12187
12312
  continue;
12188
12313
  }
12189
- this.files.writeUserFile(snapshot.path, snapshot.content);
12314
+ if (secret) {
12315
+ this.files.writeUserSecretFile(snapshot.path, snapshot.content);
12316
+ } else {
12317
+ this.files.writeUserFile(snapshot.path, snapshot.content);
12318
+ }
12190
12319
  } catch (error) {
12191
12320
  this.log.error(`rollback failed for ${snapshot.path}`, error);
12192
12321
  }
@@ -13021,7 +13150,14 @@ class DriftService {
13021
13150
  return preview.map((target) => this.classify({ key: target.key, label: target.label, path: target.path, format: target.format }, target.content, target.currentContent ?? null));
13022
13151
  }
13023
13152
  officialFiles(harness) {
13024
- const targets = this.adapters.get(harness).targets();
13153
+ const adapter = this.adapters.get(harness);
13154
+ let targets;
13155
+ try {
13156
+ const writes = this.activation.expectedWrites(harness);
13157
+ targets = adapter.targets().filter((target) => writes.some((write2) => write2.path === target.path));
13158
+ } catch {
13159
+ targets = adapter.targets().filter((target) => target.key !== "auth");
13160
+ }
13025
13161
  return targets.map((target) => {
13026
13162
  const live = this.files.readOptional(target.path) ?? null;
13027
13163
  const base = {
@@ -13332,6 +13468,7 @@ function createHarnessRoutes(services) {
13332
13468
  active: activation.getActive(id),
13333
13469
  profiles: profiles.list(id),
13334
13470
  fields: adapter.fields,
13471
+ modelRequired: adapter.modelRequired,
13335
13472
  targets: adapter.targets(),
13336
13473
  envVars: adapter.envVarNames,
13337
13474
  envNote: adapter.envNote,
@@ -13484,12 +13621,126 @@ async function readBody2(read) {
13484
13621
 
13485
13622
  // src/services/transfer.ts
13486
13623
  import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4, scryptSync } from "crypto";
13624
+
13625
+ // src/services/codex-login-cache.ts
13626
+ import { lstatSync } from "fs";
13627
+ import { join as join11 } from "path";
13628
+ var AUTH_FILE = "auth.json";
13629
+ var MAX_CACHE_BYTES = 1024 * 1024;
13630
+ var ICodexLoginCacheService = createDecorator("codexLoginCacheService");
13631
+ var _dec = [
13632
+ inject(IEnvironmentService, IFileService)
13633
+ ];
13634
+ var _init = __decoratorStart(undefined);
13635
+
13636
+ class CodexLoginCacheService {
13637
+ environment;
13638
+ files;
13639
+ constructor(environment, files) {
13640
+ this.environment = environment;
13641
+ this.files = files;
13642
+ }
13643
+ exists() {
13644
+ const file = this.path();
13645
+ this.assertDirectory(false);
13646
+ return this.assertRegularFile(file, false);
13647
+ }
13648
+ readOptional() {
13649
+ const file = this.path();
13650
+ this.assertDirectory(false);
13651
+ if (!this.assertRegularFile(file, false)) {
13652
+ return;
13653
+ }
13654
+ const content = this.files.readOptional(file);
13655
+ if (content === undefined) {
13656
+ return;
13657
+ }
13658
+ this.validate(content);
13659
+ return content;
13660
+ }
13661
+ validate(content) {
13662
+ if (Buffer.byteLength(content, "utf8") > MAX_CACHE_BYTES) {
13663
+ throw new HttpError(400, "Codex \u767B\u5F55\u7F13\u5B58\u8FC7\u5927\uFF0C\u62D2\u7EDD\u8FC1\u79FB");
13664
+ }
13665
+ try {
13666
+ const value = JSON.parse(content);
13667
+ if (!isPlainObject2(value)) {
13668
+ throw new Error("not an object");
13669
+ }
13670
+ } catch {
13671
+ throw new HttpError(400, "Codex \u767B\u5F55\u7F13\u5B58\u4E0D\u662F\u6709\u6548\u7684 JSON \u5BF9\u8C61\uFF0C\u62D2\u7EDD\u8FC1\u79FB");
13672
+ }
13673
+ }
13674
+ prepareWrite(content) {
13675
+ this.validate(content);
13676
+ const directory = this.assertDirectory(true);
13677
+ const path = join11(directory, AUTH_FILE);
13678
+ this.assertRegularFile(path, false);
13679
+ return { path, content };
13680
+ }
13681
+ write(content) {
13682
+ const write2 = this.prepareWrite(content);
13683
+ this.files.writeUserSecretFile(write2.path, write2.content);
13684
+ }
13685
+ path() {
13686
+ return join11(this.environment.harnessHomes.codex, AUTH_FILE);
13687
+ }
13688
+ assertDirectory(create) {
13689
+ const directory = this.environment.harnessHomes.codex;
13690
+ try {
13691
+ const stat2 = lstatSync(directory);
13692
+ if (stat2.isSymbolicLink() || !stat2.isDirectory()) {
13693
+ throw new HttpError(400, "Codex \u914D\u7F6E\u76EE\u5F55\u5FC5\u987B\u662F\u666E\u901A\u76EE\u5F55\uFF0C\u62D2\u7EDD\u8FC1\u79FB\u767B\u5F55\u7F13\u5B58");
13694
+ }
13695
+ return directory;
13696
+ } catch (error2) {
13697
+ if (error2.code !== "ENOENT") {
13698
+ throw error2;
13699
+ }
13700
+ if (!create) {
13701
+ return directory;
13702
+ }
13703
+ this.files.ensureDir(directory);
13704
+ const created = lstatSync(directory);
13705
+ if (created.isSymbolicLink() || !created.isDirectory()) {
13706
+ throw new HttpError(400, "Codex \u914D\u7F6E\u76EE\u5F55\u5FC5\u987B\u662F\u666E\u901A\u76EE\u5F55\uFF0C\u62D2\u7EDD\u8FC1\u79FB\u767B\u5F55\u7F13\u5B58");
13707
+ }
13708
+ return directory;
13709
+ }
13710
+ }
13711
+ assertRegularFile(file, required) {
13712
+ try {
13713
+ const stat2 = lstatSync(file);
13714
+ if (stat2.isSymbolicLink() || !stat2.isFile()) {
13715
+ throw new HttpError(400, "Codex \u767B\u5F55\u7F13\u5B58\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\uFF0C\u62D2\u7EDD\u8FC1\u79FB");
13716
+ }
13717
+ if (stat2.size > MAX_CACHE_BYTES) {
13718
+ throw new HttpError(400, "Codex \u767B\u5F55\u7F13\u5B58\u8FC7\u5927\uFF0C\u62D2\u7EDD\u8FC1\u79FB");
13719
+ }
13720
+ return true;
13721
+ } catch (error2) {
13722
+ if (error2.code === "ENOENT" && !required) {
13723
+ return false;
13724
+ }
13725
+ throw error2;
13726
+ }
13727
+ }
13728
+ }
13729
+ CodexLoginCacheService = __decorateElement(_init, 0, "CodexLoginCacheService", _dec, CodexLoginCacheService);
13730
+ __runInitializers(_init, 1, CodexLoginCacheService);
13731
+ __decoratorMetadata(_init, CodexLoginCacheService);
13732
+ let _CodexLoginCacheService = CodexLoginCacheService;
13733
+ function isPlainObject2(value) {
13734
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13735
+ }
13736
+
13737
+ // src/services/transfer.ts
13487
13738
  var FORMAT = "harness-switch-encrypted-export";
13488
13739
  var VERSION = 1;
13489
13740
  var MAX_ENCRYPTED_BYTES = 10 * 1024 * 1024;
13490
13741
  var ITransferService = createDecorator("transferService");
13491
13742
  var _dec = [
13492
- inject(IEnvironmentService, IFileService, ICryptoService, IAdapterRegistry, IActivationService, IVaultService)
13743
+ inject(IEnvironmentService, IFileService, ICryptoService, ICodexLoginCacheService, ILiveWriteService, IAdapterRegistry, IActivationService, IVaultService)
13493
13744
  ];
13494
13745
  var _init = __decoratorStart(undefined);
13495
13746
 
@@ -13497,19 +13748,30 @@ class TransferService {
13497
13748
  environment;
13498
13749
  files;
13499
13750
  crypto;
13751
+ codexLoginCache;
13752
+ liveWrite;
13500
13753
  adapters;
13501
13754
  activation;
13502
13755
  vault;
13503
- constructor(environment, files, crypto2, adapters, activation, vault) {
13756
+ constructor(environment, files, crypto2, codexLoginCache, liveWrite, adapters, activation, vault) {
13504
13757
  this.environment = environment;
13505
13758
  this.files = files;
13506
13759
  this.crypto = crypto2;
13760
+ this.codexLoginCache = codexLoginCache;
13761
+ this.liveWrite = liveWrite;
13507
13762
  this.adapters = adapters;
13508
13763
  this.activation = activation;
13509
13764
  this.vault = vault;
13510
13765
  }
13511
- exportAll(passphrase) {
13766
+ exportPreview() {
13767
+ return { codexLoginCacheAvailable: this.codexLoginCache.exists() };
13768
+ }
13769
+ exportAll(passphrase, includeCodexLoginCache) {
13512
13770
  this.assertPassphrase(passphrase);
13771
+ const codexLoginCache = includeCodexLoginCache ? this.codexLoginCache.readOptional() : undefined;
13772
+ if (includeCodexLoginCache && codexLoginCache === undefined) {
13773
+ throw new HttpError(400, "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u53EF\u5BFC\u51FA\u7684 Codex \u767B\u5F55\u7F13\u5B58");
13774
+ }
13513
13775
  const store = this.readStore();
13514
13776
  const profiles = [];
13515
13777
  for (const harness of HARNESS_IDS) {
@@ -13541,12 +13803,15 @@ class TransferService {
13541
13803
  version: VERSION,
13542
13804
  exportedAt: new Date().toISOString(),
13543
13805
  profiles,
13544
- active
13806
+ active,
13807
+ codexLoginCache
13545
13808
  }, passphrase);
13546
13809
  }
13547
- preview(envelope, passphrase) {
13810
+ preview(envelope, passphrase, conflictPolicy, restoreActive) {
13811
+ this.assertConflictPolicy(conflictPolicy);
13548
13812
  const payload = this.decrypt(envelope, passphrase);
13549
- const store = this.readStore();
13813
+ const existing = this.readStore();
13814
+ const plan = this.planImport(payload, existing, conflictPolicy, restoreActive);
13550
13815
  return {
13551
13816
  exportedAt: payload.exportedAt,
13552
13817
  profileCount: payload.profiles.length,
@@ -13554,35 +13819,41 @@ class TransferService {
13554
13819
  harness,
13555
13820
  profiles: payload.profiles.filter((profile) => profile.harness === harness).length
13556
13821
  })).filter((item) => item.profiles > 0),
13557
- conflicts: payload.profiles.filter((profile) => store[profile.harness]?.[profile.name] !== undefined).map(({ harness, name }) => ({ harness, name })),
13558
- activeCount: payload.active.length
13822
+ conflicts: payload.profiles.filter((profile) => existing[profile.harness]?.[profile.name] !== undefined).map(({ harness, name }) => ({ harness, name })),
13823
+ activeCount: payload.active.length,
13824
+ conflictPolicy,
13825
+ restoreActive,
13826
+ codexActivationAuthEffect: plan.codexActivationAuthEffect,
13827
+ codexLoginCache: {
13828
+ available: payload.codexLoginCache !== undefined,
13829
+ targetExists: this.codexLoginCache.exists()
13830
+ }
13559
13831
  };
13560
13832
  }
13561
- importAll(envelope, passphrase, conflictPolicy, restoreActive) {
13562
- if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
13563
- throw new HttpError(400, "invalid conflict policy");
13564
- }
13833
+ importAll(envelope, passphrase, conflictPolicy, restoreActive, migrateCodexLoginCache) {
13834
+ this.assertConflictPolicy(conflictPolicy);
13565
13835
  const payload = this.decrypt(envelope, passphrase);
13566
- const store = structuredClone(this.readStore());
13567
- let imported = 0;
13568
- let overwritten = 0;
13569
- let skipped = 0;
13570
- for (const profile of payload.profiles) {
13571
- this.validateProfile(profile);
13572
- store[profile.harness] ||= {};
13573
- const exists = store[profile.harness][profile.name] !== undefined;
13574
- if (exists && conflictPolicy === "skip") {
13575
- skipped++;
13576
- continue;
13836
+ if (migrateCodexLoginCache && payload.codexLoginCache === undefined) {
13837
+ throw new HttpError(400, "\u5BFC\u51FA\u5305\u4E0D\u5305\u542B\u53EF\u8FC1\u79FB\u7684 Codex \u767B\u5F55\u7F13\u5B58");
13838
+ }
13839
+ const cacheWrite = migrateCodexLoginCache ? [
13840
+ {
13841
+ ...this.codexLoginCache.prepareWrite(payload.codexLoginCache),
13842
+ format: "json",
13843
+ secret: true
13577
13844
  }
13578
- store[profile.harness][profile.name] = this.toStored(profile);
13579
- if (exists) {
13580
- overwritten++;
13581
- } else {
13582
- imported++;
13845
+ ] : [];
13846
+ const plan = this.planImport(payload, this.readStore(), conflictPolicy, restoreActive);
13847
+ const profilesPath = this.environment.files.profiles;
13848
+ const profileSnapshot = this.files.readOptional(profilesPath);
13849
+ this.liveWrite.transaction("codex", "\u5BFC\u5165\u767B\u5F55\u7F13\u5B58", cacheWrite, () => {
13850
+ try {
13851
+ this.files.writeJson(profilesPath, plan.store);
13852
+ } catch (error2) {
13853
+ this.restore(profilesPath, profileSnapshot);
13854
+ throw error2;
13583
13855
  }
13584
- }
13585
- this.files.writeJson(this.environment.files.profiles, store);
13856
+ });
13586
13857
  const warnings = [];
13587
13858
  let activeRestored = 0;
13588
13859
  if (restoreActive) {
@@ -13590,7 +13861,7 @@ class TransferService {
13590
13861
  try {
13591
13862
  if (active.official) {
13592
13863
  this.activation.activateOfficial(active.harness);
13593
- } else if (store[active.harness]?.[active.name]) {
13864
+ } else if (plan.store[active.harness]?.[active.name]) {
13594
13865
  this.activation.activate(active.harness, active.name);
13595
13866
  } else {
13596
13867
  throw new Error("\u5BF9\u5E94\u914D\u7F6E\u4E0D\u5B58\u5728");
@@ -13601,7 +13872,15 @@ class TransferService {
13601
13872
  }
13602
13873
  }
13603
13874
  }
13604
- return { ok: true, imported, overwritten, skipped, activeRestored, warnings };
13875
+ return {
13876
+ ok: true,
13877
+ imported: plan.imported,
13878
+ overwritten: plan.overwritten,
13879
+ skipped: plan.skipped,
13880
+ activeRestored,
13881
+ codexLoginCacheMigrated: cacheWrite.length > 0,
13882
+ warnings
13883
+ };
13605
13884
  }
13606
13885
  decrypt(envelope, passphrase) {
13607
13886
  this.assertPassphrase(passphrase);
@@ -13622,8 +13901,93 @@ class TransferService {
13622
13901
  throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u4E2D\u7684\u6FC0\u6D3B\u72B6\u6001\u65E0\u6548");
13623
13902
  }
13624
13903
  }
13904
+ if (payload.codexLoginCache !== undefined) {
13905
+ if (typeof payload.codexLoginCache !== "string") {
13906
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u4E2D\u7684 Codex \u767B\u5F55\u7F13\u5B58\u65E0\u6548");
13907
+ }
13908
+ this.codexLoginCache.validate(payload.codexLoginCache);
13909
+ }
13910
+ this.validatePayload(payload);
13625
13911
  return payload;
13626
13912
  }
13913
+ assertConflictPolicy(conflictPolicy) {
13914
+ if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
13915
+ throw new HttpError(400, "invalid conflict policy");
13916
+ }
13917
+ }
13918
+ validatePayload(payload) {
13919
+ const profileIds = new Set;
13920
+ for (const profile of payload.profiles) {
13921
+ this.validateProfile(profile);
13922
+ const id = profileId(profile.harness, profile.name);
13923
+ if (profileIds.has(id)) {
13924
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u5305\u542B\u91CD\u590D\u7684\u914D\u7F6E");
13925
+ }
13926
+ profileIds.add(id);
13927
+ }
13928
+ const activeHarnesses = new Set;
13929
+ for (const active of payload.active) {
13930
+ if (activeHarnesses.has(active.harness)) {
13931
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u5305\u542B\u91CD\u590D\u7684\u6FC0\u6D3B\u72B6\u6001");
13932
+ }
13933
+ activeHarnesses.add(active.harness);
13934
+ const adapter = this.adapters.get(active.harness);
13935
+ if (active.official) {
13936
+ if (active.name !== "\u5B98\u65B9\u767B\u5F55" || !adapter.renderOfficial) {
13937
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u4E2D\u7684\u5B98\u65B9\u767B\u5F55\u72B6\u6001\u65E0\u6548");
13938
+ }
13939
+ } else if (!profileIds.has(profileId(active.harness, active.name))) {
13940
+ throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u4E2D\u7684\u6FC0\u6D3B\u72B6\u6001\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u914D\u7F6E");
13941
+ }
13942
+ }
13943
+ }
13944
+ planImport(payload, existing, conflictPolicy, restoreActive) {
13945
+ const store = structuredClone(existing);
13946
+ let imported = 0;
13947
+ let overwritten = 0;
13948
+ let skipped = 0;
13949
+ for (const profile of payload.profiles) {
13950
+ store[profile.harness] ||= {};
13951
+ const exists = store[profile.harness][profile.name] !== undefined;
13952
+ if (exists && conflictPolicy === "skip") {
13953
+ skipped++;
13954
+ continue;
13955
+ }
13956
+ store[profile.harness][profile.name] = this.toStored(profile);
13957
+ if (exists) {
13958
+ overwritten++;
13959
+ } else {
13960
+ imported++;
13961
+ }
13962
+ }
13963
+ return {
13964
+ store,
13965
+ imported,
13966
+ overwritten,
13967
+ skipped,
13968
+ codexActivationAuthEffect: this.codexActivationAuthEffect(payload, store, restoreActive)
13969
+ };
13970
+ }
13971
+ codexActivationAuthEffect(payload, store, restoreActive) {
13972
+ if (!restoreActive) {
13973
+ return "none";
13974
+ }
13975
+ const active = payload.active.find((item) => item.harness === "codex");
13976
+ if (!active) {
13977
+ return "none";
13978
+ }
13979
+ if (active.official) {
13980
+ return "official-cleanup";
13981
+ }
13982
+ const profile = store.codex?.[active.name];
13983
+ if (!profile) {
13984
+ return "none";
13985
+ }
13986
+ if (profile.overrides?.auth !== undefined) {
13987
+ return "auth-override";
13988
+ }
13989
+ return profile.extras?.authMode === "openai_auth" ? "openai-api-key" : "none";
13990
+ }
13627
13991
  validateProfile(profile) {
13628
13992
  if (!profile.name || profile.name.length > 120 || /[\\/]/.test(profile.name)) {
13629
13993
  throw new HttpError(400, "\u5BFC\u51FA\u6587\u4EF6\u5305\u542B\u65E0\u6548\u7684\u914D\u7F6E\u540D\u79F0");
@@ -13650,6 +14014,14 @@ class TransferService {
13650
14014
  readStore() {
13651
14015
  return this.files.readJsonStrict(this.environment.files.profiles, {});
13652
14016
  }
14017
+ restore(path, snapshot) {
14018
+ try {
14019
+ if (snapshot === undefined)
14020
+ this.files.remove(path);
14021
+ else
14022
+ this.files.writeSecure(path, snapshot);
14023
+ } catch {}
14024
+ }
13653
14025
  resolveKey(stored) {
13654
14026
  if (!stored.provider_id) {
13655
14027
  return this.crypto.decrypt(stored.api_key);
@@ -13706,6 +14078,9 @@ function decrypt(envelope, passphrase) {
13706
14078
  throw new HttpError(400, "\u8FC1\u79FB\u5BC6\u7801\u9519\u8BEF\u6216\u5BFC\u51FA\u6587\u4EF6\u5DF2\u635F\u574F");
13707
14079
  }
13708
14080
  }
14081
+ function profileId(harness, name) {
14082
+ return `${harness}\x00${name}`;
14083
+ }
13709
14084
  function isStringRecord(value) {
13710
14085
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((item) => typeof item === "string");
13711
14086
  }
@@ -13728,17 +14103,18 @@ function isPortableActive(value) {
13728
14103
  function createTransferRoutes(services) {
13729
14104
  const app = new Hono2;
13730
14105
  const transfer = services.get(ITransferService);
14106
+ app.get("/export/preview", (c) => c.json(transfer.exportPreview()));
13731
14107
  app.post("/export", async (c) => {
13732
14108
  const body = await readBody3(c.req.json.bind(c.req));
13733
- return c.json(transfer.exportAll(String(body.passphrase ?? "")));
14109
+ return c.json(transfer.exportAll(String(body.passphrase ?? ""), body.includeCodexLoginCache === true));
13734
14110
  });
13735
14111
  app.post("/preview", async (c) => {
13736
14112
  const body = await readBody3(c.req.json.bind(c.req));
13737
- return c.json(transfer.preview(requireEnvelope(body.envelope), String(body.passphrase ?? "")));
14113
+ return c.json(transfer.preview(requireEnvelope(body.envelope), String(body.passphrase ?? ""), body.conflictPolicy ?? "skip", body.restoreActive === true));
13738
14114
  });
13739
14115
  app.post("/import", async (c) => {
13740
14116
  const body = await readBody3(c.req.json.bind(c.req));
13741
- return c.json(transfer.importAll(requireEnvelope(body.envelope), String(body.passphrase ?? ""), body.conflictPolicy ?? "skip", body.restoreActive === true));
14117
+ return c.json(transfer.importAll(requireEnvelope(body.envelope), String(body.passphrase ?? ""), body.conflictPolicy ?? "skip", body.restoreActive === true, body.migrateCodexLoginCache === true));
13742
14118
  });
13743
14119
  return app;
13744
14120
  }
@@ -13766,9 +14142,10 @@ function createUpdateRoutes(_services) {
13766
14142
  }
13767
14143
 
13768
14144
  // src/services/user-sync.ts
14145
+ import { isDeepStrictEqual } from "util";
13769
14146
  var IUserSyncService = createDecorator("userSyncService");
13770
14147
  var _dec = [
13771
- inject(IEnvironmentService, IUserService, IFileService, ICryptoService)
14148
+ inject(IEnvironmentService, IUserService, IFileService, ICryptoService, ICodexLoginCacheService, ILiveWriteService, IActivationService)
13772
14149
  ];
13773
14150
  var _init = __decoratorStart(undefined);
13774
14151
 
@@ -13777,24 +14154,31 @@ class UserSyncService {
13777
14154
  users;
13778
14155
  files;
13779
14156
  crypto;
13780
- constructor(environment, users, files, crypto2) {
14157
+ codexLoginCache;
14158
+ liveWrite;
14159
+ activation;
14160
+ constructor(environment, users, files, crypto2, codexLoginCache, liveWrite, activation) {
13781
14161
  this.environment = environment;
13782
14162
  this.users = users;
13783
14163
  this.files = files;
13784
14164
  this.crypto = crypto2;
14165
+ this.codexLoginCache = codexLoginCache;
14166
+ this.liveWrite = liveWrite;
14167
+ this.activation = activation;
13785
14168
  }
13786
14169
  preview(sourceUsername) {
13787
14170
  const target = this.environment.currentUser;
13788
14171
  const source = this.requireSource(sourceUsername, target);
13789
14172
  const portable = this.readPortable(source);
13790
- const targetProfiles = this.readProfiles();
14173
+ const targetPortable = this.readPortable(target);
13791
14174
  const conflicts = [];
13792
14175
  let profileCount = 0;
13793
14176
  const referencedProviders = new Set;
13794
14177
  for (const [harness, profiles] of Object.entries(portable.profiles)) {
13795
14178
  for (const [name, profile] of Object.entries(profiles)) {
13796
14179
  profileCount++;
13797
- if (targetProfiles[harness]?.[name]) {
14180
+ const targetProfile = targetPortable.profiles[harness]?.[name];
14181
+ if (targetProfile && !this.profilesEqual(profile, portable.providers, targetProfile, targetPortable.providers)) {
13798
14182
  conflicts.push({ harness, name });
13799
14183
  }
13800
14184
  if (profile.provider_id)
@@ -13806,16 +14190,34 @@ class UserSyncService {
13806
14190
  targetUser: target.username,
13807
14191
  profileCount,
13808
14192
  providerCount: referencedProviders.size,
13809
- conflicts
14193
+ conflicts,
14194
+ codexLoginCache: {
14195
+ available: this.environment.runAsUser(source, () => this.codexLoginCache.exists()),
14196
+ targetExists: this.codexLoginCache.exists()
14197
+ }
13810
14198
  };
13811
14199
  }
13812
- sync(sourceUsername, conflictPolicy) {
14200
+ sync(sourceUsername, conflictPolicy, migrateCodexLoginCache, overwriteHarnesses = []) {
13813
14201
  if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
13814
14202
  throw new HttpError(400, "invalid conflict policy");
13815
14203
  }
13816
14204
  const target = this.environment.currentUser;
13817
14205
  const source = this.requireSource(sourceUsername, target);
14206
+ const selectiveOverwrites = new Set(overwriteHarnesses);
14207
+ const overwriteAll = conflictPolicy === "overwrite";
13818
14208
  const portable = this.readPortable(source);
14209
+ const targetPortable = this.readPortable(target);
14210
+ const cacheContent = migrateCodexLoginCache ? this.environment.runAsUser(source, () => this.codexLoginCache.readOptional()) : undefined;
14211
+ if (migrateCodexLoginCache && cacheContent === undefined) {
14212
+ throw new HttpError(400, "\u6765\u6E90\u7528\u6237\u6CA1\u6709\u53EF\u8FC1\u79FB\u7684 Codex \u767B\u5F55\u7F13\u5B58");
14213
+ }
14214
+ const cacheWrite = cacheContent ? [
14215
+ {
14216
+ ...this.codexLoginCache.prepareWrite(cacheContent),
14217
+ format: "json",
14218
+ secret: true
14219
+ }
14220
+ ] : [];
13819
14221
  const profilesPath = this.environment.files.profiles;
13820
14222
  const vaultPath = this.environment.files.vault;
13821
14223
  const profileSnapshot = this.files.readOptional(profilesPath);
@@ -13824,6 +14226,7 @@ class UserSyncService {
13824
14226
  const targetVault = structuredClone(this.readVault());
13825
14227
  const active = this.files.readJson(this.environment.files.active, {});
13826
14228
  const warnings = [];
14229
+ const activeProfilesToReapply = new Map;
13827
14230
  let imported = 0;
13828
14231
  let overwritten = 0;
13829
14232
  let skipped = 0;
@@ -13831,7 +14234,10 @@ class UserSyncService {
13831
14234
  for (const [harness, profiles] of Object.entries(portable.profiles)) {
13832
14235
  for (const [name, profile] of Object.entries(profiles)) {
13833
14236
  const exists = targetProfiles[harness]?.[name] !== undefined;
13834
- if (exists && conflictPolicy === "skip") {
14237
+ const targetProfile = targetPortable.profiles[harness]?.[name];
14238
+ const unchanged = targetProfile !== undefined && this.profilesEqual(profile, portable.providers, targetProfile, targetPortable.providers);
14239
+ const overwrite = overwriteAll || selectiveOverwrites.has(harness);
14240
+ if (unchanged || exists && !overwrite) {
13835
14241
  skipped++;
13836
14242
  continue;
13837
14243
  }
@@ -13839,7 +14245,7 @@ class UserSyncService {
13839
14245
  if (exists) {
13840
14246
  overwritten++;
13841
14247
  if (active[harness]?.name === name) {
13842
- 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`);
14248
+ activeProfilesToReapply.set(harness, name);
13843
14249
  }
13844
14250
  } else
13845
14251
  imported++;
@@ -13878,13 +14284,23 @@ class UserSyncService {
13878
14284
  updated_at: new Date().toISOString()
13879
14285
  };
13880
14286
  }
13881
- try {
13882
- this.files.writeJson(vaultPath, targetVault);
13883
- this.files.writeJson(profilesPath, targetProfiles);
13884
- } catch (error2) {
13885
- this.restore(vaultPath, vaultSnapshot);
13886
- this.restore(profilesPath, profileSnapshot);
13887
- throw error2;
14287
+ this.liveWrite.transaction("codex", `\u540C\u6B65-${source.username}`, cacheWrite, () => {
14288
+ try {
14289
+ this.files.writeJson(vaultPath, targetVault);
14290
+ this.files.writeJson(profilesPath, targetProfiles);
14291
+ } catch (error2) {
14292
+ this.restore(vaultPath, vaultSnapshot);
14293
+ this.restore(profilesPath, profileSnapshot);
14294
+ throw error2;
14295
+ }
14296
+ });
14297
+ for (const [harness, name] of activeProfilesToReapply) {
14298
+ try {
14299
+ const result = this.activation.activate(harness, name);
14300
+ warnings.push(...result.warnings.map((warning) => `${harness}/${name}: ${warning}`));
14301
+ } catch (error2) {
14302
+ warnings.push(`${harness}/${name} \u5DF2\u66F4\u65B0\u914D\u7F6E\u5E93\uFF0C\u4F46\u81EA\u52A8\u91CD\u65B0\u6FC0\u6D3B\u5931\u8D25\uFF1A${error2 instanceof Error ? error2.message : String(error2)}`);
14303
+ }
13888
14304
  }
13889
14305
  return {
13890
14306
  ok: true,
@@ -13894,6 +14310,7 @@ class UserSyncService {
13894
14310
  overwritten,
13895
14311
  skipped,
13896
14312
  providersCopied: providerMap.size,
14313
+ codexLoginCacheMigrated: cacheWrite.length > 0,
13897
14314
  warnings
13898
14315
  };
13899
14316
  }
@@ -13910,16 +14327,18 @@ class UserSyncService {
13910
14327
  const vault = this.readVault();
13911
14328
  const portableProviders = {};
13912
14329
  for (const [id, entry] of Object.entries(vault.entries)) {
13913
- portableProviders[id] = { ...entry, apiKey: this.crypto.decrypt(entry.api_key) };
14330
+ const { api_key: encryptedKey, ...provider } = entry;
14331
+ portableProviders[id] = { ...provider, apiKey: this.crypto.decrypt(encryptedKey) };
13914
14332
  }
13915
14333
  const portableProfiles = {};
13916
14334
  for (const [harness, entries] of Object.entries(profiles)) {
13917
14335
  portableProfiles[harness] = {};
13918
14336
  for (const [name, profile] of Object.entries(entries)) {
14337
+ const { api_key: encryptedKey, ...storedProfile } = profile;
13919
14338
  const providerKey = profile.provider_id ? portableProviders[profile.provider_id]?.apiKey : undefined;
13920
14339
  portableProfiles[harness][name] = {
13921
- ...profile,
13922
- apiKey: providerKey ?? this.crypto.decrypt(profile.api_key)
14340
+ ...storedProfile,
14341
+ apiKey: providerKey ?? this.crypto.decrypt(encryptedKey)
13923
14342
  };
13924
14343
  }
13925
14344
  }
@@ -13929,6 +14348,20 @@ class UserSyncService {
13929
14348
  readProfiles() {
13930
14349
  return this.files.readJsonStrict(this.environment.files.profiles, {});
13931
14350
  }
14351
+ profilesEqual(source, sourceProviders, target, targetProviders) {
14352
+ return isDeepStrictEqual(this.comparableProfile(source, sourceProviders), this.comparableProfile(target, targetProviders));
14353
+ }
14354
+ comparableProfile(profile, providers) {
14355
+ const { updated_at: _updatedAt, provider_id: providerId, ...content } = profile;
14356
+ const provider = providerId ? providers[providerId] : undefined;
14357
+ const comparableProvider = provider ? {
14358
+ name: provider.name,
14359
+ notes: provider.notes,
14360
+ endpoints: provider.endpoints,
14361
+ apiKey: provider.apiKey
14362
+ } : providerId ? { missing: true } : undefined;
14363
+ return { ...content, provider: comparableProvider };
14364
+ }
13932
14365
  readVault() {
13933
14366
  return this.files.readJsonStrict(this.environment.files.vault, {
13934
14367
  version: 1,
@@ -13985,7 +14418,7 @@ function createUserRoutes(services) {
13985
14418
  });
13986
14419
  app.post("/sync", async (c) => {
13987
14420
  const body = await readBody4(c.req.json.bind(c.req));
13988
- return c.json(sync.sync(String(body.sourceUser ?? ""), body.conflictPolicy ?? "skip"));
14421
+ return c.json(sync.sync(String(body.sourceUser ?? ""), body.conflictPolicy ?? "skip", body.migrateCodexLoginCache === true, parseOverwriteHarnesses(body.overwriteHarnesses)));
13989
14422
  });
13990
14423
  app.post("/:username/select", (c) => {
13991
14424
  const user = users.require(decodeURIComponent(c.req.param("username")));
@@ -14002,6 +14435,14 @@ async function readBody4(read) {
14002
14435
  throw new HttpError(400, "invalid json");
14003
14436
  });
14004
14437
  }
14438
+ function parseOverwriteHarnesses(value) {
14439
+ if (value === undefined)
14440
+ return [];
14441
+ if (!Array.isArray(value) || value.some((item) => !isHarnessId(item))) {
14442
+ throw new HttpError(400, "invalid overwrite harnesses");
14443
+ }
14444
+ return [...new Set(value)];
14445
+ }
14005
14446
 
14006
14447
  // src/app.ts
14007
14448
  function createApp(services) {
@@ -14045,11 +14486,11 @@ function createApp(services) {
14045
14486
  if (c.req.path.startsWith("/api") || c.req.path === "/healthz") {
14046
14487
  return next();
14047
14488
  }
14048
- const assetPath = join11(publicDir, c.req.path.replace(/^\//, ""));
14489
+ const assetPath = join12(publicDir, c.req.path.replace(/^\//, ""));
14049
14490
  if (c.req.path !== "/" && existsSync4(assetPath)) {
14050
14491
  return serveStatic2({ root: publicDir })(c, next);
14051
14492
  }
14052
- const index = join11(publicDir, "index.html");
14493
+ const index = join12(publicDir, "index.html");
14053
14494
  if (existsSync4(index)) {
14054
14495
  c.header("Cache-Control", "no-store");
14055
14496
  return c.html(await Bun.file(index).text());
@@ -14076,6 +14517,7 @@ function createServices() {
14076
14517
  collection.set(IUserService, new SyncDescriptor(UserService));
14077
14518
  collection.set(IUserSyncService, new SyncDescriptor(UserSyncService));
14078
14519
  collection.set(IFileService, new SyncDescriptor(FileService));
14520
+ collection.set(ICodexLoginCacheService, new SyncDescriptor(CodexLoginCacheService));
14079
14521
  collection.set(ICryptoService, new SyncDescriptor(CryptoService));
14080
14522
  collection.set(IAuthService, new SyncDescriptor(AuthService));
14081
14523
  collection.set(IHarnessRegistry, new SyncDescriptor(HarnessRegistry));
@@ -14146,25 +14588,25 @@ import { createInterface } from "readline/promises";
14146
14588
 
14147
14589
  // src/cli/client.ts
14148
14590
  import { readFileSync as readFileSync4 } from "fs";
14149
- import { join as join13 } from "path";
14591
+ import { join as join14 } from "path";
14150
14592
 
14151
14593
  // src/daemon.ts
14152
14594
  import { spawn as spawn2 } from "child_process";
14153
14595
  import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
14154
14596
  import { homedir as homedir3 } from "os";
14155
- import { join as join12, resolve } from "path";
14597
+ import { join as join13, resolve } from "path";
14156
14598
  var DEFAULT_HOST = "127.0.0.1";
14157
14599
  var DEFAULT_PORT = 8787;
14158
14600
  var STOP_TIMEOUT_MS = 5000;
14159
14601
  var START_GRACE_MS = 500;
14160
14602
  function daemonDataDir() {
14161
- return process.env.HSW_DATA_DIR || join12(homedir3(), ".harness-switch");
14603
+ return process.env.HSW_DATA_DIR || join13(homedir3(), ".harness-switch");
14162
14604
  }
14163
14605
  function daemonPidFile() {
14164
- return join12(daemonDataDir(), "daemon.pid");
14606
+ return join13(daemonDataDir(), "daemon.pid");
14165
14607
  }
14166
14608
  function daemonLogFile() {
14167
- return join12(daemonDataDir(), "daemon.log");
14609
+ return join13(daemonDataDir(), "daemon.log");
14168
14610
  }
14169
14611
  function readPid() {
14170
14612
  try {
@@ -14229,7 +14671,7 @@ function printStatus() {
14229
14671
  console.log(`harness-switch daemon: ${running ? `running (pid ${pid})` : "not running"}`);
14230
14672
  console.log(` url: http://${host}:${port}`);
14231
14673
  console.log(` log: ${daemonLogFile()}`);
14232
- console.log(` password: ${join12(daemonDataDir(), "web_password")}`);
14674
+ console.log(` password: ${join13(daemonDataDir(), "web_password")}`);
14233
14675
  console.log(` data: ${daemonDataDir()}`);
14234
14676
  }
14235
14677
  async function daemonize() {
@@ -14267,7 +14709,7 @@ async function daemonize() {
14267
14709
  console.log(` url: http://${host}:${port}`);
14268
14710
  console.log(` log: ${logPath}`);
14269
14711
  console.log(" manage: harness-switch status | harness-switch stop");
14270
- console.log(` password (first run): ${join12(daemonDataDir(), "web_password")}`);
14712
+ console.log(` password (first run): ${join13(daemonDataDir(), "web_password")}`);
14271
14713
  }
14272
14714
  function usage() {
14273
14715
  return [
@@ -14334,7 +14776,7 @@ function resolveBaseUrl() {
14334
14776
  return process.env.HSW_URL || `http://127.0.0.1:${process.env.PORT || 8787}`;
14335
14777
  }
14336
14778
  function readWebPassword() {
14337
- const file = join13(daemonDataDir(), "web_password");
14779
+ const file = join14(daemonDataDir(), "web_password");
14338
14780
  try {
14339
14781
  return readFileSync4(file, "utf8").trim();
14340
14782
  } catch {
@@ -14434,6 +14876,7 @@ function cliUsage() {
14434
14876
  " --harness H limit doctor to one harness",
14435
14877
  " --user USER run list/providers/doctor/plan/activate for this Unix user",
14436
14878
  " --overwrite overwrite same-name profiles during sync (default: skip)",
14879
+ " --copy-codex-auth copy the source user\u2019s Codex auth.json during sync",
14437
14880
  "",
14438
14881
  "environment:",
14439
14882
  " HSW_URL base URL of the local service (default http://127.0.0.1:8787)",
@@ -14503,15 +14946,17 @@ async function cmdSync(client, flags, json) {
14503
14946
  }
14504
14947
  await selectUser(client, target);
14505
14948
  const conflictPolicy = hasFlag(flags, "overwrite") ? "overwrite" : "skip";
14949
+ const copyCodexAuth = hasFlag(flags, "copy-codex-auth");
14506
14950
  const payload = await client.post("/api/users/sync", {
14507
14951
  sourceUser: source,
14508
- conflictPolicy
14952
+ conflictPolicy,
14953
+ migrateCodexLoginCache: copyCodexAuth
14509
14954
  });
14510
14955
  if (json === "json") {
14511
14956
  printJson(payload);
14512
14957
  } else {
14513
14958
  console.log(`\u5DF2\u4ECE ${source} \u540C\u6B65\u5230 ${target}`);
14514
- console.log(`\u65B0\u589E=${payload.imported} \u8986\u76D6=${payload.overwritten} \u8DF3\u8FC7=${payload.skipped} \u51ED\u636E=${payload.providersCopied}`);
14959
+ console.log(`\u65B0\u589E=${payload.imported} \u8986\u76D6=${payload.overwritten} \u8DF3\u8FC7=${payload.skipped} \u51ED\u636E=${payload.providersCopied} Codex\u767B\u5F55\u7F13\u5B58=${payload.codexLoginCacheMigrated ? "\u5DF2\u8FC1\u79FB" : "\u672A\u8FC1\u79FB"}`);
14515
14960
  }
14516
14961
  return 0;
14517
14962
  }