time.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { Instance } from "../project/instance"
  2. import { Log } from "../util/log"
  3. export namespace FileTime {
  4. const log = Log.create({ service: "file.time" })
  5. export const state = Instance.state(() => {
  6. const read: {
  7. [sessionID: string]: {
  8. [path: string]: Date | undefined
  9. }
  10. } = {}
  11. return {
  12. read,
  13. }
  14. })
  15. export function read(sessionID: string, file: string) {
  16. log.info("read", { sessionID, file })
  17. const { read } = state()
  18. read[sessionID] = read[sessionID] || {}
  19. read[sessionID][file] = new Date()
  20. }
  21. export function get(sessionID: string, file: string) {
  22. return state().read[sessionID]?.[file]
  23. }
  24. export async function assert(sessionID: string, filepath: string) {
  25. const time = get(sessionID, filepath)
  26. if (!time) throw new Error(`You must read the file ${filepath} before overwriting it. Use the Read tool first`)
  27. const stats = await Bun.file(filepath).stat()
  28. if (stats.mtime.getTime() > time.getTime()) {
  29. throw new Error(
  30. `File ${filepath} has been modified since it was last read.\nLast modification: ${stats.mtime.toISOString()}\nLast read: ${time.toISOString()}\n\nPlease read the file again before modifying it.`,
  31. )
  32. }
  33. }
  34. }