spiracha 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/AGENTS.md +116 -164
  2. package/README.md +92 -237
  3. package/apps/ui/AGENTS.md +36 -7
  4. package/apps/ui/README.md +79 -6
  5. package/apps/ui/components.json +21 -0
  6. package/apps/ui/package.json +65 -0
  7. package/apps/ui/{dist/client → public}/icon.svg +2 -1
  8. package/apps/ui/src/components/antigravity-conversations-table.tsx +206 -0
  9. package/apps/ui/src/components/antigravity-keychain-panel.tsx +76 -0
  10. package/apps/ui/src/components/antigravity-workspaces-table.tsx +63 -0
  11. package/apps/ui/src/components/app-shell.tsx +124 -0
  12. package/apps/ui/src/components/breadcrumbs.tsx +53 -0
  13. package/apps/ui/src/components/claude-code-sessions-table.tsx +114 -0
  14. package/apps/ui/src/components/claude-code-workspaces-table.tsx +55 -0
  15. package/apps/ui/src/components/cursor-threads-table.tsx +189 -0
  16. package/apps/ui/src/components/cursor-workspaces-table.tsx +140 -0
  17. package/apps/ui/src/components/data-table.tsx +241 -0
  18. package/apps/ui/src/components/delete-confirm-dialog.tsx +88 -0
  19. package/apps/ui/src/components/export-dialog.tsx +184 -0
  20. package/apps/ui/src/components/json-panel.tsx +17 -0
  21. package/apps/ui/src/components/kiro-sessions-table.tsx +112 -0
  22. package/apps/ui/src/components/kiro-workspaces-table.tsx +53 -0
  23. package/apps/ui/src/components/list-search-input.tsx +18 -0
  24. package/apps/ui/src/components/loading-panel.tsx +23 -0
  25. package/apps/ui/src/components/metadata-section.tsx +31 -0
  26. package/apps/ui/src/components/metric-card.tsx +19 -0
  27. package/apps/ui/src/components/opencode-sessions-table.tsx +128 -0
  28. package/apps/ui/src/components/opencode-workspaces-table.tsx +57 -0
  29. package/apps/ui/src/components/page-header.tsx +33 -0
  30. package/apps/ui/src/components/projects-loading-state.tsx +74 -0
  31. package/apps/ui/src/components/projects-table.tsx +108 -0
  32. package/apps/ui/src/components/qoder-sessions-table.tsx +112 -0
  33. package/apps/ui/src/components/qoder-workspaces-table.tsx +53 -0
  34. package/apps/ui/src/components/recent-threads-list.tsx +52 -0
  35. package/apps/ui/src/components/reload-error-panel.tsx +20 -0
  36. package/apps/ui/src/components/text-document-panel.tsx +19 -0
  37. package/apps/ui/src/components/theme-toggle.tsx +48 -0
  38. package/apps/ui/src/components/threads-table.tsx +202 -0
  39. package/apps/ui/src/components/transcript-view.tsx +552 -0
  40. package/apps/ui/src/components/ui/alert-dialog.tsx +160 -0
  41. package/apps/ui/src/components/ui/badge.tsx +45 -0
  42. package/apps/ui/src/components/ui/button.tsx +62 -0
  43. package/apps/ui/src/components/ui/checkbox.tsx +29 -0
  44. package/apps/ui/src/components/ui/dialog.tsx +137 -0
  45. package/apps/ui/src/components/ui/dropdown-menu.tsx +217 -0
  46. package/apps/ui/src/components/ui/input.tsx +21 -0
  47. package/apps/ui/src/components/ui/scroll-area.tsx +46 -0
  48. package/apps/ui/src/components/ui/select.tsx +163 -0
  49. package/apps/ui/src/components/ui/separator.tsx +28 -0
  50. package/apps/ui/src/components/ui/sheet.tsx +107 -0
  51. package/apps/ui/src/components/ui/skeleton.tsx +7 -0
  52. package/apps/ui/src/components/ui/table.tsx +76 -0
  53. package/apps/ui/src/components/ui/tabs.tsx +71 -0
  54. package/apps/ui/src/components/ui/tooltip.tsx +44 -0
  55. package/apps/ui/src/integrations/tanstack-query/devtools.tsx +6 -0
  56. package/apps/ui/src/integrations/tanstack-query/root-provider.tsx +10 -0
  57. package/apps/ui/src/lib/antigravity-conversation-state.ts +28 -0
  58. package/apps/ui/src/lib/antigravity-queries.ts +33 -0
  59. package/apps/ui/src/lib/antigravity-server.ts +128 -0
  60. package/apps/ui/src/lib/antigravity-transcript-events.ts +335 -0
  61. package/apps/ui/src/lib/claude-code-queries.ts +26 -0
  62. package/apps/ui/src/lib/claude-code-server.ts +75 -0
  63. package/apps/ui/src/lib/claude-code-transcript-events.ts +154 -0
  64. package/apps/ui/src/lib/codex-queries.ts +66 -0
  65. package/apps/ui/src/lib/codex-server.ts +209 -0
  66. package/apps/ui/src/lib/cursor-queries.ts +37 -0
  67. package/apps/ui/src/lib/cursor-server.ts +272 -0
  68. package/apps/ui/src/lib/cursor-transcript-events.ts +229 -0
  69. package/apps/ui/src/lib/download.ts +166 -0
  70. package/apps/ui/src/lib/formatters.ts +149 -0
  71. package/apps/ui/src/lib/kiro-queries.ts +22 -0
  72. package/apps/ui/src/lib/kiro-server.ts +73 -0
  73. package/apps/ui/src/lib/kiro-transcript-events.ts +113 -0
  74. package/apps/ui/src/lib/opencode-queries.ts +37 -0
  75. package/apps/ui/src/lib/opencode-server.ts +73 -0
  76. package/apps/ui/src/lib/opencode-transcript-events.ts +221 -0
  77. package/apps/ui/src/lib/package-metadata.ts +16 -0
  78. package/apps/ui/src/lib/path-utils.ts +13 -0
  79. package/apps/ui/src/lib/qoder-queries.ts +22 -0
  80. package/apps/ui/src/lib/qoder-server.ts +79 -0
  81. package/apps/ui/src/lib/qoder-transcript-events.ts +139 -0
  82. package/apps/ui/src/lib/route-search.ts +68 -0
  83. package/apps/ui/src/lib/settings-store.tsx +59 -0
  84. package/apps/ui/src/lib/source-session-export-server.ts +56 -0
  85. package/apps/ui/src/lib/text-filter.ts +22 -0
  86. package/apps/ui/src/lib/thread-id.ts +3 -0
  87. package/apps/ui/src/lib/thread-transcript-stats.ts +57 -0
  88. package/apps/ui/src/lib/utils.ts +7 -0
  89. package/apps/ui/src/routeTree.gen.ts +730 -0
  90. package/apps/ui/src/router.tsx +20 -0
  91. package/apps/ui/src/routes/$threadId.tsx +22 -0
  92. package/apps/ui/src/routes/__root.tsx +127 -0
  93. package/apps/ui/src/routes/analytics.tsx +143 -0
  94. package/apps/ui/src/routes/antigravity-conversations.$conversationId.tsx +438 -0
  95. package/apps/ui/src/routes/antigravity.$workspaceKey.tsx +127 -0
  96. package/apps/ui/src/routes/antigravity.index.tsx +51 -0
  97. package/apps/ui/src/routes/api.v1.conversation-query.ts +12 -0
  98. package/apps/ui/src/routes/api.v1.conversations.$source.$id.export.ts +12 -0
  99. package/apps/ui/src/routes/api.v1.conversations.$source.$id.ts +12 -0
  100. package/apps/ui/src/routes/api.v1.conversations.ts +12 -0
  101. package/apps/ui/src/routes/api.v1.resolve.ts +12 -0
  102. package/apps/ui/src/routes/api.v1.sources.ts +12 -0
  103. package/apps/ui/src/routes/claude-code-sessions.$sessionId.tsx +342 -0
  104. package/apps/ui/src/routes/claude-code.$workspaceKey.tsx +135 -0
  105. package/apps/ui/src/routes/claude-code.index.tsx +48 -0
  106. package/apps/ui/src/routes/codex.$project.tsx +390 -0
  107. package/apps/ui/src/routes/codex.index.tsx +116 -0
  108. package/apps/ui/src/routes/cursor-threads.$composerId.tsx +435 -0
  109. package/apps/ui/src/routes/cursor.$workspaceKey.tsx +416 -0
  110. package/apps/ui/src/routes/cursor.index.tsx +120 -0
  111. package/apps/ui/src/routes/index.tsx +124 -0
  112. package/apps/ui/src/routes/kiro-sessions.$sessionId.tsx +345 -0
  113. package/apps/ui/src/routes/kiro.$workspaceKey.tsx +136 -0
  114. package/apps/ui/src/routes/kiro.index.tsx +48 -0
  115. package/apps/ui/src/routes/opencode-sessions.$sessionId.tsx +334 -0
  116. package/apps/ui/src/routes/opencode.$workspaceKey.tsx +135 -0
  117. package/apps/ui/src/routes/opencode.index.tsx +48 -0
  118. package/apps/ui/src/routes/qoder-sessions.$sessionId.tsx +341 -0
  119. package/apps/ui/src/routes/qoder.$workspaceKey.tsx +139 -0
  120. package/apps/ui/src/routes/qoder.index.tsx +48 -0
  121. package/apps/ui/src/routes/settings.tsx +91 -0
  122. package/apps/ui/src/routes/threads.$threadId.tsx +619 -0
  123. package/apps/ui/src/styles.css +122 -0
  124. package/apps/ui/tsconfig.json +29 -0
  125. package/apps/ui/vite.config.ts +84 -0
  126. package/bin/spiracha.ts +32 -0
  127. package/package.json +50 -60
  128. package/src/client.ts +290 -0
  129. package/src/lib/antigravity-db.ts +213 -19
  130. package/src/lib/antigravity-exporter-types.ts +1 -0
  131. package/src/lib/claude-code-db.ts +655 -0
  132. package/src/lib/claude-code-exporter-types.ts +110 -0
  133. package/src/lib/claude-code-transcript-phase.ts +25 -0
  134. package/src/lib/claude-code-transcript.ts +180 -0
  135. package/src/lib/codex-analytics.ts +1 -1
  136. package/src/lib/codex-browser-db.ts +856 -61
  137. package/src/lib/codex-browser-export.ts +24 -16
  138. package/src/lib/codex-browser-types.ts +1 -1
  139. package/src/lib/codex-thread-cache.ts +17 -1
  140. package/src/lib/{codex-exporter-types.ts → codex-thread-types.ts} +2 -30
  141. package/src/lib/{codex-exporter-transcript.ts → codex-transcript-renderer.ts} +64 -28
  142. package/src/lib/concurrency.ts +25 -0
  143. package/src/lib/conversation-api.ts +792 -0
  144. package/src/lib/conversation-data/adapter-helpers.ts +110 -0
  145. package/src/lib/conversation-data/antigravity-adapter.ts +148 -0
  146. package/src/lib/conversation-data/claude-code-adapter.ts +175 -0
  147. package/src/lib/conversation-data/codex-adapter.ts +245 -0
  148. package/src/lib/conversation-data/cursor-adapter.ts +171 -0
  149. package/src/lib/conversation-data/index.ts +311 -0
  150. package/src/lib/conversation-data/kiro-adapter.ts +140 -0
  151. package/src/lib/conversation-data/message-selector.ts +37 -0
  152. package/src/lib/conversation-data/opencode-adapter.ts +180 -0
  153. package/src/lib/conversation-data/path-match.ts +79 -0
  154. package/src/lib/conversation-data/qoder-adapter.ts +230 -0
  155. package/src/lib/conversation-data/types.ts +116 -0
  156. package/src/lib/cursor-db.ts +67 -21
  157. package/src/lib/cursor-exporter-types.ts +0 -19
  158. package/src/lib/kiro-db.ts +949 -0
  159. package/src/lib/kiro-exporter-types.ts +100 -0
  160. package/src/lib/kiro-transcript-phase.ts +41 -0
  161. package/src/lib/kiro-transcript.ts +115 -0
  162. package/src/lib/opencode-db.ts +610 -0
  163. package/src/lib/opencode-exporter-types.ts +129 -0
  164. package/src/lib/opencode-think-tags.ts +126 -0
  165. package/src/lib/opencode-transcript-phase.ts +50 -0
  166. package/src/lib/opencode-transcript.ts +194 -0
  167. package/src/lib/qoder-acp-client.ts +268 -0
  168. package/src/lib/qoder-db.ts +1601 -0
  169. package/src/lib/qoder-exporter-types.ts +114 -0
  170. package/src/lib/qoder-transcript-phase.ts +41 -0
  171. package/src/lib/qoder-transcript.ts +112 -0
  172. package/src/lib/shared.ts +25 -0
  173. package/src/lib/ui-export-archive.ts +61 -0
  174. package/apps/ui/dist/client/assets/_threadId-CAIeH5mq.js +0 -1
  175. package/apps/ui/dist/client/assets/analytics-DK2jdvmI.js +0 -1
  176. package/apps/ui/dist/client/assets/antigravity-conversations._conversationId-DmD0sN8X.js +0 -7
  177. package/apps/ui/dist/client/assets/antigravity-conversations._conversationId-KAcXtNxI.js +0 -1
  178. package/apps/ui/dist/client/assets/antigravity-keychain-panel-BRHVjFAM.js +0 -1
  179. package/apps/ui/dist/client/assets/antigravity._workspaceKey-ByitGWki.js +0 -1
  180. package/apps/ui/dist/client/assets/antigravity._workspaceKey-CGV7amas.js +0 -1
  181. package/apps/ui/dist/client/assets/antigravity.index-DEEkjlZa.js +0 -1
  182. package/apps/ui/dist/client/assets/antigravity.index-DgW25FEV.js +0 -1
  183. package/apps/ui/dist/client/assets/badge-DfWvPfKF.js +0 -1
  184. package/apps/ui/dist/client/assets/checkbox-CdHitXWQ.js +0 -1
  185. package/apps/ui/dist/client/assets/createServerFn-CgRRVpBH.js +0 -3
  186. package/apps/ui/dist/client/assets/cursor-threads._composerId-CmBFclK8.js +0 -1
  187. package/apps/ui/dist/client/assets/cursor-threads._composerId-Ti2gTm63.js +0 -1
  188. package/apps/ui/dist/client/assets/cursor._workspaceKey-CaAZjGmm.js +0 -1
  189. package/apps/ui/dist/client/assets/cursor._workspaceKey-DzD_c6j9.js +0 -1
  190. package/apps/ui/dist/client/assets/cursor.index-CrnMwDCi.js +0 -1
  191. package/apps/ui/dist/client/assets/cursor.index-PkCFVcl4.js +0 -2
  192. package/apps/ui/dist/client/assets/data-table-Br78_dk3.js +0 -4
  193. package/apps/ui/dist/client/assets/delete-confirm-dialog-BHRmyLHr.js +0 -11
  194. package/apps/ui/dist/client/assets/dist-B9pyYCVU.js +0 -1
  195. package/apps/ui/dist/client/assets/dist-BhZOxAPP.js +0 -1
  196. package/apps/ui/dist/client/assets/dist-DvMS2965.js +0 -1
  197. package/apps/ui/dist/client/assets/download-Bf0QJKD3.js +0 -1
  198. package/apps/ui/dist/client/assets/dropdown-menu-Dy5cLzTy.js +0 -1
  199. package/apps/ui/dist/client/assets/es2015-BkCWttyM.js +0 -41
  200. package/apps/ui/dist/client/assets/export-dialog-C86SYHJn.js +0 -1
  201. package/apps/ui/dist/client/assets/formatters-BM9kB7ed.js +0 -1
  202. package/apps/ui/dist/client/assets/index-CPvAP-jk.js +0 -149
  203. package/apps/ui/dist/client/assets/jsx-runtime-DGeXAQPT.js +0 -1
  204. package/apps/ui/dist/client/assets/metric-card-Dplm0ZiM.js +0 -1
  205. package/apps/ui/dist/client/assets/page-header-Cwa3p6Tl.js +0 -1
  206. package/apps/ui/dist/client/assets/projects._project-Ckf6muWZ.js +0 -1
  207. package/apps/ui/dist/client/assets/projects._project-DSDwH4NF.js +0 -1
  208. package/apps/ui/dist/client/assets/projects.index-DEfhWqa8.js +0 -1
  209. package/apps/ui/dist/client/assets/projects.index-V5ibNZII.js +0 -3
  210. package/apps/ui/dist/client/assets/react-dom-DL96Jor4.js +0 -1
  211. package/apps/ui/dist/client/assets/refresh-ccw-BgKjOiA6.js +0 -1
  212. package/apps/ui/dist/client/assets/reload-error-panel-AHqu0akK.js +0 -1
  213. package/apps/ui/dist/client/assets/routes-Df2tgpyd.js +0 -1
  214. package/apps/ui/dist/client/assets/scroll-text-fM0sMOB3.js +0 -1
  215. package/apps/ui/dist/client/assets/select-Bf2GwfPR.js +0 -1
  216. package/apps/ui/dist/client/assets/settings-5VQIzME0.js +0 -1
  217. package/apps/ui/dist/client/assets/sqlite-error-B6uZjUe8.js +0 -1
  218. package/apps/ui/dist/client/assets/styles-BhRkXgwB.css +0 -1
  219. package/apps/ui/dist/client/assets/tabs-OO4VU5KR.js +0 -7
  220. package/apps/ui/dist/client/assets/text-filter-DVAZySUS.js +0 -2
  221. package/apps/ui/dist/client/assets/threads._threadId-BB9tTsV4.js +0 -1
  222. package/apps/ui/dist/client/assets/threads._threadId-BgDhFj2I.js +0 -1
  223. package/apps/ui/dist/client/assets/useMutation-CC_B7uy5.js +0 -1
  224. package/apps/ui/dist/client/assets/useQuery-C5By6WKU.js +0 -1
  225. package/apps/ui/dist/server/assets/_tanstack-start-manifest_v-CRW2kqj0.js +0 -232
  226. package/apps/ui/dist/server/assets/_threadId-B6SrBR9E.js +0 -6
  227. package/apps/ui/dist/server/assets/analytics-CYP_LT5Y.js +0 -16
  228. package/apps/ui/dist/server/assets/analytics-CtpOMVMO.js +0 -146
  229. package/apps/ui/dist/server/assets/antigravity-conversation-state-HgzS302O.js +0 -16
  230. package/apps/ui/dist/server/assets/antigravity-conversations._conversationId-BtexWY-K.js +0 -613
  231. package/apps/ui/dist/server/assets/antigravity-conversations._conversationId-D426O-64.js +0 -11
  232. package/apps/ui/dist/server/assets/antigravity-conversations._conversationId-zMrR6v6R.js +0 -20
  233. package/apps/ui/dist/server/assets/antigravity-db-Bh8_U9uw.js +0 -580
  234. package/apps/ui/dist/server/assets/antigravity-keychain-DOiuHDwK.js +0 -126
  235. package/apps/ui/dist/server/assets/antigravity-keychain-panel-CC7FLmAK.js +0 -55
  236. package/apps/ui/dist/server/assets/antigravity-queries-CGrJO9Vr.js +0 -37
  237. package/apps/ui/dist/server/assets/antigravity-server-CHRjVFqN.js +0 -114
  238. package/apps/ui/dist/server/assets/antigravity._workspaceKey-3m_MzNFA.js +0 -11
  239. package/apps/ui/dist/server/assets/antigravity._workspaceKey-B0QeYUOh.js +0 -28
  240. package/apps/ui/dist/server/assets/antigravity._workspaceKey-C3kP-qyN.js +0 -210
  241. package/apps/ui/dist/server/assets/antigravity.index-CPCYkqCi.js +0 -104
  242. package/apps/ui/dist/server/assets/antigravity.index-DudTB3Tq.js +0 -11
  243. package/apps/ui/dist/server/assets/badge-EvdhKK_Z.js +0 -26
  244. package/apps/ui/dist/server/assets/button-CmTDnzOn.js +0 -46
  245. package/apps/ui/dist/server/assets/checkbox-C0hovF41.js +0 -19
  246. package/apps/ui/dist/server/assets/codex-queries-CtgeZ7VL.js +0 -99
  247. package/apps/ui/dist/server/assets/codex-server-CNXSJuc2.js +0 -2004
  248. package/apps/ui/dist/server/assets/concurrency-VXtYvlGh.js +0 -18
  249. package/apps/ui/dist/server/assets/createServerRpc-CF_DEwnm.js +0 -12
  250. package/apps/ui/dist/server/assets/createSsrRpc-C754NPki.js +0 -16
  251. package/apps/ui/dist/server/assets/cursor-db-cYZEU3WQ.js +0 -830
  252. package/apps/ui/dist/server/assets/cursor-exporter-types-CI3goo-c.js +0 -34
  253. package/apps/ui/dist/server/assets/cursor-queries-NCIM0Nat.js +0 -67
  254. package/apps/ui/dist/server/assets/cursor-recovery-nq-kR62j.js +0 -361
  255. package/apps/ui/dist/server/assets/cursor-server-C3q7hrp-.js +0 -213
  256. package/apps/ui/dist/server/assets/cursor-threads._composerId-BB0Y_Mao.js +0 -11
  257. package/apps/ui/dist/server/assets/cursor-threads._composerId-BPJFWfJj.js +0 -18
  258. package/apps/ui/dist/server/assets/cursor-threads._composerId-BkMMTQ3v.js +0 -582
  259. package/apps/ui/dist/server/assets/cursor-transcript-2iL3KFSK.js +0 -125
  260. package/apps/ui/dist/server/assets/cursor._workspaceKey-C5PdTaKB.js +0 -28
  261. package/apps/ui/dist/server/assets/cursor._workspaceKey-Ckj7apKI.js +0 -401
  262. package/apps/ui/dist/server/assets/cursor._workspaceKey-nmg3YIOQ.js +0 -11
  263. package/apps/ui/dist/server/assets/cursor.index-CcsX7DG0.js +0 -11
  264. package/apps/ui/dist/server/assets/cursor.index-DkWT-mxw.js +0 -189
  265. package/apps/ui/dist/server/assets/data-table-Cdct823O.js +0 -189
  266. package/apps/ui/dist/server/assets/delete-confirm-dialog-BcBNCxWB.js +0 -144
  267. package/apps/ui/dist/server/assets/download-DMmiy1xf.js +0 -92
  268. package/apps/ui/dist/server/assets/dropdown-menu-Dy_9t6TN.js +0 -36
  269. package/apps/ui/dist/server/assets/empty-plugin-adapters-B3lHh1La.js +0 -5
  270. package/apps/ui/dist/server/assets/export-dialog-BItjWgkZ.js +0 -240
  271. package/apps/ui/dist/server/assets/formatters-FJaGZgJk.js +0 -91
  272. package/apps/ui/dist/server/assets/loading-panel-BGFnWseS.js +0 -27
  273. package/apps/ui/dist/server/assets/metric-card-ByEeLu0r.js +0 -23
  274. package/apps/ui/dist/server/assets/model-label-B1NWGc65.js +0 -13
  275. package/apps/ui/dist/server/assets/page-header-VNSaM3xd.js +0 -29
  276. package/apps/ui/dist/server/assets/path-transforms-DL2IwtYd.js +0 -31
  277. package/apps/ui/dist/server/assets/projects._project-Bpbc3C-L.js +0 -20
  278. package/apps/ui/dist/server/assets/projects._project-Bshqk7JA.js +0 -12
  279. package/apps/ui/dist/server/assets/projects._project-CvZho6EQ.js +0 -395
  280. package/apps/ui/dist/server/assets/projects.index-BLXOx5eL.js +0 -12
  281. package/apps/ui/dist/server/assets/projects.index-BkLiF2FF.js +0 -182
  282. package/apps/ui/dist/server/assets/projects.index-DesYXwfi.js +0 -14
  283. package/apps/ui/dist/server/assets/reload-error-panel-BJMxY3U1.js +0 -25
  284. package/apps/ui/dist/server/assets/route-search-ts4W9MJ9.js +0 -38
  285. package/apps/ui/dist/server/assets/router-6m-ihwqA.js +0 -410
  286. package/apps/ui/dist/server/assets/routes-Bsact1uB.js +0 -184
  287. package/apps/ui/dist/server/assets/routes-BzkJgq4W.js +0 -34
  288. package/apps/ui/dist/server/assets/select-GW76p-ld.js +0 -76
  289. package/apps/ui/dist/server/assets/settings-OayxIYQQ.js +0 -100
  290. package/apps/ui/dist/server/assets/settings-store-DpEJEQ7M.js +0 -52
  291. package/apps/ui/dist/server/assets/shared-CPRNYIql.js +0 -134
  292. package/apps/ui/dist/server/assets/sqlite-error-LZDrnxdd.js +0 -13
  293. package/apps/ui/dist/server/assets/start-CI_0bSiY.js +0 -4
  294. package/apps/ui/dist/server/assets/tabs-CGA13IZM.js +0 -502
  295. package/apps/ui/dist/server/assets/text-filter-CGKxMCKt.js +0 -36
  296. package/apps/ui/dist/server/assets/threads._threadId-BSSK4nkI.js +0 -26
  297. package/apps/ui/dist/server/assets/threads._threadId-Bs0yuqO9.js +0 -18
  298. package/apps/ui/dist/server/assets/threads._threadId-D2GYkVn6.js +0 -639
  299. package/apps/ui/dist/server/assets/ui-export-files-BHLX9bhN.js +0 -83
  300. package/apps/ui/dist/server/assets/utils-C_uf36nf.js +0 -8
  301. package/apps/ui/dist/server/server.js +0 -5847
  302. package/bin/codex-chats-claude.js +0 -5
  303. package/bin/codex-chats.js +0 -5
  304. package/bin/spiracha.js +0 -5
  305. package/src/export-chats.ts +0 -120
  306. package/src/export-claude.ts +0 -36
  307. package/src/export-cursor.ts +0 -244
  308. package/src/lib/claude-exporter.ts +0 -864
  309. package/src/lib/codex-exporter-cli.ts +0 -277
  310. package/src/lib/codex-exporter-db.ts +0 -319
  311. package/src/lib/codex-exporter.ts +0 -115
  312. package/src/lib/cursor-exporter.ts +0 -266
  313. package/src/lib/interactive-cli.ts +0 -433
  314. package/src/lib/native-open.ts +0 -54
  315. package/src/mcp-server.ts +0 -137
  316. package/src/spiracha.ts +0 -116
  317. package/src/ui-cli.ts +0 -310
  318. /package/apps/ui/{dist/client → public}/manifest.json +0 -0
  319. /package/apps/ui/{dist/client → public}/robots.txt +0 -0
