project-session-store.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { InteractionSessionSchema, type InteractionSession } from "./session.js";
  4. const SESSION_DIR = ".inkos";
  5. const SESSION_FILE = "session.json";
  6. export function resolveProjectSessionPath(projectRoot: string): string {
  7. return join(projectRoot, SESSION_DIR, SESSION_FILE);
  8. }
  9. export function createProjectSession(projectRoot: string): InteractionSession {
  10. return InteractionSessionSchema.parse({
  11. sessionId: `${Date.now()}`,
  12. projectRoot,
  13. automationMode: "semi",
  14. messages: [],
  15. });
  16. }
  17. export async function loadProjectSession(projectRoot: string): Promise<InteractionSession> {
  18. try {
  19. const raw = await readFile(resolveProjectSessionPath(projectRoot), "utf-8");
  20. return InteractionSessionSchema.parse(JSON.parse(raw));
  21. } catch {
  22. return createProjectSession(projectRoot);
  23. }
  24. }
  25. export async function persistProjectSession(
  26. projectRoot: string,
  27. session: InteractionSession,
  28. ): Promise<void> {
  29. const dir = join(projectRoot, SESSION_DIR);
  30. await mkdir(dir, { recursive: true });
  31. await writeFile(resolveProjectSessionPath(projectRoot), JSON.stringify(session, null, 2), "utf-8");
  32. }
  33. export async function resolveSessionActiveBook(
  34. projectRoot: string,
  35. session: InteractionSession,
  36. ): Promise<string | undefined> {
  37. const booksDir = join(projectRoot, "books");
  38. const entries = await readdir(booksDir, { withFileTypes: true }).catch(() => []);
  39. const bookIds = entries
  40. .filter((entry) => entry.isDirectory())
  41. .map((entry) => entry.name)
  42. .sort();
  43. if (session.activeBookId && bookIds.includes(session.activeBookId)) {
  44. return session.activeBookId;
  45. }
  46. if (bookIds.length === 1) {
  47. return bookIds[0];
  48. }
  49. return undefined;
  50. }