@seaveyon/harness-switch 0.11.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -2
- package/dist/harness-switch.js +1753 -171
- package/package.json +1 -1
- package/public/assets/main.2e820b75.css +2 -0
- package/public/assets/main.f1884118.js +1 -0
- package/public/index.html +1 -1
- package/public/assets/main.c2779d04.css +0 -2
- package/public/assets/main.c5247f86.js +0 -1
package/dist/harness-switch.js
CHANGED
|
@@ -7014,7 +7014,7 @@ var require_public_api = __commonJS((exports) => {
|
|
|
7014
7014
|
});
|
|
7015
7015
|
|
|
7016
7016
|
// src/app.ts
|
|
7017
|
-
import { existsSync as
|
|
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,39 +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
|
-
};
|
|
9208
|
-
backupsDir = join2(this.dataDir, "backups");
|
|
9209
9199
|
backupRetainCount = Math.max(1, Number(process.env.HSW_BACKUP_RETAIN || 10));
|
|
9210
|
-
|
|
9211
|
-
|
|
9212
|
-
|
|
9213
|
-
|
|
9214
|
-
|
|
9215
|
-
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")
|
|
9216
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
|
+
}
|
|
9217
9241
|
ensureDataDir() {
|
|
9218
9242
|
mkdirSync(this.dataDir, { recursive: true, mode: 448 });
|
|
9219
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
|
+
};
|
|
9220
9256
|
}
|
|
9221
9257
|
function resolveSessionTtlMs() {
|
|
9222
9258
|
const hours = Number(process.env.HSW_SESSION_TTL_HOURS || 24);
|
|
@@ -9235,6 +9271,7 @@ function resolvePublicDir() {
|
|
|
9235
9271
|
import { randomBytes } from "crypto";
|
|
9236
9272
|
import {
|
|
9237
9273
|
chmodSync,
|
|
9274
|
+
chownSync,
|
|
9238
9275
|
existsSync as existsSync2,
|
|
9239
9276
|
mkdirSync as mkdirSync2,
|
|
9240
9277
|
readdirSync,
|
|
@@ -9295,7 +9332,6 @@ class FileService {
|
|
|
9295
9332
|
}
|
|
9296
9333
|
}
|
|
9297
9334
|
writeSecure(file, text) {
|
|
9298
|
-
this.environment.ensureDataDir();
|
|
9299
9335
|
this.write(file, text, 384);
|
|
9300
9336
|
}
|
|
9301
9337
|
writeUserFile(file, text) {
|
|
@@ -9313,7 +9349,22 @@ class FileService {
|
|
|
9313
9349
|
`);
|
|
9314
9350
|
}
|
|
9315
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
|
+
}
|
|
9316
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
|
+
}
|
|
9317
9368
|
}
|
|
9318
9369
|
remove(file) {
|
|
9319
9370
|
rmSync(file, { force: true, recursive: true });
|
|
@@ -9328,7 +9379,9 @@ class FileService {
|
|
|
9328
9379
|
write(file, text, mode) {
|
|
9329
9380
|
this.ensureDir(dirname2(file));
|
|
9330
9381
|
const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
9382
|
+
const owner = this.ownerOf(file);
|
|
9331
9383
|
writeFileSync(tmp, text, { encoding: "utf8", mode });
|
|
9384
|
+
this.applyOwner(tmp, owner.uid, owner.gid);
|
|
9332
9385
|
renameSync(tmp, file);
|
|
9333
9386
|
try {
|
|
9334
9387
|
chmodSync(file, mode);
|
|
@@ -9341,6 +9394,27 @@ class FileService {
|
|
|
9341
9394
|
return 384;
|
|
9342
9395
|
}
|
|
9343
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
|
+
}
|
|
9344
9418
|
}
|
|
9345
9419
|
FileService = __decorateElement(_init, 0, "FileService", _dec, FileService);
|
|
9346
9420
|
__runInitializers(_init, 1, FileService);
|
|
@@ -9455,7 +9529,7 @@ class AuthService {
|
|
|
9455
9529
|
this.log = log;
|
|
9456
9530
|
}
|
|
9457
9531
|
ensurePassword() {
|
|
9458
|
-
const file = this.environment.
|
|
9532
|
+
const file = this.environment.managerFiles.password;
|
|
9459
9533
|
if (!this.files.exists(file)) {
|
|
9460
9534
|
const password = this.crypto.randomPassword();
|
|
9461
9535
|
this.files.writeSecure(file, `${password}
|
|
@@ -9471,7 +9545,8 @@ class AuthService {
|
|
|
9471
9545
|
}
|
|
9472
9546
|
const token = randomBytes3(32).toString("base64url");
|
|
9473
9547
|
this.load().set(digest("session", token), {
|
|
9474
|
-
expires: Date.now() + this.environment.sessionTtlMs
|
|
9548
|
+
expires: Date.now() + this.environment.sessionTtlMs,
|
|
9549
|
+
username: this.environment.defaultUser.username
|
|
9475
9550
|
});
|
|
9476
9551
|
this.persist();
|
|
9477
9552
|
return token;
|
|
@@ -9496,13 +9571,29 @@ class AuthService {
|
|
|
9496
9571
|
}
|
|
9497
9572
|
return true;
|
|
9498
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
|
+
}
|
|
9499
9590
|
load() {
|
|
9500
9591
|
const loaded = this.sessions;
|
|
9501
9592
|
if (loaded) {
|
|
9502
9593
|
return loaded;
|
|
9503
9594
|
}
|
|
9504
9595
|
this.fingerprint = digest("password", this.ensurePassword());
|
|
9505
|
-
const store = this.files.readJson(this.environment.
|
|
9596
|
+
const store = this.files.readJson(this.environment.managerFiles.sessions, {
|
|
9506
9597
|
version: STORE_VERSION,
|
|
9507
9598
|
password: this.fingerprint,
|
|
9508
9599
|
sessions: {}
|
|
@@ -9512,7 +9603,10 @@ class AuthService {
|
|
|
9512
9603
|
const now = Date.now();
|
|
9513
9604
|
for (const [key, session] of Object.entries(store.sessions ?? {})) {
|
|
9514
9605
|
if (typeof session?.expires === "number" && session.expires > now) {
|
|
9515
|
-
sessions.set(key, {
|
|
9606
|
+
sessions.set(key, {
|
|
9607
|
+
expires: session.expires,
|
|
9608
|
+
username: typeof session.username === "string" ? session.username : this.environment.defaultUser.username
|
|
9609
|
+
});
|
|
9516
9610
|
}
|
|
9517
9611
|
}
|
|
9518
9612
|
}
|
|
@@ -9527,7 +9621,7 @@ class AuthService {
|
|
|
9527
9621
|
if (!sessions) {
|
|
9528
9622
|
return;
|
|
9529
9623
|
}
|
|
9530
|
-
this.files.writeJson(this.environment.
|
|
9624
|
+
this.files.writeJson(this.environment.managerFiles.sessions, {
|
|
9531
9625
|
version: STORE_VERSION,
|
|
9532
9626
|
password: this.fingerprint,
|
|
9533
9627
|
sessions: Object.fromEntries(sessions)
|
|
@@ -9542,6 +9636,91 @@ function digest(kind, value) {
|
|
|
9542
9636
|
return createHash("sha256").update(`${kind}:${value}`).digest("base64url");
|
|
9543
9637
|
}
|
|
9544
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
|
+
|
|
9545
9724
|
// src/http/middleware.ts
|
|
9546
9725
|
function createServiceMiddleware(services) {
|
|
9547
9726
|
return async (c, next) => {
|
|
@@ -9567,12 +9746,15 @@ function createOriginGuard() {
|
|
|
9567
9746
|
function createAuthGuard(services) {
|
|
9568
9747
|
const auth = services.get(IAuthService);
|
|
9569
9748
|
const environment = services.get(IEnvironmentService);
|
|
9749
|
+
const users = services.get(IUserService);
|
|
9570
9750
|
return async (c, next) => {
|
|
9571
9751
|
const token = getCookie(c, environment.cookieName);
|
|
9572
9752
|
if (!auth.isAuthenticated(token)) {
|
|
9573
9753
|
throw new HttpError(401, "authentication required");
|
|
9574
9754
|
}
|
|
9575
|
-
|
|
9755
|
+
const username = auth.userForToken(token) ?? environment.defaultUser.username;
|
|
9756
|
+
const user = users.require(username);
|
|
9757
|
+
await environment.runAsUser(user, () => next());
|
|
9576
9758
|
};
|
|
9577
9759
|
}
|
|
9578
9760
|
|
|
@@ -9593,7 +9775,7 @@ function createAuthRoutes(services) {
|
|
|
9593
9775
|
path: "/",
|
|
9594
9776
|
maxAge: environment.sessionTtlMs / 1000
|
|
9595
9777
|
});
|
|
9596
|
-
return c.json({ authenticated: true });
|
|
9778
|
+
return c.json({ authenticated: true, currentUser: environment.defaultUser.username });
|
|
9597
9779
|
});
|
|
9598
9780
|
app.post("/logout", (c) => {
|
|
9599
9781
|
auth.logout(getCookie(c, environment.cookieName));
|
|
@@ -9605,7 +9787,7 @@ function createAuthRoutes(services) {
|
|
|
9605
9787
|
if (!auth.isAuthenticated(token)) {
|
|
9606
9788
|
throw new HttpError(401, "authentication required");
|
|
9607
9789
|
}
|
|
9608
|
-
return c.json({ authenticated: true });
|
|
9790
|
+
return c.json({ authenticated: true, currentUser: auth.userForToken(token) });
|
|
9609
9791
|
});
|
|
9610
9792
|
return app;
|
|
9611
9793
|
}
|
|
@@ -9766,8 +9948,105 @@ function createBackupRoutes(services) {
|
|
|
9766
9948
|
return app;
|
|
9767
9949
|
}
|
|
9768
9950
|
|
|
9769
|
-
// src/services/
|
|
9951
|
+
// src/services/doctor.ts
|
|
9952
|
+
import { accessSync, constants, statSync as statSync2 } from "fs";
|
|
9953
|
+
import { dirname as dirname3 } from "path";
|
|
9954
|
+
|
|
9955
|
+
// src/update.ts
|
|
9956
|
+
import { spawn } from "child_process";
|
|
9957
|
+
import { mkdirSync as mkdirSync3, openSync } from "fs";
|
|
9958
|
+
import { homedir as homedir2 } from "os";
|
|
9959
|
+
import { join as join5 } from "path";
|
|
9960
|
+
|
|
9961
|
+
// src/version.ts
|
|
9770
9962
|
import { join as join4 } from "path";
|
|
9963
|
+
var cached;
|
|
9964
|
+
async function packageInfo() {
|
|
9965
|
+
if (cached)
|
|
9966
|
+
return cached;
|
|
9967
|
+
try {
|
|
9968
|
+
const pkg = JSON.parse(await Bun.file(join4(import.meta.dir, "../package.json")).text());
|
|
9969
|
+
cached = {
|
|
9970
|
+
name: typeof pkg.name === "string" ? pkg.name : "harness-switch",
|
|
9971
|
+
version: typeof pkg.version === "string" ? pkg.version : "0.0.0"
|
|
9972
|
+
};
|
|
9973
|
+
} catch {
|
|
9974
|
+
cached = { name: "harness-switch", version: "0.0.0" };
|
|
9975
|
+
}
|
|
9976
|
+
return cached;
|
|
9977
|
+
}
|
|
9978
|
+
function serverVersion() {
|
|
9979
|
+
return packageInfo().then((info) => info.version);
|
|
9980
|
+
}
|
|
9981
|
+
function packageName() {
|
|
9982
|
+
return packageInfo().then((info) => info.name);
|
|
9983
|
+
}
|
|
9984
|
+
|
|
9985
|
+
// src/update.ts
|
|
9986
|
+
var REGISTRY_URL = "https://registry.npmjs.org/";
|
|
9987
|
+
var CHECK_TIMEOUT_MS = 5000;
|
|
9988
|
+
var CACHE_TTL_MS = 5 * 60000;
|
|
9989
|
+
var cached2;
|
|
9990
|
+
function compareVersions(a, b) {
|
|
9991
|
+
const pa = a.split(".").map(Number);
|
|
9992
|
+
const pb = b.split(".").map(Number);
|
|
9993
|
+
const len = Math.max(pa.length, pb.length);
|
|
9994
|
+
for (let i = 0;i < len; i++) {
|
|
9995
|
+
const da = pa[i] ?? 0;
|
|
9996
|
+
const db = pb[i] ?? 0;
|
|
9997
|
+
if (da !== db)
|
|
9998
|
+
return da > db ? 1 : -1;
|
|
9999
|
+
}
|
|
10000
|
+
return 0;
|
|
10001
|
+
}
|
|
10002
|
+
async function checkForUpdate(force = false) {
|
|
10003
|
+
const current = await serverVersion();
|
|
10004
|
+
if (!force && cached2 && Date.now() - cached2.at < CACHE_TTL_MS) {
|
|
10005
|
+
return {
|
|
10006
|
+
current,
|
|
10007
|
+
latest: cached2.latest,
|
|
10008
|
+
updateAvailable: cached2.latest !== null && compareVersions(cached2.latest, current) > 0
|
|
10009
|
+
};
|
|
10010
|
+
}
|
|
10011
|
+
try {
|
|
10012
|
+
const name = encodeURIComponent(await packageName());
|
|
10013
|
+
const response = await fetch(`${REGISTRY_URL}${name}/latest`, {
|
|
10014
|
+
signal: AbortSignal.timeout(CHECK_TIMEOUT_MS)
|
|
10015
|
+
});
|
|
10016
|
+
if (!response.ok) {
|
|
10017
|
+
throw new Error(`registry responded ${response.status}`);
|
|
10018
|
+
}
|
|
10019
|
+
const payload = await response.json();
|
|
10020
|
+
const latest = typeof payload.version === "string" ? payload.version : null;
|
|
10021
|
+
cached2 = { latest, at: Date.now() };
|
|
10022
|
+
return {
|
|
10023
|
+
current,
|
|
10024
|
+
latest,
|
|
10025
|
+
updateAvailable: latest !== null && compareVersions(latest, current) > 0
|
|
10026
|
+
};
|
|
10027
|
+
} catch {
|
|
10028
|
+
cached2 = { latest: null, at: Date.now() };
|
|
10029
|
+
return { current, latest: null, updateAvailable: false };
|
|
10030
|
+
}
|
|
10031
|
+
}
|
|
10032
|
+
async function triggerUpdate() {
|
|
10033
|
+
if (process.env.HSW_UPDATE_SPAWN === "0") {
|
|
10034
|
+
return;
|
|
10035
|
+
}
|
|
10036
|
+
const name = await packageName();
|
|
10037
|
+
const dataDir = process.env.HSW_DATA_DIR || join5(homedir2(), ".harness-switch");
|
|
10038
|
+
mkdirSync3(dataDir, { recursive: true, mode: 448 });
|
|
10039
|
+
const logFd = openSync(join5(dataDir, "update.log"), "w");
|
|
10040
|
+
const child = spawn(process.execPath, ["x", `${name}@latest`], {
|
|
10041
|
+
detached: true,
|
|
10042
|
+
stdio: ["ignore", logFd, logFd],
|
|
10043
|
+
env: process.env
|
|
10044
|
+
});
|
|
10045
|
+
child.unref();
|
|
10046
|
+
}
|
|
10047
|
+
|
|
10048
|
+
// src/services/adapters/claude.ts
|
|
10049
|
+
import { join as join6 } from "path";
|
|
9771
10050
|
|
|
9772
10051
|
// ../../node_modules/smol-toml/dist/date.js
|
|
9773
10052
|
/*!
|
|
@@ -11012,7 +11291,7 @@ API_TIMEOUT_MS=3000000`,
|
|
|
11012
11291
|
{
|
|
11013
11292
|
key: SETTINGS,
|
|
11014
11293
|
label: "settings.json",
|
|
11015
|
-
path:
|
|
11294
|
+
path: join6(this.environment.harnessHomes.claude, "settings.json"),
|
|
11016
11295
|
format: "json"
|
|
11017
11296
|
}
|
|
11018
11297
|
];
|
|
@@ -11126,7 +11405,7 @@ function parseEnvLines(raw2) {
|
|
|
11126
11405
|
}
|
|
11127
11406
|
|
|
11128
11407
|
// src/services/adapters/codex.ts
|
|
11129
|
-
import { join as
|
|
11408
|
+
import { join as join7 } from "path";
|
|
11130
11409
|
var CONFIG = "config";
|
|
11131
11410
|
var AUTH = "auth";
|
|
11132
11411
|
var DEFAULT_ENV_KEY = "OPENAI_API_KEY";
|
|
@@ -11193,13 +11472,13 @@ class CodexAdapter {
|
|
|
11193
11472
|
{
|
|
11194
11473
|
key: CONFIG,
|
|
11195
11474
|
label: "config.toml",
|
|
11196
|
-
path:
|
|
11475
|
+
path: join7(this.environment.harnessHomes.codex, "config.toml"),
|
|
11197
11476
|
format: "toml"
|
|
11198
11477
|
},
|
|
11199
11478
|
{
|
|
11200
11479
|
key: AUTH,
|
|
11201
11480
|
label: "auth.json\uFF08\u4EC5 auth.json \u6A21\u5F0F\uFF09",
|
|
11202
|
-
path:
|
|
11481
|
+
path: join7(this.environment.harnessHomes.codex, "auth.json"),
|
|
11203
11482
|
format: "json"
|
|
11204
11483
|
}
|
|
11205
11484
|
];
|
|
@@ -11299,7 +11578,7 @@ function safeJson(text) {
|
|
|
11299
11578
|
}
|
|
11300
11579
|
|
|
11301
11580
|
// src/services/adapters/dsh.ts
|
|
11302
|
-
import { join as
|
|
11581
|
+
import { join as join8 } from "path";
|
|
11303
11582
|
var SETTINGS2 = "settings";
|
|
11304
11583
|
var CREDENTIALS = "credentials";
|
|
11305
11584
|
var DEFAULT_CONTEXT = 262144;
|
|
@@ -11365,13 +11644,13 @@ class DshAdapter {
|
|
|
11365
11644
|
{
|
|
11366
11645
|
key: SETTINGS2,
|
|
11367
11646
|
label: "settings.yaml",
|
|
11368
|
-
path:
|
|
11647
|
+
path: join8(this.environment.harnessHomes.dsh, "settings.yaml"),
|
|
11369
11648
|
format: "yaml"
|
|
11370
11649
|
},
|
|
11371
11650
|
{
|
|
11372
11651
|
key: CREDENTIALS,
|
|
11373
11652
|
label: ".credentials.yaml",
|
|
11374
|
-
path:
|
|
11653
|
+
path: join8(this.environment.harnessHomes.dsh, ".credentials.yaml"),
|
|
11375
11654
|
format: "yaml"
|
|
11376
11655
|
}
|
|
11377
11656
|
];
|
|
@@ -11507,7 +11786,7 @@ function reasoningEffortsString(value, fallback) {
|
|
|
11507
11786
|
}
|
|
11508
11787
|
|
|
11509
11788
|
// src/services/adapters/kimi.ts
|
|
11510
|
-
import { join as
|
|
11789
|
+
import { join as join9 } from "path";
|
|
11511
11790
|
var CONFIG2 = "config";
|
|
11512
11791
|
var DEFAULT_CONTEXT2 = 262144;
|
|
11513
11792
|
|
|
@@ -11553,7 +11832,7 @@ class KimiAdapter {
|
|
|
11553
11832
|
{
|
|
11554
11833
|
key: CONFIG2,
|
|
11555
11834
|
label: "config.toml",
|
|
11556
|
-
path:
|
|
11835
|
+
path: join9(this.environment.harnessHomes.kimiCode, "config.toml"),
|
|
11557
11836
|
format: "toml"
|
|
11558
11837
|
}
|
|
11559
11838
|
];
|
|
@@ -11639,7 +11918,7 @@ class KimiAdapter {
|
|
|
11639
11918
|
}
|
|
11640
11919
|
|
|
11641
11920
|
// src/services/adapters/pi.ts
|
|
11642
|
-
import { join as
|
|
11921
|
+
import { join as join10 } from "path";
|
|
11643
11922
|
var MODELS = "models";
|
|
11644
11923
|
var SETTINGS3 = "settings";
|
|
11645
11924
|
var DEFAULT_CONTEXT3 = 200000;
|
|
@@ -11713,13 +11992,13 @@ class PiAdapter {
|
|
|
11713
11992
|
{
|
|
11714
11993
|
key: MODELS,
|
|
11715
11994
|
label: "models.json",
|
|
11716
|
-
path:
|
|
11995
|
+
path: join10(this.environment.harnessHomes.piAgent, "models.json"),
|
|
11717
11996
|
format: "json"
|
|
11718
11997
|
},
|
|
11719
11998
|
{
|
|
11720
11999
|
key: SETTINGS3,
|
|
11721
12000
|
label: "settings.json",
|
|
11722
|
-
path:
|
|
12001
|
+
path: join10(this.environment.harnessHomes.piAgent, "settings.json"),
|
|
11723
12002
|
format: "json"
|
|
11724
12003
|
}
|
|
11725
12004
|
];
|
|
@@ -11952,10 +12231,194 @@ class HarnessRegistry {
|
|
|
11952
12231
|
}
|
|
11953
12232
|
}
|
|
11954
12233
|
|
|
12234
|
+
// src/services/vault.ts
|
|
12235
|
+
var IVaultService = createDecorator("vaultService");
|
|
12236
|
+
var STORE_VERSION2 = 1;
|
|
12237
|
+
var _dec = [
|
|
12238
|
+
inject(IEnvironmentService, IFileService, ICryptoService)
|
|
12239
|
+
];
|
|
12240
|
+
var _init = __decoratorStart(undefined);
|
|
12241
|
+
|
|
12242
|
+
class VaultService {
|
|
12243
|
+
environment;
|
|
12244
|
+
files;
|
|
12245
|
+
crypto;
|
|
12246
|
+
constructor(environment, files, crypto2) {
|
|
12247
|
+
this.environment = environment;
|
|
12248
|
+
this.files = files;
|
|
12249
|
+
this.crypto = crypto2;
|
|
12250
|
+
}
|
|
12251
|
+
list() {
|
|
12252
|
+
return Object.values(this.read().entries).map((entry) => this.toPublic(entry));
|
|
12253
|
+
}
|
|
12254
|
+
get(id) {
|
|
12255
|
+
return this.toPublic(this.require(id));
|
|
12256
|
+
}
|
|
12257
|
+
create(input) {
|
|
12258
|
+
const name = String(input.name ?? "").trim();
|
|
12259
|
+
if (!name) {
|
|
12260
|
+
throw new HttpError(400, "name is required");
|
|
12261
|
+
}
|
|
12262
|
+
const apiKey = String(input.apiKey ?? "");
|
|
12263
|
+
if (!apiKey) {
|
|
12264
|
+
throw new HttpError(400, "apiKey is required");
|
|
12265
|
+
}
|
|
12266
|
+
const endpoints = this.validateEndpoints(input.endpoints);
|
|
12267
|
+
const id = this.nextId(name);
|
|
12268
|
+
const now = new Date().toISOString();
|
|
12269
|
+
const store = this.read();
|
|
12270
|
+
store.entries[id] = {
|
|
12271
|
+
id,
|
|
12272
|
+
name,
|
|
12273
|
+
api_key: this.crypto.encrypt(apiKey),
|
|
12274
|
+
notes: input.notes?.trim() || undefined,
|
|
12275
|
+
endpoints,
|
|
12276
|
+
created_at: now,
|
|
12277
|
+
updated_at: now
|
|
12278
|
+
};
|
|
12279
|
+
this.write(store);
|
|
12280
|
+
return this.toPublic(store.entries[id]);
|
|
12281
|
+
}
|
|
12282
|
+
update(id, input) {
|
|
12283
|
+
const store = this.read();
|
|
12284
|
+
const entry = store.entries[id];
|
|
12285
|
+
if (!entry) {
|
|
12286
|
+
throw new HttpError(404, "provider not found");
|
|
12287
|
+
}
|
|
12288
|
+
if (input.name !== undefined) {
|
|
12289
|
+
const name = String(input.name).trim();
|
|
12290
|
+
if (!name) {
|
|
12291
|
+
throw new HttpError(400, "name is required");
|
|
12292
|
+
}
|
|
12293
|
+
entry.name = name;
|
|
12294
|
+
}
|
|
12295
|
+
if (input.apiKey !== undefined) {
|
|
12296
|
+
const apiKey = String(input.apiKey).trim();
|
|
12297
|
+
if (apiKey) {
|
|
12298
|
+
entry.api_key = this.crypto.encrypt(apiKey);
|
|
12299
|
+
}
|
|
12300
|
+
}
|
|
12301
|
+
if (input.notes !== undefined) {
|
|
12302
|
+
entry.notes = input.notes.trim() || undefined;
|
|
12303
|
+
}
|
|
12304
|
+
if (input.endpoints !== undefined) {
|
|
12305
|
+
entry.endpoints = this.validateEndpoints(input.endpoints);
|
|
12306
|
+
}
|
|
12307
|
+
entry.updated_at = new Date().toISOString();
|
|
12308
|
+
this.write(store);
|
|
12309
|
+
const affected = this.references(id);
|
|
12310
|
+
return { provider: this.toPublic(entry), affected };
|
|
12311
|
+
}
|
|
12312
|
+
remove(id) {
|
|
12313
|
+
const store = this.read();
|
|
12314
|
+
if (!store.entries[id]) {
|
|
12315
|
+
throw new HttpError(404, "provider not found");
|
|
12316
|
+
}
|
|
12317
|
+
const references = this.references(id);
|
|
12318
|
+
if (references.length > 0) {
|
|
12319
|
+
throw new HttpError(409, `Provider \u6B63\u88AB ${references.length} \u4E2A\u914D\u7F6E\u5F15\u7528\uFF0C\u8BF7\u5148\u79FB\u9664\u8FD9\u4E9B\u5F15\u7528\u518D\u5220\u9664`);
|
|
12320
|
+
}
|
|
12321
|
+
delete store.entries[id];
|
|
12322
|
+
this.write(store);
|
|
12323
|
+
}
|
|
12324
|
+
decrypt(id) {
|
|
12325
|
+
const entry = this.require(id);
|
|
12326
|
+
const plain = this.crypto.decrypt(entry.api_key);
|
|
12327
|
+
if (!plain) {
|
|
12328
|
+
throw new HttpError(500, `provider ${id} \u7684\u51ED\u636E\u65E0\u6CD5\u89E3\u5BC6`);
|
|
12329
|
+
}
|
|
12330
|
+
return plain;
|
|
12331
|
+
}
|
|
12332
|
+
references(id) {
|
|
12333
|
+
const store = this.readProfileStore();
|
|
12334
|
+
const found = [];
|
|
12335
|
+
for (const [harness, profiles] of Object.entries(store)) {
|
|
12336
|
+
for (const [name, profile] of Object.entries(profiles)) {
|
|
12337
|
+
if (profile.provider_id === id) {
|
|
12338
|
+
found.push({ harness, name });
|
|
12339
|
+
}
|
|
12340
|
+
}
|
|
12341
|
+
}
|
|
12342
|
+
return found;
|
|
12343
|
+
}
|
|
12344
|
+
require(id) {
|
|
12345
|
+
const entry = this.read().entries[id];
|
|
12346
|
+
if (!entry) {
|
|
12347
|
+
throw new HttpError(404, "provider not found");
|
|
12348
|
+
}
|
|
12349
|
+
return entry;
|
|
12350
|
+
}
|
|
12351
|
+
read() {
|
|
12352
|
+
return this.files.readJsonStrict(this.environment.files.vault, {
|
|
12353
|
+
version: STORE_VERSION2,
|
|
12354
|
+
entries: {}
|
|
12355
|
+
});
|
|
12356
|
+
}
|
|
12357
|
+
readProfileStore() {
|
|
12358
|
+
return this.files.readJsonStrict(this.environment.files.profiles, {});
|
|
12359
|
+
}
|
|
12360
|
+
write(store) {
|
|
12361
|
+
this.files.writeJson(this.environment.files.vault, store);
|
|
12362
|
+
}
|
|
12363
|
+
toPublic(entry) {
|
|
12364
|
+
return {
|
|
12365
|
+
id: entry.id,
|
|
12366
|
+
name: entry.name,
|
|
12367
|
+
notes: entry.notes,
|
|
12368
|
+
endpoints: entry.endpoints,
|
|
12369
|
+
apiKeyConfigured: true,
|
|
12370
|
+
updatedAt: entry.updated_at
|
|
12371
|
+
};
|
|
12372
|
+
}
|
|
12373
|
+
validateEndpoints(endpoints) {
|
|
12374
|
+
if (endpoints === undefined) {
|
|
12375
|
+
return [];
|
|
12376
|
+
}
|
|
12377
|
+
if (!Array.isArray(endpoints)) {
|
|
12378
|
+
throw new HttpError(400, "endpoints must be an array");
|
|
12379
|
+
}
|
|
12380
|
+
const seen = new Set;
|
|
12381
|
+
return endpoints.map((endpoint) => {
|
|
12382
|
+
const key = String(endpoint?.key ?? "").trim();
|
|
12383
|
+
if (!key) {
|
|
12384
|
+
throw new HttpError(400, "endpoint key is required");
|
|
12385
|
+
}
|
|
12386
|
+
if (key.includes("/") || key.includes("\\") || key.length > 60) {
|
|
12387
|
+
throw new HttpError(400, "endpoint key contains invalid characters");
|
|
12388
|
+
}
|
|
12389
|
+
if (seen.has(key)) {
|
|
12390
|
+
throw new HttpError(400, `duplicate endpoint ${key}`);
|
|
12391
|
+
}
|
|
12392
|
+
seen.add(key);
|
|
12393
|
+
const baseUrl = String(endpoint.baseUrl ?? "").trim();
|
|
12394
|
+
if (!baseUrl) {
|
|
12395
|
+
throw new HttpError(400, `endpoint ${key} requires a baseUrl`);
|
|
12396
|
+
}
|
|
12397
|
+
return { key, label: endpoint.label?.trim() || key, baseUrl };
|
|
12398
|
+
});
|
|
12399
|
+
}
|
|
12400
|
+
nextId(name) {
|
|
12401
|
+
const base = name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
|
|
12402
|
+
const slug = base || `provider-${Date.now().toString(36)}`;
|
|
12403
|
+
const store = this.read();
|
|
12404
|
+
let candidate = slug;
|
|
12405
|
+
let suffix = 1;
|
|
12406
|
+
while (store.entries[candidate]) {
|
|
12407
|
+
candidate = `${slug}-${suffix}`;
|
|
12408
|
+
suffix += 1;
|
|
12409
|
+
}
|
|
12410
|
+
return candidate;
|
|
12411
|
+
}
|
|
12412
|
+
}
|
|
12413
|
+
VaultService = __decorateElement(_init, 0, "VaultService", _dec, VaultService);
|
|
12414
|
+
__runInitializers(_init, 1, VaultService);
|
|
12415
|
+
__decoratorMetadata(_init, VaultService);
|
|
12416
|
+
let _VaultService = VaultService;
|
|
12417
|
+
|
|
11955
12418
|
// src/services/profiles.ts
|
|
11956
12419
|
var IProfileService = createDecorator("profileService");
|
|
11957
12420
|
var _dec = [
|
|
11958
|
-
inject(IEnvironmentService, IFileService, ICryptoService, IHarnessRegistry, IAdapterRegistry)
|
|
12421
|
+
inject(IEnvironmentService, IFileService, ICryptoService, IHarnessRegistry, IAdapterRegistry, IVaultService, ILogService)
|
|
11959
12422
|
];
|
|
11960
12423
|
var _init = __decoratorStart(undefined);
|
|
11961
12424
|
|
|
@@ -11965,12 +12428,16 @@ class ProfileService {
|
|
|
11965
12428
|
crypto;
|
|
11966
12429
|
harnesses;
|
|
11967
12430
|
adapters;
|
|
11968
|
-
|
|
12431
|
+
vault;
|
|
12432
|
+
log;
|
|
12433
|
+
constructor(environment, files, crypto2, harnesses, adapters, vault, log) {
|
|
11969
12434
|
this.environment = environment;
|
|
11970
12435
|
this.files = files;
|
|
11971
12436
|
this.crypto = crypto2;
|
|
11972
12437
|
this.harnesses = harnesses;
|
|
11973
12438
|
this.adapters = adapters;
|
|
12439
|
+
this.vault = vault;
|
|
12440
|
+
this.log = log;
|
|
11974
12441
|
}
|
|
11975
12442
|
list(harness) {
|
|
11976
12443
|
const store = this.read();
|
|
@@ -11998,17 +12465,51 @@ class ProfileService {
|
|
|
11998
12465
|
if (!isCreate && sourceName !== name && store[harness][name]) {
|
|
11999
12466
|
throw new HttpError(409, "profile already exists");
|
|
12000
12467
|
}
|
|
12001
|
-
const
|
|
12468
|
+
const hasProvider = input.providerId !== undefined;
|
|
12469
|
+
const providerId = input.providerId?.trim() || undefined;
|
|
12470
|
+
const providerEndpoint = input.providerEndpoint?.trim() || undefined;
|
|
12471
|
+
const hasInlineKey = input.apiKey !== undefined && input.apiKey.trim() !== "";
|
|
12472
|
+
const inlineKey = (input.apiKey ?? "").trim();
|
|
12473
|
+
let nextProviderId = prior?.provider_id;
|
|
12474
|
+
let nextProviderEndpoint = prior?.provider_endpoint;
|
|
12475
|
+
let apiKey = "";
|
|
12476
|
+
if (hasProvider && providerId) {
|
|
12477
|
+
const entry = this.vault.get(providerId);
|
|
12478
|
+
if (providerEndpoint) {
|
|
12479
|
+
const endpoint = entry.endpoints.find((candidate) => candidate.key === providerEndpoint);
|
|
12480
|
+
if (!endpoint) {
|
|
12481
|
+
throw new HttpError(400, `endpoint ${providerEndpoint} not found`);
|
|
12482
|
+
}
|
|
12483
|
+
nextProviderEndpoint = providerEndpoint;
|
|
12484
|
+
} else {
|
|
12485
|
+
nextProviderEndpoint = undefined;
|
|
12486
|
+
}
|
|
12487
|
+
nextProviderId = providerId;
|
|
12488
|
+
apiKey = this.vault.decrypt(providerId);
|
|
12489
|
+
} else if (hasProvider && !providerId) {
|
|
12490
|
+
nextProviderId = undefined;
|
|
12491
|
+
nextProviderEndpoint = undefined;
|
|
12492
|
+
apiKey = hasInlineKey ? inlineKey : prior ? this.crypto.decrypt(prior.api_key) : "";
|
|
12493
|
+
} else if (hasInlineKey) {
|
|
12494
|
+
nextProviderId = undefined;
|
|
12495
|
+
nextProviderEndpoint = undefined;
|
|
12496
|
+
apiKey = inlineKey;
|
|
12497
|
+
} else if (prior) {
|
|
12498
|
+
apiKey = prior.provider_id ? this.vault.decrypt(prior.provider_id) : this.crypto.decrypt(prior.api_key);
|
|
12499
|
+
}
|
|
12002
12500
|
if (isCreate && !apiKey) {
|
|
12003
12501
|
throw new HttpError(400, "apiKey is required");
|
|
12004
12502
|
}
|
|
12503
|
+
const baseUrl = this.resolveBaseUrl((input.baseUrl ?? prior?.base_url ?? "").trim(), providerId || nextProviderId, providerEndpoint || nextProviderEndpoint);
|
|
12005
12504
|
const next = {
|
|
12006
|
-
base_url:
|
|
12505
|
+
base_url: baseUrl,
|
|
12007
12506
|
api_key: this.crypto.encrypt(apiKey),
|
|
12008
12507
|
model: (input.model ?? prior?.model ?? "").trim(),
|
|
12009
12508
|
notes: input.notes ?? prior?.notes ?? "",
|
|
12010
12509
|
extras: input.extras ?? prior?.extras ?? {},
|
|
12011
12510
|
overrides: input.overrides ?? prior?.overrides ?? {},
|
|
12511
|
+
provider_id: nextProviderId,
|
|
12512
|
+
provider_endpoint: nextProviderEndpoint,
|
|
12012
12513
|
updated_at: new Date().toISOString()
|
|
12013
12514
|
};
|
|
12014
12515
|
this.adapters.get(harness).validate?.({
|
|
@@ -12040,8 +12541,8 @@ class ProfileService {
|
|
|
12040
12541
|
}
|
|
12041
12542
|
return {
|
|
12042
12543
|
name,
|
|
12043
|
-
baseUrl: stored.base_url || "",
|
|
12044
|
-
apiKey: this.
|
|
12544
|
+
baseUrl: this.resolveBaseUrl(stored.base_url || "", stored.provider_id, stored.provider_endpoint),
|
|
12545
|
+
apiKey: this.resolveKey(stored),
|
|
12045
12546
|
model: stored.model || "",
|
|
12046
12547
|
extras: stored.extras ?? {},
|
|
12047
12548
|
overrides: stored.overrides ?? {}
|
|
@@ -12059,7 +12560,7 @@ class ProfileService {
|
|
|
12059
12560
|
if (values.model !== undefined) {
|
|
12060
12561
|
stored.model = values.model;
|
|
12061
12562
|
}
|
|
12062
|
-
if (values.apiKey) {
|
|
12563
|
+
if (values.apiKey && !stored.provider_id) {
|
|
12063
12564
|
stored.api_key = this.crypto.encrypt(values.apiKey);
|
|
12064
12565
|
}
|
|
12065
12566
|
if (values.extras !== undefined) {
|
|
@@ -12067,6 +12568,27 @@ class ProfileService {
|
|
|
12067
12568
|
}
|
|
12068
12569
|
this.files.writeJson(this.environment.files.profiles, store);
|
|
12069
12570
|
}
|
|
12571
|
+
sweepVaultCache(vaultId, apiKey, endpoints) {
|
|
12572
|
+
const store = this.read();
|
|
12573
|
+
let updated = 0;
|
|
12574
|
+
for (const profiles of Object.values(store)) {
|
|
12575
|
+
for (const stored of Object.values(profiles)) {
|
|
12576
|
+
if (stored.provider_id !== vaultId) {
|
|
12577
|
+
continue;
|
|
12578
|
+
}
|
|
12579
|
+
stored.api_key = this.crypto.encrypt(apiKey);
|
|
12580
|
+
const endpoint = stored.provider_endpoint !== undefined ? endpoints.find((candidate) => candidate.key === stored.provider_endpoint) : undefined;
|
|
12581
|
+
if (endpoint) {
|
|
12582
|
+
stored.base_url = endpoint.baseUrl;
|
|
12583
|
+
}
|
|
12584
|
+
updated++;
|
|
12585
|
+
}
|
|
12586
|
+
}
|
|
12587
|
+
if (updated > 0) {
|
|
12588
|
+
this.files.writeJson(this.environment.files.profiles, store);
|
|
12589
|
+
}
|
|
12590
|
+
return updated;
|
|
12591
|
+
}
|
|
12070
12592
|
read() {
|
|
12071
12593
|
return this.files.readJsonStrict(this.environment.files.profiles, {});
|
|
12072
12594
|
}
|
|
@@ -12079,9 +12601,43 @@ class ProfileService {
|
|
|
12079
12601
|
notes: profile.notes || "",
|
|
12080
12602
|
extras: profile.extras ?? {},
|
|
12081
12603
|
overriddenTargets: Object.keys(profile.overrides ?? {}),
|
|
12604
|
+
providerId: profile.provider_id,
|
|
12605
|
+
providerEndpoint: profile.provider_endpoint,
|
|
12082
12606
|
updatedAt: profile.updated_at || ""
|
|
12083
12607
|
};
|
|
12084
12608
|
}
|
|
12609
|
+
resolveKey(stored) {
|
|
12610
|
+
if (!stored.provider_id) {
|
|
12611
|
+
return this.crypto.decrypt(stored.api_key);
|
|
12612
|
+
}
|
|
12613
|
+
try {
|
|
12614
|
+
return this.vault.decrypt(stored.provider_id);
|
|
12615
|
+
} catch {
|
|
12616
|
+
this.log.warn(`profile ${stored.provider_id} \u5F15\u7528\u7684 provider \u4E0D\u5B58\u5728\uFF0C\u56DE\u9000\u5230\u5185\u8054\u7F13\u5B58\u51ED\u636E`);
|
|
12617
|
+
return this.crypto.decrypt(stored.api_key);
|
|
12618
|
+
}
|
|
12619
|
+
}
|
|
12620
|
+
resolveBaseUrl(fallback, providerId, providerEndpoint) {
|
|
12621
|
+
if (!providerId || !providerEndpoint) {
|
|
12622
|
+
return fallback;
|
|
12623
|
+
}
|
|
12624
|
+
let entry;
|
|
12625
|
+
try {
|
|
12626
|
+
entry = this.vault.get(providerId);
|
|
12627
|
+
} catch {
|
|
12628
|
+
this.log.warn(`profile \u5F15\u7528\u7684 provider ${providerId} \u4E0D\u5B58\u5728\uFF0C\u56DE\u9000\u5230\u5185\u8054 base_url`);
|
|
12629
|
+
return fallback;
|
|
12630
|
+
}
|
|
12631
|
+
const endpoint = entry.endpoints.find((candidate) => candidate.key === providerEndpoint);
|
|
12632
|
+
if (endpoint) {
|
|
12633
|
+
return endpoint.baseUrl;
|
|
12634
|
+
}
|
|
12635
|
+
if (entry.endpoints.length > 0) {
|
|
12636
|
+
this.log.warn(`endpoint ${providerEndpoint} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u56DE\u9000\u5230 provider ${providerId} \u7684\u9996\u4E2A endpoint`);
|
|
12637
|
+
return entry.endpoints[0].baseUrl;
|
|
12638
|
+
}
|
|
12639
|
+
return fallback;
|
|
12640
|
+
}
|
|
12085
12641
|
assertName(name) {
|
|
12086
12642
|
if (!name) {
|
|
12087
12643
|
throw new HttpError(400, "name is required");
|
|
@@ -12142,7 +12698,7 @@ class ActivationService {
|
|
|
12142
12698
|
const warnings = [];
|
|
12143
12699
|
const active = this.read();
|
|
12144
12700
|
this.backfillPrevious(adapter, active[harness], name, warnings);
|
|
12145
|
-
const writes = this.
|
|
12701
|
+
const writes = this.expectedNamedWrites(harness, name);
|
|
12146
12702
|
this.liveWrite.apply(harness, name, writes);
|
|
12147
12703
|
active[harness] = {
|
|
12148
12704
|
name: profile.name,
|
|
@@ -12173,16 +12729,8 @@ class ActivationService {
|
|
|
12173
12729
|
if (!alreadyOfficial) {
|
|
12174
12730
|
this.backfillPrevious(adapter, previous, "__official__", warnings);
|
|
12175
12731
|
}
|
|
12176
|
-
const
|
|
12177
|
-
|
|
12178
|
-
baseUrl: previous.base_url,
|
|
12179
|
-
apiKey: previous.api_key,
|
|
12180
|
-
model: previous.model,
|
|
12181
|
-
extras: previous.extras ?? {}
|
|
12182
|
-
} : undefined;
|
|
12183
|
-
const targets = adapter.targets();
|
|
12184
|
-
const rendered = adapter.renderOfficial(profile, this.readCurrent(targets));
|
|
12185
|
-
this.liveWrite.apply(harness, "\u5B98\u65B9\u767B\u5F55", this.toWrites(targets, rendered));
|
|
12732
|
+
const writes = this.expectedOfficialWrites(harness);
|
|
12733
|
+
this.liveWrite.apply(harness, "\u5B98\u65B9\u767B\u5F55", writes);
|
|
12186
12734
|
active[harness] = {
|
|
12187
12735
|
name: "\u5B98\u65B9\u767B\u5F55",
|
|
12188
12736
|
base_url: "",
|
|
@@ -12266,7 +12814,19 @@ class ActivationService {
|
|
|
12266
12814
|
warnings.push(`\u672A\u80FD\u628A ${previous.name} \u7684\u73B0\u6709\u914D\u7F6E\u56DE\u586B\u4FDD\u5B58`);
|
|
12267
12815
|
}
|
|
12268
12816
|
}
|
|
12269
|
-
|
|
12817
|
+
expectedWrites(harness) {
|
|
12818
|
+
const active = this.read()[harness];
|
|
12819
|
+
if (!active) {
|
|
12820
|
+
throw new HttpError(400, "\u8BE5\u5DE5\u5177\u672A\u6FC0\u6D3B\u4EFB\u4F55\u914D\u7F6E\uFF0C\u65E0\u53EF\u6E32\u67D3\u7684\u5185\u5BB9");
|
|
12821
|
+
}
|
|
12822
|
+
if (active.official === true) {
|
|
12823
|
+
return this.expectedOfficialWrites(harness);
|
|
12824
|
+
}
|
|
12825
|
+
return this.expectedNamedWrites(harness, active.name);
|
|
12826
|
+
}
|
|
12827
|
+
expectedNamedWrites(harness, name) {
|
|
12828
|
+
const adapter = this.adapters.get(harness);
|
|
12829
|
+
const profile = this.profiles.decrypt(harness, name);
|
|
12270
12830
|
const targets = adapter.targets();
|
|
12271
12831
|
const rendered = adapter.render(profile, this.readCurrent(targets));
|
|
12272
12832
|
for (const [key, content] of Object.entries(profile.overrides)) {
|
|
@@ -12276,6 +12836,23 @@ class ActivationService {
|
|
|
12276
12836
|
}
|
|
12277
12837
|
return this.toWrites(targets, rendered);
|
|
12278
12838
|
}
|
|
12839
|
+
expectedOfficialWrites(harness) {
|
|
12840
|
+
const adapter = this.adapters.get(harness);
|
|
12841
|
+
if (!adapter.renderOfficial) {
|
|
12842
|
+
throw new HttpError(400, `${this.harnesses.label(harness)} \u4E0D\u652F\u6301\u5B98\u65B9\u8D26\u53F7\u767B\u5F55\u6A21\u5F0F`);
|
|
12843
|
+
}
|
|
12844
|
+
const active = this.read()[harness];
|
|
12845
|
+
const profile = active && active.official !== true ? {
|
|
12846
|
+
name: active.name,
|
|
12847
|
+
baseUrl: active.base_url,
|
|
12848
|
+
apiKey: active.api_key,
|
|
12849
|
+
model: active.model,
|
|
12850
|
+
extras: active.extras ?? {}
|
|
12851
|
+
} : undefined;
|
|
12852
|
+
const targets = adapter.targets();
|
|
12853
|
+
const rendered = adapter.renderOfficial(profile, this.readCurrent(targets));
|
|
12854
|
+
return this.toWrites(targets, rendered);
|
|
12855
|
+
}
|
|
12279
12856
|
toWrites(targets, rendered) {
|
|
12280
12857
|
return Object.entries(rendered).map(([key, content]) => {
|
|
12281
12858
|
const target = this.requireTarget(targets, key);
|
|
@@ -12348,6 +12925,394 @@ function shellQuote(value) {
|
|
|
12348
12925
|
return `'${String(value || "").replace(/'/g, `'"'"'`)}'`;
|
|
12349
12926
|
}
|
|
12350
12927
|
|
|
12928
|
+
// src/services/drift.ts
|
|
12929
|
+
var IDriftService = createDecorator("driftService");
|
|
12930
|
+
var SEVERITY = {
|
|
12931
|
+
unknown: 0,
|
|
12932
|
+
"in-sync": 1,
|
|
12933
|
+
drifted: 2,
|
|
12934
|
+
missing: 3,
|
|
12935
|
+
invalid: 4
|
|
12936
|
+
};
|
|
12937
|
+
var _dec = [
|
|
12938
|
+
inject(IActivationService, IAdapterRegistry, IProfileService, IFileService, ILiveWriteService, IHarnessRegistry)
|
|
12939
|
+
];
|
|
12940
|
+
var _init = __decoratorStart(undefined);
|
|
12941
|
+
|
|
12942
|
+
class DriftService {
|
|
12943
|
+
activation;
|
|
12944
|
+
adapters;
|
|
12945
|
+
profiles;
|
|
12946
|
+
files;
|
|
12947
|
+
liveWrite;
|
|
12948
|
+
harnesses;
|
|
12949
|
+
constructor(activation, adapters, profiles, files, liveWrite, harnesses) {
|
|
12950
|
+
this.activation = activation;
|
|
12951
|
+
this.adapters = adapters;
|
|
12952
|
+
this.profiles = profiles;
|
|
12953
|
+
this.files = files;
|
|
12954
|
+
this.liveWrite = liveWrite;
|
|
12955
|
+
this.harnesses = harnesses;
|
|
12956
|
+
}
|
|
12957
|
+
inspectAll() {
|
|
12958
|
+
return this.harnesses.list().map((item) => this.inspect(item.id));
|
|
12959
|
+
}
|
|
12960
|
+
inspect(harness) {
|
|
12961
|
+
const active = this.activation.getActive(harness);
|
|
12962
|
+
if (!active) {
|
|
12963
|
+
return { harness, status: "unknown", active: false, files: [] };
|
|
12964
|
+
}
|
|
12965
|
+
const files = active.official === true ? this.officialFiles(harness) : this.namedFiles(harness);
|
|
12966
|
+
return { harness, status: this.overall(files), active: true, files };
|
|
12967
|
+
}
|
|
12968
|
+
reapply(harness) {
|
|
12969
|
+
const active = this.activation.getActive(harness);
|
|
12970
|
+
if (!active) {
|
|
12971
|
+
throw new HttpError(400, "\u8BE5\u5DE5\u5177\u672A\u6FC0\u6D3B\u4EFB\u4F55\u914D\u7F6E\uFF0C\u65E0\u53EF\u91CD\u5E94\u7528\u7684\u5185\u5BB9");
|
|
12972
|
+
}
|
|
12973
|
+
const writes = this.activation.expectedWrites(harness);
|
|
12974
|
+
this.liveWrite.apply(harness, active.official === true ? "\u5B98\u65B9\u767B\u5F55" : active.name, writes);
|
|
12975
|
+
return { ok: true, files: this.inspect(harness).files };
|
|
12976
|
+
}
|
|
12977
|
+
adopt(harness) {
|
|
12978
|
+
const active = this.activation.getActive(harness);
|
|
12979
|
+
if (!active) {
|
|
12980
|
+
throw new HttpError(400, "\u8BE5\u5DE5\u5177\u672A\u6FC0\u6D3B\u4EFB\u4F55\u914D\u7F6E\uFF0C\u65E0\u53EF\u91C7\u7EB3\u7684\u5185\u5BB9");
|
|
12981
|
+
}
|
|
12982
|
+
if (active.official === true) {
|
|
12983
|
+
throw new HttpError(400, "\u5B98\u65B9\u767B\u5F55\u6A21\u5F0F\u4E0B\u6CA1\u6709\u53EF\u91C7\u7EB3\u7684\u914D\u7F6E");
|
|
12984
|
+
}
|
|
12985
|
+
const adapter = this.adapters.get(harness);
|
|
12986
|
+
if (!adapter.backfill) {
|
|
12987
|
+
throw new HttpError(400, "\u8BE5\u5DE5\u5177\u4E0D\u652F\u6301\u4ECE live \u6587\u4EF6\u56DE\u8BFB\u914D\u7F6E");
|
|
12988
|
+
}
|
|
12989
|
+
const profile = this.profiles.decrypt(harness, active.name);
|
|
12990
|
+
if (Object.keys(profile.overrides).length > 0) {
|
|
12991
|
+
throw new HttpError(409, "\u5B58\u5728\u624B\u52A8 override \u7684\u6587\u4EF6\uFF0C\u81EA\u52A8\u91C7\u7EB3\u4F1A\u4E22\u5F03\u4F60\u7684\u624B\u5DE5\u914D\u7F6E\uFF1B\u8BF7\u5148\u6062\u590D\u4E3A\u81EA\u52A8\u751F\u6210\u518D\u91C7\u7EB3");
|
|
12992
|
+
}
|
|
12993
|
+
const targets = adapter.targets();
|
|
12994
|
+
const current = this.readCurrent(targets);
|
|
12995
|
+
for (const target of targets) {
|
|
12996
|
+
const content = current[target.key];
|
|
12997
|
+
if (content !== undefined) {
|
|
12998
|
+
assertParsable(target.format, target.path, content);
|
|
12999
|
+
}
|
|
13000
|
+
}
|
|
13001
|
+
const values = adapter.backfill(profile, current);
|
|
13002
|
+
this.profiles.applyBackfill(harness, active.name, values);
|
|
13003
|
+
return { ok: true, summary: this.inspect(harness), warnings: [] };
|
|
13004
|
+
}
|
|
13005
|
+
namedFiles(harness) {
|
|
13006
|
+
const targets = this.adapters.get(harness).targets();
|
|
13007
|
+
let preview;
|
|
13008
|
+
try {
|
|
13009
|
+
preview = this.activation.preview(harness, this.activation.getActive(harness).name);
|
|
13010
|
+
} catch {
|
|
13011
|
+
return targets.map((target) => ({
|
|
13012
|
+
key: target.key,
|
|
13013
|
+
label: target.label,
|
|
13014
|
+
path: target.path,
|
|
13015
|
+
format: target.format,
|
|
13016
|
+
expectedContent: null,
|
|
13017
|
+
currentContent: this.files.readOptional(target.path) ?? null,
|
|
13018
|
+
status: "invalid"
|
|
13019
|
+
}));
|
|
13020
|
+
}
|
|
13021
|
+
return preview.map((target) => this.classify({ key: target.key, label: target.label, path: target.path, format: target.format }, target.content, target.currentContent ?? null));
|
|
13022
|
+
}
|
|
13023
|
+
officialFiles(harness) {
|
|
13024
|
+
const targets = this.adapters.get(harness).targets();
|
|
13025
|
+
return targets.map((target) => {
|
|
13026
|
+
const live = this.files.readOptional(target.path) ?? null;
|
|
13027
|
+
const base = {
|
|
13028
|
+
key: target.key,
|
|
13029
|
+
label: target.label,
|
|
13030
|
+
path: target.path,
|
|
13031
|
+
format: target.format,
|
|
13032
|
+
expectedContent: null,
|
|
13033
|
+
currentContent: live
|
|
13034
|
+
};
|
|
13035
|
+
if (live === null) {
|
|
13036
|
+
return { ...base, status: "missing" };
|
|
13037
|
+
}
|
|
13038
|
+
if (target.format === "text") {
|
|
13039
|
+
return { ...base, status: "unknown" };
|
|
13040
|
+
}
|
|
13041
|
+
try {
|
|
13042
|
+
parseValue2(target.format, live);
|
|
13043
|
+
return { ...base, status: "in-sync" };
|
|
13044
|
+
} catch {
|
|
13045
|
+
return { ...base, status: "invalid" };
|
|
13046
|
+
}
|
|
13047
|
+
});
|
|
13048
|
+
}
|
|
13049
|
+
classify(target, expected, live) {
|
|
13050
|
+
const base = {
|
|
13051
|
+
key: target.key,
|
|
13052
|
+
label: target.label,
|
|
13053
|
+
path: target.path,
|
|
13054
|
+
format: target.format,
|
|
13055
|
+
expectedContent: expected,
|
|
13056
|
+
currentContent: live
|
|
13057
|
+
};
|
|
13058
|
+
if (live === null) {
|
|
13059
|
+
return { ...base, status: "missing" };
|
|
13060
|
+
}
|
|
13061
|
+
try {
|
|
13062
|
+
const equal = semanticEqual(target.format, expected, live);
|
|
13063
|
+
return { ...base, status: equal ? "in-sync" : "drifted" };
|
|
13064
|
+
} catch {
|
|
13065
|
+
return { ...base, status: "invalid" };
|
|
13066
|
+
}
|
|
13067
|
+
}
|
|
13068
|
+
overall(files) {
|
|
13069
|
+
let worst = files.length === 0 ? "in-sync" : "unknown";
|
|
13070
|
+
for (const file of files) {
|
|
13071
|
+
if (SEVERITY[file.status] > SEVERITY[worst]) {
|
|
13072
|
+
worst = file.status;
|
|
13073
|
+
}
|
|
13074
|
+
}
|
|
13075
|
+
return worst;
|
|
13076
|
+
}
|
|
13077
|
+
readCurrent(targets) {
|
|
13078
|
+
const current = {};
|
|
13079
|
+
for (const target of targets) {
|
|
13080
|
+
current[target.key] = this.files.readOptional(target.path);
|
|
13081
|
+
}
|
|
13082
|
+
return current;
|
|
13083
|
+
}
|
|
13084
|
+
}
|
|
13085
|
+
DriftService = __decorateElement(_init, 0, "DriftService", _dec, DriftService);
|
|
13086
|
+
__runInitializers(_init, 1, DriftService);
|
|
13087
|
+
__decoratorMetadata(_init, DriftService);
|
|
13088
|
+
let _DriftService = DriftService;
|
|
13089
|
+
function semanticEqual(format, expected, live) {
|
|
13090
|
+
if (format === "text") {
|
|
13091
|
+
return expected === live;
|
|
13092
|
+
}
|
|
13093
|
+
return deepEqual(parseValue2(format, expected), parseValue2(format, live));
|
|
13094
|
+
}
|
|
13095
|
+
function parseValue2(format, text) {
|
|
13096
|
+
if (!text?.trim()) {
|
|
13097
|
+
return {};
|
|
13098
|
+
}
|
|
13099
|
+
if (format === "json") {
|
|
13100
|
+
return JSON.parse(text);
|
|
13101
|
+
}
|
|
13102
|
+
if (format === "toml") {
|
|
13103
|
+
return parse2(text);
|
|
13104
|
+
}
|
|
13105
|
+
if (format === "yaml") {
|
|
13106
|
+
const document = $parseDocument(text);
|
|
13107
|
+
if (document.errors.length > 0) {
|
|
13108
|
+
throw document.errors[0];
|
|
13109
|
+
}
|
|
13110
|
+
return document.toJS() ?? {};
|
|
13111
|
+
}
|
|
13112
|
+
return text;
|
|
13113
|
+
}
|
|
13114
|
+
function deepEqual(left, right) {
|
|
13115
|
+
if (left === right) {
|
|
13116
|
+
return true;
|
|
13117
|
+
}
|
|
13118
|
+
if (typeof left !== typeof right || left === null || right === null) {
|
|
13119
|
+
return false;
|
|
13120
|
+
}
|
|
13121
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
13122
|
+
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
|
|
13123
|
+
return false;
|
|
13124
|
+
}
|
|
13125
|
+
return left.every((value, index) => deepEqual(value, right[index]));
|
|
13126
|
+
}
|
|
13127
|
+
if (typeof left === "object" && typeof right === "object") {
|
|
13128
|
+
const leftKeys = Object.keys(left);
|
|
13129
|
+
const rightKeys = Object.keys(right);
|
|
13130
|
+
if (leftKeys.length !== rightKeys.length) {
|
|
13131
|
+
return false;
|
|
13132
|
+
}
|
|
13133
|
+
return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && deepEqual(left[key], right[key]));
|
|
13134
|
+
}
|
|
13135
|
+
return false;
|
|
13136
|
+
}
|
|
13137
|
+
|
|
13138
|
+
// src/services/doctor.ts
|
|
13139
|
+
var IDoctorService = createDecorator("doctorService");
|
|
13140
|
+
var BIN_NAMES = {
|
|
13141
|
+
claude: "claude",
|
|
13142
|
+
codex: "codex",
|
|
13143
|
+
kimi: "kimi",
|
|
13144
|
+
pi: "pi",
|
|
13145
|
+
dsh: "dsh"
|
|
13146
|
+
};
|
|
13147
|
+
var _dec = [
|
|
13148
|
+
inject(IEnvironmentService, IFileService, IHarnessRegistry, IAdapterRegistry, IActivationService, IDriftService)
|
|
13149
|
+
];
|
|
13150
|
+
var _init = __decoratorStart(undefined);
|
|
13151
|
+
|
|
13152
|
+
class DoctorService {
|
|
13153
|
+
environment;
|
|
13154
|
+
files;
|
|
13155
|
+
harnesses;
|
|
13156
|
+
adapters;
|
|
13157
|
+
activation;
|
|
13158
|
+
drift;
|
|
13159
|
+
constructor(environment, files, harnesses, adapters, activation, drift) {
|
|
13160
|
+
this.environment = environment;
|
|
13161
|
+
this.files = files;
|
|
13162
|
+
this.harnesses = harnesses;
|
|
13163
|
+
this.adapters = adapters;
|
|
13164
|
+
this.activation = activation;
|
|
13165
|
+
this.drift = drift;
|
|
13166
|
+
}
|
|
13167
|
+
async run(options = {}) {
|
|
13168
|
+
const harnessIds = options.harness ? [this.harnesses.require(options.harness)] : this.harnesses.list().map((item) => item.id);
|
|
13169
|
+
const items = [];
|
|
13170
|
+
for (const harness of harnessIds) {
|
|
13171
|
+
items.push({ harness, checks: this.harnessChecks(harness, options.probe === true) });
|
|
13172
|
+
}
|
|
13173
|
+
const update = await checkForUpdate();
|
|
13174
|
+
return { items, updatedAvailable: update.updateAvailable };
|
|
13175
|
+
}
|
|
13176
|
+
harnessChecks(harness, probe) {
|
|
13177
|
+
const checks = [];
|
|
13178
|
+
const bin = BIN_NAMES[harness];
|
|
13179
|
+
checks.push(this.commandExists(bin) ? ok(`${harness}.install`, `\u5DF2\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6 ${bin}`) : error(`${harness}.install`, `\u672A\u627E\u5230\u53EF\u6267\u884C\u6587\u4EF6 ${bin}\uFF08PATH \u4E2D\u4E0D\u5B58\u5728\uFF09\uFF0C\u5DE5\u5177\u53EF\u80FD\u672A\u5B89\u88C5`));
|
|
13180
|
+
const targets = this.adapters.get(harness).targets();
|
|
13181
|
+
for (const target of targets) {
|
|
13182
|
+
const dir = dirname3(target.path);
|
|
13183
|
+
const present = this.files.exists(dir);
|
|
13184
|
+
checks.push(present ? ok(`${harness}.configDir.${target.key}`, `${target.label} \u6240\u5728\u76EE\u5F55\u5B58\u5728\uFF08${dir}\uFF09`) : error(`${harness}.configDir.${target.key}`, `${target.label} \u6240\u5728\u76EE\u5F55\u4E0D\u5B58\u5728\uFF08${dir}\uFF09\uFF0C\u65E0\u6CD5\u5199\u5165\u914D\u7F6E`));
|
|
13185
|
+
}
|
|
13186
|
+
for (const target of targets) {
|
|
13187
|
+
const path = target.path;
|
|
13188
|
+
const exists = this.files.exists(path);
|
|
13189
|
+
if (!exists) {
|
|
13190
|
+
checks.push(warn(`${harness}.files.${target.key}`, `${target.label} \u4E0D\u5B58\u5728\uFF08${path}\uFF09`));
|
|
13191
|
+
continue;
|
|
13192
|
+
}
|
|
13193
|
+
if (!this.isReadable(path)) {
|
|
13194
|
+
checks.push(error(`${harness}.files.${target.key}`, `${target.label} \u4E0D\u53EF\u8BFB\uFF08${path}\uFF09`));
|
|
13195
|
+
continue;
|
|
13196
|
+
}
|
|
13197
|
+
if (!this.isWritable(path)) {
|
|
13198
|
+
checks.push(warn(`${harness}.files.${target.key}`, `${target.label} \u4E0D\u53EF\u5199\uFF08${path}\uFF09`));
|
|
13199
|
+
continue;
|
|
13200
|
+
}
|
|
13201
|
+
const mode = statSync2(path).mode & 511;
|
|
13202
|
+
if ((mode & 63) !== 0) {
|
|
13203
|
+
checks.push(warn(`${harness}.files.${target.key}`, `${target.label} \u5B58\u5728\u53EF\u8BFB\u5199\uFF0C\u4F46\u6743\u9650\u4E3A ${octal(mode)}\uFF0Cgroup/other \u53EF\u8BFB\uFF0C\u5EFA\u8BAE 0600`, { mode }));
|
|
13204
|
+
} else {
|
|
13205
|
+
checks.push(ok(`${harness}.files.${target.key}`, `${target.label} \u5B58\u5728\u4E14\u53EF\u8BFB\u53EF\u5199\uFF08${path}\uFF09`));
|
|
13206
|
+
}
|
|
13207
|
+
}
|
|
13208
|
+
for (const target of targets) {
|
|
13209
|
+
const content = this.files.readOptional(target.path);
|
|
13210
|
+
if (content === undefined) {
|
|
13211
|
+
continue;
|
|
13212
|
+
}
|
|
13213
|
+
try {
|
|
13214
|
+
assertParsable(target.format, target.path, content);
|
|
13215
|
+
checks.push(ok(`${harness}.parse.${target.key}`, `${target.label} \u89E3\u6790\u6B63\u5E38`));
|
|
13216
|
+
} catch (err) {
|
|
13217
|
+
checks.push(error(`${harness}.parse.${target.key}`, `${target.label} \u65E0\u6CD5\u89E3\u6790\uFF1A${err.message}`));
|
|
13218
|
+
}
|
|
13219
|
+
}
|
|
13220
|
+
const summary = this.drift.inspect(harness);
|
|
13221
|
+
if (!summary.active) {
|
|
13222
|
+
checks.push(ok(`${harness}.drift`, "\u672A\u6FC0\u6D3B\u4EFB\u4F55\u914D\u7F6E\uFF0C\u65E0\u6F02\u79FB\u53EF\u68C0\u67E5"));
|
|
13223
|
+
} else if (summary.status === "invalid") {
|
|
13224
|
+
checks.push(error(`${harness}.drift`, "live \u6587\u4EF6\u5B58\u5728\u65E0\u6CD5\u89E3\u6790\u7684\u5185\u5BB9"));
|
|
13225
|
+
} else if (summary.status === "drifted" || summary.status === "missing") {
|
|
13226
|
+
const affected = summary.files.filter((file) => file.status !== "in-sync").length;
|
|
13227
|
+
checks.push(warn(`${harness}.drift`, `${affected} \u4E2A\u6587\u4EF6\u4E0E\u6FC0\u6D3B\u914D\u7F6E\u4E0D\u4E00\u81F4\uFF08${summary.status}\uFF09`));
|
|
13228
|
+
} else {
|
|
13229
|
+
checks.push(ok(`${harness}.drift`, "live \u6587\u4EF6\u4E0E\u6FC0\u6D3B\u914D\u7F6E\u4E00\u81F4"));
|
|
13230
|
+
}
|
|
13231
|
+
if (probe) {
|
|
13232
|
+
const active = this.activation.getActive(harness);
|
|
13233
|
+
checks.push(unknown(`${harness}.probe`, "\u8FDE\u901A\u6027\u63A2\u6D4B\u5728 MVP \u4E2D\u9ED8\u8BA4\u5173\u95ED\uFF0C\u672A\u53D1\u8D77\u7F51\u7EDC\u8BF7\u6C42", {
|
|
13234
|
+
baseUrl: active?.baseUrl ?? null,
|
|
13235
|
+
enabled: false
|
|
13236
|
+
}));
|
|
13237
|
+
}
|
|
13238
|
+
return checks;
|
|
13239
|
+
}
|
|
13240
|
+
commandExists(bin) {
|
|
13241
|
+
try {
|
|
13242
|
+
const result = Bun.spawnSync(["/bin/sh", "-c", `command -v ${bin}`], {
|
|
13243
|
+
env: process.env
|
|
13244
|
+
});
|
|
13245
|
+
return result.exitCode === 0 && result.stdout.toString().trim().length > 0;
|
|
13246
|
+
} catch {
|
|
13247
|
+
return false;
|
|
13248
|
+
}
|
|
13249
|
+
}
|
|
13250
|
+
isReadable(path) {
|
|
13251
|
+
try {
|
|
13252
|
+
accessSync(path, constants.R_OK);
|
|
13253
|
+
return true;
|
|
13254
|
+
} catch {
|
|
13255
|
+
return false;
|
|
13256
|
+
}
|
|
13257
|
+
}
|
|
13258
|
+
isWritable(path) {
|
|
13259
|
+
try {
|
|
13260
|
+
accessSync(path, constants.W_OK);
|
|
13261
|
+
return true;
|
|
13262
|
+
} catch {
|
|
13263
|
+
return false;
|
|
13264
|
+
}
|
|
13265
|
+
}
|
|
13266
|
+
}
|
|
13267
|
+
DoctorService = __decorateElement(_init, 0, "DoctorService", _dec, DoctorService);
|
|
13268
|
+
__runInitializers(_init, 1, DoctorService);
|
|
13269
|
+
__decoratorMetadata(_init, DoctorService);
|
|
13270
|
+
let _DoctorService = DoctorService;
|
|
13271
|
+
function makeCheck(id, label, status, detail) {
|
|
13272
|
+
const detailObject = detail === undefined ? { message: label } : { message: label, ...detail };
|
|
13273
|
+
return { id, label, status, detail: detailObject };
|
|
13274
|
+
}
|
|
13275
|
+
function ok(id, message, detail) {
|
|
13276
|
+
return makeCheck(id, message, "ok", detail);
|
|
13277
|
+
}
|
|
13278
|
+
function warn(id, message, detail) {
|
|
13279
|
+
return makeCheck(id, message, "warn", detail);
|
|
13280
|
+
}
|
|
13281
|
+
function error(id, message, detail) {
|
|
13282
|
+
return makeCheck(id, message, "error", detail);
|
|
13283
|
+
}
|
|
13284
|
+
function unknown(id, message, detail) {
|
|
13285
|
+
return makeCheck(id, message, "unknown", detail);
|
|
13286
|
+
}
|
|
13287
|
+
function octal(mode) {
|
|
13288
|
+
return mode.toString(8).padStart(4, "0");
|
|
13289
|
+
}
|
|
13290
|
+
|
|
13291
|
+
// src/http/routes/doctor.ts
|
|
13292
|
+
function createDoctorRoutes(services) {
|
|
13293
|
+
const app = new Hono2;
|
|
13294
|
+
const doctor = services.get(IDoctorService);
|
|
13295
|
+
app.get("/", async (c) => {
|
|
13296
|
+
const probe = c.req.query("probe") === "1";
|
|
13297
|
+
const harnessParam = c.req.query("harness");
|
|
13298
|
+
const harness = harnessParam && harnessParam.length > 0 ? harnessParam : undefined;
|
|
13299
|
+
return c.json(await doctor.run({ probe, harness }));
|
|
13300
|
+
});
|
|
13301
|
+
return app;
|
|
13302
|
+
}
|
|
13303
|
+
|
|
13304
|
+
// src/http/routes/drift.ts
|
|
13305
|
+
function createDriftRoutes(services) {
|
|
13306
|
+
const app = new Hono2;
|
|
13307
|
+
const drift = services.get(IDriftService);
|
|
13308
|
+
const harnesses = services.get(IHarnessRegistry);
|
|
13309
|
+
app.get("/", (c) => c.json({ items: drift.inspectAll() }));
|
|
13310
|
+
app.get("/:harnessId", (c) => c.json(drift.inspect(harnesses.require(c.req.param("harnessId")))));
|
|
13311
|
+
app.post("/:harnessId/reapply", (c) => c.json(drift.reapply(harnesses.require(c.req.param("harnessId")))));
|
|
13312
|
+
app.post("/:harnessId/adopt", (c) => c.json(drift.adopt(harnesses.require(c.req.param("harnessId")))));
|
|
13313
|
+
return app;
|
|
13314
|
+
}
|
|
13315
|
+
|
|
12351
13316
|
// src/http/routes/harnesses.ts
|
|
12352
13317
|
function createHarnessRoutes(services) {
|
|
12353
13318
|
const app = new Hono2;
|
|
@@ -12388,7 +13353,9 @@ function createHarnessRoutes(services) {
|
|
|
12388
13353
|
model: body.model,
|
|
12389
13354
|
notes: body.notes,
|
|
12390
13355
|
extras: body.extras,
|
|
12391
|
-
overrides: body.overrides
|
|
13356
|
+
overrides: body.overrides,
|
|
13357
|
+
providerId: body.providerId,
|
|
13358
|
+
providerEndpoint: body.providerEndpoint
|
|
12392
13359
|
}, true);
|
|
12393
13360
|
return c.json(profile, 201);
|
|
12394
13361
|
});
|
|
@@ -12408,12 +13375,14 @@ function createHarnessRoutes(services) {
|
|
|
12408
13375
|
model: body.model,
|
|
12409
13376
|
notes: body.notes,
|
|
12410
13377
|
extras: body.extras,
|
|
12411
|
-
overrides: body.overrides
|
|
13378
|
+
overrides: body.overrides,
|
|
13379
|
+
providerId: body.providerId,
|
|
13380
|
+
providerEndpoint: body.providerEndpoint
|
|
12412
13381
|
}, false);
|
|
12413
13382
|
persisted = true;
|
|
12414
13383
|
activation.reconcileProfileUpdate(harnessId, name, profile.name);
|
|
12415
13384
|
return c.json(profile);
|
|
12416
|
-
} catch (
|
|
13385
|
+
} catch (error2) {
|
|
12417
13386
|
if (persisted) {
|
|
12418
13387
|
restoreProfileStore(files, environment.files.profiles, snapshot);
|
|
12419
13388
|
if (wasActive) {
|
|
@@ -12424,7 +13393,7 @@ function createHarnessRoutes(services) {
|
|
|
12424
13393
|
}
|
|
12425
13394
|
}
|
|
12426
13395
|
}
|
|
12427
|
-
throw
|
|
13396
|
+
throw error2;
|
|
12428
13397
|
}
|
|
12429
13398
|
});
|
|
12430
13399
|
app.delete("/:harnessId/profiles/:name", (c) => {
|
|
@@ -12465,6 +13434,54 @@ function restoreProfileStore(files, path, snapshot) {
|
|
|
12465
13434
|
files.writeSecure(path, snapshot);
|
|
12466
13435
|
}
|
|
12467
13436
|
|
|
13437
|
+
// src/http/routes/providers.ts
|
|
13438
|
+
function createProviderRoutes(services) {
|
|
13439
|
+
const app = new Hono2;
|
|
13440
|
+
const vault = services.get(IVaultService);
|
|
13441
|
+
const profiles = services.get(IProfileService);
|
|
13442
|
+
const activation = services.get(IActivationService);
|
|
13443
|
+
const log = services.get(ILogService);
|
|
13444
|
+
app.get("/", (c) => c.json({ items: vault.list() }));
|
|
13445
|
+
app.get("/:id", (c) => c.json(vault.get(decodeURIComponent(c.req.param("id")))));
|
|
13446
|
+
app.post("/", async (c) => {
|
|
13447
|
+
const body = await readBody2(c.req.json.bind(c.req));
|
|
13448
|
+
return c.json({ provider: vault.create(body), warnings: [] }, 201);
|
|
13449
|
+
});
|
|
13450
|
+
app.patch("/:id", async (c) => {
|
|
13451
|
+
const id = decodeURIComponent(c.req.param("id"));
|
|
13452
|
+
const body = await readBody2(c.req.json.bind(c.req));
|
|
13453
|
+
const { provider, affected } = vault.update(id, body);
|
|
13454
|
+
profiles.sweepVaultCache(id, vault.decrypt(id), provider.endpoints);
|
|
13455
|
+
const warnings = [];
|
|
13456
|
+
for (const ref of affected) {
|
|
13457
|
+
if (activation.getActive(ref.harness)?.name !== ref.name) {
|
|
13458
|
+
continue;
|
|
13459
|
+
}
|
|
13460
|
+
const profile = profiles.get(ref.harness, ref.name);
|
|
13461
|
+
if (profile?.providerEndpoint && !provider.endpoints.some((ep) => ep.key === profile.providerEndpoint)) {
|
|
13462
|
+
warnings.push(`${ref.harness}/${ref.name}: endpoint ${profile.providerEndpoint} \u5DF2\u4E0D\u5B58\u5728\uFF0C\u5C06\u56DE\u9000\u5230 provider \u9996\u4E2A endpoint`);
|
|
13463
|
+
}
|
|
13464
|
+
try {
|
|
13465
|
+
activation.activate(ref.harness, ref.name);
|
|
13466
|
+
} catch (error2) {
|
|
13467
|
+
log.error(`providers update: failed to re-apply ${ref.harness}/${ref.name}`, error2);
|
|
13468
|
+
warnings.push(`${ref.harness}/${ref.name} \u91CD\u65B0\u5E94\u7528\u5931\u8D25\uFF1A${error2.message}`);
|
|
13469
|
+
}
|
|
13470
|
+
}
|
|
13471
|
+
return c.json({ provider, warnings });
|
|
13472
|
+
});
|
|
13473
|
+
app.delete("/:id", (c) => {
|
|
13474
|
+
vault.remove(decodeURIComponent(c.req.param("id")));
|
|
13475
|
+
return c.json({ ok: true });
|
|
13476
|
+
});
|
|
13477
|
+
return app;
|
|
13478
|
+
}
|
|
13479
|
+
async function readBody2(read) {
|
|
13480
|
+
return read().catch(() => {
|
|
13481
|
+
throw new HttpError(400, "invalid json");
|
|
13482
|
+
});
|
|
13483
|
+
}
|
|
13484
|
+
|
|
12468
13485
|
// src/services/transfer.ts
|
|
12469
13486
|
import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes4, scryptSync } from "crypto";
|
|
12470
13487
|
var FORMAT = "harness-switch-encrypted-export";
|
|
@@ -12472,7 +13489,7 @@ var VERSION = 1;
|
|
|
12472
13489
|
var MAX_ENCRYPTED_BYTES = 10 * 1024 * 1024;
|
|
12473
13490
|
var ITransferService = createDecorator("transferService");
|
|
12474
13491
|
var _dec = [
|
|
12475
|
-
inject(IEnvironmentService, IFileService, ICryptoService, IAdapterRegistry, IActivationService)
|
|
13492
|
+
inject(IEnvironmentService, IFileService, ICryptoService, IAdapterRegistry, IActivationService, IVaultService)
|
|
12476
13493
|
];
|
|
12477
13494
|
var _init = __decoratorStart(undefined);
|
|
12478
13495
|
|
|
@@ -12482,12 +13499,14 @@ class TransferService {
|
|
|
12482
13499
|
crypto;
|
|
12483
13500
|
adapters;
|
|
12484
13501
|
activation;
|
|
12485
|
-
|
|
13502
|
+
vault;
|
|
13503
|
+
constructor(environment, files, crypto2, adapters, activation, vault) {
|
|
12486
13504
|
this.environment = environment;
|
|
12487
13505
|
this.files = files;
|
|
12488
13506
|
this.crypto = crypto2;
|
|
12489
13507
|
this.adapters = adapters;
|
|
12490
13508
|
this.activation = activation;
|
|
13509
|
+
this.vault = vault;
|
|
12491
13510
|
}
|
|
12492
13511
|
exportAll(passphrase) {
|
|
12493
13512
|
this.assertPassphrase(passphrase);
|
|
@@ -12499,7 +13518,7 @@ class TransferService {
|
|
|
12499
13518
|
harness,
|
|
12500
13519
|
name,
|
|
12501
13520
|
baseUrl: stored.base_url || "",
|
|
12502
|
-
apiKey: this.
|
|
13521
|
+
apiKey: this.resolveKey(stored),
|
|
12503
13522
|
model: stored.model || "",
|
|
12504
13523
|
notes: stored.notes || "",
|
|
12505
13524
|
extras: stored.extras ?? {},
|
|
@@ -12577,8 +13596,8 @@ class TransferService {
|
|
|
12577
13596
|
throw new Error("\u5BF9\u5E94\u914D\u7F6E\u4E0D\u5B58\u5728");
|
|
12578
13597
|
}
|
|
12579
13598
|
activeRestored++;
|
|
12580
|
-
} catch (
|
|
12581
|
-
warnings.push(`${active.harness}/${active.name} \u672A\u80FD\u6062\u590D\u6FC0\u6D3B\u72B6\u6001\uFF1A${
|
|
13599
|
+
} catch (error2) {
|
|
13600
|
+
warnings.push(`${active.harness}/${active.name} \u672A\u80FD\u6062\u590D\u6FC0\u6D3B\u72B6\u6001\uFF1A${error2.message}`);
|
|
12582
13601
|
}
|
|
12583
13602
|
}
|
|
12584
13603
|
}
|
|
@@ -12631,6 +13650,16 @@ class TransferService {
|
|
|
12631
13650
|
readStore() {
|
|
12632
13651
|
return this.files.readJsonStrict(this.environment.files.profiles, {});
|
|
12633
13652
|
}
|
|
13653
|
+
resolveKey(stored) {
|
|
13654
|
+
if (!stored.provider_id) {
|
|
13655
|
+
return this.crypto.decrypt(stored.api_key);
|
|
13656
|
+
}
|
|
13657
|
+
try {
|
|
13658
|
+
return this.vault.decrypt(stored.provider_id);
|
|
13659
|
+
} catch {
|
|
13660
|
+
return this.crypto.decrypt(stored.api_key);
|
|
13661
|
+
}
|
|
13662
|
+
}
|
|
12634
13663
|
assertPassphrase(passphrase) {
|
|
12635
13664
|
if (passphrase.length < 8) {
|
|
12636
13665
|
throw new HttpError(400, "\u8FC1\u79FB\u5BC6\u7801\u81F3\u5C11\u9700\u8981 8 \u4E2A\u5B57\u7B26");
|
|
@@ -12700,15 +13729,15 @@ function createTransferRoutes(services) {
|
|
|
12700
13729
|
const app = new Hono2;
|
|
12701
13730
|
const transfer = services.get(ITransferService);
|
|
12702
13731
|
app.post("/export", async (c) => {
|
|
12703
|
-
const body = await
|
|
13732
|
+
const body = await readBody3(c.req.json.bind(c.req));
|
|
12704
13733
|
return c.json(transfer.exportAll(String(body.passphrase ?? "")));
|
|
12705
13734
|
});
|
|
12706
13735
|
app.post("/preview", async (c) => {
|
|
12707
|
-
const body = await
|
|
13736
|
+
const body = await readBody3(c.req.json.bind(c.req));
|
|
12708
13737
|
return c.json(transfer.preview(requireEnvelope(body.envelope), String(body.passphrase ?? "")));
|
|
12709
13738
|
});
|
|
12710
13739
|
app.post("/import", async (c) => {
|
|
12711
|
-
const body = await
|
|
13740
|
+
const body = await readBody3(c.req.json.bind(c.req));
|
|
12712
13741
|
return c.json(transfer.importAll(requireEnvelope(body.envelope), String(body.passphrase ?? ""), body.conflictPolicy ?? "skip", body.restoreActive === true));
|
|
12713
13742
|
});
|
|
12714
13743
|
return app;
|
|
@@ -12719,113 +13748,259 @@ function requireEnvelope(envelope) {
|
|
|
12719
13748
|
}
|
|
12720
13749
|
return envelope;
|
|
12721
13750
|
}
|
|
12722
|
-
async function
|
|
13751
|
+
async function readBody3(read) {
|
|
12723
13752
|
return read().catch(() => {
|
|
12724
13753
|
throw new HttpError(400, "invalid json");
|
|
12725
13754
|
});
|
|
12726
13755
|
}
|
|
12727
13756
|
|
|
12728
|
-
// src/update.ts
|
|
12729
|
-
|
|
12730
|
-
|
|
12731
|
-
|
|
12732
|
-
|
|
13757
|
+
// src/http/routes/update.ts
|
|
13758
|
+
function createUpdateRoutes(_services) {
|
|
13759
|
+
const api = new Hono2;
|
|
13760
|
+
api.get("/check", async (c) => c.json(await checkForUpdate(c.req.query("force") === "1")));
|
|
13761
|
+
api.post("/", async (c) => {
|
|
13762
|
+
await triggerUpdate();
|
|
13763
|
+
return c.json({ status: "updating" }, 202);
|
|
13764
|
+
});
|
|
13765
|
+
return api;
|
|
13766
|
+
}
|
|
12733
13767
|
|
|
12734
|
-
// src/
|
|
12735
|
-
|
|
12736
|
-
var
|
|
12737
|
-
|
|
12738
|
-
|
|
12739
|
-
|
|
12740
|
-
try {
|
|
12741
|
-
const pkg = JSON.parse(await Bun.file(join9(import.meta.dir, "../package.json")).text());
|
|
12742
|
-
cached = {
|
|
12743
|
-
name: typeof pkg.name === "string" ? pkg.name : "harness-switch",
|
|
12744
|
-
version: typeof pkg.version === "string" ? pkg.version : "0.0.0"
|
|
12745
|
-
};
|
|
12746
|
-
} catch {
|
|
12747
|
-
cached = { name: "harness-switch", version: "0.0.0" };
|
|
12748
|
-
}
|
|
12749
|
-
return cached;
|
|
12750
|
-
}
|
|
12751
|
-
function serverVersion() {
|
|
12752
|
-
return packageInfo().then((info) => info.version);
|
|
12753
|
-
}
|
|
12754
|
-
function packageName() {
|
|
12755
|
-
return packageInfo().then((info) => info.name);
|
|
12756
|
-
}
|
|
13768
|
+
// src/services/user-sync.ts
|
|
13769
|
+
var IUserSyncService = createDecorator("userSyncService");
|
|
13770
|
+
var _dec = [
|
|
13771
|
+
inject(IEnvironmentService, IUserService, IFileService, ICryptoService)
|
|
13772
|
+
];
|
|
13773
|
+
var _init = __decoratorStart(undefined);
|
|
12757
13774
|
|
|
12758
|
-
|
|
12759
|
-
|
|
12760
|
-
|
|
12761
|
-
|
|
12762
|
-
|
|
12763
|
-
|
|
12764
|
-
|
|
12765
|
-
|
|
12766
|
-
|
|
12767
|
-
|
|
12768
|
-
const da = pa[i] ?? 0;
|
|
12769
|
-
const db = pb[i] ?? 0;
|
|
12770
|
-
if (da !== db)
|
|
12771
|
-
return da > db ? 1 : -1;
|
|
13775
|
+
class UserSyncService {
|
|
13776
|
+
environment;
|
|
13777
|
+
users;
|
|
13778
|
+
files;
|
|
13779
|
+
crypto;
|
|
13780
|
+
constructor(environment, users, files, crypto2) {
|
|
13781
|
+
this.environment = environment;
|
|
13782
|
+
this.users = users;
|
|
13783
|
+
this.files = files;
|
|
13784
|
+
this.crypto = crypto2;
|
|
12772
13785
|
}
|
|
12773
|
-
|
|
12774
|
-
|
|
12775
|
-
|
|
12776
|
-
|
|
12777
|
-
|
|
13786
|
+
preview(sourceUsername) {
|
|
13787
|
+
const target = this.environment.currentUser;
|
|
13788
|
+
const source = this.requireSource(sourceUsername, target);
|
|
13789
|
+
const portable = this.readPortable(source);
|
|
13790
|
+
const targetProfiles = this.readProfiles();
|
|
13791
|
+
const conflicts = [];
|
|
13792
|
+
let profileCount = 0;
|
|
13793
|
+
const referencedProviders = new Set;
|
|
13794
|
+
for (const [harness, profiles] of Object.entries(portable.profiles)) {
|
|
13795
|
+
for (const [name, profile] of Object.entries(profiles)) {
|
|
13796
|
+
profileCount++;
|
|
13797
|
+
if (targetProfiles[harness]?.[name]) {
|
|
13798
|
+
conflicts.push({ harness, name });
|
|
13799
|
+
}
|
|
13800
|
+
if (profile.provider_id)
|
|
13801
|
+
referencedProviders.add(profile.provider_id);
|
|
13802
|
+
}
|
|
13803
|
+
}
|
|
12778
13804
|
return {
|
|
12779
|
-
|
|
12780
|
-
|
|
12781
|
-
|
|
13805
|
+
sourceUser: source.username,
|
|
13806
|
+
targetUser: target.username,
|
|
13807
|
+
profileCount,
|
|
13808
|
+
providerCount: referencedProviders.size,
|
|
13809
|
+
conflicts
|
|
12782
13810
|
};
|
|
12783
13811
|
}
|
|
12784
|
-
|
|
12785
|
-
|
|
12786
|
-
|
|
12787
|
-
|
|
12788
|
-
|
|
12789
|
-
|
|
12790
|
-
|
|
13812
|
+
sync(sourceUsername, conflictPolicy) {
|
|
13813
|
+
if (conflictPolicy !== "skip" && conflictPolicy !== "overwrite") {
|
|
13814
|
+
throw new HttpError(400, "invalid conflict policy");
|
|
13815
|
+
}
|
|
13816
|
+
const target = this.environment.currentUser;
|
|
13817
|
+
const source = this.requireSource(sourceUsername, target);
|
|
13818
|
+
const portable = this.readPortable(source);
|
|
13819
|
+
const profilesPath = this.environment.files.profiles;
|
|
13820
|
+
const vaultPath = this.environment.files.vault;
|
|
13821
|
+
const profileSnapshot = this.files.readOptional(profilesPath);
|
|
13822
|
+
const vaultSnapshot = this.files.readOptional(vaultPath);
|
|
13823
|
+
const targetProfiles = structuredClone(this.readProfiles());
|
|
13824
|
+
const targetVault = structuredClone(this.readVault());
|
|
13825
|
+
const active = this.files.readJson(this.environment.files.active, {});
|
|
13826
|
+
const warnings = [];
|
|
13827
|
+
let imported = 0;
|
|
13828
|
+
let overwritten = 0;
|
|
13829
|
+
let skipped = 0;
|
|
13830
|
+
const selected = [];
|
|
13831
|
+
for (const [harness, profiles] of Object.entries(portable.profiles)) {
|
|
13832
|
+
for (const [name, profile] of Object.entries(profiles)) {
|
|
13833
|
+
const exists = targetProfiles[harness]?.[name] !== undefined;
|
|
13834
|
+
if (exists && conflictPolicy === "skip") {
|
|
13835
|
+
skipped++;
|
|
13836
|
+
continue;
|
|
13837
|
+
}
|
|
13838
|
+
selected.push({ harness, name, profile });
|
|
13839
|
+
if (exists) {
|
|
13840
|
+
overwritten++;
|
|
13841
|
+
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`);
|
|
13843
|
+
}
|
|
13844
|
+
} else
|
|
13845
|
+
imported++;
|
|
13846
|
+
}
|
|
13847
|
+
}
|
|
13848
|
+
const providerMap = new Map;
|
|
13849
|
+
for (const { profile } of selected) {
|
|
13850
|
+
const sourceId = profile.provider_id;
|
|
13851
|
+
if (!sourceId || providerMap.has(sourceId))
|
|
13852
|
+
continue;
|
|
13853
|
+
const provider = portable.providers[sourceId];
|
|
13854
|
+
if (!provider) {
|
|
13855
|
+
continue;
|
|
13856
|
+
}
|
|
13857
|
+
const targetId = this.availableProviderId(sourceId, source.username, targetVault);
|
|
13858
|
+
providerMap.set(sourceId, targetId);
|
|
13859
|
+
const { apiKey, ...storedProvider } = provider;
|
|
13860
|
+
targetVault.entries[targetId] = {
|
|
13861
|
+
...storedProvider,
|
|
13862
|
+
id: targetId,
|
|
13863
|
+
api_key: this.crypto.encrypt(apiKey),
|
|
13864
|
+
created_at: new Date().toISOString(),
|
|
13865
|
+
updated_at: new Date().toISOString(),
|
|
13866
|
+
synced_from: { username: source.username, provider_id: sourceId }
|
|
13867
|
+
};
|
|
13868
|
+
}
|
|
13869
|
+
for (const { harness, name, profile } of selected) {
|
|
13870
|
+
targetProfiles[harness] ||= {};
|
|
13871
|
+
const mappedProvider = profile.provider_id ? providerMap.get(profile.provider_id) : undefined;
|
|
13872
|
+
const { apiKey, ...storedProfile } = profile;
|
|
13873
|
+
targetProfiles[harness][name] = {
|
|
13874
|
+
...storedProfile,
|
|
13875
|
+
api_key: this.crypto.encrypt(apiKey),
|
|
13876
|
+
provider_id: mappedProvider,
|
|
13877
|
+
provider_endpoint: mappedProvider ? profile.provider_endpoint : undefined,
|
|
13878
|
+
updated_at: new Date().toISOString()
|
|
13879
|
+
};
|
|
13880
|
+
}
|
|
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;
|
|
12791
13888
|
}
|
|
12792
|
-
const payload = await response.json();
|
|
12793
|
-
const latest = typeof payload.version === "string" ? payload.version : null;
|
|
12794
|
-
cached2 = { latest, at: Date.now() };
|
|
12795
13889
|
return {
|
|
12796
|
-
|
|
12797
|
-
|
|
12798
|
-
|
|
13890
|
+
ok: true,
|
|
13891
|
+
sourceUser: source.username,
|
|
13892
|
+
targetUser: target.username,
|
|
13893
|
+
imported,
|
|
13894
|
+
overwritten,
|
|
13895
|
+
skipped,
|
|
13896
|
+
providersCopied: providerMap.size,
|
|
13897
|
+
warnings
|
|
12799
13898
|
};
|
|
12800
|
-
} catch {
|
|
12801
|
-
return { current, latest: null, updateAvailable: false };
|
|
12802
13899
|
}
|
|
12803
|
-
|
|
12804
|
-
|
|
12805
|
-
|
|
12806
|
-
|
|
13900
|
+
requireSource(sourceUsername, target) {
|
|
13901
|
+
const source = this.users.require(sourceUsername);
|
|
13902
|
+
if (source.username === target.username) {
|
|
13903
|
+
throw new HttpError(400, "\u6765\u6E90\u7528\u6237\u4E0D\u80FD\u4E0E\u5F53\u524D\u76EE\u6807\u7528\u6237\u76F8\u540C");
|
|
13904
|
+
}
|
|
13905
|
+
return source;
|
|
13906
|
+
}
|
|
13907
|
+
readPortable(source) {
|
|
13908
|
+
return this.environment.runAsUser(source, () => {
|
|
13909
|
+
const profiles = this.readProfiles();
|
|
13910
|
+
const vault = this.readVault();
|
|
13911
|
+
const portableProviders = {};
|
|
13912
|
+
for (const [id, entry] of Object.entries(vault.entries)) {
|
|
13913
|
+
portableProviders[id] = { ...entry, apiKey: this.crypto.decrypt(entry.api_key) };
|
|
13914
|
+
}
|
|
13915
|
+
const portableProfiles = {};
|
|
13916
|
+
for (const [harness, entries] of Object.entries(profiles)) {
|
|
13917
|
+
portableProfiles[harness] = {};
|
|
13918
|
+
for (const [name, profile] of Object.entries(entries)) {
|
|
13919
|
+
const providerKey = profile.provider_id ? portableProviders[profile.provider_id]?.apiKey : undefined;
|
|
13920
|
+
portableProfiles[harness][name] = {
|
|
13921
|
+
...profile,
|
|
13922
|
+
apiKey: providerKey ?? this.crypto.decrypt(profile.api_key)
|
|
13923
|
+
};
|
|
13924
|
+
}
|
|
13925
|
+
}
|
|
13926
|
+
return { profiles: portableProfiles, providers: portableProviders };
|
|
13927
|
+
});
|
|
13928
|
+
}
|
|
13929
|
+
readProfiles() {
|
|
13930
|
+
return this.files.readJsonStrict(this.environment.files.profiles, {});
|
|
13931
|
+
}
|
|
13932
|
+
readVault() {
|
|
13933
|
+
return this.files.readJsonStrict(this.environment.files.vault, {
|
|
13934
|
+
version: 1,
|
|
13935
|
+
entries: {}
|
|
13936
|
+
});
|
|
13937
|
+
}
|
|
13938
|
+
availableProviderId(sourceId, sourceUsername, target) {
|
|
13939
|
+
const previous = Object.values(target.entries).find((entry) => entry.synced_from?.username === sourceUsername && entry.synced_from.provider_id === sourceId);
|
|
13940
|
+
if (previous)
|
|
13941
|
+
return previous.id;
|
|
13942
|
+
if (!target.entries[sourceId])
|
|
13943
|
+
return sourceId;
|
|
13944
|
+
const suffix = sourceUsername.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").slice(0, 24);
|
|
13945
|
+
const base = `${sourceId}-${suffix || "copy"}`.slice(0, 60);
|
|
13946
|
+
let candidate = base;
|
|
13947
|
+
let index = 2;
|
|
13948
|
+
while (target.entries[candidate]) {
|
|
13949
|
+
candidate = `${base}-${index}`.slice(0, 64);
|
|
13950
|
+
index++;
|
|
13951
|
+
}
|
|
13952
|
+
return candidate;
|
|
13953
|
+
}
|
|
13954
|
+
restore(path, snapshot) {
|
|
13955
|
+
try {
|
|
13956
|
+
if (snapshot === undefined)
|
|
13957
|
+
this.files.remove(path);
|
|
13958
|
+
else
|
|
13959
|
+
this.files.writeSecure(path, snapshot);
|
|
13960
|
+
} catch {}
|
|
12807
13961
|
}
|
|
12808
|
-
const name = await packageName();
|
|
12809
|
-
const dataDir = process.env.HSW_DATA_DIR || join10(homedir2(), ".harness-switch");
|
|
12810
|
-
mkdirSync3(dataDir, { recursive: true, mode: 448 });
|
|
12811
|
-
const logFd = openSync(join10(dataDir, "update.log"), "w");
|
|
12812
|
-
const child = spawn(process.execPath, ["x", `${name}@latest`], {
|
|
12813
|
-
detached: true,
|
|
12814
|
-
stdio: ["ignore", logFd, logFd],
|
|
12815
|
-
env: process.env
|
|
12816
|
-
});
|
|
12817
|
-
child.unref();
|
|
12818
13962
|
}
|
|
13963
|
+
UserSyncService = __decorateElement(_init, 0, "UserSyncService", _dec, UserSyncService);
|
|
13964
|
+
__runInitializers(_init, 1, UserSyncService);
|
|
13965
|
+
__decoratorMetadata(_init, UserSyncService);
|
|
13966
|
+
let _UserSyncService = UserSyncService;
|
|
12819
13967
|
|
|
12820
|
-
// src/http/routes/
|
|
12821
|
-
function
|
|
12822
|
-
const
|
|
12823
|
-
|
|
12824
|
-
|
|
12825
|
-
|
|
12826
|
-
|
|
13968
|
+
// src/http/routes/users.ts
|
|
13969
|
+
function createUserRoutes(services) {
|
|
13970
|
+
const app = new Hono2;
|
|
13971
|
+
const auth = services.get(IAuthService);
|
|
13972
|
+
const environment = services.get(IEnvironmentService);
|
|
13973
|
+
const users = services.get(IUserService);
|
|
13974
|
+
const sync = services.get(IUserSyncService);
|
|
13975
|
+
app.get("/", (c) => {
|
|
13976
|
+
const current = environment.currentUser.username;
|
|
13977
|
+
return c.json({
|
|
13978
|
+
currentUser: current,
|
|
13979
|
+
items: users.list().map((user) => ({ ...user, current: user.username === current }))
|
|
13980
|
+
});
|
|
13981
|
+
});
|
|
13982
|
+
app.post("/sync/preview", async (c) => {
|
|
13983
|
+
const body = await readBody4(c.req.json.bind(c.req));
|
|
13984
|
+
return c.json(sync.preview(String(body.sourceUser ?? "")));
|
|
13985
|
+
});
|
|
13986
|
+
app.post("/sync", async (c) => {
|
|
13987
|
+
const body = await readBody4(c.req.json.bind(c.req));
|
|
13988
|
+
return c.json(sync.sync(String(body.sourceUser ?? ""), body.conflictPolicy ?? "skip"));
|
|
13989
|
+
});
|
|
13990
|
+
app.post("/:username/select", (c) => {
|
|
13991
|
+
const user = users.require(decodeURIComponent(c.req.param("username")));
|
|
13992
|
+
const token = getCookie(c, environment.cookieName);
|
|
13993
|
+
if (!token)
|
|
13994
|
+
throw new HttpError(401, "authentication required");
|
|
13995
|
+
auth.selectUser(token, user.username);
|
|
13996
|
+
return c.json({ currentUser: user.username });
|
|
13997
|
+
});
|
|
13998
|
+
return app;
|
|
13999
|
+
}
|
|
14000
|
+
async function readBody4(read) {
|
|
14001
|
+
return read().catch(() => {
|
|
14002
|
+
throw new HttpError(400, "invalid json");
|
|
12827
14003
|
});
|
|
12828
|
-
return api;
|
|
12829
14004
|
}
|
|
12830
14005
|
|
|
12831
14006
|
// src/app.ts
|
|
@@ -12839,6 +14014,9 @@ function createApp(services) {
|
|
|
12839
14014
|
api.use("*", createOriginGuard());
|
|
12840
14015
|
api.get("/version", async (c) => c.json({ name: "harness-switch", version: await serverVersion() }));
|
|
12841
14016
|
api.route("/auth", createAuthRoutes(services));
|
|
14017
|
+
api.use("/users/*", createAuthGuard(services));
|
|
14018
|
+
api.use("/users", createAuthGuard(services));
|
|
14019
|
+
api.route("/users", createUserRoutes(services));
|
|
12842
14020
|
api.use("/harnesses/*", createAuthGuard(services));
|
|
12843
14021
|
api.use("/harnesses", createAuthGuard(services));
|
|
12844
14022
|
api.route("/harnesses", createHarnessRoutes(services));
|
|
@@ -12850,20 +14028,29 @@ function createApp(services) {
|
|
|
12850
14028
|
api.use("/update/*", createAuthGuard(services));
|
|
12851
14029
|
api.use("/update", createAuthGuard(services));
|
|
12852
14030
|
api.route("/update", createUpdateRoutes(services));
|
|
14031
|
+
api.use("/providers/*", createAuthGuard(services));
|
|
14032
|
+
api.use("/providers", createAuthGuard(services));
|
|
14033
|
+
api.route("/providers", createProviderRoutes(services));
|
|
14034
|
+
api.use("/doctor/*", createAuthGuard(services));
|
|
14035
|
+
api.use("/doctor", createAuthGuard(services));
|
|
14036
|
+
api.route("/doctor", createDoctorRoutes(services));
|
|
14037
|
+
api.use("/drift/*", createAuthGuard(services));
|
|
14038
|
+
api.use("/drift", createAuthGuard(services));
|
|
14039
|
+
api.route("/drift", createDriftRoutes(services));
|
|
12853
14040
|
app.route("/api", api);
|
|
12854
14041
|
const publicDir = environment.publicDir;
|
|
12855
|
-
if (
|
|
14042
|
+
if (existsSync4(publicDir)) {
|
|
12856
14043
|
app.use("/assets/*", serveStatic2({ root: publicDir }));
|
|
12857
14044
|
app.get("*", async (c, next) => {
|
|
12858
14045
|
if (c.req.path.startsWith("/api") || c.req.path === "/healthz") {
|
|
12859
14046
|
return next();
|
|
12860
14047
|
}
|
|
12861
14048
|
const assetPath = join11(publicDir, c.req.path.replace(/^\//, ""));
|
|
12862
|
-
if (c.req.path !== "/" &&
|
|
14049
|
+
if (c.req.path !== "/" && existsSync4(assetPath)) {
|
|
12863
14050
|
return serveStatic2({ root: publicDir })(c, next);
|
|
12864
14051
|
}
|
|
12865
14052
|
const index = join11(publicDir, "index.html");
|
|
12866
|
-
if (
|
|
14053
|
+
if (existsSync4(index)) {
|
|
12867
14054
|
c.header("Cache-Control", "no-store");
|
|
12868
14055
|
return c.html(await Bun.file(index).text());
|
|
12869
14056
|
}
|
|
@@ -12871,11 +14058,11 @@ function createApp(services) {
|
|
|
12871
14058
|
});
|
|
12872
14059
|
}
|
|
12873
14060
|
app.notFound((c) => c.json({ error: "not found" }, 404));
|
|
12874
|
-
app.onError((
|
|
12875
|
-
if (
|
|
12876
|
-
return c.json({ error:
|
|
14061
|
+
app.onError((error2, c) => {
|
|
14062
|
+
if (error2 instanceof HttpError) {
|
|
14063
|
+
return c.json({ error: error2.message }, error2.status);
|
|
12877
14064
|
}
|
|
12878
|
-
log.error("unhandled error",
|
|
14065
|
+
log.error("unhandled error", error2);
|
|
12879
14066
|
return c.json({ error: "internal server error" }, 500);
|
|
12880
14067
|
});
|
|
12881
14068
|
return app;
|
|
@@ -12886,6 +14073,8 @@ function createServices() {
|
|
|
12886
14073
|
const collection = new ServiceCollection;
|
|
12887
14074
|
collection.set(ILogService, new SyncDescriptor(LogService));
|
|
12888
14075
|
collection.set(IEnvironmentService, new SyncDescriptor(EnvironmentService));
|
|
14076
|
+
collection.set(IUserService, new SyncDescriptor(UserService));
|
|
14077
|
+
collection.set(IUserSyncService, new SyncDescriptor(UserSyncService));
|
|
12889
14078
|
collection.set(IFileService, new SyncDescriptor(FileService));
|
|
12890
14079
|
collection.set(ICryptoService, new SyncDescriptor(CryptoService));
|
|
12891
14080
|
collection.set(IAuthService, new SyncDescriptor(AuthService));
|
|
@@ -12893,15 +14082,75 @@ function createServices() {
|
|
|
12893
14082
|
collection.set(IAdapterRegistry, new SyncDescriptor(AdapterRegistry));
|
|
12894
14083
|
collection.set(IBackupService, new SyncDescriptor(BackupService));
|
|
12895
14084
|
collection.set(ILiveWriteService, new SyncDescriptor(LiveWriteService));
|
|
14085
|
+
collection.set(IVaultService, new SyncDescriptor(VaultService));
|
|
12896
14086
|
collection.set(IProfileService, new SyncDescriptor(ProfileService));
|
|
12897
14087
|
collection.set(IActivationService, new SyncDescriptor(ActivationService));
|
|
12898
14088
|
collection.set(ITransferService, new SyncDescriptor(TransferService));
|
|
14089
|
+
collection.set(IDriftService, new SyncDescriptor(DriftService));
|
|
14090
|
+
collection.set(IDoctorService, new SyncDescriptor(DoctorService));
|
|
12899
14091
|
return new InstantiationService(collection);
|
|
12900
14092
|
}
|
|
12901
14093
|
|
|
14094
|
+
// src/cli/args.ts
|
|
14095
|
+
function parseArgs(argv) {
|
|
14096
|
+
const flags = {};
|
|
14097
|
+
const positional = [];
|
|
14098
|
+
const valueFlags = new Set(["user", "from", "to", "harness"]);
|
|
14099
|
+
for (let index = 0;index < argv.length; index++) {
|
|
14100
|
+
const arg = argv[index];
|
|
14101
|
+
if (arg.startsWith("--")) {
|
|
14102
|
+
const body = arg.slice(2);
|
|
14103
|
+
const separator = body.indexOf("=");
|
|
14104
|
+
if (separator !== -1) {
|
|
14105
|
+
flags[body.slice(0, separator)] = body.slice(separator + 1);
|
|
14106
|
+
} else {
|
|
14107
|
+
const next = argv[index + 1];
|
|
14108
|
+
if (valueFlags.has(body) && next && !next.startsWith("--")) {
|
|
14109
|
+
flags[body] = next;
|
|
14110
|
+
index++;
|
|
14111
|
+
} else {
|
|
14112
|
+
flags[body] = true;
|
|
14113
|
+
}
|
|
14114
|
+
}
|
|
14115
|
+
} else {
|
|
14116
|
+
positional.push(arg);
|
|
14117
|
+
}
|
|
14118
|
+
}
|
|
14119
|
+
return { flags, positional };
|
|
14120
|
+
}
|
|
14121
|
+
function flagValue(flags, name, fallback = "") {
|
|
14122
|
+
const value = flags[name];
|
|
14123
|
+
return typeof value === "string" ? value : fallback;
|
|
14124
|
+
}
|
|
14125
|
+
function hasFlag(flags, name) {
|
|
14126
|
+
return flags[name] === true || typeof flags[name] === "string" && flags[name] !== "";
|
|
14127
|
+
}
|
|
14128
|
+
function requirePositional(positional, index, what) {
|
|
14129
|
+
const value = positional[index];
|
|
14130
|
+
if (!value) {
|
|
14131
|
+
throw new CliError(`\u7F3A\u5C11\u53C2\u6570\uFF1A${what}`);
|
|
14132
|
+
}
|
|
14133
|
+
return value;
|
|
14134
|
+
}
|
|
14135
|
+
|
|
14136
|
+
class CliError extends Error {
|
|
14137
|
+
constructor(message) {
|
|
14138
|
+
super(message);
|
|
14139
|
+
this.name = "CliError";
|
|
14140
|
+
}
|
|
14141
|
+
}
|
|
14142
|
+
|
|
14143
|
+
// src/cli/commands.ts
|
|
14144
|
+
import { stdin, stdout } from "process";
|
|
14145
|
+
import { createInterface } from "readline/promises";
|
|
14146
|
+
|
|
14147
|
+
// src/cli/client.ts
|
|
14148
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
14149
|
+
import { join as join13 } from "path";
|
|
14150
|
+
|
|
12902
14151
|
// src/daemon.ts
|
|
12903
14152
|
import { spawn as spawn2 } from "child_process";
|
|
12904
|
-
import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as
|
|
14153
|
+
import { mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
|
|
12905
14154
|
import { homedir as homedir3 } from "os";
|
|
12906
14155
|
import { join as join12, resolve } from "path";
|
|
12907
14156
|
var DEFAULT_HOST = "127.0.0.1";
|
|
@@ -12919,7 +14168,7 @@ function daemonLogFile() {
|
|
|
12919
14168
|
}
|
|
12920
14169
|
function readPid() {
|
|
12921
14170
|
try {
|
|
12922
|
-
const raw2 =
|
|
14171
|
+
const raw2 = readFileSync3(daemonPidFile(), "utf8").trim();
|
|
12923
14172
|
const pid = Number(raw2);
|
|
12924
14173
|
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
12925
14174
|
} catch {
|
|
@@ -13021,7 +14270,337 @@ async function daemonize() {
|
|
|
13021
14270
|
console.log(` password (first run): ${join12(daemonDataDir(), "web_password")}`);
|
|
13022
14271
|
}
|
|
13023
14272
|
function usage() {
|
|
13024
|
-
return
|
|
14273
|
+
return [
|
|
14274
|
+
"usage: harness-switch [server|daemon|status|stop]",
|
|
14275
|
+
" harness-switch [list|providers|doctor|plan|activate] [options]",
|
|
14276
|
+
" CLI commands run against the local data directory; add --json for machine output"
|
|
14277
|
+
].join(`
|
|
14278
|
+
`);
|
|
14279
|
+
}
|
|
14280
|
+
|
|
14281
|
+
// src/cli/client.ts
|
|
14282
|
+
class CliClient {
|
|
14283
|
+
baseUrl;
|
|
14284
|
+
password;
|
|
14285
|
+
cookie = "";
|
|
14286
|
+
constructor(baseUrl, password) {
|
|
14287
|
+
this.baseUrl = baseUrl;
|
|
14288
|
+
this.password = password;
|
|
14289
|
+
}
|
|
14290
|
+
async login() {
|
|
14291
|
+
const response = await this.fetch("/api/auth/login", {
|
|
14292
|
+
method: "POST",
|
|
14293
|
+
headers: { "Content-Type": "application/json" },
|
|
14294
|
+
body: JSON.stringify({ password: this.password })
|
|
14295
|
+
});
|
|
14296
|
+
const setCookie2 = response.headers.get("set-cookie") ?? "";
|
|
14297
|
+
const match2 = /hsw_session=([^;]+)/.exec(setCookie2);
|
|
14298
|
+
if (!response.ok || !match2) {
|
|
14299
|
+
throw new CliError(response.ok ? "\u767B\u5F55\u5931\u8D25\uFF1A\u670D\u52A1\u7AEF\u672A\u8FD4\u56DE\u4F1A\u8BDD" : `\u767B\u5F55\u5931\u8D25\uFF1A${await errorMessage(response)}`);
|
|
14300
|
+
}
|
|
14301
|
+
this.cookie = match2[1];
|
|
14302
|
+
}
|
|
14303
|
+
async get(path) {
|
|
14304
|
+
return this.request("GET", path);
|
|
14305
|
+
}
|
|
14306
|
+
async post(path, body) {
|
|
14307
|
+
return this.request("POST", path, body);
|
|
14308
|
+
}
|
|
14309
|
+
async request(method, path, body) {
|
|
14310
|
+
const response = await this.fetch(path, {
|
|
14311
|
+
method,
|
|
14312
|
+
headers: {
|
|
14313
|
+
Cookie: `hsw_session=${this.cookie}`,
|
|
14314
|
+
...body !== undefined ? { "Content-Type": "application/json" } : {}
|
|
14315
|
+
},
|
|
14316
|
+
body: body !== undefined ? JSON.stringify(body) : undefined
|
|
14317
|
+
});
|
|
14318
|
+
const payload = await response.json().catch(() => null);
|
|
14319
|
+
if (!response.ok) {
|
|
14320
|
+
const message = payload && typeof payload.error === "string" ? payload.error : `\u8BF7\u6C42\u5931\u8D25\uFF1AHTTP ${response.status}`;
|
|
14321
|
+
throw new CliError(message);
|
|
14322
|
+
}
|
|
14323
|
+
return payload;
|
|
14324
|
+
}
|
|
14325
|
+
async fetch(path, init) {
|
|
14326
|
+
try {
|
|
14327
|
+
return await fetch(`${this.baseUrl}${path}`, init);
|
|
14328
|
+
} catch {
|
|
14329
|
+
throw new CliError(`\u65E0\u6CD5\u8FDE\u63A5\u672C\u5730\u670D\u52A1 ${this.baseUrl}\uFF0C\u8BF7\u5148\u542F\u52A8\u670D\u52A1\uFF08harness-switch daemon \u6216 server\uFF09`);
|
|
14330
|
+
}
|
|
14331
|
+
}
|
|
14332
|
+
}
|
|
14333
|
+
function resolveBaseUrl() {
|
|
14334
|
+
return process.env.HSW_URL || `http://127.0.0.1:${process.env.PORT || 8787}`;
|
|
14335
|
+
}
|
|
14336
|
+
function readWebPassword() {
|
|
14337
|
+
const file = join13(daemonDataDir(), "web_password");
|
|
14338
|
+
try {
|
|
14339
|
+
return readFileSync4(file, "utf8").trim();
|
|
14340
|
+
} catch {
|
|
14341
|
+
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`);
|
|
14342
|
+
}
|
|
14343
|
+
}
|
|
14344
|
+
async function errorMessage(response) {
|
|
14345
|
+
try {
|
|
14346
|
+
const payload = await response.json();
|
|
14347
|
+
if (typeof payload.error === "string") {
|
|
14348
|
+
return payload.error;
|
|
14349
|
+
}
|
|
14350
|
+
} catch {}
|
|
14351
|
+
return `HTTP ${response.status}`;
|
|
14352
|
+
}
|
|
14353
|
+
|
|
14354
|
+
// src/cli/output.ts
|
|
14355
|
+
function printJson(value) {
|
|
14356
|
+
console.log(JSON.stringify(value, null, 2));
|
|
14357
|
+
}
|
|
14358
|
+
function printListHuman(payload) {
|
|
14359
|
+
console.log(`env file: ${payload.envFile}`);
|
|
14360
|
+
for (const item of payload.items) {
|
|
14361
|
+
const active = item.active ? item.active.official ? "\u5B98\u65B9\u767B\u5F55" : item.active.name : "-";
|
|
14362
|
+
console.log(`${item.id.padEnd(8)} ${item.label.padEnd(14)} ${item.mode.padEnd(9)} active=${active} profiles=${item.profiles.length}`);
|
|
14363
|
+
}
|
|
14364
|
+
}
|
|
14365
|
+
function printProvidersHuman(items) {
|
|
14366
|
+
if (items.length === 0) {
|
|
14367
|
+
console.log("(no providers)");
|
|
14368
|
+
return;
|
|
14369
|
+
}
|
|
14370
|
+
for (const entry of items) {
|
|
14371
|
+
const endpoints = entry.endpoints.map((endpoint) => endpoint.key).join(",") || "-";
|
|
14372
|
+
const configured = entry.apiKeyConfigured ? "key=set" : "key=missing";
|
|
14373
|
+
console.log(`${entry.id.padEnd(24)} ${entry.name.padEnd(20)} ${configured.padEnd(9)} endpoints=${endpoints}`);
|
|
14374
|
+
}
|
|
14375
|
+
}
|
|
14376
|
+
function printDoctorHuman(report) {
|
|
14377
|
+
console.log(`harness-switch doctor updateAvailable=${report.updatedAvailable}`);
|
|
14378
|
+
for (const item of report.items) {
|
|
14379
|
+
console.log("");
|
|
14380
|
+
console.log(`${item.harness}:`);
|
|
14381
|
+
for (const check of item.checks) {
|
|
14382
|
+
printCheck(check);
|
|
14383
|
+
}
|
|
14384
|
+
}
|
|
14385
|
+
}
|
|
14386
|
+
function printCheck(check) {
|
|
14387
|
+
const tag = check.status === "ok" ? "[ok]" : check.status === "warn" ? "[warn]" : check.status === "error" ? "[error]" : "[unknown]";
|
|
14388
|
+
const message = detailMessage(check.detail) ?? check.label;
|
|
14389
|
+
console.log(` ${tag} ${message}`);
|
|
14390
|
+
}
|
|
14391
|
+
function detailMessage(detail) {
|
|
14392
|
+
if (typeof detail === "object" && detail !== null) {
|
|
14393
|
+
const message = detail.message;
|
|
14394
|
+
if (typeof message === "string") {
|
|
14395
|
+
return message;
|
|
14396
|
+
}
|
|
14397
|
+
}
|
|
14398
|
+
return;
|
|
14399
|
+
}
|
|
14400
|
+
function printPlanHuman(harness, profile, targets) {
|
|
14401
|
+
console.log(`plan ${harness}/${profile}:`);
|
|
14402
|
+
for (const target of targets) {
|
|
14403
|
+
const changed = target.content !== target.currentContent;
|
|
14404
|
+
const marker = target.overridden ? " (override)" : changed ? " (\u5C06\u5199\u5165)" : " (\u65E0\u53D8\u66F4)";
|
|
14405
|
+
console.log(`- ${target.path}${marker}`);
|
|
14406
|
+
}
|
|
14407
|
+
console.log("");
|
|
14408
|
+
console.log("\u5185\u5BB9\u5305\u542B API key\uFF0C\u8BF7\u4EC5\u5728\u53EF\u4FE1\u7EC8\u7AEF\u67E5\u770B\u3002");
|
|
14409
|
+
}
|
|
14410
|
+
function printActivateHuman(harness, profile, result) {
|
|
14411
|
+
console.log(`\u5DF2\u6FC0\u6D3B ${harness}/${profile}`);
|
|
14412
|
+
console.log(`env: ${result.envFile}`);
|
|
14413
|
+
for (const warning of result.warnings) {
|
|
14414
|
+
console.log(`warning: ${warning}`);
|
|
14415
|
+
}
|
|
14416
|
+
}
|
|
14417
|
+
function cliUsage() {
|
|
14418
|
+
return [
|
|
14419
|
+
"usage: harness-switch <command> [options]",
|
|
14420
|
+
"",
|
|
14421
|
+
"commands:",
|
|
14422
|
+
" list list harnesses, active profiles and live targets",
|
|
14423
|
+
" providers list Provider Vault entries",
|
|
14424
|
+
" doctor [--probe] [--harness H] run diagnostics (add --probe for /models checks)",
|
|
14425
|
+
" plan <harness> <profile> show the exact content activation would write",
|
|
14426
|
+
" activate <harness> <profile> activate a profile (add --yes to skip the prompt)",
|
|
14427
|
+
" users list manageable local Unix users",
|
|
14428
|
+
" sync --from USER --to USER copy profiles and credentials between users",
|
|
14429
|
+
"",
|
|
14430
|
+
"options:",
|
|
14431
|
+
" --json machine-readable JSON output",
|
|
14432
|
+
" --yes skip confirmation for activate",
|
|
14433
|
+
" --probe run the /models connectivity probe in doctor",
|
|
14434
|
+
" --harness H limit doctor to one harness",
|
|
14435
|
+
" --user USER run list/providers/doctor/plan/activate for this Unix user",
|
|
14436
|
+
" --overwrite overwrite same-name profiles during sync (default: skip)",
|
|
14437
|
+
"",
|
|
14438
|
+
"environment:",
|
|
14439
|
+
" HSW_URL base URL of the local service (default http://127.0.0.1:8787)",
|
|
14440
|
+
" PORT port override when HSW_URL is unset",
|
|
14441
|
+
" HSW_DATA_DIR data directory holding web_password (default ~/.harness-switch)"
|
|
14442
|
+
].join(`
|
|
14443
|
+
`);
|
|
14444
|
+
}
|
|
14445
|
+
|
|
14446
|
+
// src/cli/commands.ts
|
|
14447
|
+
async function runCli(command, positional, flags) {
|
|
14448
|
+
const json = hasFlag(flags, "json") ? "json" : "human";
|
|
14449
|
+
let client;
|
|
14450
|
+
try {
|
|
14451
|
+
client = new CliClient(resolveBaseUrl(), readWebPassword());
|
|
14452
|
+
await client.login();
|
|
14453
|
+
const selectedUser = flagValue(flags, "user");
|
|
14454
|
+
if (selectedUser) {
|
|
14455
|
+
await selectUser(client, selectedUser);
|
|
14456
|
+
}
|
|
14457
|
+
} catch (error2) {
|
|
14458
|
+
return fail(error2, json);
|
|
14459
|
+
}
|
|
14460
|
+
try {
|
|
14461
|
+
switch (command) {
|
|
14462
|
+
case "list":
|
|
14463
|
+
return await cmdList(client, json);
|
|
14464
|
+
case "providers":
|
|
14465
|
+
return await cmdProviders(client, json);
|
|
14466
|
+
case "doctor":
|
|
14467
|
+
return await cmdDoctor(client, flags, json);
|
|
14468
|
+
case "plan":
|
|
14469
|
+
return await cmdPlan(client, positional, json);
|
|
14470
|
+
case "activate":
|
|
14471
|
+
return await cmdActivate(client, positional, flags, json);
|
|
14472
|
+
case "users":
|
|
14473
|
+
return await cmdUsers(client, json);
|
|
14474
|
+
case "sync":
|
|
14475
|
+
return await cmdSync(client, flags, json);
|
|
14476
|
+
default:
|
|
14477
|
+
console.error(cliUsage());
|
|
14478
|
+
throw new CliError(`unknown command: ${command}`);
|
|
14479
|
+
}
|
|
14480
|
+
} catch (error2) {
|
|
14481
|
+
return fail(error2, json);
|
|
14482
|
+
}
|
|
14483
|
+
}
|
|
14484
|
+
async function selectUser(client, username) {
|
|
14485
|
+
await client.post(`/api/users/${encodeURIComponent(username)}/select`);
|
|
14486
|
+
}
|
|
14487
|
+
async function cmdUsers(client, json) {
|
|
14488
|
+
const payload = await client.get("/api/users");
|
|
14489
|
+
if (json === "json") {
|
|
14490
|
+
printJson(payload);
|
|
14491
|
+
} else {
|
|
14492
|
+
for (const user of payload.items) {
|
|
14493
|
+
console.log(`${user.current ? "*" : " "} ${user.username.padEnd(20)} ${user.homeDir}`);
|
|
14494
|
+
}
|
|
14495
|
+
}
|
|
14496
|
+
return 0;
|
|
14497
|
+
}
|
|
14498
|
+
async function cmdSync(client, flags, json) {
|
|
14499
|
+
const source = flagValue(flags, "from");
|
|
14500
|
+
const target = flagValue(flags, "to") || flagValue(flags, "user");
|
|
14501
|
+
if (!source || !target) {
|
|
14502
|
+
throw new CliError("sync \u9700\u8981 --from <\u6765\u6E90\u7528\u6237> \u548C --to <\u76EE\u6807\u7528\u6237>");
|
|
14503
|
+
}
|
|
14504
|
+
await selectUser(client, target);
|
|
14505
|
+
const conflictPolicy = hasFlag(flags, "overwrite") ? "overwrite" : "skip";
|
|
14506
|
+
const payload = await client.post("/api/users/sync", {
|
|
14507
|
+
sourceUser: source,
|
|
14508
|
+
conflictPolicy
|
|
14509
|
+
});
|
|
14510
|
+
if (json === "json") {
|
|
14511
|
+
printJson(payload);
|
|
14512
|
+
} else {
|
|
14513
|
+
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}`);
|
|
14515
|
+
}
|
|
14516
|
+
return 0;
|
|
14517
|
+
}
|
|
14518
|
+
async function cmdList(client, json) {
|
|
14519
|
+
const payload = await client.get("/api/harnesses");
|
|
14520
|
+
if (json === "json") {
|
|
14521
|
+
printJson(payload);
|
|
14522
|
+
} else {
|
|
14523
|
+
printListHuman(payload);
|
|
14524
|
+
}
|
|
14525
|
+
return 0;
|
|
14526
|
+
}
|
|
14527
|
+
async function cmdProviders(client, json) {
|
|
14528
|
+
const payload = await client.get("/api/providers");
|
|
14529
|
+
if (json === "json") {
|
|
14530
|
+
printJson(payload);
|
|
14531
|
+
} else {
|
|
14532
|
+
printProvidersHuman(payload.items);
|
|
14533
|
+
}
|
|
14534
|
+
return 0;
|
|
14535
|
+
}
|
|
14536
|
+
async function cmdDoctor(client, flags, json) {
|
|
14537
|
+
const query = new URLSearchParams;
|
|
14538
|
+
if (hasFlag(flags, "probe")) {
|
|
14539
|
+
query.set("probe", "1");
|
|
14540
|
+
}
|
|
14541
|
+
const harness = flagValue(flags, "harness");
|
|
14542
|
+
if (harness) {
|
|
14543
|
+
query.set("harness", harness);
|
|
14544
|
+
}
|
|
14545
|
+
const suffix = query.size > 0 ? `?${query.toString()}` : "";
|
|
14546
|
+
const payload = await client.get(`/api/doctor${suffix}`);
|
|
14547
|
+
if (json === "json") {
|
|
14548
|
+
printJson(payload);
|
|
14549
|
+
} else {
|
|
14550
|
+
printDoctorHuman(payload);
|
|
14551
|
+
}
|
|
14552
|
+
return 0;
|
|
14553
|
+
}
|
|
14554
|
+
async function cmdPlan(client, positional, json) {
|
|
14555
|
+
const harness = requirePositional(positional, 0, "harness");
|
|
14556
|
+
const profile = requirePositional(positional, 1, "profile");
|
|
14557
|
+
const payload = await client.get(`/api/harnesses/${encodeURIComponent(harness)}/profiles/${encodeURIComponent(profile)}/preview`);
|
|
14558
|
+
if (json === "json") {
|
|
14559
|
+
printJson({ harness, profile, ...payload });
|
|
14560
|
+
} else {
|
|
14561
|
+
printPlanHuman(harness, profile, payload.targets);
|
|
14562
|
+
}
|
|
14563
|
+
return 0;
|
|
14564
|
+
}
|
|
14565
|
+
async function cmdActivate(client, positional, flags, json) {
|
|
14566
|
+
const harness = requirePositional(positional, 0, "harness");
|
|
14567
|
+
const profile = requirePositional(positional, 1, "profile");
|
|
14568
|
+
if (!hasFlag(flags, "yes")) {
|
|
14569
|
+
if (!stdin.isTTY) {
|
|
14570
|
+
throw new CliError("\u975E\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u9700\u8981 --yes \u786E\u8BA4\u624D\u80FD\u6FC0\u6D3B");
|
|
14571
|
+
}
|
|
14572
|
+
const preview = await client.get(`/api/harnesses/${encodeURIComponent(harness)}/profiles/${encodeURIComponent(profile)}/preview`);
|
|
14573
|
+
if (json === "human") {
|
|
14574
|
+
printPlanHuman(harness, profile, preview.targets);
|
|
14575
|
+
}
|
|
14576
|
+
const readline = createInterface({ input: stdin, output: stdout });
|
|
14577
|
+
const answer = (await readline.question(`\u786E\u8BA4\u6FC0\u6D3B ${harness}/${profile}\uFF1F[y/N] `)).trim().toLowerCase();
|
|
14578
|
+
readline.close();
|
|
14579
|
+
if (answer !== "y" && answer !== "yes") {
|
|
14580
|
+
if (json === "json") {
|
|
14581
|
+
printJson({ cancelled: true });
|
|
14582
|
+
} else {
|
|
14583
|
+
console.log("\u5DF2\u53D6\u6D88");
|
|
14584
|
+
}
|
|
14585
|
+
return 0;
|
|
14586
|
+
}
|
|
14587
|
+
}
|
|
14588
|
+
const payload = await client.post(`/api/harnesses/${encodeURIComponent(harness)}/profiles/${encodeURIComponent(profile)}/activate`);
|
|
14589
|
+
if (json === "json") {
|
|
14590
|
+
printJson({ harness, profile, ...payload });
|
|
14591
|
+
} else {
|
|
14592
|
+
printActivateHuman(harness, profile, payload);
|
|
14593
|
+
}
|
|
14594
|
+
return 0;
|
|
14595
|
+
}
|
|
14596
|
+
function fail(error2, json) {
|
|
14597
|
+
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
14598
|
+
if (json === "json") {
|
|
14599
|
+
printJson({ error: { code: 1, message } });
|
|
14600
|
+
} else {
|
|
14601
|
+
console.error(`error: ${message}`);
|
|
14602
|
+
}
|
|
14603
|
+
return 1;
|
|
13025
14604
|
}
|
|
13026
14605
|
|
|
13027
14606
|
// src/main.ts
|
|
@@ -13041,13 +14620,16 @@ async function runServer() {
|
|
|
13041
14620
|
log.info(`data directory: ${environment.dataDir}`);
|
|
13042
14621
|
log.info(`listening on http://${server.hostname}:${server.port}`);
|
|
13043
14622
|
}
|
|
13044
|
-
var command = process.argv
|
|
14623
|
+
var [command, ...rest] = process.argv.slice(2);
|
|
13045
14624
|
if (command === "server") {
|
|
13046
14625
|
await runServer();
|
|
13047
14626
|
} else if (command === "stop") {
|
|
13048
14627
|
await stopDaemon();
|
|
13049
14628
|
} else if (command === "status") {
|
|
13050
14629
|
printStatus();
|
|
14630
|
+
} else if (command === "list" || command === "providers" || command === "doctor" || command === "plan" || command === "activate" || command === "users" || command === "sync") {
|
|
14631
|
+
const { flags, positional } = parseArgs(rest);
|
|
14632
|
+
process.exitCode = await runCli(command, positional, flags);
|
|
13051
14633
|
} else if (command === undefined || command === "daemon") {
|
|
13052
14634
|
await daemonize();
|
|
13053
14635
|
} else {
|