@@ -1,2004 +0,0 @@
1
- import { t as createServerFn } from "../server.js";
2
- import { t as createServerRpc } from "./createServerRpc-CF_DEwnm.js";
3
- import { a as cleanInlineTitle, c as formatInlineLiteral, d as readJsonlObjects, h as renderSection, i as cleanExtractedText, l as formatModelLabel, m as renderMetadataBlock, n as asObject, o as createExportWriteStream, p as renderDocumentTitle, r as asString, s as finalizeExportWriteStream, t as asNumber, u as getPortablePathBasename } from "./shared-CPRNYIql.js";
4
- import { t as mapWithConcurrency } from "./concurrency-VXtYvlGh.js";
5
- import { t as isRetryableSqliteError } from "./sqlite-error-LZDrnxdd.js";
6
- import { t as applyPathTransforms } from "./path-transforms-DL2IwtYd.js";
7
- import { a as sanitizeExportFileName, n as ensureUiExportDir, o as zipExportDirectory, r as getExportMimeType, s as zipExportFile, t as buildUiExportDownloadUrl } from "./ui-export-files-BHLX9bhN.js";
8
- import { finished } from "node:stream/promises";
9
- import { z } from "zod";
10
- import { Database } from "bun:sqlite";
11
- import { copyFile, mkdir, mkdtemp, readdir, rename, rm, stat, utimes } from "node:fs/promises";
12
- import os from "node:os";
13
- import path from "node:path";
14
- import { createReadStream } from "node:fs";
15
- import { createHash, randomUUID } from "node:crypto";
16
- //#region ../../src/lib/codex-exporter-types.ts
17
- var DEFAULT_CODEX_DIR = path.join(os.homedir(), ".codex");
18
- var DEFAULT_DB_PATH = path.join(DEFAULT_CODEX_DIR, "state_5.sqlite");
19
- path.join(DEFAULT_CODEX_DIR, "sessions");
20
- path.join(process.cwd(), "exports");
21
- //#endregion
22
- //#region ../../src/lib/codex-thread-parser.ts
23
- var createEmptyStats = () => {
24
- return {
25
- assistantMessageCount: 0,
26
- commentaryCount: 0,
27
- execCommandCount: 0,
28
- finalAnswerCount: 0,
29
- messageCount: 0,
30
- toolCallCount: 0,
31
- toolOutputCount: 0,
32
- userMessageCount: 0,
33
- webSearchEventCount: 0
34
- };
35
- };
36
- var createEmptySessionMeta = () => {
37
- return {
38
- baseInstructions: null,
39
- cli_version: void 0,
40
- cwd: void 0,
41
- dynamicTools: [],
42
- git: null,
43
- id: void 0,
44
- modelProvider: null,
45
- originator: void 0,
46
- source: void 0,
47
- threadSource: null,
48
- timestamp: void 0
49
- };
50
- };
51
- var parseCodexTranscriptFile = async (sessionFile, options = {}) => {
52
- const sessionMeta = createEmptySessionMeta();
53
- const turnContexts = [];
54
- const events = [];
55
- const stats = createEmptyStats();
56
- const includeRaw = options.includeRaw ?? true;
57
- const maxEvents = options.maxEvents ?? Number.POSITIVE_INFINITY;
58
- const maxTurnContexts = options.maxTurnContexts ?? Number.POSITIVE_INFINITY;
59
- let sequence = 0;
60
- for await (const parsed of readJsonlObjects(sessionFile)) {
61
- captureSessionMeta$1(parsed, sessionMeta);
62
- if (asString(parsed.type) === "turn_context") {
63
- if (turnContexts.length < maxTurnContexts) captureTurnContext(parsed, turnContexts);
64
- continue;
65
- }
66
- const event = toThreadEvent(parsed, sequence, includeRaw);
67
- if (!event) continue;
68
- events.push(event);
69
- updateTranscriptStats(stats, event);
70
- sequence += 1;
71
- if (events.length >= maxEvents) break;
72
- }
73
- return {
74
- events,
75
- isPartial: Number.isFinite(maxEvents) || Number.isFinite(maxTurnContexts),
76
- rawIncluded: includeRaw,
77
- sessionMeta,
78
- sourceFileSizeBytes: options.sourceFileSizeBytes ?? null,
79
- stats,
80
- statsArePartial: Number.isFinite(maxEvents),
81
- turnContexts
82
- };
83
- };
84
- var captureSessionMeta$1 = (parsed, sessionMeta) => {
85
- if (parsed.type !== "session_meta") return;
86
- const payload = asObject(parsed.payload);
87
- if (!payload) return;
88
- sessionMeta.baseInstructions = payload.base_instructions ?? sessionMeta.baseInstructions;
89
- sessionMeta.cli_version = asString(payload.cli_version) ?? sessionMeta.cli_version;
90
- sessionMeta.cwd = asString(payload.cwd) ?? sessionMeta.cwd;
91
- sessionMeta.dynamicTools = parseDynamicTools(payload.dynamic_tools) ?? sessionMeta.dynamicTools;
92
- sessionMeta.git = asObject(payload.git) ?? sessionMeta.git;
93
- sessionMeta.id = asString(payload.id) ?? sessionMeta.id;
94
- sessionMeta.modelProvider = asString(payload.model_provider) ?? sessionMeta.modelProvider;
95
- sessionMeta.originator = asString(payload.originator) ?? sessionMeta.originator;
96
- sessionMeta.source = asString(payload.source) ?? sessionMeta.source;
97
- sessionMeta.threadSource = asString(payload.thread_source) ?? sessionMeta.threadSource;
98
- sessionMeta.timestamp = asString(payload.timestamp) ?? sessionMeta.timestamp;
99
- };
100
- var parseDynamicTools = (value) => {
101
- if (!Array.isArray(value)) return null;
102
- return value.flatMap((entry) => {
103
- const tool = asObject(entry);
104
- if (!tool) return [];
105
- return [{
106
- deferLoading: tool.deferLoading === true || tool.defer_loading === true,
107
- description: asString(tool.description) ?? "",
108
- inputSchema: asObject(tool.inputSchema) ?? asObject(tool.input_schema) ?? null,
109
- name: asString(tool.name) ?? "unknown",
110
- namespace: asString(tool.namespace)
111
- }];
112
- });
113
- };
114
- var captureTurnContext = (parsed, turnContexts) => {
115
- const payload = asObject(parsed.payload);
116
- if (!payload) return;
117
- turnContexts.push({
118
- payload,
119
- timestamp: asString(parsed.timestamp)
120
- });
121
- };
122
- var toThreadEvent = (parsed, sequence, includeRaw) => {
123
- const payload = asObject(parsed.payload);
124
- if (!payload) return null;
125
- const payloadType = asString(payload.type);
126
- const timestamp = asString(parsed.timestamp);
127
- if (parsed.type === "event_msg") return buildEventMessage(payload, payloadType, includeRaw ? parsed : {}, sequence, timestamp);
128
- if (parsed.type !== "response_item") return null;
129
- return buildResponseItemEvent(payload, payloadType, includeRaw ? parsed : {}, sequence, timestamp);
130
- };
131
- var buildEventMessage = (payload, payloadType, raw, sequence, timestamp) => {
132
- if (payloadType === "task_started") return createTaskStartedEvent(payload, raw, sequence, timestamp);
133
- if (payloadType === "task_complete") return createTaskCompleteEvent(payload, raw, sequence, timestamp);
134
- return null;
135
- };
136
- var buildResponseItemEvent = (payload, payloadType, raw, sequence, timestamp) => {
137
- if (payloadType === "message") return createMessageEvent(payload, raw, sequence, timestamp);
138
- if (payloadType === "user_message") return createUserMessageEvent(payload, raw, sequence, timestamp);
139
- if (payloadType === "agent_message") return createAgentMessageEvent(payload, raw, sequence, timestamp);
140
- if (payloadType === "function_call") return createToolCallEvent(payload, raw, sequence, timestamp);
141
- if (payloadType === "function_call_output") return createToolOutputEvent(payload, raw, sequence, timestamp);
142
- if (payloadType === "reasoning") return createReasoningEvent(payload, raw, sequence, timestamp);
143
- if (payloadType === "token_count") return createTokenCountEvent(payload, raw, sequence, timestamp);
144
- if (payloadType === "web_search_call" || payloadType === "web_search_end") return createWebSearchEvent(payload, raw, sequence, timestamp);
145
- if (payloadType === "task_started") return createTaskStartedEvent(payload, raw, sequence, timestamp);
146
- if (payloadType === "task_complete") return createTaskCompleteEvent(payload, raw, sequence, timestamp);
147
- return null;
148
- };
149
- var createMessageEvent = (payload, raw, sequence, timestamp) => {
150
- const role = asString(payload.role);
151
- const content = payload.content;
152
- if (!role || content === void 0) return null;
153
- return {
154
- isHiddenByDefault: shouldHideTranscriptText(role, extractText$1(content)),
155
- kind: "message",
156
- memoryCitation: null,
157
- model: asString(payload.model),
158
- phase: asString(payload.phase),
159
- raw,
160
- role,
161
- sequence,
162
- text: extractText$1(content),
163
- timestamp,
164
- variant: "message"
165
- };
166
- };
167
- var createUserMessageEvent = (payload, raw, sequence, timestamp) => {
168
- return {
169
- isHiddenByDefault: shouldHideTranscriptText("user", asString(payload.message)?.trim() ?? ""),
170
- kind: "message",
171
- memoryCitation: null,
172
- model: null,
173
- phase: null,
174
- raw,
175
- role: "user",
176
- sequence,
177
- text: asString(payload.message)?.trim() ?? "",
178
- timestamp,
179
- variant: "user_message"
180
- };
181
- };
182
- var createAgentMessageEvent = (payload, raw, sequence, timestamp) => {
183
- return {
184
- isHiddenByDefault: false,
185
- kind: "message",
186
- memoryCitation: payload.memory_citation ?? null,
187
- model: asString(payload.model),
188
- phase: asString(payload.phase),
189
- raw,
190
- role: "assistant",
191
- sequence,
192
- text: asString(payload.message)?.trim() ?? "",
193
- timestamp,
194
- variant: "agent_message"
195
- };
196
- };
197
- var createToolCallEvent = (payload, raw, sequence, timestamp) => {
198
- const name = asString(payload.name) ?? "unknown";
199
- const argumentsText = asString(payload.arguments);
200
- const parsedArguments = parseExecCommandArguments$1(argumentsText);
201
- return {
202
- argumentsParseFailed: parsedArguments.argumentsParseFailed,
203
- argumentsText,
204
- callId: asString(payload.call_id),
205
- command: parsedArguments.cmd,
206
- kind: "tool_call",
207
- name,
208
- raw,
209
- sequence,
210
- timestamp,
211
- workdir: parsedArguments.workdir
212
- };
213
- };
214
- var createToolOutputEvent = (payload, raw, sequence, timestamp) => {
215
- const outputText = asString(payload.output) ?? "";
216
- return {
217
- callId: asString(payload.call_id),
218
- exitCode: parseExitCode(outputText),
219
- kind: "tool_output",
220
- outputText,
221
- raw,
222
- sequence,
223
- summary: formatToolOutputSummary$1(outputText),
224
- timestamp,
225
- wallTime: parseWallTime(outputText)
226
- };
227
- };
228
- var createReasoningEvent = (payload, raw, sequence, timestamp) => {
229
- return {
230
- content: payload.content ?? null,
231
- hasEncryptedContent: Boolean(asString(payload.encrypted_content)),
232
- kind: "reasoning",
233
- raw,
234
- sequence,
235
- summary: toStringArray(payload.summary),
236
- timestamp
237
- };
238
- };
239
- var createTokenCountEvent = (payload, raw, sequence, timestamp) => {
240
- return {
241
- info: payload.info ?? null,
242
- kind: "token_count",
243
- rateLimits: payload.rate_limits ?? null,
244
- raw,
245
- sequence,
246
- timestamp
247
- };
248
- };
249
- var createTaskStartedEvent = (payload, raw, sequence, timestamp) => {
250
- return {
251
- collaborationModeKind: asString(payload.collaboration_mode_kind),
252
- kind: "task_started",
253
- modelContextWindow: asNumber(payload.model_context_window),
254
- raw,
255
- sequence,
256
- startedAt: asNumber(payload.started_at),
257
- timestamp,
258
- turnId: asString(payload.turn_id)
259
- };
260
- };
261
- var createTaskCompleteEvent = (payload, raw, sequence, timestamp) => {
262
- return {
263
- completedAt: asNumber(payload.completed_at),
264
- durationMs: asNumber(payload.duration_ms),
265
- kind: "task_complete",
266
- lastAgentMessage: asString(payload.last_agent_message),
267
- raw,
268
- sequence,
269
- timestamp,
270
- timeToFirstTokenMs: asNumber(payload.time_to_first_token_ms),
271
- turnId: asString(payload.turn_id)
272
- };
273
- };
274
- var createWebSearchEvent = (payload, raw, sequence, timestamp) => {
275
- const payloadType = asString(payload.type);
276
- return {
277
- action: payload.action ?? null,
278
- callId: asString(payload.call_id),
279
- kind: "web_search",
280
- phase: payloadType === "web_search_end" ? "end" : "call",
281
- query: asString(payload.query),
282
- raw,
283
- sequence,
284
- status: asString(payload.status),
285
- timestamp
286
- };
287
- };
288
- var updateTranscriptStats = (stats, event) => {
289
- if (event.kind === "message") {
290
- stats.messageCount += 1;
291
- if (event.role === "assistant") stats.assistantMessageCount += 1;
292
- if (event.role === "user") stats.userMessageCount += 1;
293
- if (event.phase === "commentary") stats.commentaryCount += 1;
294
- if (event.phase === "final_answer") stats.finalAnswerCount += 1;
295
- return;
296
- }
297
- if (event.kind === "tool_call") {
298
- stats.toolCallCount += 1;
299
- if (event.name === "exec_command") stats.execCommandCount += 1;
300
- return;
301
- }
302
- if (event.kind === "tool_output") {
303
- stats.toolOutputCount += 1;
304
- return;
305
- }
306
- if (event.kind === "web_search") stats.webSearchEventCount += 1;
307
- };
308
- var toStringArray = (value) => {
309
- if (!Array.isArray(value)) return [];
310
- return value.map((entry) => asString(entry)).filter((entry) => Boolean(entry));
311
- };
312
- var parseExitCode = (outputText) => {
313
- const match = /Process exited with code (\d+)/u.exec(outputText);
314
- return match ? Number(match[1]) : null;
315
- };
316
- var parseWallTime = (outputText) => {
317
- return /Wall time: ([^\n]+)/u.exec(outputText)?.[1] ?? null;
318
- };
319
- var formatToolOutputSummary$1 = (outputText) => {
320
- return outputText.split("\n").map((line) => line.trim()).filter(Boolean).filter((line) => {
321
- return line.startsWith("Command: ") || line.startsWith("Process exited with code ") || line.startsWith("Wall time: ");
322
- }).join("\n");
323
- };
324
- var parseExecCommandArguments$1 = (argumentsText) => {
325
- if (!argumentsText) return {
326
- argumentsParseFailed: false,
327
- cmd: null,
328
- workdir: null
329
- };
330
- try {
331
- const parsed = JSON.parse(argumentsText);
332
- return {
333
- argumentsParseFailed: false,
334
- cmd: typeof parsed.cmd === "string" ? parsed.cmd : null,
335
- workdir: typeof parsed.workdir === "string" ? parsed.workdir : null
336
- };
337
- } catch {
338
- return {
339
- argumentsParseFailed: true,
340
- cmd: null,
341
- workdir: null
342
- };
343
- }
344
- };
345
- var extractText$1 = (content) => {
346
- if (typeof content === "string") return content.trim();
347
- if (Array.isArray(content)) return content.map((entry) => extractTextPart(entry)).filter(Boolean).join("\n\n").trim();
348
- if (content && typeof content === "object") return asString(content.text)?.trim() ?? "";
349
- return "";
350
- };
351
- var extractTextPart = (entry) => {
352
- const objectValue = asObject(entry);
353
- if (!objectValue) return "";
354
- const type = asString(objectValue.type);
355
- const text = asString(objectValue.text);
356
- if (type === "input_image") return "[Image attached]";
357
- return text ?? "";
358
- };
359
- var shouldHideTranscriptText = (role, text) => {
360
- if (!text) return true;
361
- if (role === "developer") return true;
362
- return text.startsWith("# AGENTS.md instructions for ") || text.startsWith("<permissions instructions>") || text.startsWith("<app-context>") || text.startsWith("<environment_context>") || text.startsWith("<collaboration_mode>") || text.startsWith("<skills_instructions>") || text.startsWith("<plugins_instructions>") || text.includes("Filesystem sandboxing defines which files can be read or written.");
363
- };
364
- //#endregion
365
- //#region ../../src/lib/ui-cache.ts
366
- var CACHE_DIR = path.join(os.tmpdir(), "spiracha-ui-cache");
367
- var CACHE_ENVELOPE_VERSION = 1;
368
- var ensureCacheDir = async () => {
369
- await mkdir(CACHE_DIR, { recursive: true });
370
- };
371
- var toCachePath = (key) => {
372
- const safeKey = key.replace(/[^a-zA-Z0-9._-]/gu, "_");
373
- return path.join(CACHE_DIR, `${safeKey}-${hashCacheKeyParts(key)}.json`);
374
- };
375
- var hashCacheKeyParts = (...parts) => {
376
- return createHash("sha1").update(parts.join("|")).digest("hex");
377
- };
378
- var hashCacheKeyPartsIterable = (parts) => {
379
- const hash = createHash("sha1");
380
- for (const part of parts) {
381
- hash.update(String(part.length));
382
- hash.update(":");
383
- hash.update(part);
384
- hash.update(";");
385
- }
386
- return hash.digest("hex");
387
- };
388
- var getFileFingerprint = async (filePath) => {
389
- const metadata = await stat(filePath);
390
- return `${filePath}:${metadata.size}:${metadata.mtimeMs}`;
391
- };
392
- var getCachedJson = async (key) => {
393
- await ensureCacheDir();
394
- const filePath = toCachePath(key);
395
- const file = Bun.file(filePath);
396
- if (!await file.exists()) return null;
397
- let parsed;
398
- try {
399
- parsed = await file.json();
400
- } catch {
401
- await rm(filePath, { force: true });
402
- return null;
403
- }
404
- if (parsed && typeof parsed === "object" && "version" in parsed && parsed.version === CACHE_ENVELOPE_VERSION && "value" in parsed) return parsed.value;
405
- await rm(filePath, { force: true });
406
- return null;
407
- };
408
- var setCachedJson = async (key, value) => {
409
- await ensureCacheDir();
410
- const filePath = toCachePath(key);
411
- const tempPath = `${filePath}.${randomUUID()}.tmp`;
412
- const envelope = {
413
- value,
414
- version: CACHE_ENVELOPE_VERSION
415
- };
416
- await Bun.write(tempPath, JSON.stringify(envelope));
417
- await rename(tempPath, filePath);
418
- };
419
- var withCachedJson = async (key, loader) => {
420
- const filePath = toCachePath(key);
421
- const existedBeforeRead = await Bun.file(filePath).exists();
422
- const cached = await getCachedJson(key);
423
- if (cached !== null || existedBeforeRead && await Bun.file(filePath).exists()) return cached;
424
- const value = await loader();
425
- await setCachedJson(key, value);
426
- return value;
427
- };
428
- var invalidateCacheByPrefix = async (...prefixes) => {
429
- await ensureCacheDir();
430
- const entries = await readdir(CACHE_DIR);
431
- await Promise.all(entries.filter((entry) => prefixes.some((prefix) => entry.startsWith(prefix))).map((entry) => rm(path.join(CACHE_DIR, entry), { force: true })));
432
- };
433
- //#endregion
434
- //#region ../../src/lib/codex-thread-cache.ts
435
- var LARGE_THREAD_SIZE_BYTES = 100 * 1024 * 1024;
436
- var getCachedParsedCodexTranscript = async (sessionFile) => {
437
- const fingerprint = await getFileFingerprint(sessionFile);
438
- return withCachedJson(`thread-${hashCacheKeyParts(path.basename(sessionFile), fingerprint)}`, async () => parseCodexTranscriptFile(sessionFile));
439
- };
440
- var getThreadRolloutLoadState = async (sessionFile, largeTranscriptThresholdBytes = LARGE_THREAD_SIZE_BYTES) => {
441
- const metadata = await stat(sessionFile);
442
- return {
443
- fileSizeBytes: metadata.size,
444
- shouldDeferTranscriptLoad: metadata.size > largeTranscriptThresholdBytes
445
- };
446
- };
447
- var getCachedThreadTranscriptPreview = async (sessionFile, options = {}) => {
448
- const threshold = options.largeTranscriptThresholdBytes ?? 104857600;
449
- const previewEventLimit = options.previewEventLimit ?? 200;
450
- const fingerprint = await getFileFingerprint(sessionFile);
451
- const { fileSizeBytes, shouldDeferTranscriptLoad } = await getThreadRolloutLoadState(sessionFile, threshold);
452
- return withCachedJson(`thread-preview-${hashCacheKeyParts(path.basename(sessionFile), fingerprint, String(threshold), String(previewEventLimit))}`, async () => {
453
- if (!shouldDeferTranscriptLoad) return parseCodexTranscriptFile(sessionFile, { sourceFileSizeBytes: fileSizeBytes });
454
- return parseCodexTranscriptFile(sessionFile, {
455
- includeRaw: false,
456
- maxEvents: previewEventLimit,
457
- maxTurnContexts: 0,
458
- sourceFileSizeBytes: fileSizeBytes
459
- });
460
- });
461
- };
462
- //#endregion
463
- //#region ../../src/lib/sqlite-retry.ts
464
- var DEFAULT_RETRY_DELAYS_MS = [
465
- 40,
466
- 120,
467
- 250
468
- ];
469
- var SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
470
- var sleepSync = (delayMs) => {
471
- if (delayMs <= 0) return;
472
- Atomics.wait(SLEEP_BUFFER, 0, 0, delayMs);
473
- };
474
- var toRetryExhaustedError = (attemptCount, error) => {
475
- const message = error instanceof Error ? error.message : String(error);
476
- return new Error(`SQLite operation failed after ${attemptCount} attempts: ${message}`, { cause: error });
477
- };
478
- var shouldRetrySqliteError = (error, attempt, delaysMs) => {
479
- return isRetryableSqliteError(error) && attempt < delaysMs.length;
480
- };
481
- var runWithSqliteRetry = ({ action, delaysMs = DEFAULT_RETRY_DELAYS_MS, sleep = sleepSync }) => {
482
- let attempt = 0;
483
- while (true) try {
484
- return action();
485
- } catch (error) {
486
- if (!shouldRetrySqliteError(error, attempt, delaysMs)) {
487
- if (isRetryableSqliteError(error)) throw toRetryExhaustedError(attempt + 1, error);
488
- throw error;
489
- }
490
- sleep(delaysMs[attempt] ?? 0);
491
- attempt += 1;
492
- }
493
- };
494
- //#endregion
495
- //#region ../../src/lib/codex-browser-db.ts
496
- var SQLITE_DELETE_BATCH_SIZE = 400;
497
- var SESSION_FILE_DELETE_CONCURRENCY = 16;
498
- var THREAD_LIST_IO_CONCURRENCY = 8;
499
- var chunkValues = (values, chunkSize) => {
500
- const chunks = [];
501
- for (let index = 0; index < values.length; index += chunkSize) chunks.push(values.slice(index, index + chunkSize));
502
- return chunks;
503
- };
504
- var isPromiseLike = (value) => {
505
- if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
506
- return "then" in value && typeof value.then === "function";
507
- };
508
- var openReadonlyDb = (dbPath, busyTimeoutMs) => {
509
- const db = new Database(dbPath, { readonly: true });
510
- try {
511
- db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}`);
512
- return db;
513
- } catch (error) {
514
- db.close();
515
- throw error;
516
- }
517
- };
518
- var openWritableDb = (dbPath, busyTimeoutMs) => {
519
- const db = new Database(dbPath);
520
- try {
521
- db.exec(`PRAGMA busy_timeout = ${busyTimeoutMs}`);
522
- return db;
523
- } catch (error) {
524
- db.close();
525
- throw error;
526
- }
527
- };
528
- var toTimestampMs = (thread) => {
529
- return thread.updated_at_ms ?? thread.updated_at * 1e3;
530
- };
531
- var parseDynamicToolRow = (row) => {
532
- return {
533
- deferLoading: Number(row.defer_loading ?? 0) === 1,
534
- description: String(row.description ?? ""),
535
- inputSchema: parseJsonSafely$1(typeof row.input_schema === "string" ? row.input_schema : null),
536
- name: String(row.name ?? "unknown"),
537
- namespace: typeof row.namespace === "string" ? row.namespace : null,
538
- position: Number(row.position ?? 0),
539
- threadId: String(row.thread_id)
540
- };
541
- };
542
- var parseJsonSafely$1 = (value) => {
543
- if (!value) return null;
544
- try {
545
- return JSON.parse(value);
546
- } catch {
547
- return null;
548
- }
549
- };
550
- var withReadonlyDb = (dbPath, callback) => {
551
- return runWithSqliteRetry({ action: () => {
552
- const db = openReadonlyDb(dbPath, 5e3);
553
- try {
554
- const result = callback(db);
555
- if (isPromiseLike(result)) throw new Error("Database callbacks must be synchronous");
556
- return result;
557
- } finally {
558
- db.close();
559
- }
560
- } });
561
- };
562
- var withWritableDb = (dbPath, callback) => {
563
- const db = runWithSqliteRetry({ action: () => {
564
- return openWritableDb(dbPath, 5e3);
565
- } });
566
- try {
567
- const result = callback(db);
568
- if (isPromiseLike(result)) throw new Error("Database callbacks must be synchronous");
569
- return result;
570
- } finally {
571
- db.close();
572
- }
573
- };
574
- var resolveCodexThreadDbPath = () => {
575
- const configuredDbPath = process.env.SPIRACHA_CODEX_DB?.trim();
576
- if (configuredDbPath) return configuredDbPath;
577
- const candidates = [
578
- DEFAULT_DB_PATH,
579
- path.join(DEFAULT_CODEX_DIR, "sqlite", "state_5.sqlite"),
580
- path.join(os.homedir(), ".codex", "state_5.sqlite")
581
- ];
582
- for (const candidate of candidates) try {
583
- runWithSqliteRetry({ action: () => {
584
- return openReadonlyDb(candidate, 1500);
585
- } }).close();
586
- return candidate;
587
- } catch {}
588
- throw new Error(`Unable to open Codex thread database. Tried: ${candidates.join(", ")}`);
589
- };
590
- var readAllThreads = (dbPath) => {
591
- return withReadonlyDb(dbPath, (db) => {
592
- return db.query("SELECT * FROM threads ORDER BY COALESCE(updated_at_ms, updated_at * 1000) DESC, id DESC").all();
593
- });
594
- };
595
- var filterThreadsByProject = (threads, projectName) => {
596
- if (!projectName) return threads;
597
- return threads.filter((thread) => getPortablePathBasename(thread.cwd) === projectName);
598
- };
599
- var buildProjectSummaryMap = (threads) => {
600
- const projectMap = /* @__PURE__ */ new Map();
601
- for (const thread of threads) {
602
- const projectName = getPortablePathBasename(thread.cwd);
603
- if (!projectName) continue;
604
- const current = projectMap.get(projectName) ?? {
605
- archivedThreadCount: 0,
606
- cwdPaths: /* @__PURE__ */ new Set(),
607
- lastUpdatedAtMs: null,
608
- modelNames: /* @__PURE__ */ new Set(),
609
- name: projectName,
610
- threadCount: 0,
611
- totalTokens: 0
612
- };
613
- current.archivedThreadCount += thread.archived ? 1 : 0;
614
- current.cwdPaths.add(thread.cwd);
615
- current.lastUpdatedAtMs = Math.max(current.lastUpdatedAtMs ?? 0, toTimestampMs(thread));
616
- if (thread.model) current.modelNames.add(thread.model);
617
- current.threadCount += 1;
618
- current.totalTokens += thread.tokens_used;
619
- projectMap.set(projectName, current);
620
- }
621
- return projectMap;
622
- };
623
- var mapProjectSummaries = (projectMap) => {
624
- return [...projectMap.values()].map((project) => {
625
- return {
626
- archivedThreadCount: project.archivedThreadCount,
627
- cwdPaths: [...project.cwdPaths].sort(),
628
- lastUpdatedAtMs: project.lastUpdatedAtMs,
629
- modelNames: [...project.modelNames].sort(),
630
- name: project.name,
631
- threadCount: project.threadCount,
632
- totalTokens: project.totalTokens
633
- };
634
- }).sort((left, right) => {
635
- if (left.totalTokens !== right.totalTokens) return right.totalTokens - left.totalTokens;
636
- return left.name.localeCompare(right.name);
637
- });
638
- };
639
- var getRelationsForThread = (db, threadId, existingTableNames) => {
640
- if (!existingTableNames.has("thread_spawn_edges")) return {
641
- childEdges: [],
642
- parentThreadId: null
643
- };
644
- const parentRow = db.query("SELECT parent_thread_id, child_thread_id, status FROM thread_spawn_edges WHERE child_thread_id = ? LIMIT 1").get(threadId);
645
- return {
646
- childEdges: db.query("SELECT parent_thread_id, child_thread_id, status FROM thread_spawn_edges WHERE parent_thread_id = ? ORDER BY child_thread_id ASC").all(threadId),
647
- parentThreadId: parentRow?.parent_thread_id ?? null
648
- };
649
- };
650
- var getExistingTableNames = (db) => {
651
- const rows = db.query("SELECT name FROM sqlite_master WHERE type = ?").all("table");
652
- return new Set(rows.map((row) => row.name));
653
- };
654
- var getThreadDeleteTargets = (db, threadIds) => {
655
- if (threadIds.length === 0) return [];
656
- const targets = [];
657
- for (const threadIdChunk of chunkValues(threadIds, SQLITE_DELETE_BATCH_SIZE)) {
658
- const placeholders = threadIdChunk.map(() => "?").join(", ");
659
- targets.push(...db.query(`SELECT id, rollout_path FROM threads WHERE id IN (${placeholders})`).all(...threadIdChunk));
660
- }
661
- return targets;
662
- };
663
- var deleteThreadIds = (db, threadIds) => {
664
- if (threadIds.length === 0) return {
665
- deletedSessionFiles: [],
666
- deletedThreadIds: []
667
- };
668
- const existingTableNames = getExistingTableNames(db);
669
- const threadTargets = getThreadDeleteTargets(db, threadIds);
670
- const existingIds = threadTargets.map((target) => target.id);
671
- if (existingIds.length === 0) return {
672
- deletedSessionFiles: [],
673
- deletedThreadIds: []
674
- };
675
- db.transaction((ids) => {
676
- for (const threadIdChunk of chunkValues(ids, SQLITE_DELETE_BATCH_SIZE)) {
677
- const placeholders = threadIdChunk.map(() => "?").join(", ");
678
- if (existingTableNames.has("thread_dynamic_tools")) db.query(`DELETE FROM thread_dynamic_tools WHERE thread_id IN (${placeholders})`).run(...threadIdChunk);
679
- if (existingTableNames.has("thread_goals")) db.query(`DELETE FROM thread_goals WHERE thread_id IN (${placeholders})`).run(...threadIdChunk);
680
- if (existingTableNames.has("stage1_outputs")) db.query(`DELETE FROM stage1_outputs WHERE thread_id IN (${placeholders})`).run(...threadIdChunk);
681
- if (existingTableNames.has("thread_spawn_edges")) db.query(`DELETE FROM thread_spawn_edges WHERE parent_thread_id IN (${placeholders}) OR child_thread_id IN (${placeholders})`).run(...threadIdChunk, ...threadIdChunk);
682
- db.query(`DELETE FROM threads WHERE id IN (${placeholders})`).run(...threadIdChunk);
683
- }
684
- })(existingIds);
685
- return {
686
- deletedSessionFiles: threadTargets.map((target) => target.rollout_path),
687
- deletedThreadIds: existingIds
688
- };
689
- };
690
- var deleteThreadSessionFiles = async (sessionFiles) => {
691
- const uniqueSessionFiles = [...new Set(sessionFiles)];
692
- await mapWithConcurrency(uniqueSessionFiles, SESSION_FILE_DELETE_CONCURRENCY, async (sessionFile) => {
693
- await rm(sessionFile, { force: true });
694
- return sessionFile;
695
- });
696
- return uniqueSessionFiles;
697
- };
698
- var listCodexProjects = (dbPath) => {
699
- return mapProjectSummaries(buildProjectSummaryMap(readAllThreads(dbPath)));
700
- };
701
- var compactThreadListRow = (thread) => {
702
- return {
703
- ...thread,
704
- preview: cleanInlineTitle(thread.preview || thread.first_user_message || ""),
705
- title: cleanInlineTitle(thread.title)
706
- };
707
- };
708
- var listProjectThreads = async (dbPath, projectName, options = {}) => {
709
- return (await mapWithConcurrency(filterThreadsByProject(readAllThreads(dbPath), projectName), THREAD_LIST_IO_CONCURRENCY, async (thread) => {
710
- const rollout = await getThreadRolloutLoadState(thread.rollout_path, options.largeTranscriptThresholdBytes);
711
- if (rollout.shouldDeferTranscriptLoad) return {
712
- project: projectName,
713
- rolloutSizeBytes: rollout.fileSizeBytes,
714
- stats: {
715
- deferred: true,
716
- execCommandCount: 0,
717
- toolCallCount: 0,
718
- webSearchEventCount: 0
719
- },
720
- thread: compactThreadListRow(thread)
721
- };
722
- const transcript = await getCachedParsedCodexTranscript(thread.rollout_path);
723
- return {
724
- project: projectName,
725
- rolloutSizeBytes: rollout.fileSizeBytes,
726
- stats: {
727
- deferred: false,
728
- execCommandCount: transcript.stats.execCommandCount,
729
- toolCallCount: transcript.stats.toolCallCount,
730
- webSearchEventCount: transcript.stats.webSearchEventCount
731
- },
732
- thread: compactThreadListRow(thread)
733
- };
734
- })).sort((left, right) => toTimestampMs(right.thread) - toTimestampMs(left.thread));
735
- };
736
- var getThreadBrowseData = (dbPath, threadId) => {
737
- return withReadonlyDb(dbPath, (db) => {
738
- const existingTableNames = getExistingTableNames(db);
739
- const thread = db.query("SELECT * FROM threads WHERE id = ? LIMIT 1").get(threadId);
740
- if (!thread) throw new Error(`Thread not found: ${threadId}`);
741
- return {
742
- dynamicTools: (existingTableNames.has("thread_dynamic_tools") ? db.query("SELECT thread_id, position, name, description, input_schema, defer_loading, namespace FROM thread_dynamic_tools WHERE thread_id = ? ORDER BY position ASC").all(threadId) : []).map((row) => parseDynamicToolRow(row)),
743
- project: getPortablePathBasename(thread.cwd),
744
- relations: getRelationsForThread(db, threadId, existingTableNames),
745
- thread
746
- };
747
- });
748
- };
749
- var getCodexDashboardSummary = (dbPath) => {
750
- const threads = readAllThreads(dbPath);
751
- const projects = mapProjectSummaries(buildProjectSummaryMap(threads));
752
- const threadsWithRelations = withReadonlyDb(dbPath, (db) => {
753
- if (!getExistingTableNames(db).has("thread_spawn_edges")) return 0;
754
- const rows = db.query("SELECT parent_thread_id, child_thread_id FROM thread_spawn_edges").all();
755
- return new Set(rows.flatMap((row) => [row.parent_thread_id, row.child_thread_id])).size;
756
- });
757
- return {
758
- activeThreads: threads.filter((thread) => !thread.archived).length,
759
- archivedThreads: threads.filter((thread) => Boolean(thread.archived)).length,
760
- recentThreads: threads.slice(0, 5).filter((thread) => Boolean(getPortablePathBasename(thread.cwd))).map((thread) => ({
761
- project: getPortablePathBasename(thread.cwd),
762
- thread: compactThreadListRow(thread)
763
- })),
764
- threadsWithRelations,
765
- topProjectsByThreadCount: [...projects].sort((left, right) => {
766
- if (left.threadCount !== right.threadCount) return right.threadCount - left.threadCount;
767
- return left.name.localeCompare(right.name);
768
- }).slice(0, 5),
769
- topProjectsByTokens: projects.slice(0, 5),
770
- totalProjects: projects.length,
771
- totalThreads: threads.length,
772
- totalTokens: threads.reduce((sum, thread) => sum + thread.tokens_used, 0)
773
- };
774
- };
775
- var deleteCodexThread = async (dbPath, threadId, options = {}) => {
776
- const result = withWritableDb(dbPath, (db) => {
777
- return deleteThreadIds(db, [threadId]);
778
- });
779
- try {
780
- if (options.deleteSessionFiles) return {
781
- ...result,
782
- deletedSessionFiles: await deleteThreadSessionFiles(result.deletedSessionFiles)
783
- };
784
- return {
785
- ...result,
786
- deletedSessionFiles: []
787
- };
788
- } finally {
789
- await invalidateCodexUiCaches();
790
- }
791
- };
792
- var deleteCodexThreads = async (dbPath, threadIds, options = {}) => {
793
- const result = withWritableDb(dbPath, (db) => {
794
- return deleteThreadIds(db, threadIds);
795
- });
796
- try {
797
- if (options.deleteSessionFiles) return {
798
- ...result,
799
- deletedSessionFiles: await deleteThreadSessionFiles(result.deletedSessionFiles)
800
- };
801
- return {
802
- ...result,
803
- deletedSessionFiles: []
804
- };
805
- } finally {
806
- await invalidateCodexUiCaches();
807
- }
808
- };
809
- var deleteCodexProject = async (dbPath, projectName, options = {}) => {
810
- const result = withWritableDb(dbPath, (db) => {
811
- return {
812
- ...deleteThreadIds(db, db.query("SELECT id, cwd FROM threads").all().filter((thread) => getPortablePathBasename(thread.cwd) === projectName).map((thread) => thread.id)),
813
- projectName
814
- };
815
- });
816
- try {
817
- if (options.deleteSessionFiles) return {
818
- ...result,
819
- deletedSessionFiles: await deleteThreadSessionFiles(result.deletedSessionFiles)
820
- };
821
- return {
822
- ...result,
823
- deletedSessionFiles: []
824
- };
825
- } finally {
826
- await invalidateCodexUiCaches();
827
- }
828
- };
829
- var listScopedThreads = (dbPath, projectName) => {
830
- return filterThreadsByProject(readAllThreads(dbPath), projectName);
831
- };
832
- var invalidateCodexUiCaches = async () => {
833
- await invalidateCacheByPrefix("analytics-", "thread-");
834
- };
835
- var resolveAnalyticsTranscriptConcurrency = (configuredValue = process.env.SPIRACHA_ANALYTICS_TRANSCRIPT_CONCURRENCY) => {
836
- const parsed = Number(configuredValue);
837
- if (!Number.isInteger(parsed) || parsed < 1) return 8;
838
- return parsed;
839
- };
840
- var roundToTwoDecimals = (value) => {
841
- return Number(value.toFixed(2));
842
- };
843
- var incrementCount = (counts, key) => {
844
- counts.set(key, (counts.get(key) ?? 0) + 1);
845
- };
846
- var toDistribution = (counts) => {
847
- return [...counts.entries()].map(([label, count]) => ({
848
- count,
849
- label
850
- })).sort((left, right) => {
851
- if (left.count !== right.count) return right.count - left.count;
852
- return left.label.localeCompare(right.label);
853
- });
854
- };
855
- var buildModelsByTokens = (threads) => {
856
- const models = /* @__PURE__ */ new Map();
857
- for (const thread of threads) {
858
- const model = thread.model ?? "unknown";
859
- const current = models.get(model) ?? {
860
- threadCount: 0,
861
- totalTokens: 0
862
- };
863
- current.threadCount += 1;
864
- current.totalTokens += thread.tokens_used;
865
- models.set(model, current);
866
- }
867
- return [...models.entries()].map(([model, value]) => ({
868
- model,
869
- ...value
870
- })).sort((left, right) => {
871
- if (left.totalTokens !== right.totalTokens) return right.totalTokens - left.totalTokens;
872
- return left.model.localeCompare(right.model);
873
- });
874
- };
875
- var timestampSignature = (thread) => {
876
- return String(thread.updated_at_ms ?? thread.updated_at * 1e3);
877
- };
878
- var threadMetadataCacheKeyParts = (thread) => [
879
- thread.id,
880
- thread.rollout_path,
881
- timestampSignature(thread),
882
- String(thread.created_at_ms ?? thread.created_at * 1e3),
883
- String(thread.tokens_used),
884
- String(thread.archived),
885
- String(thread.archived_at ?? ""),
886
- thread.cwd,
887
- thread.model ?? "",
888
- thread.model_provider,
889
- thread.cli_version,
890
- thread.title,
891
- thread.preview
892
- ];
893
- var buildCodexAnalyticsCacheKey = (dbPath, threads, project) => {
894
- return `analytics-${hashCacheKeyPartsIterable((function* () {
895
- yield "v2";
896
- yield dbPath;
897
- yield project ?? "all";
898
- yield String(threads.length);
899
- for (const thread of threads) yield* threadMetadataCacheKeyParts(thread);
900
- })())}`;
901
- };
902
- var buildThreadAnalyticsCacheKey = (thread) => {
903
- return `thread-analytics-${hashCacheKeyParts("v1", ...threadMetadataCacheKeyParts(thread))}`;
904
- };
905
- var parseThreadAnalyticsFile = async (sessionFile) => {
906
- const toolNames = [];
907
- let hasWebSearch = false;
908
- for await (const parsed of readJsonlObjects(sessionFile)) {
909
- if (parsed.type !== "response_item") continue;
910
- const payload = asObject(parsed.payload);
911
- if (!payload) continue;
912
- const payloadType = asString(payload.type);
913
- if (payloadType === "function_call") {
914
- toolNames.push(asString(payload.name) ?? "unknown");
915
- continue;
916
- }
917
- if (payloadType === "web_search_call" || payloadType === "web_search_end") hasWebSearch = true;
918
- }
919
- return {
920
- hasWebSearch,
921
- toolNames
922
- };
923
- };
924
- var getCachedThreadAnalytics = async (thread) => {
925
- return withCachedJson(buildThreadAnalyticsCacheKey(thread), () => parseThreadAnalyticsFile(thread.rollout_path));
926
- };
927
- var computeCodexAnalyticsFromThreads = async (threads, options = {}) => {
928
- const totalTokens = threads.reduce((sum, thread) => sum + thread.tokens_used, 0);
929
- const projectNames = new Set(threads.map((thread) => getPortablePathBasename(thread.cwd)).filter(Boolean));
930
- const toolUsage = /* @__PURE__ */ new Map();
931
- let threadsWithWebSearch = 0;
932
- const loadThreadAnalytics = options.loadThreadAnalytics ?? getCachedThreadAnalytics;
933
- const threadAnalytics = await mapWithConcurrency(threads, options.transcriptConcurrency ?? resolveAnalyticsTranscriptConcurrency(), (thread) => loadThreadAnalytics(thread));
934
- for (const analytics of threadAnalytics) {
935
- if (analytics.hasWebSearch) threadsWithWebSearch += 1;
936
- for (const toolName of analytics.toolNames) incrementCount(toolUsage, toolName);
937
- }
938
- return {
939
- modelsByTokens: buildModelsByTokens(threads),
940
- summary: {
941
- archivedThreads: threads.filter((thread) => Boolean(thread.archived)).length,
942
- averageTokensPerThread: threads.length === 0 ? 0 : roundToTwoDecimals(totalTokens / threads.length),
943
- distinctToolNames: toolUsage.size,
944
- threadsWithWebSearch,
945
- totalProjects: projectNames.size,
946
- totalThreads: threads.length,
947
- totalTokens
948
- },
949
- toolUsage: toDistribution(toolUsage).map((item) => ({
950
- count: item.count,
951
- name: item.label
952
- }))
953
- };
954
- };
955
- var getCodexAnalytics = async (input) => {
956
- const threads = listScopedThreads(input.dbPath, input.project);
957
- return withCachedJson(buildCodexAnalyticsCacheKey(input.dbPath, threads, input.project), async () => computeCodexAnalyticsFromThreads(threads, { transcriptConcurrency: input.transcriptConcurrency }));
958
- };
959
- //#endregion
960
- //#region ../../src/lib/codex-exporter-db.ts
961
- var matchesFilters = (value, options) => {
962
- return matchesCwdFilter(value, options.cwdFilter) && matchesProjectFilter(value, options.projectFilter);
963
- };
964
- var toCodexRelativePath = (targetPath) => {
965
- const codexRoot = path.resolve(DEFAULT_CODEX_DIR);
966
- const normalized = path.resolve(targetPath);
967
- if (normalized.startsWith(`${codexRoot}${path.sep}`)) return path.relative(codexRoot, normalized);
968
- return normalized;
969
- };
970
- var matchesCwdFilter = (value, cwdFilter) => {
971
- if (!cwdFilter) return true;
972
- return value === cwdFilter;
973
- };
974
- var matchesProjectFilter = (value, projectFilter) => {
975
- if (!projectFilter) return true;
976
- if (!value) return false;
977
- return getPortablePathBasename(value) === projectFilter;
978
- };
979
- //#endregion
980
- //#region ../../src/lib/codex-exporter-transcript.ts
981
- var convertSessionFile = async (target, options) => {
982
- let transcriptState;
983
- try {
984
- transcriptState = await collectCodexTranscript(target.sessionFile, options, target.thread?.model ?? null);
985
- } catch (error) {
986
- const message = error instanceof Error ? error.message : String(error);
987
- throw new Error(`Failed to read Codex transcript ${target.sessionFile}: ${message}`);
988
- }
989
- if (!matchesFilters(target.thread?.cwd ?? transcriptState.sessionMeta.cwd ?? null, options)) return null;
990
- if (transcriptState.sections.length === 0) return null;
991
- return [
992
- renderDocumentTitle(getTitle(target, transcriptState.sessionMeta), options.outputFormat),
993
- "",
994
- options.includeMetadata ? renderMetadataBlock(buildMetadataEntries(target, transcriptState.sessionMeta, options), options.outputFormat) : "",
995
- ...transcriptState.sections
996
- ].filter(Boolean).join("\n").trimEnd() + "\n";
997
- };
998
- var writeSessionFileExport = async (target, options, outputPath, transform = (text) => text) => {
999
- const transcriptOutputPath = `${outputPath}.transcript.tmp`;
1000
- let transcriptStream = null;
1001
- const state = {
1002
- assistantModel: target.thread?.model ?? null,
1003
- sections: [],
1004
- sessionMeta: {}
1005
- };
1006
- let wroteSection = false;
1007
- try {
1008
- transcriptStream = await createExportWriteStream(transcriptOutputPath);
1009
- for await (const parsed of readJsonlObjects(target.sessionFile)) {
1010
- captureSessionMeta(parsed, state.sessionMeta);
1011
- const block = renderCodexTranscriptRecord(parsed, options, state);
1012
- if (!block) continue;
1013
- transcriptStream.write(transform(wroteSection ? `${getSectionSeparator()}${block}` : block));
1014
- wroteSection = true;
1015
- }
1016
- await finalizeExportWriteStream(transcriptStream);
1017
- transcriptStream = null;
1018
- if (!matchesFilters(target.thread?.cwd ?? state.sessionMeta.cwd ?? null, options) || !wroteSection) return false;
1019
- const outputStream = await createExportWriteStream(outputPath);
1020
- try {
1021
- const prefix = buildStreamExportPrefix(target, state.sessionMeta, options);
1022
- if (prefix) outputStream.write(transform(prefix));
1023
- const transcriptReadStream = createReadStream(transcriptOutputPath, { encoding: "utf8" });
1024
- transcriptReadStream.pipe(outputStream, { end: false });
1025
- await finished(transcriptReadStream);
1026
- outputStream.write("\n");
1027
- await finalizeExportWriteStream(outputStream);
1028
- } catch (error) {
1029
- outputStream.destroy();
1030
- throw error;
1031
- }
1032
- return true;
1033
- } catch (error) {
1034
- if (transcriptStream) transcriptStream.destroy();
1035
- throw error;
1036
- } finally {
1037
- await rm(transcriptOutputPath, { force: true });
1038
- }
1039
- };
1040
- var collectCodexTranscript = async (sessionFile, options, assistantModel = null) => {
1041
- const state = {
1042
- assistantModel,
1043
- sections: [],
1044
- sessionMeta: {}
1045
- };
1046
- for await (const parsed of readJsonlObjects(sessionFile)) processCodexTranscriptRecord(parsed, options, state);
1047
- return state;
1048
- };
1049
- var getSectionSeparator = () => "\n";
1050
- var processCodexTranscriptRecord = (parsed, options, state) => {
1051
- captureSessionMeta(parsed, state.sessionMeta);
1052
- const block = renderCodexTranscriptRecord(parsed, options, state);
1053
- if (block) state.sections.push(block);
1054
- };
1055
- var renderCodexTranscriptRecord = (parsed, options, state) => {
1056
- const message = extractMessageRecord(parsed);
1057
- if (message) return processCodexMessageRecord(message, options, state);
1058
- if (!options.includeTools) return "";
1059
- const tool = extractToolRecord(parsed);
1060
- if (!tool) return "";
1061
- return renderToolBlock(tool, options.outputFormat);
1062
- };
1063
- var processCodexMessageRecord = (message, options, state) => {
1064
- return renderMessageBlock(message, options.outputFormat, state.assistantModel, options.includeCommentary);
1065
- };
1066
- var buildStreamExportPrefix = (target, sessionMeta, options) => {
1067
- if (!options.includeMetadata) return "";
1068
- return `${[
1069
- renderDocumentTitle(getTitle(target, sessionMeta), options.outputFormat),
1070
- "",
1071
- renderMetadataBlock(buildMetadataEntries(target, sessionMeta, options), options.outputFormat)
1072
- ].filter(Boolean).join("\n")}\n`;
1073
- };
1074
- var formatToolOutputSummary = (outputText, outputFormat) => {
1075
- if (!outputText) return "";
1076
- const lines = outputText.split("\n").map((line) => line.trim()).filter(Boolean);
1077
- if (lines.length === 0) return "";
1078
- const summaryLines = [];
1079
- const command = lines.find((line) => line.startsWith("Command: "));
1080
- const exit = lines.find((line) => line.startsWith("Process exited with code "));
1081
- const wall = lines.find((line) => line.startsWith("Wall time: "));
1082
- if (command) summaryLines.push(command);
1083
- if (exit) summaryLines.push(exit);
1084
- if (wall) summaryLines.push(wall);
1085
- if (outputFormat === "md") return summaryLines.map((line) => `*${line}*`).join("\n");
1086
- return summaryLines.join("\n");
1087
- };
1088
- var parseExecCommandArguments = (argumentsText) => {
1089
- if (!argumentsText) return {
1090
- argumentsParseFailed: false,
1091
- cmd: null,
1092
- workdir: null
1093
- };
1094
- try {
1095
- const parsed = JSON.parse(argumentsText);
1096
- return {
1097
- argumentsParseFailed: false,
1098
- cmd: typeof parsed.cmd === "string" ? parsed.cmd : null,
1099
- workdir: typeof parsed.workdir === "string" ? parsed.workdir : null
1100
- };
1101
- } catch {
1102
- return {
1103
- argumentsParseFailed: true,
1104
- cmd: null,
1105
- workdir: null
1106
- };
1107
- }
1108
- };
1109
- var getTitle = (target, sessionMeta) => {
1110
- if (target.thread?.title) return cleanInlineTitle(target.thread.title);
1111
- return sessionMeta.id ?? path.basename(target.sessionFile, ".jsonl");
1112
- };
1113
- var buildMetadataEntries = (target, sessionMeta, options) => {
1114
- return [
1115
- ...buildCodexExportIdentityMetadata(target, sessionMeta),
1116
- ...buildCodexExportPathMetadata(target, options),
1117
- ...buildCodexRelationMetadata(target),
1118
- ...buildCodexThreadMetadata(target, sessionMeta),
1119
- ...buildCodexAgentMetadata(target)
1120
- ];
1121
- };
1122
- var buildCodexExportIdentityMetadata = (target, sessionMeta) => {
1123
- const thread = target.thread;
1124
- return [
1125
- {
1126
- key: "exported_from",
1127
- value: thread ? "thread_db_and_session_jsonl" : "session_jsonl_fallback"
1128
- },
1129
- {
1130
- key: "fallback_reason",
1131
- value: target.fallbackReason
1132
- },
1133
- {
1134
- key: "thread_id",
1135
- value: thread?.id ?? sessionMeta.id ?? null
1136
- },
1137
- {
1138
- key: "title",
1139
- value: thread?.title || null
1140
- }
1141
- ];
1142
- };
1143
- var buildCodexExportPathMetadata = (target, options) => {
1144
- const relativeOutputPath = target.outputRelativePath;
1145
- return [
1146
- {
1147
- key: "source_output_relative_path",
1148
- value: relativeOutputPath
1149
- },
1150
- {
1151
- key: options.outputFormat === "md" ? "source_markdown_path" : "source_text_path",
1152
- value: relativeOutputPath
1153
- },
1154
- {
1155
- key: "rollout_path",
1156
- value: target.sessionFile
1157
- },
1158
- {
1159
- key: "rollout_path_relative_to_codex",
1160
- value: toCodexRelativePath(target.sessionFile)
1161
- }
1162
- ];
1163
- };
1164
- var buildCodexRelationMetadata = (target) => {
1165
- const childThreadIds = target.relations.childEdges.map((edge) => edge.child_thread_id);
1166
- const childEdges = target.relations.childEdges.map((edge) => ({
1167
- child_thread_id: edge.child_thread_id,
1168
- status: edge.status
1169
- }));
1170
- return [
1171
- {
1172
- key: "parent_thread_id",
1173
- value: target.relations.parentThreadId
1174
- },
1175
- {
1176
- key: "child_thread_ids",
1177
- value: childThreadIds
1178
- },
1179
- {
1180
- key: "spawn_edges",
1181
- value: childEdges
1182
- }
1183
- ];
1184
- };
1185
- var buildCodexThreadMetadata = (target, sessionMeta) => {
1186
- return [...buildCodexThreadTimingMetadata(target, sessionMeta), ...buildCodexThreadIdentityMetadata(target, sessionMeta)];
1187
- };
1188
- var buildCodexThreadTimingMetadata = (target, sessionMeta) => {
1189
- const thread = target.thread;
1190
- return [
1191
- {
1192
- key: "created_at_unix",
1193
- value: thread?.created_at ?? null
1194
- },
1195
- {
1196
- key: "created_at_iso",
1197
- value: formatUnixSeconds(thread?.created_at ?? null)
1198
- },
1199
- {
1200
- key: "updated_at_unix",
1201
- value: thread?.updated_at ?? null
1202
- },
1203
- {
1204
- key: "updated_at_iso",
1205
- value: formatUnixSeconds(thread?.updated_at ?? null)
1206
- },
1207
- {
1208
- key: "archived_at_unix",
1209
- value: thread?.archived_at ?? null
1210
- },
1211
- {
1212
- key: "archived_at_iso",
1213
- value: formatUnixSeconds(thread?.archived_at ?? null)
1214
- },
1215
- {
1216
- key: "session_started_at_iso",
1217
- value: sessionMeta.timestamp ?? null
1218
- }
1219
- ];
1220
- };
1221
- var buildCodexThreadIdentityMetadata = (target, sessionMeta) => {
1222
- const thread = target.thread;
1223
- return [
1224
- {
1225
- key: "archived",
1226
- value: thread ? Boolean(thread.archived) : null
1227
- },
1228
- {
1229
- key: "source",
1230
- value: thread?.source ?? sessionMeta.source ?? null
1231
- },
1232
- {
1233
- key: "originator",
1234
- value: sessionMeta.originator ?? null
1235
- },
1236
- {
1237
- key: "model_provider",
1238
- value: thread?.model_provider ?? null
1239
- },
1240
- {
1241
- key: "model",
1242
- value: thread?.model ?? null
1243
- },
1244
- {
1245
- key: "reasoning_effort",
1246
- value: thread?.reasoning_effort ?? null
1247
- },
1248
- {
1249
- key: "cli_version",
1250
- value: thread?.cli_version || sessionMeta.cli_version || null
1251
- },
1252
- {
1253
- key: "cwd",
1254
- value: thread?.cwd || sessionMeta.cwd || null
1255
- },
1256
- {
1257
- key: "approval_mode",
1258
- value: thread?.approval_mode ?? null
1259
- },
1260
- {
1261
- key: "sandbox_policy",
1262
- value: parseJsonSafely(thread?.sandbox_policy ?? null)
1263
- },
1264
- {
1265
- key: "memory_mode",
1266
- value: thread?.memory_mode ?? null
1267
- },
1268
- {
1269
- key: "tokens_used",
1270
- value: thread?.tokens_used ?? null
1271
- },
1272
- {
1273
- key: "has_user_event",
1274
- value: thread ? Boolean(thread.has_user_event) : null
1275
- }
1276
- ];
1277
- };
1278
- var buildCodexAgentMetadata = (target) => {
1279
- const thread = target.thread;
1280
- return [
1281
- {
1282
- key: "git_sha",
1283
- value: thread?.git_sha ?? null
1284
- },
1285
- {
1286
- key: "git_branch",
1287
- value: thread?.git_branch ?? null
1288
- },
1289
- {
1290
- key: "git_origin_url",
1291
- value: thread?.git_origin_url ?? null
1292
- },
1293
- {
1294
- key: "agent_nickname",
1295
- value: thread?.agent_nickname ?? null
1296
- },
1297
- {
1298
- key: "agent_role",
1299
- value: thread?.agent_role ?? null
1300
- },
1301
- {
1302
- key: "agent_path",
1303
- value: thread?.agent_path ?? null
1304
- },
1305
- {
1306
- key: "first_user_message",
1307
- value: thread?.first_user_message || null
1308
- }
1309
- ];
1310
- };
1311
- var parseJsonSafely = (value) => {
1312
- if (!value) return null;
1313
- try {
1314
- return JSON.parse(value);
1315
- } catch {
1316
- return value;
1317
- }
1318
- };
1319
- var formatUnixSeconds = (value) => {
1320
- if (value === null || value === void 0) return null;
1321
- return (/* @__PURE__ */ new Date(value * 1e3)).toISOString();
1322
- };
1323
- var captureSessionMeta = (parsed, meta) => {
1324
- if (parsed.type !== "session_meta") return;
1325
- const payload = asObject(parsed.payload);
1326
- if (!payload) return;
1327
- meta.id = asString(payload.id) ?? meta.id;
1328
- meta.timestamp = asString(payload.timestamp) ?? meta.timestamp;
1329
- meta.cwd = asString(payload.cwd) ?? meta.cwd;
1330
- meta.source = asString(payload.source) ?? meta.source;
1331
- meta.originator = asString(payload.originator) ?? meta.originator;
1332
- meta.cli_version = asString(payload.cli_version) ?? meta.cli_version;
1333
- };
1334
- var extractMessageRecord = (parsed) => {
1335
- if (parsed.type === "message") {
1336
- const directMessage = normalizeMessage(parsed);
1337
- if (directMessage) return directMessage;
1338
- }
1339
- if (parsed.type !== "response_item") return null;
1340
- const payload = asObject(parsed.payload);
1341
- if (!payload) return null;
1342
- if (payload.type !== "message" && payload.type !== "agent_message" && payload.type !== "user_message") return null;
1343
- return normalizeMessage(payload);
1344
- };
1345
- var normalizeMessage = (value) => {
1346
- const type = asString(value.type);
1347
- const role = asString(value.role) ?? (type === "agent_message" ? "assistant" : type === "user_message" ? "user" : null);
1348
- const content = value.content ?? asString(value.message);
1349
- const phase = asString(value.phase);
1350
- if (!role || content === void 0) return null;
1351
- return {
1352
- content,
1353
- model: asString(value.model),
1354
- phase: phase ?? void 0,
1355
- role
1356
- };
1357
- };
1358
- var extractToolRecord = (parsed) => {
1359
- if (parsed.type !== "response_item") return null;
1360
- const payload = asObject(parsed.payload);
1361
- if (!payload) return null;
1362
- if (payload.type === "function_call") {
1363
- const name = asString(payload.name);
1364
- const argumentsText = asString(payload.arguments);
1365
- const callId = asString(payload.call_id);
1366
- if (name !== "exec_command") return null;
1367
- return {
1368
- argumentsText: argumentsText ?? void 0,
1369
- callId,
1370
- kind: "call",
1371
- name
1372
- };
1373
- }
1374
- if (payload.type === "function_call_output") {
1375
- const callId = asString(payload.call_id);
1376
- const outputText = asString(payload.output);
1377
- if (!outputText?.includes("Command: ")) return null;
1378
- return {
1379
- callId,
1380
- kind: "output",
1381
- name: "function_call_output",
1382
- outputText: outputText ?? void 0
1383
- };
1384
- }
1385
- return null;
1386
- };
1387
- var renderMessageBlock = (message, outputFormat, assistantModel, includeCommentary) => {
1388
- if (message.role !== "user" && message.role !== "assistant") return "";
1389
- if (message.role === "assistant" && message.phase === "commentary" && !includeCommentary) return "";
1390
- const text = cleanExtractedText(stripPreviewBlock(extractText(message.content))).trim();
1391
- if (!text || shouldSkipMessage(message.role, text)) return "";
1392
- return renderSection(message.role === "user" ? "User" : formatModelLabel(message.model ?? assistantModel), message.phase ? `Phase: ${message.phase}\n\n${text}` : text, outputFormat);
1393
- };
1394
- var renderToolBlock = (tool, outputFormat) => {
1395
- if (tool.kind === "call") {
1396
- const details = formatToolCallDetails(tool, outputFormat);
1397
- return details ? renderSection("Tool", details, outputFormat) : "";
1398
- }
1399
- const summary = formatToolOutputSummary(tool.outputText ?? "", outputFormat);
1400
- return summary ? renderSection("Tool Output", summary, outputFormat) : "";
1401
- };
1402
- var stripPreviewBlock = (text) => {
1403
- const parts = text.split(/\n{2,}/).map((part) => part.trim()).filter(Boolean);
1404
- if (parts.length < 2) return text.trim();
1405
- const first = parts[0];
1406
- const second = parts[1];
1407
- const isTranscriptHeading = (value) => /^##\s+.+$/i.test(value);
1408
- if (!(!/^([UA]):/i.test(first) && !isTranscriptHeading(first) && /^([UA]):/i.test(second) === false && isTranscriptHeading(second))) return text.trim();
1409
- return parts.slice(1).join("\n\n");
1410
- };
1411
- var shouldSkipMessage = (role, text) => {
1412
- if (text.startsWith("<environment_context>")) return true;
1413
- if (text.startsWith("AGENTS.md instructions for ")) return true;
1414
- if (text.startsWith("# AGENTS.md instructions for ")) return true;
1415
- if (role === "user" && text.includes("<environment_context>")) return true;
1416
- return false;
1417
- };
1418
- var formatToolCallDetails = (tool, outputFormat) => {
1419
- if (tool.name !== "exec_command") return "";
1420
- const details = parseExecCommandArguments(tool.argumentsText);
1421
- return details.cmd ? `Command: ${formatInlineLiteral(details.cmd, outputFormat)}` : "";
1422
- };
1423
- var extractText = (content) => {
1424
- if (typeof content === "string") return content;
1425
- if (Array.isArray(content)) return content.map((item) => extractContentPart(item)).filter((part) => part.length > 0).join("\n\n");
1426
- if (content && typeof content === "object") {
1427
- const text = asString(content.text);
1428
- if (text) return text;
1429
- }
1430
- return "";
1431
- };
1432
- var extractContentPart = (value) => {
1433
- if (!value || typeof value !== "object" || Array.isArray(value)) return "";
1434
- const item = value;
1435
- const type = asString(item.type);
1436
- const text = asString(item.text);
1437
- if ((type === "input_text" || type === "output_text" || type === "text") && text) return text;
1438
- if (type === "input_image") return "[Image attached]";
1439
- return text ?? "";
1440
- };
1441
- //#endregion
1442
- //#region ../../src/lib/codex-browser-export.ts
1443
- var LARGE_BROWSER_EXPORT_THRESHOLD_BYTES = 128 * 1024 * 1024;
1444
- var formatReadableExportDate = (value) => {
1445
- const date = new Date(value);
1446
- return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(date.getUTCDate()).padStart(2, "0")}-${String(date.getUTCHours()).padStart(2, "0")}${String(date.getUTCMinutes()).padStart(2, "0")}`;
1447
- };
1448
- var buildExportBaseName = (thread) => {
1449
- return `${sanitizeExportFileName(getPortablePathBasename(thread.cwd) || "thread") || "thread"}-${formatReadableExportDate(thread.updated_at_ms ?? thread.updated_at * 1e3)}-${thread.id.slice(0, 8)}`;
1450
- };
1451
- var buildBatchExportBaseName = (threads) => {
1452
- const firstThread = threads[0];
1453
- if (!firstThread) throw new Error("No threads selected for export");
1454
- return `${sanitizeExportFileName(getPortablePathBasename(firstThread.cwd) || "threads") || "threads"}-${formatReadableExportDate(Math.max(...threads.map((thread) => thread.updated_at_ms ?? thread.updated_at * 1e3)))}-threads-${threads.length}`;
1455
- };
1456
- var buildUniqueArchivePath = (exportDir, exportBaseName) => {
1457
- return path.join(exportDir, `${exportBaseName}-${randomUUID()}.zip`);
1458
- };
1459
- var buildUniqueBatchEntryBaseName = (baseName, threadId, usedBaseNames) => {
1460
- if (!usedBaseNames.has(baseName)) {
1461
- usedBaseNames.add(baseName);
1462
- return baseName;
1463
- }
1464
- const collisionSafeBaseName = `${baseName}-${threadId}`;
1465
- usedBaseNames.add(collisionSafeBaseName);
1466
- return collisionSafeBaseName;
1467
- };
1468
- var toDownloadOptions = (input) => {
1469
- return {
1470
- cwdFilter: null,
1471
- dbPath: input.dbPath,
1472
- flat: false,
1473
- includeCommentary: input.includeCommentary,
1474
- includeMetadata: input.includeMetadata,
1475
- includeTools: input.includeTools,
1476
- inputDir: "",
1477
- outputDir: "",
1478
- outputFormat: input.outputFormat,
1479
- projectFilter: null,
1480
- threadIds: [input.threadId]
1481
- };
1482
- };
1483
- var resolvePublicExportDir = async (publicExportDir) => {
1484
- if (publicExportDir) {
1485
- await ensureDirectory(publicExportDir);
1486
- return publicExportDir;
1487
- }
1488
- return ensureUiExportDir();
1489
- };
1490
- var ensureDirectory = async (directoryPath) => {
1491
- await mkdir(directoryPath, { recursive: true });
1492
- };
1493
- var createExportWorkspace = async (exportDir, exportBaseName) => {
1494
- return mkdtemp(path.join(exportDir, `${exportBaseName}-`));
1495
- };
1496
- var getRolloutSnapshot = async (rolloutPath) => {
1497
- const metadata = await stat(rolloutPath);
1498
- return {
1499
- mtimeMs: metadata.mtimeMs,
1500
- sizeBytes: metadata.size
1501
- };
1502
- };
1503
- var logExportEvent = (level, event, details) => {
1504
- console[level](`[spiracha:export] ${event}`, details);
1505
- };
1506
- var logRolloutChangeIfDetected = (threadId, beforeSnapshot, afterSnapshot) => {
1507
- if (beforeSnapshot.mtimeMs === afterSnapshot.mtimeMs && beforeSnapshot.sizeBytes === afterSnapshot.sizeBytes) return;
1508
- logExportEvent("warn", "rollout_changed_during_export", {
1509
- afterMtimeMs: afterSnapshot.mtimeMs,
1510
- afterSizeBytes: afterSnapshot.sizeBytes,
1511
- beforeMtimeMs: beforeSnapshot.mtimeMs,
1512
- beforeSizeBytes: beforeSnapshot.sizeBytes,
1513
- threadId
1514
- });
1515
- };
1516
- var cleanupExportWorkspace = async (workspacePath) => {
1517
- try {
1518
- await rm(workspacePath, {
1519
- force: true,
1520
- recursive: true
1521
- });
1522
- } catch (error) {
1523
- logExportEvent("warn", "workspace_cleanup_failed", {
1524
- error: error instanceof Error ? error.message : String(error),
1525
- workspacePath
1526
- });
1527
- }
1528
- };
1529
- var renderCodexThreadDownload = async (input) => {
1530
- const startedAt = Date.now();
1531
- const browseData = getThreadBrowseData(input.dbPath, input.threadId);
1532
- const extension = input.outputFormat === "md" ? "md" : "txt";
1533
- const fileBaseName = buildExportBaseName(browseData.thread);
1534
- const fileName = `${fileBaseName}.${extension}`;
1535
- const mimeType = getExportMimeType(input.outputFormat);
1536
- const transform = (text) => input.pathDisplaySettings ? applyPathTransforms(text, {
1537
- ...input.pathDisplaySettings,
1538
- projectPath: browseData.thread.cwd
1539
- }) : text;
1540
- const rolloutSnapshotBefore = await getRolloutSnapshot(browseData.thread.rollout_path);
1541
- logExportEvent("info", "single_start", {
1542
- fileName,
1543
- sizeBytes: rolloutSnapshotBefore.sizeBytes,
1544
- threadId: input.threadId
1545
- });
1546
- try {
1547
- if (input.zipArchive || rolloutSnapshotBefore.sizeBytes > (input.largeExportThresholdBytes ?? LARGE_BROWSER_EXPORT_THRESHOLD_BYTES)) {
1548
- const exportBaseName = fileBaseName;
1549
- const exportDir = await resolvePublicExportDir(input.publicExportDir);
1550
- const workspaceDir = await createExportWorkspace(exportDir, exportBaseName);
1551
- const savedPath = path.join(workspaceDir, `${exportBaseName}.${extension}`);
1552
- const zipPath = buildUniqueArchivePath(exportDir, exportBaseName);
1553
- try {
1554
- if (!await writeSessionFileExport({
1555
- fallbackReason: null,
1556
- outputRelativePath: fileName,
1557
- relations: browseData.relations,
1558
- sessionFile: browseData.thread.rollout_path,
1559
- thread: browseData.thread
1560
- }, toDownloadOptions(input), savedPath, transform)) throw new Error(`Thread ${input.threadId} produced no exportable content`);
1561
- await zipExportFile(savedPath, zipPath);
1562
- } finally {
1563
- await cleanupExportWorkspace(workspaceDir);
1564
- }
1565
- const rolloutSnapshotAfter = await getRolloutSnapshot(browseData.thread.rollout_path);
1566
- logRolloutChangeIfDetected(input.threadId, rolloutSnapshotBefore, rolloutSnapshotAfter);
1567
- const zipStat = await Bun.file(zipPath).stat();
1568
- logExportEvent("info", "single_zip_ready", {
1569
- downloadUrl: buildUiExportDownloadUrl(zipPath),
1570
- durationMs: Date.now() - startedAt,
1571
- fileName: `${exportBaseName}.zip`,
1572
- sizeBytes: zipStat.size,
1573
- threadId: input.threadId,
1574
- zipPath
1575
- });
1576
- return {
1577
- downloadUrl: buildUiExportDownloadUrl(zipPath),
1578
- fileName: `${exportBaseName}.zip`,
1579
- mimeType: "application/zip",
1580
- mode: "download_url"
1581
- };
1582
- }
1583
- const content = await convertSessionFile({
1584
- fallbackReason: null,
1585
- outputRelativePath: fileName,
1586
- relations: browseData.relations,
1587
- sessionFile: browseData.thread.rollout_path,
1588
- thread: browseData.thread
1589
- }, toDownloadOptions(input));
1590
- if (!content) throw new Error(`Thread ${input.threadId} produced no exportable content`);
1591
- const rolloutSnapshotAfter = await getRolloutSnapshot(browseData.thread.rollout_path);
1592
- logRolloutChangeIfDetected(input.threadId, rolloutSnapshotBefore, rolloutSnapshotAfter);
1593
- logExportEvent("info", "single_inline_ready", {
1594
- durationMs: Date.now() - startedAt,
1595
- fileName,
1596
- sizeBytes: content.length,
1597
- threadId: input.threadId
1598
- });
1599
- return {
1600
- content: transform(content),
1601
- fileName,
1602
- mimeType,
1603
- mode: "download"
1604
- };
1605
- } catch (error) {
1606
- logExportEvent("error", "single_error", {
1607
- error: error instanceof Error ? error.message : String(error),
1608
- fileName,
1609
- threadId: input.threadId
1610
- });
1611
- throw error;
1612
- }
1613
- };
1614
- var renderCodexThreadsDownload = async (input) => {
1615
- const startedAt = Date.now();
1616
- const threadIds = [...new Set(input.threadIds)];
1617
- if (threadIds.length === 0) throw new Error("No threads selected for export");
1618
- const browseEntries = threadIds.map((threadId) => getThreadBrowseData(input.dbPath, threadId));
1619
- const threads = browseEntries.map((entry) => entry.thread);
1620
- const exportDir = await resolvePublicExportDir(input.publicExportDir);
1621
- const exportBaseName = buildBatchExportBaseName(threads);
1622
- const bundleDirectory = await createExportWorkspace(exportDir, exportBaseName);
1623
- const zipPath = buildUniqueArchivePath(exportDir, exportBaseName);
1624
- const usedBatchEntryBaseNames = /* @__PURE__ */ new Set();
1625
- logExportEvent("info", "batch_start", {
1626
- exportBaseName,
1627
- selectedThreadCount: threadIds.length,
1628
- selectedThreadIds: threadIds,
1629
- zipPath
1630
- });
1631
- try {
1632
- for (const entry of browseEntries) {
1633
- const rolloutSnapshotBefore = await getRolloutSnapshot(entry.thread.rollout_path);
1634
- const singleBaseName = buildExportBaseName(entry.thread);
1635
- const uniqueBaseName = buildUniqueBatchEntryBaseName(singleBaseName, entry.thread.id, usedBatchEntryBaseNames);
1636
- const relativeFileName = `${uniqueBaseName}.${input.outputFormat === "md" ? "md" : "txt"}`;
1637
- const savedPath = path.join(bundleDirectory, relativeFileName);
1638
- const transform = (text) => input.pathDisplaySettings ? applyPathTransforms(text, {
1639
- ...input.pathDisplaySettings,
1640
- projectPath: entry.thread.cwd
1641
- }) : text;
1642
- if (uniqueBaseName !== singleBaseName) logExportEvent("warn", "batch_entry_name_collision", {
1643
- resolvedFileName: relativeFileName,
1644
- singleBaseName,
1645
- threadId: entry.thread.id
1646
- });
1647
- if (!await writeSessionFileExport({
1648
- fallbackReason: null,
1649
- outputRelativePath: relativeFileName,
1650
- relations: entry.relations,
1651
- sessionFile: entry.thread.rollout_path,
1652
- thread: entry.thread
1653
- }, {
1654
- ...toDownloadOptions({
1655
- ...input,
1656
- threadId: entry.thread.id
1657
- }),
1658
- threadIds: [entry.thread.id]
1659
- }, savedPath, transform)) throw new Error(`Thread ${entry.thread.id} produced no exportable content`);
1660
- const rolloutSnapshotAfter = await getRolloutSnapshot(entry.thread.rollout_path);
1661
- logRolloutChangeIfDetected(entry.thread.id, rolloutSnapshotBefore, rolloutSnapshotAfter);
1662
- }
1663
- await zipExportDirectory(bundleDirectory, zipPath);
1664
- } catch (error) {
1665
- logExportEvent("error", "batch_error", {
1666
- error: error instanceof Error ? error.message : String(error),
1667
- exportBaseName,
1668
- selectedThreadCount: threadIds.length,
1669
- selectedThreadIds: threadIds,
1670
- zipPath
1671
- });
1672
- throw error;
1673
- } finally {
1674
- await cleanupExportWorkspace(bundleDirectory);
1675
- }
1676
- const zipStat = await Bun.file(zipPath).stat();
1677
- logExportEvent("info", "batch_ready", {
1678
- downloadUrl: buildUiExportDownloadUrl(zipPath),
1679
- durationMs: Date.now() - startedAt,
1680
- fileName: `${exportBaseName}.zip`,
1681
- selectedThreadCount: threadIds.length,
1682
- selectedThreadIds: threadIds,
1683
- sizeBytes: zipStat.size,
1684
- zipPath
1685
- });
1686
- return {
1687
- downloadUrl: buildUiExportDownloadUrl(zipPath),
1688
- fileName: `${exportBaseName}.zip`,
1689
- mimeType: "application/zip",
1690
- mode: "download_url"
1691
- };
1692
- };
1693
- //#endregion
1694
- //#region ../../src/lib/codex-thread-recovery.ts
1695
- var backupFile = async (filePath, label) => {
1696
- const backupPath = `${filePath}.bak-${label}-${(/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "").replace(/\.\d{3}Z$/, "Z").replace("T", "-")}`;
1697
- await copyFile(filePath, backupPath);
1698
- return backupPath;
1699
- };
1700
- var resolveCodexDirFromDbPath = (dbPath) => {
1701
- const dbDir = path.dirname(dbPath);
1702
- return path.basename(dbDir) === "sqlite" ? path.dirname(dbDir) : dbDir;
1703
- };
1704
- var assertRequiredStatePath = async (filePath) => {
1705
- if (!await Bun.file(filePath).exists()) throw new Error(`Required Codex state file not found: ${filePath}`);
1706
- };
1707
- var readGlobalState = async (globalStatePath) => {
1708
- return await Bun.file(globalStatePath).json();
1709
- };
1710
- var writeGlobalState = async (globalStatePath, state) => {
1711
- await Bun.write(globalStatePath, JSON.stringify(state));
1712
- };
1713
- var updateGlobalRoots = (state, projectCwds) => {
1714
- const savedRoots = state["electron-saved-workspace-roots"] ?? [];
1715
- const projectOrder = state["project-order"] ?? [];
1716
- const missingSaved = projectCwds.filter((cwd) => !savedRoots.includes(cwd));
1717
- const missingProjectOrder = projectCwds.filter((cwd) => !projectOrder.includes(cwd));
1718
- if (missingSaved.length === 0 && missingProjectOrder.length === 0) return {
1719
- projectRootsAdded: 0,
1720
- savedRootsAdded: 0,
1721
- state
1722
- };
1723
- state["electron-saved-workspace-roots"] = [...savedRoots, ...missingSaved];
1724
- state["project-order"] = [...projectOrder, ...missingProjectOrder];
1725
- return {
1726
- projectRootsAdded: missingProjectOrder.length,
1727
- savedRootsAdded: missingSaved.length,
1728
- state
1729
- };
1730
- };
1731
- var getProjectTopLevelThreads = (db, projectName) => {
1732
- return db.query("SELECT id, cwd, rollout_path, thread_source FROM threads WHERE archived = 0").all().filter((thread) => {
1733
- return getPortablePathBasename(thread.cwd) === projectName && thread.thread_source !== "subagent";
1734
- });
1735
- };
1736
- var refreshThreadRows = (db, threadIds) => {
1737
- if (threadIds.length === 0) return 0;
1738
- const nowSeconds = Math.floor(Date.now() / 1e3);
1739
- const nowMs = Date.now();
1740
- const placeholders = threadIds.map(() => "?").join(", ");
1741
- const result = db.prepare(`
1742
- UPDATE threads
1743
- SET updated_at = ?1,
1744
- updated_at_ms = ?2,
1745
- has_user_event = 1
1746
- WHERE id IN (${placeholders})
1747
- `).run(nowSeconds, nowMs, ...threadIds);
1748
- return Number(result.changes);
1749
- };
1750
- var refreshSessionIndex = async (sessionIndexPath, threadIds) => {
1751
- if (threadIds.length === 0) return 0;
1752
- const now = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
1753
- const threadIdSet = new Set(threadIds);
1754
- const lines = (await Bun.file(sessionIndexPath).text()).split("\n");
1755
- let updated = 0;
1756
- const rewrittenLines = [];
1757
- for (const line of lines) {
1758
- if (!line.trim()) continue;
1759
- const parsed = JSON.parse(line);
1760
- if (parsed.id && threadIdSet.has(parsed.id)) {
1761
- parsed.updated_at = now;
1762
- updated += 1;
1763
- }
1764
- rewrittenLines.push(JSON.stringify(parsed));
1765
- }
1766
- await Bun.write(sessionIndexPath, `${rewrittenLines.join("\n")}\n`);
1767
- return updated;
1768
- };
1769
- var touchRolloutFiles = async (codexDir, rolloutPaths) => {
1770
- const now = /* @__PURE__ */ new Date();
1771
- let touched = 0;
1772
- for (const rolloutPath of rolloutPaths) {
1773
- const absolutePath = path.isAbsolute(rolloutPath) ? rolloutPath : path.join(codexDir, rolloutPath);
1774
- if (!await Bun.file(absolutePath).exists()) continue;
1775
- await utimes(absolutePath, now, now);
1776
- touched += 1;
1777
- }
1778
- return touched;
1779
- };
1780
- var recoverCodexProjectThreads = async (dbPath, projectName) => {
1781
- const codexDir = resolveCodexDirFromDbPath(dbPath);
1782
- const globalStatePath = path.join(codexDir, ".codex-global-state.json");
1783
- const sessionIndexPath = path.join(codexDir, "session_index.jsonl");
1784
- await assertRequiredStatePath(dbPath);
1785
- await assertRequiredStatePath(globalStatePath);
1786
- await assertRequiredStatePath(sessionIndexPath);
1787
- const backups = {
1788
- globalState: await backupFile(globalStatePath, "recover-project-roots"),
1789
- sessionIndex: await backupFile(sessionIndexPath, "recover-project-session-index"),
1790
- stateDb: await backupFile(dbPath, "recover-project-threads")
1791
- };
1792
- const globalState = await readGlobalState(globalStatePath);
1793
- const db = runWithSqliteRetry({ action: () => {
1794
- const opened = new Database(dbPath);
1795
- opened.exec("PRAGMA busy_timeout = 5000");
1796
- return opened;
1797
- } });
1798
- try {
1799
- const topLevelThreads = getProjectTopLevelThreads(db, projectName);
1800
- const projectCwds = [...new Set(topLevelThreads.map((thread) => thread.cwd))];
1801
- const rootUpdateResult = updateGlobalRoots(globalState, projectCwds);
1802
- await writeGlobalState(globalStatePath, rootUpdateResult.state);
1803
- const threadIds = topLevelThreads.map((thread) => thread.id);
1804
- const rolloutPaths = topLevelThreads.map((thread) => thread.rollout_path);
1805
- const threadDbRowsUpdated = refreshThreadRows(db, threadIds);
1806
- const sessionIndexRowsUpdated = await refreshSessionIndex(sessionIndexPath, threadIds);
1807
- const rolloutFilesTouched = await touchRolloutFiles(codexDir, rolloutPaths);
1808
- return {
1809
- backups,
1810
- projectName,
1811
- projectRootsAdded: rootUpdateResult.projectRootsAdded,
1812
- resolvedCwds: projectCwds,
1813
- rolloutFilesTouched,
1814
- savedRootsAdded: rootUpdateResult.savedRootsAdded,
1815
- sessionIndexRowsUpdated,
1816
- threadDbRowsUpdated,
1817
- topLevelThreadsFound: threadIds.length
1818
- };
1819
- } finally {
1820
- db.close();
1821
- }
1822
- };
1823
- //#endregion
1824
- //#region src/lib/codex-server.ts?tss-serverfn-split
1825
- var projectSchema = z.object({ project: z.string().min(1) });
1826
- var deleteProjectSchema = z.object({
1827
- deleteSessionFiles: z.boolean().default(false),
1828
- project: z.string().min(1)
1829
- });
1830
- var threadSchema = z.object({ threadId: z.string().min(1) });
1831
- var deleteThreadSchema = z.object({
1832
- deleteSessionFiles: z.boolean().default(false),
1833
- threadId: z.string().min(1)
1834
- });
1835
- var deleteThreadsSchema = z.object({
1836
- deleteSessionFiles: z.boolean().default(false),
1837
- threadIds: z.array(z.string().min(1)).min(1)
1838
- });
1839
- var analyticsSchema = z.object({ project: z.string().min(1).nullable() });
1840
- var exportSchema = z.object({
1841
- convertToProjectRoot: z.boolean(),
1842
- includeCommentary: z.boolean(),
1843
- includeMetadata: z.boolean(),
1844
- includeTools: z.boolean(),
1845
- outputFormat: z.enum(["md", "txt"]),
1846
- redactUsername: z.boolean(),
1847
- threadId: z.string().min(1),
1848
- zipArchive: z.boolean().default(false)
1849
- });
1850
- var exportThreadsSchema = z.object({
1851
- convertToProjectRoot: z.boolean(),
1852
- includeCommentary: z.boolean(),
1853
- includeMetadata: z.boolean(),
1854
- includeTools: z.boolean(),
1855
- outputFormat: z.enum(["md", "txt"]),
1856
- redactUsername: z.boolean(),
1857
- threadIds: z.array(z.string().min(1)).min(1),
1858
- zipArchive: z.boolean().default(true)
1859
- });
1860
- var getDbPath = () => process.env.SPIRACHA_CODEX_DB?.trim() || resolveCodexThreadDbPath();
1861
- var isMissingFileError = (error) => {
1862
- return error instanceof Error && /ENOENT|no such file/i.test(error.message);
1863
- };
1864
- var getDashboardSummaryFn_createServerFn_handler = createServerRpc({
1865
- id: "792690638a3b10035a5b7368c3d98bdc70cbfe1e36a4aa5f45b1c49b8b1025b0",
1866
- name: "getDashboardSummaryFn",
1867
- filename: "src/lib/codex-server.ts"
1868
- }, (opts) => getDashboardSummaryFn.__executeServer(opts));
1869
- var getDashboardSummaryFn = createServerFn({ method: "GET" }).handler(getDashboardSummaryFn_createServerFn_handler, async () => {
1870
- return getCodexDashboardSummary(getDbPath());
1871
- });
1872
- var listProjectsFn_createServerFn_handler = createServerRpc({
1873
- id: "ccefccb816ba13508f23db4e31067b3403e750225257592d3ae11071ffc3fd6f",
1874
- name: "listProjectsFn",
1875
- filename: "src/lib/codex-server.ts"
1876
- }, (opts) => listProjectsFn.__executeServer(opts));
1877
- var listProjectsFn = createServerFn({ method: "GET" }).handler(listProjectsFn_createServerFn_handler, async () => {
1878
- return listCodexProjects(getDbPath());
1879
- });
1880
- var listProjectThreadsFn_createServerFn_handler = createServerRpc({
1881
- id: "59fb2cb4d60c8e7d47e0afcc914ee6f9d9f4bf076c8e66eab1693066753655b3",
1882
- name: "listProjectThreadsFn",
1883
- filename: "src/lib/codex-server.ts"
1884
- }, (opts) => listProjectThreadsFn.__executeServer(opts));
1885
- var listProjectThreadsFn = createServerFn({ method: "GET" }).validator(projectSchema).handler(listProjectThreadsFn_createServerFn_handler, async ({ data }) => {
1886
- return listProjectThreads(getDbPath(), data.project);
1887
- });
1888
- var getThreadSnapshotFn_createServerFn_handler = createServerRpc({
1889
- id: "72991e2b6e0adbf8d63bb8b139dad88a00b77b7030ec28ceac36c3cce7846b4c",
1890
- name: "getThreadSnapshotFn",
1891
- filename: "src/lib/codex-server.ts"
1892
- }, (opts) => getThreadSnapshotFn.__executeServer(opts));
1893
- var getThreadSnapshotFn = createServerFn({ method: "GET" }).validator(threadSchema).handler(getThreadSnapshotFn_createServerFn_handler, async ({ data }) => {
1894
- const browseData = getThreadBrowseData(getDbPath(), data.threadId);
1895
- const rollout = await getThreadRolloutLoadState(browseData.thread.rollout_path);
1896
- let transcript = null;
1897
- let transcriptState = rollout.shouldDeferTranscriptLoad ? "deferred" : "available";
1898
- if (!rollout.shouldDeferTranscriptLoad) try {
1899
- transcript = await getCachedParsedCodexTranscript(browseData.thread.rollout_path);
1900
- } catch (error) {
1901
- if (!isMissingFileError(error)) throw error;
1902
- transcriptState = "missing";
1903
- }
1904
- return {
1905
- ...browseData,
1906
- availableTools: browseData.dynamicTools.length > 0 ? browseData.dynamicTools : transcript?.sessionMeta.dynamicTools ?? [],
1907
- rollout,
1908
- transcript,
1909
- transcriptState
1910
- };
1911
- });
1912
- var getThreadTranscriptFn_createServerFn_handler = createServerRpc({
1913
- id: "5da27045f7e28ded6353bc16aace284af7ef1b4010ef04d0186a6feadb466497",
1914
- name: "getThreadTranscriptFn",
1915
- filename: "src/lib/codex-server.ts"
1916
- }, (opts) => getThreadTranscriptFn.__executeServer(opts));
1917
- var getThreadTranscriptFn = createServerFn({ method: "GET" }).validator(threadSchema).handler(getThreadTranscriptFn_createServerFn_handler, async ({ data }) => {
1918
- return getCachedThreadTranscriptPreview(getThreadBrowseData(getDbPath(), data.threadId).thread.rollout_path);
1919
- });
1920
- var getAnalyticsFn_createServerFn_handler = createServerRpc({
1921
- id: "4712520da0f07bbd1f0907e5a162fe518516ff4caca3fd23876cc65539d87d7a",
1922
- name: "getAnalyticsFn",
1923
- filename: "src/lib/codex-server.ts"
1924
- }, (opts) => getAnalyticsFn.__executeServer(opts));
1925
- var getAnalyticsFn = createServerFn({ method: "GET" }).validator(analyticsSchema).handler(getAnalyticsFn_createServerFn_handler, async ({ data }) => {
1926
- return getCodexAnalytics({
1927
- dbPath: getDbPath(),
1928
- project: data.project
1929
- });
1930
- });
1931
- var exportThreadFn_createServerFn_handler = createServerRpc({
1932
- id: "0814663c3bdc58135f97d210d145ef0be5ca54ef9a5f1e3030be9b1bfc901e30",
1933
- name: "exportThreadFn",
1934
- filename: "src/lib/codex-server.ts"
1935
- }, (opts) => exportThreadFn.__executeServer(opts));
1936
- var exportThreadFn = createServerFn({ method: "POST" }).validator(exportSchema).handler(exportThreadFn_createServerFn_handler, async ({ data }) => {
1937
- return renderCodexThreadDownload({
1938
- dbPath: getDbPath(),
1939
- includeCommentary: data.includeCommentary,
1940
- includeMetadata: data.includeMetadata,
1941
- includeTools: data.includeTools,
1942
- outputFormat: data.outputFormat,
1943
- pathDisplaySettings: {
1944
- convertToProjectRoot: data.convertToProjectRoot,
1945
- redactUsername: data.redactUsername
1946
- },
1947
- threadId: data.threadId,
1948
- zipArchive: data.zipArchive
1949
- });
1950
- });
1951
- var exportThreadsFn_createServerFn_handler = createServerRpc({
1952
- id: "b4e15c006e9a277470958bb008f89b5b0acc7256109581de44cf17d587d174a5",
1953
- name: "exportThreadsFn",
1954
- filename: "src/lib/codex-server.ts"
1955
- }, (opts) => exportThreadsFn.__executeServer(opts));
1956
- var exportThreadsFn = createServerFn({ method: "POST" }).validator(exportThreadsSchema).handler(exportThreadsFn_createServerFn_handler, async ({ data }) => {
1957
- return renderCodexThreadsDownload({
1958
- dbPath: getDbPath(),
1959
- includeCommentary: data.includeCommentary,
1960
- includeMetadata: data.includeMetadata,
1961
- includeTools: data.includeTools,
1962
- outputFormat: data.outputFormat,
1963
- pathDisplaySettings: {
1964
- convertToProjectRoot: data.convertToProjectRoot,
1965
- redactUsername: data.redactUsername
1966
- },
1967
- threadIds: data.threadIds,
1968
- zipArchive: data.zipArchive
1969
- });
1970
- });
1971
- var deleteThreadFn_createServerFn_handler = createServerRpc({
1972
- id: "29727b7ad5b8fe42e83817376653e064d9fe8888799f056b2e59296b3396568b",
1973
- name: "deleteThreadFn",
1974
- filename: "src/lib/codex-server.ts"
1975
- }, (opts) => deleteThreadFn.__executeServer(opts));
1976
- var deleteThreadFn = createServerFn({ method: "POST" }).validator(deleteThreadSchema).handler(deleteThreadFn_createServerFn_handler, async ({ data }) => {
1977
- return deleteCodexThread(getDbPath(), data.threadId, { deleteSessionFiles: data.deleteSessionFiles });
1978
- });
1979
- var deleteThreadsFn_createServerFn_handler = createServerRpc({
1980
- id: "96aa60bf7dd9b5bde415bcf3ad6f6955a975eecd9aa0516cf401cc39bebebe6c",
1981
- name: "deleteThreadsFn",
1982
- filename: "src/lib/codex-server.ts"
1983
- }, (opts) => deleteThreadsFn.__executeServer(opts));
1984
- var deleteThreadsFn = createServerFn({ method: "POST" }).validator(deleteThreadsSchema).handler(deleteThreadsFn_createServerFn_handler, async ({ data }) => {
1985
- return deleteCodexThreads(getDbPath(), data.threadIds, { deleteSessionFiles: data.deleteSessionFiles });
1986
- });
1987
- var deleteProjectFn_createServerFn_handler = createServerRpc({
1988
- id: "164ee82cdd565ed96591a64312f0f7bd961040baf066a89d9f5636330d11360b",
1989
- name: "deleteProjectFn",
1990
- filename: "src/lib/codex-server.ts"
1991
- }, (opts) => deleteProjectFn.__executeServer(opts));
1992
- var deleteProjectFn = createServerFn({ method: "POST" }).validator(deleteProjectSchema).handler(deleteProjectFn_createServerFn_handler, async ({ data }) => {
1993
- return deleteCodexProject(getDbPath(), data.project, { deleteSessionFiles: data.deleteSessionFiles });
1994
- });
1995
- var recoverProjectThreadsFn_createServerFn_handler = createServerRpc({
1996
- id: "412c05e00aef3ad43905593fdfd2f566561259da7e1f5d6f1c03428ff33c6867",
1997
- name: "recoverProjectThreadsFn",
1998
- filename: "src/lib/codex-server.ts"
1999
- }, (opts) => recoverProjectThreadsFn.__executeServer(opts));
2000
- var recoverProjectThreadsFn = createServerFn({ method: "POST" }).validator(projectSchema).handler(recoverProjectThreadsFn_createServerFn_handler, async ({ data }) => {
2001
- return recoverCodexProjectThreads(getDbPath(), data.project);
2002
- });
2003
- //#endregion
2004
- export { deleteProjectFn_createServerFn_handler, deleteThreadFn_createServerFn_handler, deleteThreadsFn_createServerFn_handler, exportThreadFn_createServerFn_handler, exportThreadsFn_createServerFn_handler, getAnalyticsFn_createServerFn_handler, getDashboardSummaryFn_createServerFn_handler, getThreadSnapshotFn_createServerFn_handler, getThreadTranscriptFn_createServerFn_handler, listProjectThreadsFn_createServerFn_handler, listProjectsFn_createServerFn_handler, recoverProjectThreadsFn_createServerFn_handler };