@michengai/dsh-codex-ui 1.1.48 → 2.0.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/lib/index.mjs CHANGED
@@ -1,20 +1,10 @@
1
+ import { t as CODEX_UI_API_ENDPOINTS } from "./business-api-CSNUY-u5.mjs";
1
2
  import { spawn } from "node:child_process";
2
3
  import { existsSync, readFileSync } from "node:fs";
3
- import { lstat, mkdir, open, readFile, readdir, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
4
+ import { readFile, rm, unlink, writeFile } from "node:fs/promises";
4
5
  import { homedir } from "node:os";
5
- import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
6
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
- import { randomBytes, randomUUID } from "node:crypto";
8
- //#region src/business-api.ts
9
- const CODEX_UI_API_BASE = "/api/dsh-codex-ui";
10
- const CODEX_UI_API_ENDPOINTS = Object.freeze({
11
- connectors: `${CODEX_UI_API_BASE}/connectors`,
12
- dependencies: `${CODEX_UI_API_BASE}/dependencies`,
13
- openInExplorer: `${CODEX_UI_API_BASE}/open-in-explorer`,
14
- preferences: `${CODEX_UI_API_BASE}/preferences`,
15
- sessionMove: `${CODEX_UI_API_BASE}/session-move`
16
- });
17
- //#endregion
18
8
  //#region src/npm-downloads.ts
19
9
  /** 关于页使用的 npm 累计下载量;历史不完整时返回 undefined,不把局部统计当总量。 */
20
10
  const cache = /* @__PURE__ */ new Map();
@@ -467,16 +457,6 @@ function newerVersion(installed, latest) {
467
457
  for (let index = 0; index < current.core.length; index += 1) if (candidate.core[index] !== current.core[index]) return candidate.core[index] > current.core[index];
468
458
  return comparePrerelease(candidate.prerelease, current.prerelease) > 0;
469
459
  }
470
- const OFFICIAL_TURN_NAVIGATOR_MIN_VERSION = "0.1.2-alpha.2";
471
- /** 官方轮次导航从 DSH alpha.2 起成为运行时能力;版本判断不依赖其私有 DOM。 */
472
- function supportsOfficialTurnNavigator(version) {
473
- return version === OFFICIAL_TURN_NAVIGATOR_MIN_VERSION || newerVersion(OFFICIAL_TURN_NAVIGATOR_MIN_VERSION, version);
474
- }
475
- /** 只读取本地运行时清单,不访问 npm registry。 */
476
- async function runtimeSupportsOfficialTurnNavigator(runtime = resolveDependencyRuntime()) {
477
- const version = await installedPackageVersion("@deepseek-ai/dsh", runtime);
478
- return version !== void 0 && supportsOfficialTurnNavigator(version);
479
- }
480
460
  /** 返回当前 profile 中固定管理插件的实际安装版本与 npm latest 状态。 */
481
461
  async function dependencyStatuses(runtime = resolveDependencyRuntime()) {
482
462
  const bundleNames = await profileBundleNames(runtime);
@@ -1037,28 +1017,6 @@ async function installDependenciesLocked(ids, requestHotUpdate, runtime) {
1037
1017
  }
1038
1018
  }
1039
1019
  //#endregion
1040
- //#region src/explorer-path-policy.ts
1041
- function normalizedWindowsPath(path) {
1042
- if (!win32.isAbsolute(path)) return void 0;
1043
- const normalized = win32.normalize(path.trim()).replace(/[\\/]+$/, "");
1044
- const root = win32.parse(normalized).root;
1045
- if (root.startsWith("\\\\") || normalized.toLocaleLowerCase("en-US") === root.replace(/[\\/]+$/, "").toLocaleLowerCase("en-US")) return;
1046
- return normalized;
1047
- }
1048
- /**
1049
- * 仅允许打开注册表中已有的工作区根目录。
1050
- * 不接受子目录、盘符根或 UNC,避免同源页面把 Host 端点当成任意路径启动器。
1051
- */
1052
- function authorizedExplorerWorkspacePath(path, workspaceRoots) {
1053
- const target = normalizedWindowsPath(path);
1054
- if (target === void 0) return void 0;
1055
- const targetKey = target.toLocaleLowerCase("en-US");
1056
- for (const root of workspaceRoots) {
1057
- const normalizedRoot = normalizedWindowsPath(root);
1058
- if (normalizedRoot !== void 0 && normalizedRoot.toLocaleLowerCase("en-US") === targetKey) return normalizedRoot;
1059
- }
1060
- }
1061
- //#endregion
1062
1020
  //#region src/host-services.ts
1063
1021
  function requireService(ctx, key, method) {
1064
1022
  const service = ctx.get(key);
@@ -1067,973 +1025,11 @@ function requireService(ctx, key, method) {
1067
1025
  }
1068
1026
  /** 在唯一的宿主边界校验服务能力;宿主 API 变更时立即失败,不会静默返回 503。 */
1069
1027
  function hostServices(ctx) {
1070
- const emit = ctx.emit;
1071
- return {
1072
- webServer: requireService(ctx, "webServer", "register"),
1073
- agents: requireService(ctx, "agents", "get"),
1074
- sessions: requireService(ctx, "sessions", "get"),
1075
- sessionPersistence: requireService(ctx, "sessionPersistence", "list"),
1076
- tools: requireService(ctx, "tools", "schemas"),
1077
- workspaceRegistry: requireService(ctx, "workspaceRegistry", "list"),
1078
- sessionProjectionCache: ctx.get("sessionProjectionCache"),
1079
- emit: (event, ...args) => {
1080
- emit.call(ctx, event, ...args);
1081
- },
1082
- logger: {
1083
- warn: (message) => {
1084
- ctx.logger.warn("%s", message);
1085
- },
1086
- info: (message) => {
1087
- ctx.logger.info("%s", message);
1088
- }
1089
- }
1090
- };
1091
- }
1092
- //#endregion
1093
- //#region src/native-explorer.ts
1094
- const WINDOWS_EXPLORER_TIMEOUT_MS = 8e3;
1095
- const WINDOWS_FOREGROUND_EXPLORER_SCRIPT = String.raw`
1096
- $ErrorActionPreference = 'Stop'
1097
-
1098
- Add-Type -TypeDefinition @'
1099
- using System;
1100
- using System.Runtime.InteropServices;
1101
- public static class DcuWindowFocus {
1102
- [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
1103
- [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
1104
- [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
1105
- [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool attach);
1106
- [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int command);
1107
- [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
1108
- [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
1109
- }
1110
- '@
1111
-
1112
- $shell = New-Object -ComObject Shell.Application
1113
-
1114
- function Find-ExplorerWindow([string]$path) {
1115
- foreach ($item in @($shell.Windows())) {
1116
- try {
1117
- $candidate = [IO.Path]::GetFullPath([string]$item.Document.Folder.Self.Path).TrimEnd('\')
1118
- if ($candidate -ieq $path) { return $item }
1119
- } catch {}
1120
- }
1121
- return $null
1122
- }
1123
-
1124
- function Open-ExplorerInForeground([string]$target) {
1125
- $target = [IO.Path]::GetFullPath($target).TrimEnd('\')
1126
- $window = Find-ExplorerWindow $target
1127
- if ($null -eq $window) {
1128
- $shell.Explore($target)
1129
- for ($attempt = 0; $attempt -lt 120 -and $null -eq $window; $attempt += 1) {
1130
- Start-Sleep -Milliseconds 25
1131
- $window = Find-ExplorerWindow $target
1132
- }
1133
- }
1134
- if ($null -eq $window) { throw 'Explorer window was not found.' }
1135
-
1136
- $handle = [IntPtr]([long]$window.HWND)
1137
- $foreground = [DcuWindowFocus]::GetForegroundWindow()
1138
- $foregroundProcessId = 0
1139
- $foregroundThread = [DcuWindowFocus]::GetWindowThreadProcessId($foreground, [ref]$foregroundProcessId)
1140
- $currentThread = [DcuWindowFocus]::GetCurrentThreadId()
1141
- $attached = $foregroundThread -ne 0 -and [DcuWindowFocus]::AttachThreadInput($currentThread, $foregroundThread, $true)
1142
- try {
1143
- [void][DcuWindowFocus]::ShowWindowAsync($handle, 3)
1144
- [void][DcuWindowFocus]::BringWindowToTop($handle)
1145
- if (-not [DcuWindowFocus]::SetForegroundWindow($handle)) { throw 'Explorer could not be activated.' }
1146
- } finally {
1147
- if ($attached) { [void][DcuWindowFocus]::AttachThreadInput($currentThread, $foregroundThread, $false) }
1148
- }
1149
- }
1150
-
1151
- [Console]::Out.WriteLine('READY')
1152
- [Console]::Out.Flush()
1153
- while (($line = [Console]::In.ReadLine()) -ne $null) {
1154
- if ([string]::IsNullOrWhiteSpace($line)) { continue }
1155
- $parts = $line.Split([char]9, 2)
1156
- $requestId = $parts[0]
1157
- try {
1158
- if ($parts.Count -ne 2) { throw 'Invalid request.' }
1159
- $target = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($parts[1]))
1160
- Open-ExplorerInForeground $target
1161
- [Console]::Out.WriteLine(('OK' + [char]9 + $requestId))
1162
- } catch {
1163
- $message = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$_.Exception.Message))
1164
- [Console]::Out.WriteLine(('ERR' + [char]9 + $requestId + [char]9 + $message))
1165
- }
1166
- [Console]::Out.Flush()
1167
- }
1168
- `;
1169
- /**
1170
- * 常驻的 Windows Explorer 前台激活助手。
1171
- * PowerShell 与窗口 API 只在 Host 启动时初始化一次,点击时仅发送一行路径请求。
1172
- */
1173
- var ForegroundExplorer = class {
1174
- run;
1175
- platform;
1176
- child;
1177
- startupChild;
1178
- starting;
1179
- stdout = "";
1180
- sequence = 0;
1181
- pending = /* @__PURE__ */ new Map();
1182
- disposed = false;
1183
- constructor(run = spawn, platform = process.platform) {
1184
- this.run = run;
1185
- this.platform = platform;
1186
- }
1187
- /** 在用户点击前完成 PowerShell 与窗口 API 初始化。 */
1188
- warmup() {
1189
- if (this.platform !== "win32") return Promise.resolve();
1190
- return this.ensureStarted().then(() => void 0);
1191
- }
1192
- async open(path) {
1193
- if (this.platform !== "win32") throw new Error("foreground Explorer is only available on Windows");
1194
- if (!isAbsolute(path)) throw new Error("Explorer path must be absolute");
1195
- if (this.disposed) throw new Error("Explorer helper has been disposed");
1196
- const child = await this.ensureStarted();
1197
- const requestId = String(++this.sequence);
1198
- const encodedPath = Buffer.from(path, "utf8").toString("base64");
1199
- return await new Promise((resolve, reject) => {
1200
- const timeout = setTimeout(() => {
1201
- this.pending.delete(requestId);
1202
- reject(/* @__PURE__ */ new Error("Explorer activation timed out"));
1203
- }, WINDOWS_EXPLORER_TIMEOUT_MS);
1204
- timeout.unref?.();
1205
- this.pending.set(requestId, {
1206
- resolve,
1207
- reject,
1208
- timeout
1209
- });
1210
- child.stdin.write(`${requestId}\t${encodedPath}\n`, (error) => {
1211
- if (error === null || error === void 0) return;
1212
- const request = this.pending.get(requestId);
1213
- if (request === void 0) return;
1214
- clearTimeout(request.timeout);
1215
- this.pending.delete(requestId);
1216
- request.reject(error);
1217
- });
1218
- });
1219
- }
1220
- dispose() {
1221
- this.disposed = true;
1222
- this.failAll(/* @__PURE__ */ new Error("Explorer helper has been disposed"));
1223
- this.startupChild?.kill();
1224
- this.child?.kill();
1225
- this.startupChild = void 0;
1226
- this.child = void 0;
1227
- this.starting = void 0;
1228
- }
1229
- ensureStarted() {
1230
- if (this.disposed) return Promise.reject(/* @__PURE__ */ new Error("Explorer helper has been disposed"));
1231
- if (this.child !== void 0) return Promise.resolve(this.child);
1232
- if (this.starting !== void 0) return this.starting;
1233
- const encoded = Buffer.from(WINDOWS_FOREGROUND_EXPLORER_SCRIPT, "utf16le").toString("base64");
1234
- this.starting = new Promise((resolve, reject) => {
1235
- const child = this.run("powershell.exe", [
1236
- "-NoLogo",
1237
- "-NoProfile",
1238
- "-NonInteractive",
1239
- "-EncodedCommand",
1240
- encoded
1241
- ], { windowsHide: true });
1242
- this.startupChild = child;
1243
- let settled = false;
1244
- const finishStart = (error) => {
1245
- if (settled) return;
1246
- settled = true;
1247
- clearTimeout(startupTimeout);
1248
- if (error !== void 0) {
1249
- this.starting = void 0;
1250
- if (this.startupChild === child) this.startupChild = void 0;
1251
- child.kill();
1252
- reject(error);
1253
- return;
1254
- }
1255
- if (this.disposed) {
1256
- this.starting = void 0;
1257
- if (this.startupChild === child) this.startupChild = void 0;
1258
- child.kill();
1259
- reject(/* @__PURE__ */ new Error("Explorer helper has been disposed"));
1260
- return;
1261
- }
1262
- if (this.startupChild === child) this.startupChild = void 0;
1263
- this.child = child;
1264
- this.starting = void 0;
1265
- resolve(child);
1266
- };
1267
- const startupTimeout = setTimeout(() => finishStart(/* @__PURE__ */ new Error("Explorer helper startup timed out")), WINDOWS_EXPLORER_TIMEOUT_MS);
1268
- startupTimeout.unref?.();
1269
- child.stdout.on("data", (chunk) => {
1270
- this.stdout += String(chunk);
1271
- let newline = this.stdout.indexOf("\n");
1272
- while (newline >= 0) {
1273
- const line = this.stdout.slice(0, newline).trimEnd();
1274
- this.stdout = this.stdout.slice(newline + 1);
1275
- if (line === "READY") finishStart();
1276
- else this.handleResponse(line);
1277
- newline = this.stdout.indexOf("\n");
1278
- }
1279
- });
1280
- child.once("error", (error) => finishStart(error));
1281
- child.once("exit", () => {
1282
- if (!settled) finishStart(/* @__PURE__ */ new Error("Explorer helper exited during startup"));
1283
- if (this.child === child) this.child = void 0;
1284
- this.failAll(/* @__PURE__ */ new Error("Explorer helper exited"));
1285
- });
1286
- });
1287
- return this.starting;
1288
- }
1289
- handleResponse(line) {
1290
- const [status, requestId, encodedMessage] = line.split(" ");
1291
- const request = requestId === void 0 ? void 0 : this.pending.get(requestId);
1292
- if (request === void 0) return;
1293
- clearTimeout(request.timeout);
1294
- this.pending.delete(requestId);
1295
- if (status === "OK") {
1296
- request.resolve();
1297
- return;
1298
- }
1299
- const message = encodedMessage === void 0 ? "Explorer activation failed" : Buffer.from(encodedMessage, "base64").toString("utf8");
1300
- request.reject(new Error(message));
1301
- }
1302
- failAll(error) {
1303
- for (const request of this.pending.values()) {
1304
- clearTimeout(request.timeout);
1305
- request.reject(error);
1306
- }
1307
- this.pending.clear();
1308
- }
1309
- };
1310
- //#endregion
1311
- //#region src/session-migration.ts
1312
- var SessionMoveError = class extends Error {
1313
- code;
1314
- constructor(code, message, options) {
1315
- super(message, options);
1316
- this.code = code;
1317
- this.name = "SessionMoveError";
1318
- }
1319
- };
1320
- const movingSessions = /* @__PURE__ */ new Set();
1321
- const ZSTD_MAGIC = 4247762216;
1322
- /** 旧宿主 list() 直接给会话头;0.1.6 起返回 { header, revision }。 */
1323
- function persistedSessionHeader(item) {
1324
- if (item === null || typeof item !== "object") return void 0;
1325
- const record = item;
1326
- if (typeof record.id === "string" && record.id.length > 0) return record;
1327
- const nested = record.header;
1328
- if (nested !== null && typeof nested === "object") {
1329
- const header = nested;
1330
- if (typeof header.id === "string" && header.id.length > 0) return header;
1331
- }
1332
- }
1333
- async function listPersistedHeader(persistence, sessionId) {
1334
- for (const item of await persistence.list()) {
1335
- const header = persistedSessionHeader(item);
1336
- if (header?.id === sessionId) return header;
1337
- }
1338
- }
1339
- function isMissingArtifact(error) {
1340
- if (error.code === "ENOENT") return true;
1341
- return error.name === "SessionPersistenceNotFoundError";
1342
- }
1343
- function missingArtifactError(error) {
1344
- return new SessionMoveError("session-move/session-not-found", "读取会话持久化记录失败。", error === void 0 ? void 0 : { cause: error });
1345
- }
1346
- async function loadStoredSession(persistence, sessionId) {
1347
- try {
1348
- if (typeof persistence.loadStored === "function") return persistence.loadStored(sessionId);
1349
- if (typeof persistence.open !== "function") return void 0;
1350
- const handle = await persistence.open(sessionId, "read");
1351
- try {
1352
- const { events } = await handle.read();
1353
- return {
1354
- meta: handle.header,
1355
- events,
1356
- inheritedEventCount: handle.inheritedEventCount
1357
- };
1358
- } finally {
1359
- await handle.close();
1360
- }
1361
- } catch (error) {
1362
- if (isMissingArtifact(error)) throw missingArtifactError(error);
1363
- throw error;
1364
- }
1365
- }
1366
- function locateArtifact(persistence, meta) {
1367
- if (typeof persistence.locate !== "function") return void 0;
1368
- return persistence.locate(meta);
1369
- }
1370
- async function resolveArtifactPath(persistence, sessionId, meta) {
1371
- const located = locateArtifact(persistence, meta);
1372
- if (located?.path !== void 0 && located.path !== "") return located.path;
1373
- if (typeof persistence.resolveCurrentLog === "function") return persistence.resolveCurrentLog(sessionId);
1374
- }
1375
- function firstZstdFrameEnd(buffer) {
1376
- if (buffer.length < 4 || buffer.readUInt32LE(0) !== ZSTD_MAGIC) return void 0;
1377
- let offset = 4;
1378
- if (offset >= buffer.length) return void 0;
1379
- const descriptor = buffer.readUInt8(offset);
1380
- offset += 1;
1381
- if ((descriptor & 24) !== 0) return void 0;
1382
- const contentSizeFlag = descriptor >>> 6;
1383
- const singleSegment = (descriptor & 32) !== 0;
1384
- const checksum = (descriptor & 4) !== 0;
1385
- const dictionaryFlag = descriptor & 3;
1386
- const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
1387
- const contentSizeBytes = contentSizeFlag === 0 ? singleSegment ? 1 : 0 : 1 << contentSizeFlag;
1388
- offset += (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
1389
- for (;;) {
1390
- if (buffer.length - offset < 3) return void 0;
1391
- const blockHeader = buffer.readUIntLE(offset, 3);
1392
- offset += 3;
1393
- const lastBlock = (blockHeader & 1) !== 0;
1394
- const blockType = blockHeader >>> 1 & 3;
1395
- const blockSize = blockHeader >>> 3;
1396
- if (blockType === 3) return void 0;
1397
- const payloadBytes = blockType === 1 ? 1 : blockSize;
1398
- if (buffer.length - offset < payloadBytes) return void 0;
1399
- offset += payloadBytes;
1400
- if (lastBlock) break;
1401
- }
1402
- if (checksum) {
1403
- if (buffer.length - offset < 4) return void 0;
1404
- offset += 4;
1405
- }
1406
- return offset;
1407
- }
1408
- async function zlibZstd(name, data, options) {
1409
- const transform = (await import("node:zlib"))[name];
1410
- if (typeof transform !== "function") throw new SessionMoveError("session-move/zstd-unavailable", "当前 Node.js 运行时不支持 Zstd 会话迁移。");
1411
- return new Promise((resolvePromise, rejectPromise) => {
1412
- const done = (error, output) => {
1413
- if (error === null) resolvePromise(output);
1414
- else rejectPromise(error);
1415
- };
1416
- if (options === void 0) transform(data, done);
1417
- else transform(data, options, done);
1418
- });
1419
- }
1420
- async function zstdChecksumOptions() {
1421
- const { constants } = await import("node:zlib");
1422
- const flag = constants.ZSTD_c_checksumFlag;
1423
- return typeof flag === "number" ? { params: { [flag]: 1 } } : void 0;
1424
- }
1425
- function isSessionGenerationFilename(name) {
1426
- return /^session(?:\.v[1-9]\d*)?\.jsonl(?:\.zstd)?$/.test(name);
1427
- }
1428
- async function decodeArtifactFile(path) {
1429
- let bytes;
1430
- try {
1431
- bytes = await readFile(path);
1432
- } catch (error) {
1433
- if (isMissingArtifact(error)) throw missingArtifactError(error);
1434
- throw error;
1435
- }
1436
- if (!(path.endsWith(".zstd") || bytes.length >= 4 && bytes.readUInt32LE(0) === ZSTD_MAGIC)) {
1437
- const text = bytes.toString("utf8");
1438
- const newlineIndex = text.indexOf("\n");
1439
- return {
1440
- firstLine: newlineIndex < 0 ? text : text.slice(0, newlineIndex),
1441
- body: newlineIndex < 0 ? "" : text.slice(newlineIndex + 1),
1442
- zstd: false
1443
- };
1444
- }
1445
- const frameEnd = firstZstdFrameEnd(bytes);
1446
- if (frameEnd === void 0) throw new SessionMoveError("session-move/artifact-invalid", "会话工件头部无法解析。");
1447
- return {
1448
- firstLine: (await zlibZstd("zstdDecompress", bytes.subarray(0, frameEnd))).toString("utf8").replace(/\n$/, ""),
1449
- body: "",
1450
- zstd: true,
1451
- trailingZstd: bytes.subarray(frameEnd)
1452
- };
1453
- }
1454
- async function readSessionArtifact(persistence, sessionId, meta) {
1455
- try {
1456
- const path = await resolveArtifactPath(persistence, sessionId, meta);
1457
- if (path === void 0) throw new SessionMoveError("session-move/path-invalid", "宿主无法定位会话工件。");
1458
- if (typeof persistence.readRaw === "function") {
1459
- const raw = await persistence.readRaw(sessionId);
1460
- if (raw === void 0) throw missingArtifactError();
1461
- const newlineIndex = raw.content.indexOf("\n");
1462
- return {
1463
- path,
1464
- decoded: {
1465
- firstLine: newlineIndex < 0 ? raw.content : raw.content.slice(0, newlineIndex),
1466
- body: newlineIndex < 0 ? "" : raw.content.slice(newlineIndex + 1),
1467
- zstd: path.endsWith(".zstd")
1468
- }
1469
- };
1470
- }
1471
- return {
1472
- path,
1473
- decoded: await decodeArtifactFile(path)
1474
- };
1475
- } catch (error) {
1476
- if (error instanceof SessionMoveError) throw error;
1477
- if (isMissingArtifact(error)) throw missingArtifactError(error);
1478
- throw error;
1479
- }
1480
- }
1481
- async function encodeRewrittenArtifact(firstLine, decoded, encodeArtifact) {
1482
- if (decoded.zstd && decoded.trailingZstd !== void 0) {
1483
- const headerFrame = await zlibZstd("zstdCompress", Buffer.from(`${firstLine}\n`, "utf8"), await zstdChecksumOptions());
1484
- return Buffer.concat([headerFrame, decoded.trailingZstd]);
1485
- }
1486
- return encodeArtifact(firstLine, decoded.body, decoded.zstd);
1487
- }
1488
- function rawSessionIds(workspace) {
1489
- return Array.isArray(workspace.record?.sessionIds) ? workspace.record.sessionIds : workspace.sessionIds;
1490
- }
1491
- function validIdentifier(value) {
1492
- return value.length > 0 && value.length <= 512 && !/[\u0000-\u001f\u007f]/.test(value);
1493
- }
1494
- async function pathExists(path) {
1495
- try {
1496
- await lstat(path);
1497
- return true;
1498
- } catch (error) {
1499
- if (error.code === "ENOENT") return false;
1500
- throw error;
1501
- }
1502
- }
1503
- async function writeTemporaryFile(finalPath, data) {
1504
- const temporaryPath = `${finalPath}.${randomBytes(6).toString("hex")}.tmp`;
1505
- const handle = await open(temporaryPath, "wx", 384);
1506
- try {
1507
- await handle.writeFile(data);
1508
- await handle.sync();
1509
- } finally {
1510
- await handle.close();
1511
- }
1512
- return temporaryPath;
1513
- }
1514
- async function encodeSessionArtifact(headerLine, body, zstd) {
1515
- if (!zstd) return Buffer.from(`${headerLine}\n${body}`, "utf8");
1516
- const options = await zstdChecksumOptions();
1517
- const headerFrame = await zlibZstd("zstdCompress", Buffer.from(`${headerLine}\n`, "utf8"), options);
1518
- if (body === "") return headerFrame;
1519
- const bodyFrame = await zlibZstd("zstdCompress", Buffer.from(body, "utf8"), options);
1520
- return Buffer.concat([headerFrame, bodyFrame]);
1521
- }
1522
- var ArtifactDirectoryMove = class {
1523
- oldArtifact;
1524
- newArtifact;
1525
- directoryMoved = false;
1526
- backupCreated = false;
1527
- published = false;
1528
- temporaryPath;
1529
- extraBackups = [];
1530
- oldDirectory;
1531
- newDirectory;
1532
- movedOldArtifact;
1533
- backupArtifact;
1534
- constructor(oldArtifact, newArtifact) {
1535
- this.oldArtifact = oldArtifact;
1536
- this.newArtifact = newArtifact;
1537
- this.oldDirectory = dirname(oldArtifact);
1538
- this.newDirectory = dirname(newArtifact);
1539
- const relativeArtifact = relative(this.oldDirectory, oldArtifact);
1540
- if (relativeArtifact.startsWith("..") || resolve(this.oldDirectory, relativeArtifact) !== resolve(oldArtifact)) throw new SessionMoveError("session-move/path-invalid", "会话工件路径无效。");
1541
- this.movedOldArtifact = join(this.newDirectory, relativeArtifact);
1542
- this.backupArtifact = join(this.newDirectory, `${basename(oldArtifact)}.${randomBytes(6).toString("hex")}.dcu-backup`);
1543
- }
1544
- async publish(bytes, siblings) {
1545
- if (resolve(this.oldDirectory).toLowerCase() === resolve(this.newDirectory).toLowerCase()) throw new SessionMoveError("session-move/path-conflict", "源项目和目标项目使用了相同的会话目录。");
1546
- if (await pathExists(this.newDirectory)) throw new SessionMoveError("session-move/destination-occupied", "目标项目已经存在同名会话工件。");
1547
- try {
1548
- await mkdir(dirname(this.newDirectory), { recursive: true });
1549
- await rename(this.oldDirectory, this.newDirectory);
1550
- this.directoryMoved = true;
1551
- await rename(this.movedOldArtifact, this.backupArtifact);
1552
- this.backupCreated = true;
1553
- this.temporaryPath = await writeTemporaryFile(this.newArtifact, bytes);
1554
- await rename(this.temporaryPath, this.newArtifact);
1555
- this.temporaryPath = void 0;
1556
- this.published = true;
1557
- if (siblings !== void 0) await this.rewriteSiblingGenerations(siblings);
1558
- } catch (error) {
1559
- try {
1560
- await this.rollback();
1561
- } catch (rollbackError) {
1562
- throw new SessionMoveError("session-move/rollback-failed", "迁移会话工件失败,且自动回滚未完整完成。", { cause: rollbackError });
1563
- }
1564
- if (error instanceof SessionMoveError) throw error;
1565
- throw new SessionMoveError("session-move/artifact-failed", "迁移会话工件失败,原会话已恢复。", { cause: error });
1566
- }
1567
- }
1568
- async rewriteSiblingGenerations(siblings) {
1569
- for (const name of await readdir(this.newDirectory)) {
1570
- if (!isSessionGenerationFilename(name)) continue;
1571
- const path = join(this.newDirectory, name);
1572
- if (resolve(path) === resolve(this.newArtifact) || resolve(path) === resolve(this.backupArtifact)) continue;
1573
- let decoded;
1574
- try {
1575
- decoded = await decodeArtifactFile(path);
1576
- } catch {
1577
- continue;
1578
- }
1579
- let header;
1580
- try {
1581
- header = JSON.parse(decoded.firstLine);
1582
- } catch {
1583
- continue;
1584
- }
1585
- if (header.id !== siblings.sessionId) continue;
1586
- const backup = join(this.newDirectory, `${name}.${randomBytes(6).toString("hex")}.dcu-backup`);
1587
- await rename(path, backup);
1588
- this.extraBackups.push({
1589
- path,
1590
- backup
1591
- });
1592
- const rewritten = await encodeRewrittenArtifact(JSON.stringify({
1593
- ...header,
1594
- cwd: siblings.targetCwd
1595
- }), decoded, siblings.encodeArtifact);
1596
- this.temporaryPath = await writeTemporaryFile(path, rewritten);
1597
- await rename(this.temporaryPath, path);
1598
- this.temporaryPath = void 0;
1599
- }
1600
- }
1601
- async rollback() {
1602
- const failures = [];
1603
- if (this.temporaryPath !== void 0) {
1604
- try {
1605
- await rm(this.temporaryPath, { force: true });
1606
- } catch (error) {
1607
- failures.push(error);
1608
- }
1609
- this.temporaryPath = void 0;
1610
- }
1611
- for (const extra of this.extraBackups.splice(0).reverse()) {
1612
- try {
1613
- await rm(extra.path, { force: true });
1614
- } catch (error) {
1615
- failures.push(error);
1616
- }
1617
- try {
1618
- await rename(extra.backup, extra.path);
1619
- } catch (error) {
1620
- failures.push(error);
1621
- }
1622
- }
1623
- if (this.published) try {
1624
- await rm(this.newArtifact, { force: true });
1625
- this.published = false;
1626
- } catch (error) {
1627
- failures.push(error);
1628
- }
1629
- if (this.backupCreated) try {
1630
- await rename(this.backupArtifact, this.movedOldArtifact);
1631
- this.backupCreated = false;
1632
- } catch (error) {
1633
- failures.push(error);
1634
- }
1635
- if (this.directoryMoved) try {
1636
- await mkdir(dirname(this.oldDirectory), { recursive: true });
1637
- await rename(this.newDirectory, this.oldDirectory);
1638
- this.directoryMoved = false;
1639
- } catch (error) {
1640
- failures.push(error);
1641
- }
1642
- if (failures.length > 0) throw new AggregateError(failures, "会话工件回滚失败");
1643
- }
1644
- async commit(logger) {
1645
- const leftovers = [...this.backupCreated ? [this.backupArtifact] : [], ...this.extraBackups.splice(0).map((extra) => extra.backup)];
1646
- this.backupCreated = false;
1647
- for (const backup of leftovers) try {
1648
- await rm(backup, { force: true });
1649
- } catch (error) {
1650
- logger?.warn(`会话迁移成功,但旧工件备份清理失败:${String(error)}`);
1651
- }
1652
- }
1653
- };
1654
- function workspaceSnapshots(workspaces, sessionId) {
1655
- return workspaces.map((workspace) => {
1656
- const ids = [...rawSessionIds(workspace)];
1657
- const index = ids.indexOf(sessionId);
1658
- return {
1659
- workspace,
1660
- contained: index >= 0,
1661
- beforeId: index >= 0 ? ids[index + 1] : void 0
1662
- };
1663
- });
1664
- }
1665
- async function restoreWorkspaceSnapshots(snapshots, sessionId) {
1666
- for (const snapshot of snapshots) if (!snapshot.contained && rawSessionIds(snapshot.workspace).includes(sessionId)) await snapshot.workspace.detachSession(sessionId);
1667
- for (const snapshot of snapshots) {
1668
- if (!snapshot.contained) continue;
1669
- if (!rawSessionIds(snapshot.workspace).includes(sessionId)) await snapshot.workspace.attachSession(sessionId);
1670
- const currentIds = rawSessionIds(snapshot.workspace);
1671
- const beforeId = snapshot.beforeId !== void 0 && currentIds.includes(snapshot.beforeId) ? snapshot.beforeId : void 0;
1672
- await snapshot.workspace.insertSessionBefore(sessionId, beforeId);
1673
- }
1674
- }
1675
- async function enterStoredSession(services, sessionId, stored) {
1676
- const preparation = services.sessionPersistence.prepare === void 0 ? void 0 : await services.sessionPersistence.prepare(sessionId);
1677
- const session = preparation?.session ?? services.sessions.prepare(sessionId, {
1678
- seedSource: "persistence",
1679
- seed: stored.events,
1680
- meta: stored.meta,
1681
- inheritedEventCount: stored.inheritedEventCount
1682
- });
1683
- const detach = services.sessions.enter(session);
1684
- try {
1685
- services.sessions.announce?.(session);
1686
- } catch (error) {
1687
- detach();
1688
- preparation?.[Symbol.dispose]();
1689
- throw error;
1690
- }
1691
- return {
1692
- detach,
1693
- releasePreparation: () => {
1694
- preparation?.[Symbol.dispose]();
1695
- }
1696
- };
1697
- }
1698
- function detachOriginalEntry(store, sessionId, entry) {
1699
- if (store === void 0 || entry === void 0 || store.get(sessionId) !== entry) return;
1700
- if (entry.detach === void 0) throw new SessionMoveError("session-move/service-unavailable", "宿主无法安全释放原会话入口。");
1701
- entry.detach();
1702
- if (store.get(sessionId) === entry) throw new SessionMoveError("session-move/quiesce-failed", "原会话入口未能完整释放。");
1703
- }
1704
- async function rollbackMove(services, sessionId, transaction, snapshots, originalStored, originalEntry, enteredPlaceholder) {
1705
- const failures = [];
1706
- try {
1707
- enteredPlaceholder?.detach();
1708
- } catch (error) {
1709
- failures.push(error);
1710
- }
1711
- try {
1712
- enteredPlaceholder?.releasePreparation();
1713
- } catch (error) {
1714
- failures.push(error);
1715
- }
1716
- try {
1717
- await transaction.rollback();
1718
- } catch (error) {
1719
- failures.push(error);
1720
- }
1721
- let restored;
1722
- try {
1723
- if (services.sessions.get(sessionId) === void 0) restored = await enterStoredSession(services, sessionId, originalStored);
1724
- await restoreWorkspaceSnapshots(snapshots, sessionId);
1725
- } catch (error) {
1726
- failures.push(error);
1727
- } finally {
1728
- try {
1729
- if (originalEntry === void 0) restored?.detach();
1730
- restored?.releasePreparation();
1731
- } catch (error) {
1732
- failures.push(error);
1733
- }
1734
- }
1735
- if (failures.length > 0) throw new AggregateError(failures, "会话迁移回滚失败");
1736
- }
1737
- async function moveAccounting(target, snapshots, sessionId) {
1738
- for (const snapshot of snapshots) if (snapshot.workspace.id !== target.id && snapshot.contained) await snapshot.workspace.detachSession(sessionId);
1739
- await target.attachSession(sessionId);
1740
- }
1741
- /**
1742
- * 把持久化会话完整迁移到目标项目。整个会话目录一起移动,当前代际和同目录旧代际的 cwd 一并改写;任何提交前失败都会恢复原工件和项目顺序。
1743
- */
1744
- async function moveSessionToWorkspace(services, sessionId, targetWorkspaceId, options = {}) {
1745
- if (!validIdentifier(sessionId) || !validIdentifier(targetWorkspaceId)) throw new SessionMoveError("session-move/invalid-request", "会话或目标项目标识无效。");
1746
- if (movingSessions.has(sessionId)) throw new SessionMoveError("session-move/busy", "该会话正在移动,请稍后重试。");
1747
- movingSessions.add(sessionId);
1748
- try {
1749
- const workspaces = services.workspaceRegistry.list();
1750
- const target = workspaces.find((workspace) => workspace.id === targetWorkspaceId);
1751
- if (target === void 0) throw new SessionMoveError("session-move/workspace-not-found", "目标项目不存在。");
1752
- const snapshots = workspaceSnapshots(workspaces, sessionId);
1753
- const targetSnapshot = snapshots.find((snapshot) => snapshot.workspace.id === target.id);
1754
- const sources = snapshots.filter((snapshot) => snapshot.contained && snapshot.workspace.id !== target.id);
1755
- if (sources.length > 1 || targetSnapshot?.contained === true && sources.length > 0) throw new SessionMoveError("session-move/accounting-invalid", "会话当前的项目归属不一致,无法安全移动。");
1756
- const persistedHeader = await listPersistedHeader(services.sessionPersistence, sessionId);
1757
- if (persistedHeader === void 0) throw new SessionMoveError("session-move/session-not-found", "该会话没有可迁移的持久化记录。");
1758
- if (persistedHeader.origin === "subagent") throw new SessionMoveError("session-move/subagent-unsupported", "子代理会话不能移动到其他项目。");
1759
- const targetPath = await realpath(target.path);
1760
- let currentPath;
1761
- if (persistedHeader.cwd !== void 0) try {
1762
- currentPath = await realpath(persistedHeader.cwd);
1763
- } catch {
1764
- currentPath = void 0;
1765
- }
1766
- if (currentPath === targetPath && targetSnapshot?.contained === true && sources.length === 0) return {
1767
- sessionId,
1768
- moved: false,
1769
- fromWorkspaceIds: [target.id],
1770
- toWorkspaceId: target.id,
1771
- toWorkspaceTitle: target.title || target.id
1772
- };
1773
- const liveSession = services.sessions.get(sessionId);
1774
- const originalEntry = services.sessions.store?.get(sessionId);
1775
- if (liveSession !== void 0 && (services.sessions.store === void 0 || originalEntry === void 0)) throw new SessionMoveError("session-move/service-unavailable", "宿主无法提供可恢复的会话入口,暂时不能移动活跃会话。");
1776
- if (currentPath === targetPath) {
1777
- const stored = liveSession === void 0 ? await loadStoredSession(services.sessionPersistence, sessionId) : void 0;
1778
- if (liveSession === void 0 && stored === void 0) throw new SessionMoveError("session-move/session-not-found", "读取会话持久化记录失败。");
1779
- let enteredPlaceholder;
1780
- try {
1781
- if (stored !== void 0) enteredPlaceholder = await enterStoredSession(services, sessionId, stored);
1782
- await moveAccounting(target, snapshots, sessionId);
1783
- } catch (error) {
1784
- try {
1785
- await restoreWorkspaceSnapshots(snapshots, sessionId);
1786
- } catch (rollbackError) {
1787
- throw new SessionMoveError("session-move/rollback-failed", "恢复项目归属失败。", { cause: rollbackError });
1788
- }
1789
- throw new SessionMoveError("session-move/accounting-failed", "更新项目归属失败,原会话已恢复。", { cause: error });
1790
- } finally {
1791
- enteredPlaceholder?.detach();
1792
- enteredPlaceholder?.releasePreparation();
1793
- }
1794
- return {
1795
- sessionId,
1796
- moved: true,
1797
- fromWorkspaceIds: sources.map((snapshot) => snapshot.workspace.id),
1798
- toWorkspaceId: target.id,
1799
- toWorkspaceTitle: target.title || target.id
1800
- };
1801
- }
1802
- const agent = services.agents.get(sessionId);
1803
- try {
1804
- if (agent !== void 0) {
1805
- agent.cancel({ kind: "disposed" });
1806
- await agent.whenIdle?.();
1807
- }
1808
- if (liveSession !== void 0) await services.sessions.flush(liveSession);
1809
- } catch (error) {
1810
- throw new SessionMoveError("session-move/quiesce-failed", "会话仍在运行,暂时无法移动。", { cause: error });
1811
- }
1812
- const originalStored = await loadStoredSession(services.sessionPersistence, sessionId);
1813
- if (originalStored === void 0) throw new SessionMoveError("session-move/session-not-found", "读取会话持久化记录失败。");
1814
- const artifact = await readSessionArtifact(services.sessionPersistence, sessionId, persistedHeader);
1815
- let header;
1816
- try {
1817
- header = JSON.parse(artifact.decoded.firstLine);
1818
- } catch (error) {
1819
- throw new SessionMoveError("session-move/artifact-invalid", "会话工件头部无法解析。", { cause: error });
1820
- }
1821
- if (header.id !== sessionId) throw new SessionMoveError("session-move/artifact-invalid", "会话工件标识与请求不一致。");
1822
- const targetHeader = {
1823
- ...header,
1824
- cwd: targetPath
1825
- };
1826
- const targetMeta = {
1827
- ...originalStored.meta,
1828
- cwd: targetPath
1829
- };
1830
- const newPath = locateArtifact(services.sessionPersistence, targetMeta)?.path;
1831
- if (newPath === void 0) throw new SessionMoveError("session-move/path-invalid", "宿主无法定位会话工件。");
1832
- const encoder = options.encodeArtifact ?? encodeSessionArtifact;
1833
- const bytes = await encodeRewrittenArtifact(JSON.stringify(targetHeader), artifact.decoded, encoder);
1834
- const transaction = new ArtifactDirectoryMove(artifact.path, newPath);
1835
- try {
1836
- await agent?.scope?.dispose?.();
1837
- services.agents.store?.delete(sessionId);
1838
- detachOriginalEntry(services.sessions.store, sessionId, originalEntry);
1839
- } catch (error) {
1840
- if (originalEntry !== void 0 && services.sessions.get(sessionId) === void 0) try {
1841
- (await enterStoredSession(services, sessionId, originalStored)).releasePreparation();
1842
- } catch (restoreError) {
1843
- throw new SessionMoveError("session-move/rollback-failed", "恢复原会话入口失败。", { cause: restoreError });
1844
- }
1845
- throw new SessionMoveError("session-move/quiesce-failed", "会话仍在运行,暂时无法移动。", { cause: error });
1846
- }
1847
- let enteredPlaceholder;
1848
- try {
1849
- await transaction.publish(bytes, {
1850
- sessionId,
1851
- targetCwd: targetPath,
1852
- encodeArtifact: encoder
1853
- });
1854
- let movedStored;
1855
- try {
1856
- movedStored = await loadStoredSession(services.sessionPersistence, sessionId);
1857
- } catch (error) {
1858
- throw new SessionMoveError("session-move/validation-failed", "迁移后的会话工件校验失败。", { cause: error });
1859
- }
1860
- if (movedStored === void 0 || movedStored.meta.cwd !== targetPath) throw new SessionMoveError("session-move/validation-failed", "迁移后的会话工件校验失败。");
1861
- enteredPlaceholder = await enterStoredSession(services, sessionId, movedStored);
1862
- try {
1863
- await moveAccounting(target, snapshots, sessionId);
1864
- } catch (error) {
1865
- throw new SessionMoveError("session-move/accounting-failed", "更新项目归属失败。", { cause: error });
1866
- }
1867
- enteredPlaceholder.detach();
1868
- enteredPlaceholder.releasePreparation();
1869
- enteredPlaceholder = void 0;
1870
- await transaction.commit(services.logger);
1871
- } catch (error) {
1872
- try {
1873
- await rollbackMove(services, sessionId, transaction, snapshots, originalStored, originalEntry, enteredPlaceholder);
1874
- } catch (rollbackError) {
1875
- throw new SessionMoveError("session-move/rollback-failed", "会话移动失败,且自动回滚未完整完成。", { cause: rollbackError });
1876
- }
1877
- if (error instanceof SessionMoveError) throw error;
1878
- throw new SessionMoveError("session-move/failed", "会话移动失败,原会话已恢复。", { cause: error });
1879
- }
1880
- try {
1881
- await services.sessionProjectionCache?.coldSnapshot?.(sessionId);
1882
- } catch (error) {
1883
- services.logger?.warn(`会话已移动,但投影缓存刷新失败:${String(error)}`);
1884
- }
1885
- services.logger?.info?.(`会话 ${sessionId} 已移动到项目 ${target.id}`);
1886
- return {
1887
- sessionId,
1888
- moved: true,
1889
- fromWorkspaceIds: sources.map((snapshot) => snapshot.workspace.id),
1890
- toWorkspaceId: target.id,
1891
- toWorkspaceTitle: target.title || target.id
1892
- };
1893
- } finally {
1894
- movingSessions.delete(sessionId);
1895
- }
1896
- }
1897
- //#endregion
1898
- //#region src/onboarding-settings.ts
1899
- /**
1900
- * 停用官方设置壳后,仍登记引导设置。
1901
- * 不能 import `@deepseek-ai/dsh-client-ui-settings-general`:裸模块名会向上解析到
1902
- * `~/.dsh/profiles/node_modules` 里的 0.1.2 残留,其 `settings.register` 在新宿主上不存在,
1903
- * 会让整个渲染进程启动失败。
1904
- */
1905
- function registerOnboardingSettings(ctx) {
1906
- ctx.inject(["settings"], (settingsCtx) => {
1907
- const bound = settingsCtx;
1908
- const settings = bound.settings;
1909
- try {
1910
- if (typeof settings?.configure === "function") return bound.effect(() => {
1911
- const dispose = settings.configure({ auto: false }, ctx.fiber);
1912
- return typeof dispose === "function" ? dispose : () => {};
1913
- });
1914
- ctx.logger.warn("[michengai-codex-ui] 当前宿主缺少 settings.configure 接口,跳过引导设置注册。");
1915
- } catch (error) {
1916
- ctx.logger.warn("[michengai-codex-ui] 引导设置注册已跳过:%s", error);
1917
- }
1918
- });
1919
- }
1920
- /** 校验结构和归属;存储兼容模式保留旧 locale 下合法的大小写变体名称。 */
1921
- function parseGroups(value, preserveCaseVariants) {
1922
- if (!Array.isArray(value) || value.length > 100) return void 0;
1923
- const groupIds = /* @__PURE__ */ new Set();
1924
- const groupTitles = /* @__PURE__ */ new Set();
1925
- const workspaceIds = /* @__PURE__ */ new Set();
1926
- const groups = [];
1927
- for (const valueGroup of value) {
1928
- if (valueGroup === null || typeof valueGroup !== "object") return void 0;
1929
- const group = valueGroup;
1930
- const id = typeof group.id === "string" ? group.id.trim() : "";
1931
- const title = typeof group.title === "string" ? group.title.trim() : "";
1932
- if (id === "" || id.length > 128 || title === "" || title.length > 80) return void 0;
1933
- const titleKey = preserveCaseVariants ? title : title.toLowerCase();
1934
- if (groupIds.has(id) || groupTitles.has(titleKey)) return void 0;
1935
- if (!Array.isArray(group.workspaceIds) || group.workspaceIds.length > 1e3) return void 0;
1936
- const normalizedIds = [...new Set(group.workspaceIds)];
1937
- if (!normalizedIds.every((workspaceId) => typeof workspaceId === "string" && workspaceId.trim() !== "" && workspaceId.length <= 256)) return void 0;
1938
- if (normalizedIds.some((workspaceId) => workspaceIds.has(workspaceId))) return void 0;
1939
- groupIds.add(id);
1940
- groupTitles.add(titleKey);
1941
- normalizedIds.forEach((workspaceId) => workspaceIds.add(workspaceId));
1942
- groups.push({
1943
- id,
1944
- title,
1945
- workspaceIds: normalizedIds
1946
- });
1947
- }
1948
- return groups;
1949
- }
1950
- /** 旧数据可往返保存且不改名;新名称的大小写判重由创建、重命名操作执行。 */
1951
- function parseStoredWorkspaceGroups(value) {
1952
- return parseGroups(value, true);
1953
- }
1954
- //#endregion
1955
- //#region src/workspace-preferences.ts
1956
- const WORKSPACE_PREFERENCES_FILE = ".dsh-codex-ui-preferences.json";
1957
- /** Desktop 和普通 DSH Web 共用 Profile;服务换端口或重启后目录仍保持稳定。 */
1958
- function workspacePreferencesPath(profileDir = process.env.DSH_PROFILE_DIR ?? resolve(homedir(), ".dsh", "profiles", "web")) {
1959
- return resolve(profileDir, WORKSPACE_PREFERENCES_FILE);
1960
- }
1961
- /** 严格校验来自 HTTP 或磁盘的数据,避免损坏配置被静默写回。 */
1962
- function parsePinnedWorkspaceIds(value) {
1963
- if (!Array.isArray(value) || value.length > 1e3) return void 0;
1964
- if (!value.every((id) => typeof id === "string" && id.trim() !== "" && id.length <= 256)) return void 0;
1965
- return [...new Set(value)];
1966
- }
1967
- function parseWorkspacePreferences(value) {
1968
- if (value === null || typeof value !== "object") return void 0;
1969
- const record = value;
1970
- const pinnedWorkspaceIds = parsePinnedWorkspaceIds(record.pinnedWorkspaceIds);
1971
- if (pinnedWorkspaceIds === void 0) return void 0;
1972
- if (record.version === 1) return {
1973
- version: 2,
1974
- pinnedWorkspaceIds,
1975
- workspaceGroups: []
1976
- };
1977
- if (record.version !== 2) return void 0;
1978
- const workspaceGroups = parseStoredWorkspaceGroups(record.workspaceGroups);
1979
- return workspaceGroups === void 0 ? void 0 : {
1980
- version: 2,
1981
- pinnedWorkspaceIds,
1982
- workspaceGroups
1983
- };
1984
- }
1985
- async function readWorkspacePreferences(path = workspacePreferencesPath()) {
1986
- try {
1987
- const preferences = parseWorkspacePreferences(JSON.parse(await readFile(path, "utf8")));
1988
- if (preferences === void 0) throw new Error("置顶偏好文件格式无效。");
1989
- return {
1990
- ...preferences,
1991
- exists: true
1992
- };
1993
- } catch (error) {
1994
- if (error.code === "ENOENT") return {
1995
- version: 2,
1996
- pinnedWorkspaceIds: [],
1997
- workspaceGroups: [],
1998
- exists: false
1999
- };
2000
- throw error;
2001
- }
2002
- }
2003
- function temporaryPath(path) {
2004
- return join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
2005
- }
2006
- let writeQueue = Promise.resolve();
2007
- /** 串行、原子保存,避免快速拖动排序产生乱序或半截 JSON。 */
2008
- function writeWorkspacePreferences(pinnedWorkspaceIds, workspaceGroups = [], path = workspacePreferencesPath()) {
2009
- const normalized = parsePinnedWorkspaceIds([...pinnedWorkspaceIds]);
2010
- const normalizedGroups = parseStoredWorkspaceGroups([...workspaceGroups]);
2011
- if (normalized === void 0 || normalizedGroups === void 0) return Promise.reject(/* @__PURE__ */ new Error("工作区偏好数据无效。"));
2012
- const task = writeQueue.catch(() => void 0).then(async () => {
2013
- await mkdir(dirname(path), { recursive: true });
2014
- const temporary = temporaryPath(path);
2015
- try {
2016
- await writeFile(temporary, `${JSON.stringify({
2017
- version: 2,
2018
- pinnedWorkspaceIds: normalized,
2019
- workspaceGroups: normalizedGroups
2020
- }, void 0, 2)}\n`, "utf8");
2021
- await rename(temporary, path);
2022
- } finally {
2023
- await rm(temporary, { force: true }).catch(() => void 0);
2024
- }
2025
- });
2026
- writeQueue = task;
2027
- return task;
1028
+ return { webServer: requireService(ctx, "webServer", "register") };
2028
1029
  }
2029
1030
  //#endregion
2030
1031
  //#region src/index.ts
2031
- const connectorsEndpoint = CODEX_UI_API_ENDPOINTS.connectors;
2032
1032
  const dependenciesEndpoint = CODEX_UI_API_ENDPOINTS.dependencies;
2033
- const explorerEndpoint = CODEX_UI_API_ENDPOINTS.openInExplorer;
2034
- const preferencesEndpoint = CODEX_UI_API_ENDPOINTS.preferences;
2035
- const sessionMoveEndpoint = CODEX_UI_API_ENDPOINTS.sessionMove;
2036
- const maxPreferencesBodyBytes = 32768;
2037
1033
  function headerValue(headers, name) {
2038
1034
  const value = headers[name];
2039
1035
  if (typeof value === "string") return value;
@@ -2047,7 +1043,7 @@ function publicDependencyError(error) {
2047
1043
  }
2048
1044
  var RequestBodyTooLargeError = class extends Error {};
2049
1045
  /** 有界读取 Node HTTP body;偏好接口只接受很小的 JSON。 */
2050
- async function readRequestBody(request, maxBytes = maxPreferencesBodyBytes) {
1046
+ async function readRequestBody(request, maxBytes = 32768) {
2051
1047
  const declared = Number(headerValue(request.headers ?? {}, "content-length"));
2052
1048
  if (Number.isFinite(declared) && declared > maxBytes) throw new RequestBodyTooLargeError("请求体过大。");
2053
1049
  if (request[Symbol.asyncIterator] === void 0) return "";
@@ -2090,98 +1086,11 @@ function authenticateBusinessRequest(ctx, request, response, errorBody = (_statu
2090
1086
  return reject(503, "宿主认证服务暂不可用。");
2091
1087
  }
2092
1088
  }
2093
- const inject = [
2094
- "webServer",
2095
- "agents",
2096
- "tools",
2097
- "workspaceRegistry",
2098
- "sessions",
2099
- "sessionPersistence"
2100
- ];
2101
- function sessionMoveStatus(error) {
2102
- if (!(error instanceof SessionMoveError)) return 500;
2103
- if (error.code === "session-move/invalid-request") return 400;
2104
- if (error.code === "session-move/session-not-found" || error.code === "session-move/workspace-not-found") return 404;
2105
- if (error.code === "session-move/service-unavailable") return 503;
2106
- if (error.code === "session-move/zstd-unavailable") return 501;
2107
- if (error.code === "session-move/busy" || error.code === "session-move/subagent-unsupported" || error.code === "session-move/accounting-invalid" || error.code === "session-move/destination-occupied") return 409;
2108
- return 500;
2109
- }
2110
- function publicSessionMoveError(error) {
2111
- const code = error instanceof SessionMoveError ? error.code : "session-move/failed";
2112
- return {
2113
- code,
2114
- error: {
2115
- "session-move/invalid-request": "会话或目标项目标识无效。",
2116
- "session-move/session-not-found": "该会话没有可迁移的持久化记录。",
2117
- "session-move/workspace-not-found": "目标项目不存在。",
2118
- "session-move/service-unavailable": "宿主暂时无法安全移动活跃会话。",
2119
- "session-move/subagent-unsupported": "子代理会话不能移动到其他项目。",
2120
- "session-move/busy": "该会话正在移动,请稍后重试。",
2121
- "session-move/accounting-invalid": "会话当前的项目归属不一致,无法安全移动。",
2122
- "session-move/destination-occupied": "目标项目已经存在同名会话工件。",
2123
- "session-move/zstd-unavailable": "当前运行环境不支持该会话的存储格式。",
2124
- "session-move/rollback-failed": "移动失败,自动恢复未完整完成,请查看服务端日志。"
2125
- }[code] ?? "暂时无法移动该会话,请稍后重试。"
2126
- };
2127
- }
2128
- function sessionMoveAuthenticationError(status, error) {
2129
- return {
2130
- ok: false,
2131
- code: status === 401 ? "session-move/unauthorized" : status === 403 ? "session-move/forbidden" : "session-move/service-unavailable",
2132
- error
2133
- };
2134
- }
1089
+ const inject = ["webServer"];
2135
1090
  /** 提供不泄露地址、命令和凭证的连接器目录。 */
2136
1091
  function apply(ctx) {
2137
- registerOnboardingSettings(ctx);
2138
1092
  const host = hostServices(ctx);
2139
1093
  ctx.effect(() => {
2140
- const foregroundExplorer = new ForegroundExplorer();
2141
- foregroundExplorer.warmup().catch((error) => ctx.logger.warn("foreground explorer warmup failed: %s", error));
2142
- const disposeConnectors = host.webServer.register({
2143
- kind: "exact",
2144
- path: connectorsEndpoint,
2145
- handler: async (request, response) => {
2146
- if (!authenticateBusinessRequest(ctx, request, response)) return;
2147
- if (request.method !== "GET" && request.method !== "HEAD") {
2148
- response.writeHead(405);
2149
- response.end();
2150
- return;
2151
- }
2152
- try {
2153
- const sessionId = new URL(request.url ?? "/", "http://localhost").searchParams.get("sessionId");
2154
- const scope = sessionId === null ? void 0 : host.agents.get(sessionId);
2155
- const connectors = /* @__PURE__ */ new Map();
2156
- for (const tool of host.tools.schemas(scope)) {
2157
- const match = /^mcp__([A-Za-z0-9_-]+?)__(.+)$/.exec(tool.name);
2158
- if (match === null) continue;
2159
- const [, serverName, toolName] = match;
2160
- const tools = connectors.get(serverName) ?? [];
2161
- tools.push({
2162
- name: toolName,
2163
- description: tool.description ?? ""
2164
- });
2165
- connectors.set(serverName, tools);
2166
- }
2167
- const payload = [...connectors].sort(([a], [b]) => a.localeCompare(b)).map(([name, tools]) => ({
2168
- name,
2169
- tools
2170
- }));
2171
- response.writeHead(200, {
2172
- "content-type": "application/json; charset=utf-8",
2173
- "cache-control": "no-store"
2174
- });
2175
- response.end(request.method === "HEAD" ? void 0 : JSON.stringify({ connectors: payload }));
2176
- } catch {
2177
- response.writeHead(503, {
2178
- "content-type": "application/json; charset=utf-8",
2179
- "cache-control": "no-store"
2180
- });
2181
- response.end(JSON.stringify({ error: "连接器目录暂不可用。" }));
2182
- }
2183
- }
2184
- });
2185
1094
  const disposeDependencies = host.webServer.register({
2186
1095
  kind: "exact",
2187
1096
  path: dependenciesEndpoint,
@@ -2190,15 +1099,6 @@ function apply(ctx) {
2190
1099
  const url = new URL(request.url ?? "/", "http://localhost");
2191
1100
  try {
2192
1101
  if (request.method === "GET") {
2193
- if (url.searchParams.get("action") === "capabilities") {
2194
- const capabilities = { officialTurnNavigator: await runtimeSupportsOfficialTurnNavigator(resolveDependencyRuntime(ctx)) };
2195
- response.writeHead(200, {
2196
- "content-type": "application/json; charset=utf-8",
2197
- "cache-control": "no-store"
2198
- });
2199
- response.end(JSON.stringify({ capabilities }));
2200
- return;
2201
- }
2202
1102
  if (url.searchParams.get("action") === "progress") {
2203
1103
  response.writeHead(200, {
2204
1104
  "content-type": "application/json; charset=utf-8",
@@ -2269,203 +1169,9 @@ function apply(ctx) {
2269
1169
  }
2270
1170
  }
2271
1171
  });
2272
- const disposePreferences = host.webServer.register({
2273
- kind: "exact",
2274
- path: preferencesEndpoint,
2275
- handler: async (request, response) => {
2276
- if (!authenticateBusinessRequest(ctx, request, response)) return;
2277
- try {
2278
- if (request.method === "GET" || request.method === "HEAD") {
2279
- const preferences = await readWorkspacePreferences();
2280
- response.writeHead(200, {
2281
- "content-type": "application/json; charset=utf-8",
2282
- "cache-control": "no-store"
2283
- });
2284
- response.end(request.method === "HEAD" ? void 0 : JSON.stringify(preferences));
2285
- return;
2286
- }
2287
- if (request.method === "PUT") {
2288
- const body = JSON.parse(await readRequestBody(request));
2289
- const record = body !== null && typeof body === "object" ? body : void 0;
2290
- const pinnedWorkspaceIds = record === void 0 ? void 0 : parsePinnedWorkspaceIds(record.pinnedWorkspaceIds);
2291
- const existing = await readWorkspacePreferences();
2292
- const workspaceGroups = record === void 0 ? void 0 : "workspaceGroups" in record ? parseStoredWorkspaceGroups(record.workspaceGroups) : existing.workspaceGroups;
2293
- const introducesTitleConflict = workspaceGroups?.some((group) => !existing.workspaceGroups.some((previous) => previous.id === group.id && previous.title === group.title) && workspaceGroups.some((other) => other.id !== group.id && other.title.toLowerCase() === group.title.toLowerCase())) === true;
2294
- if (pinnedWorkspaceIds === void 0 || workspaceGroups === void 0 || introducesTitleConflict) {
2295
- response.writeHead(400, {
2296
- "content-type": "application/json; charset=utf-8",
2297
- "cache-control": "no-store"
2298
- });
2299
- response.end(JSON.stringify({ error: "工作区偏好格式无效。" }));
2300
- return;
2301
- }
2302
- await writeWorkspacePreferences(pinnedWorkspaceIds, workspaceGroups);
2303
- response.writeHead(200, {
2304
- "content-type": "application/json; charset=utf-8",
2305
- "cache-control": "no-store"
2306
- });
2307
- response.end(JSON.stringify({
2308
- version: 2,
2309
- pinnedWorkspaceIds,
2310
- workspaceGroups,
2311
- exists: true
2312
- }));
2313
- return;
2314
- }
2315
- response.writeHead(405, { allow: "GET, HEAD, PUT" });
2316
- response.end();
2317
- } catch (error) {
2318
- if (error instanceof RequestBodyTooLargeError) {
2319
- response.writeHead(413, {
2320
- "content-type": "application/json; charset=utf-8",
2321
- "cache-control": "no-store"
2322
- });
2323
- response.end(JSON.stringify({ error: "请求体过大。" }));
2324
- return;
2325
- }
2326
- if (error instanceof SyntaxError) {
2327
- response.writeHead(400, {
2328
- "content-type": "application/json; charset=utf-8",
2329
- "cache-control": "no-store"
2330
- });
2331
- response.end(JSON.stringify({ error: "置顶偏好格式无效。" }));
2332
- return;
2333
- }
2334
- ctx.logger.warn("preferences endpoint failed: %s", error);
2335
- response.writeHead(503, {
2336
- "content-type": "application/json; charset=utf-8",
2337
- "cache-control": "no-store"
2338
- });
2339
- response.end(JSON.stringify({ error: "置顶偏好暂不可用。" }));
2340
- }
2341
- }
2342
- });
2343
- const disposeSessionMove = host.webServer.register({
2344
- kind: "exact",
2345
- path: sessionMoveEndpoint,
2346
- handler: async (request, response) => {
2347
- if (!authenticateBusinessRequest(ctx, request, response, sessionMoveAuthenticationError)) return;
2348
- if (request.method !== "POST") {
2349
- response.writeHead(405, { allow: "POST" });
2350
- response.end();
2351
- return;
2352
- }
2353
- try {
2354
- const body = JSON.parse(await readRequestBody(request));
2355
- const record = body !== null && typeof body === "object" ? body : void 0;
2356
- const sessionId = typeof record?.sessionId === "string" ? record.sessionId.trim() : "";
2357
- const targetWorkspaceId = typeof record?.targetWorkspaceId === "string" ? record.targetWorkspaceId.trim() : "";
2358
- const result = await moveSessionToWorkspace(host, sessionId, targetWorkspaceId);
2359
- response.writeHead(200, {
2360
- "content-type": "application/json; charset=utf-8",
2361
- "cache-control": "no-store"
2362
- });
2363
- response.end(JSON.stringify({
2364
- ok: true,
2365
- result
2366
- }));
2367
- } catch (error) {
2368
- if (error instanceof RequestBodyTooLargeError) {
2369
- response.writeHead(413, {
2370
- "content-type": "application/json; charset=utf-8",
2371
- "cache-control": "no-store"
2372
- });
2373
- response.end(JSON.stringify({
2374
- ok: false,
2375
- code: "session-move/invalid-request",
2376
- error: "请求体过大。"
2377
- }));
2378
- return;
2379
- }
2380
- if (error instanceof SyntaxError) {
2381
- response.writeHead(400, {
2382
- "content-type": "application/json; charset=utf-8",
2383
- "cache-control": "no-store"
2384
- });
2385
- response.end(JSON.stringify({
2386
- ok: false,
2387
- code: "session-move/invalid-request",
2388
- error: "请求格式无效。"
2389
- }));
2390
- return;
2391
- }
2392
- ctx.logger.warn("session move failed: %s", error);
2393
- const payload = publicSessionMoveError(error);
2394
- response.writeHead(sessionMoveStatus(error), {
2395
- "content-type": "application/json; charset=utf-8",
2396
- "cache-control": "no-store"
2397
- });
2398
- response.end(JSON.stringify({
2399
- ok: false,
2400
- ...payload
2401
- }));
2402
- }
2403
- }
2404
- });
2405
- const disposeExplorer = host.webServer.register({
2406
- kind: "exact",
2407
- path: explorerEndpoint,
2408
- handler: async (request, response) => {
2409
- if (!authenticateBusinessRequest(ctx, request, response)) return;
2410
- if (request.method !== "POST") {
2411
- response.writeHead(405, { allow: "POST" });
2412
- response.end();
2413
- return;
2414
- }
2415
- if (process.platform !== "win32") {
2416
- response.writeHead(501, {
2417
- "content-type": "application/json; charset=utf-8",
2418
- "cache-control": "no-store"
2419
- });
2420
- response.end(JSON.stringify({ error: "当前平台使用系统默认打开方式。" }));
2421
- return;
2422
- }
2423
- try {
2424
- const body = JSON.parse(await readRequestBody(request));
2425
- if (typeof body.path !== "string" || body.path.trim() === "") {
2426
- response.writeHead(400, {
2427
- "content-type": "application/json; charset=utf-8",
2428
- "cache-control": "no-store"
2429
- });
2430
- response.end(JSON.stringify({ error: "目录路径无效。" }));
2431
- return;
2432
- }
2433
- const authorizedPath = authorizedExplorerWorkspacePath(body.path, host.workspaceRegistry.list().map((workspace) => workspace.path));
2434
- if (authorizedPath === void 0) {
2435
- response.writeHead(403, {
2436
- "content-type": "application/json; charset=utf-8",
2437
- "cache-control": "no-store"
2438
- });
2439
- response.end(JSON.stringify({ error: "仅允许打开已注册的工作区目录。" }));
2440
- return;
2441
- }
2442
- await foregroundExplorer.open(authorizedPath);
2443
- response.writeHead(200, {
2444
- "content-type": "application/json; charset=utf-8",
2445
- "cache-control": "no-store"
2446
- });
2447
- response.end(JSON.stringify({
2448
- opened: true,
2449
- foreground: true
2450
- }));
2451
- } catch (error) {
2452
- ctx.logger.warn("foreground explorer open failed: %s", error);
2453
- response.writeHead(error instanceof SyntaxError ? 400 : 503, {
2454
- "content-type": "application/json; charset=utf-8",
2455
- "cache-control": "no-store"
2456
- });
2457
- response.end(JSON.stringify({ error: error instanceof SyntaxError ? "目录路径格式无效。" : "无法在前台打开资源管理器。" }));
2458
- }
2459
- }
2460
- });
2461
1172
  return () => {
2462
1173
  disposeDependencyInstaller();
2463
- foregroundExplorer.dispose();
2464
- disposeConnectors();
2465
1174
  disposeDependencies();
2466
- disposeExplorer();
2467
- disposePreferences();
2468
- disposeSessionMove();
2469
1175
  };
2470
1176
  }, "michengai-codex-ui: catalogs");
2471
1177
  }