export.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import type { Argv } from "yargs"
  2. import { Session } from "../../session"
  3. import { cmd } from "./cmd"
  4. import { bootstrap } from "../bootstrap"
  5. import { UI } from "../ui"
  6. import * as prompts from "@clack/prompts"
  7. import { EOL } from "os"
  8. export const ExportCommand = cmd({
  9. command: "export [sessionID]",
  10. describe: "export session data as JSON",
  11. builder: (yargs: Argv) => {
  12. return yargs.positional("sessionID", {
  13. describe: "session id to export",
  14. type: "string",
  15. })
  16. },
  17. handler: async (args) => {
  18. await bootstrap(process.cwd(), async () => {
  19. let sessionID = args.sessionID
  20. process.stderr.write(`Exporting session: ${sessionID ?? "latest"}`)
  21. if (!sessionID) {
  22. UI.empty()
  23. prompts.intro("Export session", {
  24. output: process.stderr,
  25. })
  26. const sessions = []
  27. for await (const session of Session.list()) {
  28. sessions.push(session)
  29. }
  30. if (sessions.length === 0) {
  31. prompts.log.error("No sessions found", {
  32. output: process.stderr,
  33. })
  34. prompts.outro("Done", {
  35. output: process.stderr,
  36. })
  37. return
  38. }
  39. sessions.sort((a, b) => b.time.updated - a.time.updated)
  40. const selectedSession = await prompts.autocomplete({
  41. message: "Select session to export",
  42. maxItems: 10,
  43. options: sessions.map((session) => ({
  44. label: session.title,
  45. value: session.id,
  46. hint: `${new Date(session.time.updated).toLocaleString()} • ${session.id.slice(-8)}`,
  47. })),
  48. output: process.stderr,
  49. })
  50. if (prompts.isCancel(selectedSession)) {
  51. throw new UI.CancelledError()
  52. }
  53. sessionID = selectedSession as string
  54. prompts.outro("Exporting session...", {
  55. output: process.stderr,
  56. })
  57. }
  58. try {
  59. const sessionInfo = await Session.get(sessionID!)
  60. const messages = await Session.messages({ sessionID: sessionID! })
  61. const exportData = {
  62. info: sessionInfo,
  63. messages: messages.map((msg) => ({
  64. info: msg.info,
  65. parts: msg.parts,
  66. })),
  67. }
  68. process.stdout.write(JSON.stringify(exportData, null, 2))
  69. process.stdout.write(EOL)
  70. } catch (error) {
  71. UI.error(`Session not found: ${sessionID!}`)
  72. process.exit(1)
  73. }
  74. })
  75. },
  76. })