repo.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { readFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { atomicWritePrivateTextFile, withFileLock } from "@zcode/shared/node";
  4. import {
  5. botsConfigFileSchema,
  6. botsStateFileSchema,
  7. type BotsConfigFile,
  8. type BotsStateFile,
  9. type BotContextState,
  10. } from "@zcode/shared";
  11. import { getAppConfigDir } from "../paths.js";
  12. import {
  13. BOTS_CONFIG_FILE,
  14. BOTS_LEGACY_CONFIG_FILE,
  15. BOTS_LEGACY_STATE_FILE,
  16. BOTS_V2_STATE_FILE,
  17. BOTS_STATE_FILE,
  18. createDefaultBotsConfig,
  19. } from "./config.js";
  20. import { importLegacyBotConfig, importLegacyBotState } from "./storageMigration.js";
  21. async function readOptionalJson(path: string): Promise<unknown | undefined> {
  22. try {
  23. return JSON.parse(await readFile(path, "utf8"));
  24. } catch (error) {
  25. if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
  26. throw error;
  27. }
  28. }
  29. async function writeJson(path: string, value: unknown): Promise<void> {
  30. await atomicWritePrivateTextFile(path, `${JSON.stringify(value, null, 2)}\n`);
  31. }
  32. export class BotsRepo {
  33. private readonly configDir = getAppConfigDir();
  34. async readConfig(): Promise<BotsConfigFile> {
  35. const path = join(this.configDir, BOTS_CONFIG_FILE);
  36. return withFileLock(path, async () => {
  37. const current = await readOptionalJson(path);
  38. // 回滚兼容:v3 已存在就只认 v3;损坏时暴露错误,绝不能恢复旧 Bot 或覆盖用户新修改。
  39. if (current !== undefined) return botsConfigFileSchema.parse(current);
  40. const legacy = await readOptionalJson(join(this.configDir, BOTS_LEGACY_CONFIG_FILE));
  41. const config = botsConfigFileSchema.parse(
  42. legacy === undefined ? createDefaultBotsConfig() : importLegacyBotConfig(legacy),
  43. );
  44. await writeJson(path, config);
  45. return config;
  46. });
  47. }
  48. async writeConfig(config: BotsConfigFile): Promise<BotsConfigFile> {
  49. const parsed = botsConfigFileSchema.parse(config);
  50. const path = join(this.configDir, BOTS_CONFIG_FILE);
  51. await withFileLock(path, () => writeJson(path, parsed));
  52. return parsed;
  53. }
  54. async readState(): Promise<BotsStateFile> {
  55. const path = join(this.configDir, BOTS_STATE_FILE);
  56. return withFileLock(path, () => this.readStateUnlocked(path));
  57. }
  58. private async readStateUnlocked(path: string): Promise<BotsStateFile> {
  59. const current = await readOptionalJson(path);
  60. if (current !== undefined) return botsStateFileSchema.parse(current);
  61. const v2 = await readOptionalJson(join(this.configDir, BOTS_V2_STATE_FILE));
  62. const legacy =
  63. v2 === undefined ? await readOptionalJson(join(this.configDir, BOTS_LEGACY_STATE_FILE)) : v2;
  64. const state = botsStateFileSchema.parse(
  65. legacy === undefined ? { version: 3, bots: {} } : importLegacyBotState(legacy),
  66. );
  67. // 在同一文件锁内固定迁移结果;后续登录/套餐变化不再重新解释旧身份。
  68. await writeJson(path, state);
  69. return state;
  70. }
  71. /** 锁覆盖完整读改写,避免两个 Bot 或 provider cursor 覆盖其他 context。 */
  72. async updateContext(
  73. botId: string,
  74. update: (current: BotContextState | undefined) => BotContextState | undefined,
  75. ): Promise<BotContextState | undefined> {
  76. const path = join(this.configDir, BOTS_STATE_FILE);
  77. return withFileLock(path, async () => {
  78. const state = await this.readStateUnlocked(path);
  79. const next = update(state.bots[botId]);
  80. if (next) state.bots[botId] = next;
  81. else delete state.bots[botId];
  82. const parsed = botsStateFileSchema.parse(state);
  83. await writeJson(path, parsed);
  84. return parsed.bots[botId];
  85. });
  86. }
  87. async writeState(state: BotsStateFile): Promise<BotsStateFile> {
  88. const parsed = botsStateFileSchema.parse(state);
  89. const path = join(this.configDir, BOTS_STATE_FILE);
  90. await withFileLock(path, () => writeJson(path, parsed));
  91. return parsed;
  92. }
  93. }