session-jsonl.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { appendFile } from 'node:fs/promises'
  2. import { join } from 'node:path'
  3. import type { Context } from 'cordis'
  4. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  5. export const name = 'session-jsonl'
  6. export const inject = ['sessions']
  7. /**
  8. * Minimal persistence plugin: buffers session events (write-behind) and
  9. * drains to a JSONL file at every `session/flush` checkpoint — the pattern a
  10. * real JSONL/sqlite persistence plugin would follow.
  11. */
  12. export function apply(ctx: Context) {
  13. const buffers = new Map<Session, SessionEvent[]>()
  14. const path = (session: Session) => join(import.meta.dirname, '..', `${session.id}.jsonl`)
  15. ctx.on('session/event', (session, event) => {
  16. let buffer = buffers.get(session)
  17. if (!buffer) buffers.set(session, buffer = [])
  18. buffer.push(event)
  19. })
  20. const flush = async (session: Session) => {
  21. const buffer = buffers.get(session)
  22. if (!buffer?.length) return
  23. const lines = buffer.splice(0).map(event => JSON.stringify(event) + '\n').join('')
  24. await appendFile(path(session), lines)
  25. }
  26. ctx.on('session/flush', flush)
  27. ctx.effect(() => () => {
  28. // drain remaining buffers on dispose
  29. for (const session of buffers.keys()) void flush(session)
  30. }, 'session-jsonl')
  31. }