paths.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /* path 规则集中维护:旧 task 快照与 provider 配置路径仍在这里收口。 */
  2. import { lstatSync } from "node:fs";
  3. import { cp } from "node:fs/promises";
  4. import { createHash } from "node:crypto";
  5. import { basename, join, win32 } from "node:path";
  6. import { homedir } from "node:os";
  7. import {
  8. DATA_BASE_DIR_FORBIDDEN_WINDOWS_INSTALL_DIR_ERROR_CODE,
  9. ZCODE_AGENT_RUNTIME,
  10. } from "@zcode/shared";
  11. let _dataBaseDir: string | null = null;
  12. export const ZCODE_WINDOWS_APP_INSTALL_DIR_ENV = "ZCODE_WINDOWS_APP_INSTALL_DIR";
  13. const envDataBaseDir = process.env.ZCODE_DATA_BASE_DIR?.trim() || null;
  14. const defaultDataBaseDir = process.env.HOME?.trim() || homedir();
  15. export interface DataBaseDirTargetValidationOptions {
  16. platform?: NodeJS.Platform | string;
  17. env?: Record<string, string | undefined>;
  18. appInstallDir?: string | null;
  19. }
  20. export type DataBaseDirTargetValidationResult =
  21. | { ok: true }
  22. | {
  23. ok: false;
  24. code: typeof DATA_BASE_DIR_FORBIDDEN_WINDOWS_INSTALL_DIR_ERROR_CODE;
  25. forbiddenDir: string;
  26. };
  27. /** Set the base directory for app data (replaces homedir() prefix). */
  28. export function setDataBaseDir(dir: string | null): void {
  29. _dataBaseDir = dir?.trim() || null;
  30. }
  31. /** Get the current base directory. Priority: setDataBaseDir() > env ZCODE_DATA_BASE_DIR > homedir(). */
  32. export function getDataBaseDir(): string {
  33. if (_dataBaseDir) return _dataBaseDir;
  34. if (envDataBaseDir) return envDataBaseDir;
  35. // 服务实例会启动后台刷新任务;若每次调用都动态读取 HOME,
  36. // 测试或宿主切换环境变量后,旧实例可能把数据写到新实例目录。
  37. return defaultDataBaseDir;
  38. }
  39. /** {dataBaseDir}/.zcode */
  40. export function getZCodeDataRootDir(): string {
  41. return join(getDataBaseDir(), ".zcode");
  42. }
  43. /** 非项目对话共享的真实工作目录;默认 ~/.zcode/workspace/default。 */
  44. export function getConversationWorkspaceDir(): string {
  45. return join(getZCodeDataRootDir(), "workspace", "default");
  46. }
  47. /** {dataBaseDir}/.zcode/v2 */
  48. export function getAppConfigDir(): string {
  49. return join(getZCodeDataRootDir(), "v2");
  50. }
  51. function readEnvValue(env: Record<string, string | undefined>, key: string): string | undefined {
  52. const direct = env[key]?.trim();
  53. if (direct) {
  54. return direct;
  55. }
  56. const lowerKey = key.toLowerCase();
  57. for (const [candidateKey, value] of Object.entries(env)) {
  58. if (candidateKey.toLowerCase() !== lowerKey) {
  59. continue;
  60. }
  61. const trimmed = value?.trim();
  62. if (trimmed) {
  63. return trimmed;
  64. }
  65. }
  66. return undefined;
  67. }
  68. function normalizeWindowsComparablePath(pathValue: string): string | null {
  69. const trimmed = pathValue.trim();
  70. if (!trimmed) {
  71. return null;
  72. }
  73. const normalized = win32.normalize(trimmed).replace(/[\\/]+$/, "");
  74. if (!normalized) {
  75. return null;
  76. }
  77. return win32
  78. .resolve(normalized)
  79. .replace(/[\\/]+$/, "")
  80. .toLowerCase();
  81. }
  82. function isWindowsPathEqualOrInside(pathValue: string, rootValue: string): boolean {
  83. const normalizedPath = normalizeWindowsComparablePath(pathValue);
  84. const normalizedRoot = normalizeWindowsComparablePath(rootValue);
  85. if (!normalizedPath || !normalizedRoot) {
  86. return false;
  87. }
  88. return normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}\\`);
  89. }
  90. function collectWindowsForbiddenAppInstallDirs(
  91. options: Required<Pick<DataBaseDirTargetValidationOptions, "env">> &
  92. Pick<DataBaseDirTargetValidationOptions, "appInstallDir">,
  93. ): string[] {
  94. const env = options.env;
  95. const programFiles = readEnvValue(env, "ProgramFiles");
  96. const programFilesX86 = readEnvValue(env, "ProgramFiles(x86)");
  97. const programW6432 = readEnvValue(env, "ProgramW6432");
  98. const localAppData = readEnvValue(env, "LOCALAPPDATA");
  99. const candidates = [
  100. options.appInstallDir,
  101. readEnvValue(env, ZCODE_WINDOWS_APP_INSTALL_DIR_ENV),
  102. programFiles ? win32.join(programFiles, "ZCode") : null,
  103. programFilesX86 ? win32.join(programFilesX86, "ZCode") : null,
  104. programW6432 ? win32.join(programW6432, "ZCode") : null,
  105. localAppData ? win32.join(localAppData, "Programs", "ZCode") : null,
  106. ];
  107. const seen = new Set<string>();
  108. const result: string[] = [];
  109. for (const candidate of candidates) {
  110. const normalized =
  111. typeof candidate === "string" ? normalizeWindowsComparablePath(candidate) : null;
  112. if (!candidate || !normalized || seen.has(normalized)) {
  113. continue;
  114. }
  115. seen.add(normalized);
  116. result.push(candidate);
  117. }
  118. return result;
  119. }
  120. export function validateDataBaseDirTarget(
  121. targetBaseDir: string,
  122. options: DataBaseDirTargetValidationOptions = {},
  123. ): DataBaseDirTargetValidationResult {
  124. if ((options.platform ?? process.platform) !== "win32") {
  125. return { ok: true };
  126. }
  127. for (const forbiddenDir of collectWindowsForbiddenAppInstallDirs({
  128. env: options.env ?? process.env,
  129. appInstallDir: options.appInstallDir ?? null,
  130. })) {
  131. if (isWindowsPathEqualOrInside(targetBaseDir, forbiddenDir)) {
  132. return {
  133. ok: false,
  134. code: DATA_BASE_DIR_FORBIDDEN_WINDOWS_INSTALL_DIR_ERROR_CODE,
  135. forbiddenDir,
  136. };
  137. }
  138. }
  139. return { ok: true };
  140. }
  141. export function getExportLogStageDir(): string {
  142. return join(getZCodeDataRootDir(), "export-log-stage");
  143. }
  144. export function getExportLogDir(): string {
  145. return join(getZCodeDataRootDir(), "export-log");
  146. }
  147. export function getFeedbackRootDir(): string {
  148. return join(getZCodeDataRootDir(), "feedback");
  149. }
  150. export function getFeedbackAttachmentDir(): string {
  151. return join(getFeedbackRootDir(), "attachments");
  152. }
  153. export function getFeedbackLogArchiveDir(): string {
  154. return join(getFeedbackRootDir(), "logs");
  155. }
  156. export function getGitCheckpointIndexRootDir(): string {
  157. return join(getZCodeDataRootDir(), "git-checkpoint-index");
  158. }
  159. /** ~/.zcode/v2/tasks-index.sqlite */
  160. export function getTasksIndexDatabasePath(): string {
  161. return join(getAppConfigDir(), "tasks-index.sqlite");
  162. }
  163. /** workspace 级身份键:远程优先使用 workspaceIdentity,本地回退 workspacePath。 */
  164. function getWorkspaceKey(workspacePath: string, workspaceIdentity?: string): string {
  165. return workspaceIdentity?.trim() || workspacePath;
  166. }
  167. /** 与 ZCode session 持久化一致:使用 workspaceKey 的 SHA-256 前 12 位 */
  168. export function getWorkspaceHash(workspacePath: string, workspaceIdentity?: string): string {
  169. return createHash("sha256")
  170. .update(getWorkspaceKey(workspacePath, workspaceIdentity))
  171. .digest("hex")
  172. .slice(0, 12);
  173. }
  174. /** ~/.zcode/v2/sessions/{workspaceHash} */
  175. function getTaskSessionDir(workspacePath: string, workspaceIdentity?: string): string {
  176. return join(getAppConfigDir(), "sessions", getWorkspaceHash(workspacePath, workspaceIdentity));
  177. }
  178. /** ~/.zcode/v2/sessions/{workspaceHash}/{taskId}.json */
  179. export function getLegacyTaskSessionSnapshotPath(
  180. workspacePath: string,
  181. taskId: string,
  182. workspaceIdentity?: string,
  183. ): string {
  184. return join(getTaskSessionDir(workspacePath, workspaceIdentity), `${taskId}.json`);
  185. }
  186. /** ~/.zcode/v2/sessions/{workspaceHash}/{taskId}.deleted.json */
  187. export function getLegacyDeletedTaskSessionSnapshotPath(
  188. workspacePath: string,
  189. taskId: string,
  190. workspaceIdentity?: string,
  191. ): string {
  192. return join(getTaskSessionDir(workspacePath, workspaceIdentity), `${taskId}.deleted.json`);
  193. }
  194. /**
  195. * GLM(唯一 agent provider)的配置目录:~/.zcode/cli。
  196. * Bugfix:GLM 配置改为直接读写新版 zcode-cli 的全局配置目录,不做 workspace 隔离,
  197. * 避免同机不同工作区配置漂移。
  198. */
  199. export function getProviderWorkspaceConfigDir(): string {
  200. return ZCODE_AGENT_RUNTIME.nativeConfigDir
  201. ? join(getDataBaseDir(), ZCODE_AGENT_RUNTIME.nativeConfigDir)
  202. : join(getDataBaseDir(), ".zcode", "cli");
  203. }
  204. /**
  205. * Copy the .zcode/v2 data directory from one base dir to another.
  206. * Excludes setting.json and its transient atomic-write siblings — bootstrap
  207. * state must only live at the default homedir location.
  208. */
  209. export async function copyDataDirectory(oldBaseDir: string, newBaseDir: string): Promise<void> {
  210. const oldDir = join(oldBaseDir, ".zcode", "v2");
  211. const newDir = join(newBaseDir, ".zcode", "v2");
  212. await cp(oldDir, newDir, {
  213. recursive: true,
  214. force: false,
  215. filter: (source) => {
  216. const sourceName = basename(source);
  217. if (sourceName === "setting.json" || sourceName.startsWith("setting.json.")) {
  218. // setting.json.lock 和 setting.json.*.tmp 由原子写入短暂创建/删除,
  219. // 复制过程中扫描到已消失的 lock 会触发 ENOENT,并让数据目录迁移失败。
  220. // 这些文件都属于 bootstrap 写入中间态,不能迁移到新数据根。
  221. return false;
  222. }
  223. // Windows 非提权环境下 fs.cp 无法复制符号链接(EPERM)。
  224. // 跳过符号链接可避免 Windows 非提权环境下 fs.cp 报 EPERM。
  225. try {
  226. if (lstatSync(source).isSymbolicLink()) return false;
  227. } catch {
  228. // lstat 失败时放行,让 cp 自行处理
  229. }
  230. return true;
  231. },
  232. });
  233. }