contracts.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import { z } from "zod";
  2. import type { RemoteTarget } from "#src/remoteTarget.js";
  3. import { publicZCodeErrorCodeSchema } from "./errorCodes.js";
  4. import { REMOTE_ASSET_INSTALL_MODES } from "../remoteAssetInstallMode.js";
  5. import { isKnownRemoteResourcePackageId } from "../remoteResourcePackages.js";
  6. import { wslUserSchema } from "../wslUserValidation.js";
  7. import { serverRemoteWorkspaceInfoSchema } from "../server-remote.js";
  8. const nonEmptyStringSchema = z.string().trim().min(1);
  9. const credentialKeySchema = nonEmptyStringSchema;
  10. const timestampSchema = z.number().int().nonnegative();
  11. export const sourceServerTransportKindSchema = z.enum(["ssh", "wsl", "docker"]);
  12. export type SourceServerTransportKind = z.infer<typeof sourceServerTransportKindSchema>;
  13. export const sshProfileTargetSchema = z
  14. .object({
  15. kind: z.literal("ssh"),
  16. host: nonEmptyStringSchema,
  17. port: z.number().int().positive().max(65_535).optional(),
  18. username: nonEmptyStringSchema,
  19. sshConfigAlias: nonEmptyStringSchema.optional(),
  20. privateKeyPath: z.string().optional(),
  21. assetInstallMode: z.enum(REMOTE_ASSET_INSTALL_MODES).optional(),
  22. resourcePackages: z
  23. .object({
  24. selectedPackageIds: z.array(z.string().refine(isKnownRemoteResourcePackageId)).optional(),
  25. })
  26. .strict()
  27. .optional(),
  28. passwordCredentialKey: credentialKeySchema.optional(),
  29. privateKeyPassphraseCredentialKey: credentialKeySchema.optional(),
  30. })
  31. .strict();
  32. export const wslProfileTargetSchema = z
  33. .object({
  34. kind: z.literal("wsl"),
  35. distro: z.string().optional(),
  36. user: wslUserSchema.optional(),
  37. })
  38. .strict();
  39. export const dockerProfileTargetSchema = z
  40. .object({
  41. kind: z.literal("docker"),
  42. container: nonEmptyStringSchema,
  43. })
  44. .strict();
  45. export const sourceServerProfileTargetSchema = z.discriminatedUnion("kind", [
  46. sshProfileTargetSchema,
  47. wslProfileTargetSchema,
  48. dockerProfileTargetSchema,
  49. ]);
  50. export type SSHProfileTarget = z.infer<typeof sshProfileTargetSchema>;
  51. export type WSLProfileTarget = z.infer<typeof wslProfileTargetSchema>;
  52. export type DockerProfileTarget = z.infer<typeof dockerProfileTargetSchema>;
  53. export type SourceServerProfileTarget = z.infer<typeof sourceServerProfileTargetSchema>;
  54. /** 升级授权只绑定执行身份,不携带凭据或可变 Profile 内容。 */
  55. export const sourceServerUpdateTargetSchema = z.discriminatedUnion("kind", [
  56. z
  57. .object({
  58. kind: z.literal("ssh"),
  59. host: nonEmptyStringSchema.toLowerCase(),
  60. port: z.number().int().positive().max(65_535).default(22),
  61. username: nonEmptyStringSchema,
  62. sshConfigAlias: nonEmptyStringSchema.optional(),
  63. })
  64. .strict(),
  65. z
  66. .object({
  67. kind: z.literal("wsl"),
  68. distro: nonEmptyStringSchema,
  69. user: wslUserSchema.refine((value) => value.length > 0),
  70. })
  71. .strict(),
  72. dockerProfileTargetSchema,
  73. ]);
  74. export type SourceServerUpdateTarget = z.infer<typeof sourceServerUpdateTargetSchema>;
  75. export function getSourceServerUpdateTarget(
  76. target: Exclude<RemoteTarget, { kind: "server" }>,
  77. ): SourceServerUpdateTarget {
  78. switch (target.kind) {
  79. case "ssh":
  80. return sourceServerUpdateTargetSchema.parse({
  81. kind: target.kind,
  82. host: target.host,
  83. port: target.port ?? 22,
  84. username: target.username,
  85. ...(target.sshConfigAlias?.trim() ? { sshConfigAlias: target.sshConfigAlias.trim() } : {}),
  86. });
  87. case "wsl":
  88. return sourceServerUpdateTargetSchema.parse({
  89. kind: target.kind,
  90. distro: target.distro,
  91. user: target.user,
  92. });
  93. case "docker":
  94. return sourceServerUpdateTargetSchema.parse({
  95. kind: target.kind,
  96. container: target.container,
  97. });
  98. }
  99. }
  100. export function isSameSourceServerUpdateTarget(
  101. left: Exclude<RemoteTarget, { kind: "server" }>,
  102. right: Exclude<RemoteTarget, { kind: "server" }>,
  103. ): boolean {
  104. if (
  105. [left, right].some(
  106. (target) => target.kind === "wsl" && (!target.distro?.trim() || !target.user?.trim()),
  107. )
  108. )
  109. return false;
  110. return (
  111. JSON.stringify(getSourceServerUpdateTarget(left)) ===
  112. JSON.stringify(getSourceServerUpdateTarget(right))
  113. );
  114. }
  115. export const sourceServerUpdateRequestSchema = z
  116. .object({
  117. profileId: nonEmptyStringSchema,
  118. force: z.boolean().optional(),
  119. /** 用户已确认把较新的远端切换到本机 Desktop 版本;方向由远端 CLI 判定。 */
  120. allowDowngrade: z.boolean().optional(),
  121. expectedTarget: sourceServerUpdateTargetSchema.optional(),
  122. })
  123. .strict();
  124. export type SourceServerUpdateRequest = z.input<typeof sourceServerUpdateRequestSchema>;
  125. /** 取消更新只接收线路身份;是否处于可取消的本机阶段由 Host 判断(R3 §6.3)。 */
  126. export const sourceServerUpdateCancelProfileIdSchema = z.string().uuid();
  127. /**
  128. * 设备级生命周期操作(停止、重启远端服务,RDLC-01)只接收设备身份;具体走哪条连接由 Host 路由,
  129. * Renderer 不传 profileId。
  130. */
  131. export const sourceServerLifecycleSourceIdSchema = z.string().uuid();
  132. const connectionProfileBaseShape = {
  133. profileId: z.string().uuid(),
  134. sourceServerId: z.string().uuid().optional(),
  135. displayName: nonEmptyStringSchema.optional(),
  136. lastConnectedAt: timestampSchema.optional(),
  137. lastConnectError: z.string().optional(),
  138. createdAt: timestampSchema,
  139. lifecycleState: z.enum(["active", "retired"]).default("active"),
  140. retiredReason: z.literal("source-reinstalled").optional(),
  141. retiredAt: timestampSchema.optional(),
  142. };
  143. export const connectionProfileSchema = z.discriminatedUnion("transport", [
  144. z
  145. .object({
  146. ...connectionProfileBaseShape,
  147. transport: z.literal("ssh"),
  148. target: sshProfileTargetSchema,
  149. })
  150. .strict(),
  151. z
  152. .object({
  153. ...connectionProfileBaseShape,
  154. transport: z.literal("wsl"),
  155. target: wslProfileTargetSchema,
  156. })
  157. .strict(),
  158. z
  159. .object({
  160. ...connectionProfileBaseShape,
  161. transport: z.literal("docker"),
  162. target: dockerProfileTargetSchema,
  163. })
  164. .strict(),
  165. ]);
  166. export type ConnectionProfile = z.infer<typeof connectionProfileSchema>;
  167. export const sourceServerRecordSchema = z
  168. .object({
  169. sourceServerId: z.string().uuid(),
  170. displayName: nonEmptyStringSchema,
  171. osUser: nonEmptyStringSchema.optional(),
  172. hostname: nonEmptyStringSchema.optional(),
  173. lastSeenVersion: nonEmptyStringSchema.optional(),
  174. lastOnlineAt: timestampSchema.optional(),
  175. preferredProfileId: z.string().uuid().optional(),
  176. installState: z.enum(["installed", "uninstalled"]).default("installed"),
  177. declaredWorkspaces: z
  178. .array(
  179. z
  180. .object({
  181. workspacePath: nonEmptyStringSchema,
  182. workspaceIdentity: nonEmptyStringSchema,
  183. label: nonEmptyStringSchema.optional(),
  184. })
  185. .strict(),
  186. )
  187. .default([]),
  188. })
  189. .strict();
  190. export type SourceServerRecord = z.infer<typeof sourceServerRecordSchema>;
  191. export const sourceServerWorkspaceHistoryEntrySchema = z
  192. .object({
  193. workspacePath: nonEmptyStringSchema,
  194. workspaceIdentity: nonEmptyStringSchema.optional(),
  195. legacyWorkspaceIdentity: nonEmptyStringSchema.optional(),
  196. profileId: z.string().uuid(),
  197. sourceServerId: z.string().uuid().optional(),
  198. lastOpenedAt: timestampSchema,
  199. })
  200. .strict();
  201. export type SourceServerWorkspaceHistoryEntry = z.infer<
  202. typeof sourceServerWorkspaceHistoryEntrySchema
  203. >;
  204. export const sourceServerMigrationConflictSchema = z
  205. .object({
  206. kind: z.enum(["task-identity", "config-file"]),
  207. key: nonEmptyStringSchema,
  208. taskId: nonEmptyStringSchema.optional(),
  209. relativePath: nonEmptyStringSchema.optional(),
  210. sourceKey: nonEmptyStringSchema,
  211. canonicalKey: nonEmptyStringSchema,
  212. reason: nonEmptyStringSchema,
  213. })
  214. .strict();
  215. export type SourceServerMigrationConflict = z.infer<typeof sourceServerMigrationConflictSchema>;
  216. export const sourceServerMigrationReportRowSchema = z
  217. .object({
  218. migrationId: nonEmptyStringSchema,
  219. workspacePath: nonEmptyStringSchema,
  220. canonicalKey: nonEmptyStringSchema,
  221. variantKeys: z.array(nonEmptyStringSchema),
  222. status: z.enum(["running", "completed", "failed", "abandoned", "abandoned-diverged"]),
  223. phase: nonEmptyStringSchema.optional(),
  224. errorCode: nonEmptyStringSchema.optional(),
  225. taskBackupPath: nonEmptyStringSchema.optional(),
  226. sessionBackupPath: nonEmptyStringSchema.optional(),
  227. updatedAt: timestampSchema,
  228. abandonedAt: timestampSchema.optional(),
  229. abandonedTrigger: nonEmptyStringSchema.optional(),
  230. conflicts: z.array(sourceServerMigrationConflictSchema),
  231. })
  232. .strict();
  233. export type SourceServerMigrationReportRow = z.infer<typeof sourceServerMigrationReportRowSchema>;
  234. export const sourceServerMigrationReportSchema = z
  235. .object({ rows: z.array(sourceServerMigrationReportRowSchema) })
  236. .strict();
  237. export type SourceServerMigrationReport = z.infer<typeof sourceServerMigrationReportSchema>;
  238. export const sourceServerMigrationPathActionSchema = z
  239. .object({
  240. workspacePath: nonEmptyStringSchema,
  241. migrationId: nonEmptyStringSchema.optional(),
  242. })
  243. .strict();
  244. export type SourceServerMigrationPathAction = z.infer<typeof sourceServerMigrationPathActionSchema>;
  245. export const sourceServerResolveWorkspaceRequestSchema = z
  246. .object({
  247. workspacePath: nonEmptyStringSchema,
  248. legacyRouteHint: nonEmptyStringSchema.optional(),
  249. })
  250. .strict();
  251. export type SourceServerResolveWorkspaceRequest = z.infer<
  252. typeof sourceServerResolveWorkspaceRequestSchema
  253. >;
  254. export const sourceServerResolveWorkspaceResultSchema = z
  255. .object({
  256. canonicalWorkspaceKey: nonEmptyStringSchema,
  257. mergedKeys: z.array(nonEmptyStringSchema),
  258. migrationId: nonEmptyStringSchema.optional(),
  259. })
  260. .strict();
  261. export type SourceServerResolveWorkspaceResult = z.infer<
  262. typeof sourceServerResolveWorkspaceResultSchema
  263. >;
  264. export const sourceServerConnectionStateSchema = z.enum([
  265. "absent",
  266. "bootstrapping",
  267. "needs-install",
  268. "needs-upgrade",
  269. "updating",
  270. "online",
  271. "retrying",
  272. "offline",
  273. "identity-change-pending",
  274. "failed",
  275. ]);
  276. export type SourceServerConnectionState = z.infer<typeof sourceServerConnectionStateSchema>;
  277. /** 远端任务 owner 的活动投影;身份用于隔离,实际路径仅用于展示。 */
  278. export const sourceServerRunningTaskSchema = z
  279. .object({
  280. sessionId: nonEmptyStringSchema,
  281. workspacePath: nonEmptyStringSchema,
  282. workspaceIdentity: nonEmptyStringSchema.optional(),
  283. })
  284. .strict();
  285. export type SourceServerRunningTask = z.infer<typeof sourceServerRunningTaskSchema>;
  286. export const sourceServerRunningTasksSchema = z.array(sourceServerRunningTaskSchema);
  287. /**
  288. * 停止 / 重启远端服务确认前按设备读取的运行中任务(RDLC-01)。`available: false` 表示设备没有提供
  289. * 可信清单(远端输出 null、命令失败或输出不符 schema),不能当作“没有任务”;空数组才是没有任务。
  290. */
  291. export const sourceServerRunningTasksResultSchema = z.discriminatedUnion("available", [
  292. z.object({ available: z.literal(true), tasks: sourceServerRunningTasksSchema }).strict(),
  293. z.object({ available: z.literal(false) }).strict(),
  294. ]);
  295. export type SourceServerRunningTasksResult = z.infer<typeof sourceServerRunningTasksResultSchema>;
  296. /** 只读安装预览;sizeBytes 是安装包实际大小,不代表解压后的磁盘占用。 */
  297. export const sourceServerInstallPreviewSchema = z
  298. .object({
  299. version: nonEmptyStringSchema,
  300. installPath: nonEmptyStringSchema.optional(),
  301. sizeBytes: z.number().int().positive(),
  302. })
  303. .strict();
  304. export type SourceServerInstallPreview = z.infer<typeof sourceServerInstallPreviewSchema>;
  305. export const sourceServerConnectionStateSnapshotSchema = z
  306. .object({
  307. profileId: z.string().uuid(),
  308. sourceServerId: z.string().uuid().optional(),
  309. state: sourceServerConnectionStateSchema,
  310. error: z.string().optional(),
  311. updateAvailability: z.enum(["none", "available", "required"]).optional(),
  312. currentVersion: nonEmptyStringSchema.optional(),
  313. availableVersion: nonEmptyStringSchema.optional(),
  314. minimumVersion: nonEmptyStringSchema.optional(),
  315. upgradeTarget: z.enum(["controller", "server"]).optional(),
  316. /** 远端当前 release 由显式降级安装时,被替换的版本;向导据此不自动升级。 */
  317. downgradedFrom: nonEmptyStringSchema.optional(),
  318. /** 更新处于本机阶段(probe、release 解析与本机下载),`cancelSourceUpdate` 可取消(R3 §6.3)。 */
  319. updateCancelable: z.literal(true).optional(),
  320. errorCode: publicZCodeErrorCodeSchema.optional(),
  321. retryable: z.boolean().optional(),
  322. installPreview: sourceServerInstallPreviewSchema.optional(),
  323. runningTasks: sourceServerRunningTasksSchema.optional(),
  324. pendingSourceServerId: z.string().uuid().optional(),
  325. recoveryAttempt: z.number().int().positive().optional(),
  326. recoveryLimit: z.number().int().positive().optional(),
  327. recoveryBudgetExhausted: z.boolean().optional(),
  328. updatedAt: timestampSchema,
  329. })
  330. .strict();
  331. export type SourceServerConnectionStateSnapshot = z.infer<
  332. typeof sourceServerConnectionStateSnapshotSchema
  333. >;
  334. export const sourceServerManagementSnapshotRequestSchema = z
  335. .object({
  336. refreshMigrationCounts: z.boolean().optional(),
  337. })
  338. .strict();
  339. export type SourceServerManagementSnapshotRequest = z.infer<
  340. typeof sourceServerManagementSnapshotRequestSchema
  341. >;
  342. export const sourceServerManagementSnapshotSchema = z
  343. .object({
  344. generation: z.number().int().nonnegative(),
  345. profiles: z.array(connectionProfileSchema),
  346. servers: z.array(sourceServerRecordSchema),
  347. workspaceHistory: z.array(sourceServerWorkspaceHistoryEntrySchema),
  348. states: z.array(sourceServerConnectionStateSnapshotSchema),
  349. failedPathCount: z.number().int().nonnegative(),
  350. abandonedPathCount: z.number().int().nonnegative(),
  351. migrationCounts: z.array(
  352. z.discriminatedUnion("status", [
  353. z
  354. .object({
  355. sourceServerId: nonEmptyStringSchema,
  356. status: z.literal("available"),
  357. failedPathCount: z.number().int().nonnegative(),
  358. abandonedPathCount: z.number().int().nonnegative(),
  359. })
  360. .strict(),
  361. z
  362. .object({
  363. sourceServerId: nonEmptyStringSchema,
  364. status: z.literal("requires-connection"),
  365. })
  366. .strict(),
  367. z.object({ sourceServerId: nonEmptyStringSchema, status: z.literal("loading") }).strict(),
  368. z
  369. .object({ sourceServerId: nonEmptyStringSchema, status: z.literal("unavailable") })
  370. .strict(),
  371. ]),
  372. ),
  373. })
  374. .strict();
  375. export type SourceServerManagementSnapshot = z.infer<typeof sourceServerManagementSnapshotSchema>;
  376. export const sourceServerManagementStateDeltaSchema = z
  377. .object({
  378. generation: z.number().int().positive(),
  379. state: sourceServerConnectionStateSnapshotSchema,
  380. })
  381. .strict();
  382. export type SourceServerManagementStateDelta = z.infer<
  383. typeof sourceServerManagementStateDeltaSchema
  384. >;
  385. export const sourceServerManagementDirectoryDeltaSchema = z
  386. .object({
  387. generation: z.number().int().positive(),
  388. })
  389. .strict();
  390. export type SourceServerManagementDirectoryDelta = z.infer<
  391. typeof sourceServerManagementDirectoryDeltaSchema
  392. >;
  393. /** Server CLI 的可选逐行进度;终态仍由退出码和最后一行结果决定。 */
  394. export const sourceServerInstallProgressSchema = z
  395. .object({
  396. type: z.literal("source-server-install-progress"),
  397. phase: z.enum(["verify-archive", "extract", "verify", "restart"]),
  398. })
  399. .strict();
  400. export type SourceServerInstallProgress = z.infer<typeof sourceServerInstallProgressSchema>;
  401. export const sourceServerOperationLogSchema = z
  402. .object({
  403. profileId: z.string().uuid(),
  404. operation: z.enum(["connect", "update", "stop", "restart"]),
  405. phase: nonEmptyStringSchema,
  406. level: z.enum(["info", "warn", "error"]),
  407. message: z.string(),
  408. progress: z.number().min(0).max(1).optional(),
  409. timestamp: timestampSchema,
  410. })
  411. .strict();
  412. export type SourceServerOperationLog = z.infer<typeof sourceServerOperationLogSchema>;
  413. export type SourceServerDeclaredWorkspaceWire = z.infer<typeof serverRemoteWorkspaceInfoSchema>;