@cloudcli-ai/cloudcli 1.37.1 → 1.37.3

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 (402) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/abnfDiagram-N423BO3Z-CJntskwA.js +1 -0
  3. package/dist/assets/arc-CIfH4uMN.js +1 -0
  4. package/dist/assets/architectureDiagram-T3A2C74G-_IpEkukg.js +36 -0
  5. package/dist/assets/blockDiagram-VBNYF7ZC-BttxrpgZ.js +132 -0
  6. package/dist/assets/c4Diagram-5PPSVZJV-g51dSRr1.js +10 -0
  7. package/dist/assets/channel-C5xU9jMw.js +1 -0
  8. package/dist/assets/chunk-2GRJ4B5K-D_-LbQUa.js +1 -0
  9. package/dist/assets/chunk-2Q5K7J3B-BtlHzwaO.js +1 -0
  10. package/dist/assets/chunk-5RXB4S5H-UzkpvpAT.js +231 -0
  11. package/dist/assets/chunk-5VM5RSS4-BKwx5Gag.js +15 -0
  12. package/dist/assets/chunk-6Q2QTUOP-D_KEBH5f.js +88 -0
  13. package/dist/assets/chunk-GF5L2VYU-rK2DGyto.js +206 -0
  14. package/dist/assets/chunk-JWPE2WC7-CeBl_N9i.js +1 -0
  15. package/dist/assets/chunk-KBJHAD2P-BiQLWVIr.js +1 -0
  16. package/dist/assets/chunk-RYQCIY6F-C1knVGV5.js +1 -0
  17. package/dist/assets/chunk-XXDRQBXY-CtKbJkvF.js +1 -0
  18. package/dist/assets/classDiagram-JCYQIIEL-CRrL3vp7.js +1 -0
  19. package/dist/assets/classDiagram-v2-OCEON4UE-CRrL3vp7.js +1 -0
  20. package/dist/assets/cose-bilkent-JH36ORCC-DjX8y40Z.js +1 -0
  21. package/dist/assets/cynefin-VYW2F7L2-DM6YeRba.js +178 -0
  22. package/dist/assets/cynefinDiagram-MW4NZA55-wZJ-vy5B.js +62 -0
  23. package/dist/assets/cytoscape.esm-C10L9Icf.js +331 -0
  24. package/dist/assets/dagre-VZM6K2ZE-BzP0ejkH.js +4 -0
  25. package/dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  26. package/dist/assets/diagram-7IWD3JNH-BTL_j23J.js +30 -0
  27. package/dist/assets/diagram-B4RE2ZJO-Cf1Norgu.js +3 -0
  28. package/dist/assets/diagram-LBJQPF4R-DPiUEKr-.js +24 -0
  29. package/dist/assets/diagram-Q27KOJAE-CTcTpiz5.js +24 -0
  30. package/dist/assets/diagram-UB23O5K3-DPMSdYm0.js +41 -0
  31. package/dist/assets/ebnfDiagram-BXEA7PRR-7yvD6uiF.js +1 -0
  32. package/dist/assets/erDiagram-JOGREHBK-CfgeDoV6.js +85 -0
  33. package/dist/assets/flowDiagram-UKHOOZJN-B27ng5zu.js +156 -0
  34. package/dist/assets/ganttDiagram-PKOTCBZU-CcC6b_7t.js +292 -0
  35. package/dist/assets/gitGraphDiagram-DS77QQ5N-BX5kPGrO.js +106 -0
  36. package/dist/assets/graph-Cx-EqisW.js +1 -0
  37. package/dist/assets/index-BTDHQ6Id.css +32 -0
  38. package/dist/assets/index-sFfz8iBR.js +4931 -0
  39. package/dist/assets/infoDiagram-6WML65LV-CUP-SlN4.js +2 -0
  40. package/dist/assets/init-Gi6I4Gst.js +1 -0
  41. package/dist/assets/ishikawaDiagram-WSZJBQD7-BTTDhOpX.js +70 -0
  42. package/dist/assets/journeyDiagram-NVQOT4AX-ARXcc61m.js +139 -0
  43. package/dist/assets/kanban-definition-27J2QSJJ-BieMpqMA.js +89 -0
  44. package/dist/assets/layout-D6BstSzF.js +1 -0
  45. package/dist/assets/linear-61vxjRnP.js +1 -0
  46. package/dist/assets/map-CV9uif0g.js +1 -0
  47. package/dist/assets/mermaid.core-nhnwkfQx.js +312 -0
  48. package/dist/assets/mindmap-definition-FAOFIHXS-Cm6x5vT1.js +96 -0
  49. package/dist/assets/ordinal-Cboi1Yqb.js +1 -0
  50. package/dist/assets/pegDiagram-VL7TDLO6-CcYBq_9H.js +1 -0
  51. package/dist/assets/pieDiagram-7S7Q4E2Y-CfvIjfzo.js +39 -0
  52. package/dist/assets/quadrantDiagram-CIZ2JOQS-SgYoWPNb.js +7 -0
  53. package/dist/assets/railroadDiagram-AXF67PYL-D2Mu5E_f.js +1 -0
  54. package/dist/assets/requirementDiagram-LRYGKXZP-Azwe_k4Q.js +84 -0
  55. package/dist/assets/sankeyDiagram-W5VNT64P-DN1Ju3PA.js +40 -0
  56. package/dist/assets/sequenceDiagram-SI44F4Z6-Bj4qC34S.js +162 -0
  57. package/dist/assets/server.browser-CtX3Hdl5.js +27 -0
  58. package/dist/assets/sizeCapture-X5ZJPWSS-Co4PdklG.js +1 -0
  59. package/dist/assets/stateDiagram-OKZ733FA-nOvL9dRC.js +1 -0
  60. package/dist/assets/stateDiagram-v2-UEYNNEHI-DNv8ppw7.js +1 -0
  61. package/dist/assets/swimlanes-SLNWSIFB-CCK3wMid.js +2 -0
  62. package/dist/assets/swimlanesDiagram-ULZ7WXOC-DnfbNQEp.js +8 -0
  63. package/dist/assets/timeline-definition-Z64GVDOM-BC29RNFm.js +120 -0
  64. package/dist/assets/{vendor-codemirror-OwyKSvPE.js → vendor-codemirror-CYrSt7-U.js} +18 -18
  65. package/dist/assets/vennDiagram-T6HMQDX7-pZlZCtEo.js +34 -0
  66. package/dist/assets/wardleyDiagram-T6FBY63Y-De8k2-zM.js +78 -0
  67. package/dist/assets/xychartDiagram-ELKLHX3M-Bk8ykH0w.js +7 -0
  68. package/dist/index.html +3 -3
  69. package/dist-server/server/index.js +8 -5
  70. package/dist-server/server/index.js.map +1 -1
  71. package/dist-server/server/modules/agent/agent.module.js +2 -1
  72. package/dist-server/server/modules/agent/agent.module.js.map +1 -1
  73. package/dist-server/server/modules/agent/agent.routes.js +2 -2
  74. package/dist-server/server/modules/agent/agent.routes.js.map +1 -1
  75. package/dist-server/server/modules/agent/tests/agent.routes.test.js +30 -1
  76. package/dist-server/server/modules/agent/tests/agent.routes.test.js.map +1 -1
  77. package/dist-server/server/modules/auth/auth.middleware.js +1 -1
  78. package/dist-server/server/modules/auth/auth.middleware.js.map +1 -1
  79. package/dist-server/server/modules/browser-use/browser-use-runtime.js +10 -0
  80. package/dist-server/server/modules/browser-use/browser-use-runtime.js.map +1 -0
  81. package/dist-server/server/modules/browser-use/browser-use.routes.js +39 -33
  82. package/dist-server/server/modules/browser-use/browser-use.routes.js.map +1 -1
  83. package/dist-server/server/modules/browser-use/browser-use.service.js +3 -6
  84. package/dist-server/server/modules/browser-use/browser-use.service.js.map +1 -1
  85. package/dist-server/server/modules/browser-use/index.js +2 -0
  86. package/dist-server/server/modules/browser-use/index.js.map +1 -1
  87. package/dist-server/server/modules/cli/cli.js +9 -3
  88. package/dist-server/server/modules/cli/cli.js.map +1 -1
  89. package/dist-server/server/modules/cli/cli.module.js +0 -1
  90. package/dist-server/server/modules/cli/cli.module.js.map +1 -1
  91. package/dist-server/server/modules/cli/cli.service.js +0 -18
  92. package/dist-server/server/modules/cli/cli.service.js.map +1 -1
  93. package/dist-server/server/modules/cli/tests/cli-environment-bootstrap.test.js +154 -0
  94. package/dist-server/server/modules/cli/tests/cli-environment-bootstrap.test.js.map +1 -0
  95. package/dist-server/server/modules/cli/tests/cli.service.test.js +0 -3
  96. package/dist-server/server/modules/cli/tests/cli.service.test.js.map +1 -1
  97. package/dist-server/server/modules/database/connection.js +1 -1
  98. package/dist-server/server/modules/database/connection.js.map +1 -1
  99. package/dist-server/server/modules/database/index.js +5 -0
  100. package/dist-server/server/modules/database/index.js.map +1 -1
  101. package/dist-server/server/modules/database/migrations.js +32 -1
  102. package/dist-server/server/modules/database/migrations.js.map +1 -1
  103. package/dist-server/server/modules/database/repositories/scheduled-messages.db.js +71 -0
  104. package/dist-server/server/modules/database/repositories/scheduled-messages.db.js.map +1 -0
  105. package/dist-server/server/modules/database/repositories/session-drafts.db.js +105 -0
  106. package/dist-server/server/modules/database/repositories/session-drafts.db.js.map +1 -0
  107. package/dist-server/server/modules/database/repositories/sessions.db.js +137 -5
  108. package/dist-server/server/modules/database/repositories/sessions.db.js.map +1 -1
  109. package/dist-server/server/modules/database/repositories/user-preferences.db.js +65 -0
  110. package/dist-server/server/modules/database/repositories/user-preferences.db.js.map +1 -0
  111. package/dist-server/server/modules/database/schema.js +92 -0
  112. package/dist-server/server/modules/database/schema.js.map +1 -1
  113. package/dist-server/server/modules/database/tests/sessions.db.integration.test.js +39 -0
  114. package/dist-server/server/modules/database/tests/sessions.db.integration.test.js.map +1 -1
  115. package/dist-server/server/modules/database/tests/user-preferences.db.integration.test.js +105 -0
  116. package/dist-server/server/modules/database/tests/user-preferences.db.integration.test.js.map +1 -0
  117. package/dist-server/server/modules/file-tree/file-tree.service.js +18 -10
  118. package/dist-server/server/modules/file-tree/file-tree.service.js.map +1 -1
  119. package/dist-server/server/modules/file-tree/tests/file-tree.service.test.js +62 -11
  120. package/dist-server/server/modules/file-tree/tests/file-tree.service.test.js.map +1 -1
  121. package/dist-server/server/modules/git/git-branch.service.js +15 -0
  122. package/dist-server/server/modules/git/git-branch.service.js.map +1 -0
  123. package/dist-server/server/modules/git/git.routes.js +15 -7
  124. package/dist-server/server/modules/git/git.routes.js.map +1 -1
  125. package/dist-server/server/modules/git/tests/git-branch.service.test.js +52 -0
  126. package/dist-server/server/modules/git/tests/git-branch.service.test.js.map +1 -0
  127. package/dist-server/server/modules/git/tests/git-init.routes.test.js +84 -0
  128. package/dist-server/server/modules/git/tests/git-init.routes.test.js.map +1 -1
  129. package/dist-server/server/modules/notifications/index.js +3 -1
  130. package/dist-server/server/modules/notifications/index.js.map +1 -1
  131. package/dist-server/server/modules/notifications/services/notification-orchestrator.service.js +22 -1
  132. package/dist-server/server/modules/notifications/services/notification-orchestrator.service.js.map +1 -1
  133. package/dist-server/server/modules/projects/services/project-delete.service.js +12 -1
  134. package/dist-server/server/modules/projects/services/project-delete.service.js.map +1 -1
  135. package/dist-server/server/modules/projects/services/project-star.service.js +2 -2
  136. package/dist-server/server/modules/projects/services/project-star.service.js.map +1 -1
  137. package/dist-server/server/modules/providers/index.js +3 -0
  138. package/dist-server/server/modules/providers/index.js.map +1 -1
  139. package/dist-server/server/modules/providers/list/claude/claude-auth.provider.js +20 -1
  140. package/dist-server/server/modules/providers/list/claude/claude-auth.provider.js.map +1 -1
  141. package/dist-server/server/modules/providers/list/claude/claude-fork.provider.js +46 -0
  142. package/dist-server/server/modules/providers/list/claude/claude-fork.provider.js.map +1 -0
  143. package/dist-server/server/modules/providers/list/claude/claude-models.provider.js +35 -6
  144. package/dist-server/server/modules/providers/list/claude/claude-models.provider.js.map +1 -1
  145. package/dist-server/server/modules/providers/list/claude/claude-runtime.provider.js +422 -86
  146. package/dist-server/server/modules/providers/list/claude/claude-runtime.provider.js.map +1 -1
  147. package/dist-server/server/modules/providers/list/claude/claude-sessions.provider.js +388 -50
  148. package/dist-server/server/modules/providers/list/claude/claude-sessions.provider.js.map +1 -1
  149. package/dist-server/server/modules/providers/list/claude/claude-skills.provider.js +4 -1
  150. package/dist-server/server/modules/providers/list/claude/claude-skills.provider.js.map +1 -1
  151. package/dist-server/server/modules/providers/list/claude/claude.provider.js +2 -0
  152. package/dist-server/server/modules/providers/list/claude/claude.provider.js.map +1 -1
  153. package/dist-server/server/modules/providers/list/codex/codex-app-server.client.js +204 -0
  154. package/dist-server/server/modules/providers/list/codex/codex-app-server.client.js.map +1 -0
  155. package/dist-server/server/modules/providers/list/codex/codex-fork.provider.js +32 -0
  156. package/dist-server/server/modules/providers/list/codex/codex-fork.provider.js.map +1 -0
  157. package/dist-server/server/modules/providers/list/codex/codex-models.provider.js +16 -0
  158. package/dist-server/server/modules/providers/list/codex/codex-models.provider.js.map +1 -1
  159. package/dist-server/server/modules/providers/list/codex/codex-runtime.provider.js +60 -49
  160. package/dist-server/server/modules/providers/list/codex/codex-runtime.provider.js.map +1 -1
  161. package/dist-server/server/modules/providers/list/codex/codex-session-synchronizer.provider.js +8 -0
  162. package/dist-server/server/modules/providers/list/codex/codex-session-synchronizer.provider.js.map +1 -1
  163. package/dist-server/server/modules/providers/list/codex/codex-sessions.provider.js +1565 -432
  164. package/dist-server/server/modules/providers/list/codex/codex-sessions.provider.js.map +1 -1
  165. package/dist-server/server/modules/providers/list/codex/codex.provider.js +2 -0
  166. package/dist-server/server/modules/providers/list/codex/codex.provider.js.map +1 -1
  167. package/dist-server/server/modules/providers/list/cursor/cursor-runtime.provider.js +8 -6
  168. package/dist-server/server/modules/providers/list/cursor/cursor-runtime.provider.js.map +1 -1
  169. package/dist-server/server/modules/providers/list/cursor/cursor-session-synchronizer.provider.js.map +1 -1
  170. package/dist-server/server/modules/providers/list/opencode/opencode-models.provider.js +258 -6
  171. package/dist-server/server/modules/providers/list/opencode/opencode-models.provider.js.map +1 -1
  172. package/dist-server/server/modules/providers/provider.routes.js +29 -0
  173. package/dist-server/server/modules/providers/provider.routes.js.map +1 -1
  174. package/dist-server/server/modules/providers/services/provider-capabilities.service.js +14 -0
  175. package/dist-server/server/modules/providers/services/provider-capabilities.service.js.map +1 -1
  176. package/dist-server/server/modules/providers/services/provider-token-usage.service.js +139 -35
  177. package/dist-server/server/modules/providers/services/provider-token-usage.service.js.map +1 -1
  178. package/dist-server/server/modules/providers/services/session-conversations-search.service.js +63 -7
  179. package/dist-server/server/modules/providers/services/session-conversations-search.service.js.map +1 -1
  180. package/dist-server/server/modules/providers/services/session-history-cache.service.js +87 -0
  181. package/dist-server/server/modules/providers/services/session-history-cache.service.js.map +1 -0
  182. package/dist-server/server/modules/providers/services/session-synchronizer.service.js +105 -32
  183. package/dist-server/server/modules/providers/services/session-synchronizer.service.js.map +1 -1
  184. package/dist-server/server/modules/providers/services/sessions-watcher.service.js +3 -60
  185. package/dist-server/server/modules/providers/services/sessions-watcher.service.js.map +1 -1
  186. package/dist-server/server/modules/providers/services/sessions.service.js +179 -9
  187. package/dist-server/server/modules/providers/services/sessions.service.js.map +1 -1
  188. package/dist-server/server/modules/providers/tests/claude-auth.test.js +52 -0
  189. package/dist-server/server/modules/providers/tests/claude-auth.test.js.map +1 -1
  190. package/dist-server/server/modules/providers/tests/claude-models.test.js +39 -0
  191. package/dist-server/server/modules/providers/tests/claude-models.test.js.map +1 -0
  192. package/dist-server/server/modules/providers/tests/claude-sessions.test.js +465 -39
  193. package/dist-server/server/modules/providers/tests/claude-sessions.test.js.map +1 -1
  194. package/dist-server/server/modules/providers/tests/claude-subagent-echo.test.js +16 -0
  195. package/dist-server/server/modules/providers/tests/claude-subagent-echo.test.js.map +1 -0
  196. package/dist-server/server/modules/providers/tests/claude-token-budget.test.js +85 -0
  197. package/dist-server/server/modules/providers/tests/claude-token-budget.test.js.map +1 -0
  198. package/dist-server/server/modules/providers/tests/codex-message-editing.test.js +338 -0
  199. package/dist-server/server/modules/providers/tests/codex-message-editing.test.js.map +1 -0
  200. package/dist-server/server/modules/providers/tests/codex-runtime.test.js +51 -0
  201. package/dist-server/server/modules/providers/tests/codex-runtime.test.js.map +1 -0
  202. package/dist-server/server/modules/providers/tests/codex-session-fork.test.js +54 -0
  203. package/dist-server/server/modules/providers/tests/codex-session-fork.test.js.map +1 -0
  204. package/dist-server/server/modules/providers/tests/codex-sessions.test.js +304 -15
  205. package/dist-server/server/modules/providers/tests/codex-sessions.test.js.map +1 -1
  206. package/dist-server/server/modules/providers/tests/opencode-models.test.js +117 -4
  207. package/dist-server/server/modules/providers/tests/opencode-models.test.js.map +1 -1
  208. package/dist-server/server/modules/providers/tests/provider-token-usage.service.test.js +164 -1
  209. package/dist-server/server/modules/providers/tests/provider-token-usage.service.test.js.map +1 -1
  210. package/dist-server/server/modules/providers/tests/provider.routes.test.js +35 -0
  211. package/dist-server/server/modules/providers/tests/provider.routes.test.js.map +1 -1
  212. package/dist-server/server/modules/providers/tests/session-fork.test.js +113 -0
  213. package/dist-server/server/modules/providers/tests/session-fork.test.js.map +1 -0
  214. package/dist-server/server/modules/providers/tests/session-history-cache.service.test.js +120 -0
  215. package/dist-server/server/modules/providers/tests/session-history-cache.service.test.js.map +1 -0
  216. package/dist-server/server/modules/providers/tests/session-orphan-prune.test.js +90 -0
  217. package/dist-server/server/modules/providers/tests/session-orphan-prune.test.js.map +1 -0
  218. package/dist-server/server/modules/providers/tests/session-synchronizer-coalescing.test.js +122 -0
  219. package/dist-server/server/modules/providers/tests/session-synchronizer-coalescing.test.js.map +1 -0
  220. package/dist-server/server/modules/providers/tests/sessions.service.test.js +45 -1
  221. package/dist-server/server/modules/providers/tests/sessions.service.test.js.map +1 -1
  222. package/dist-server/server/modules/providers/tests/skills.test.js +15 -3
  223. package/dist-server/server/modules/providers/tests/skills.test.js.map +1 -1
  224. package/dist-server/server/modules/scheduled-messages/index.js +5 -0
  225. package/dist-server/server/modules/scheduled-messages/index.js.map +1 -0
  226. package/dist-server/server/modules/scheduled-messages/scheduled-messages.routes.js +47 -0
  227. package/dist-server/server/modules/scheduled-messages/scheduled-messages.routes.js.map +1 -0
  228. package/dist-server/server/modules/scheduled-messages/services/scheduled-message-dispatcher.service.js +163 -0
  229. package/dist-server/server/modules/scheduled-messages/services/scheduled-message-dispatcher.service.js.map +1 -0
  230. package/dist-server/server/modules/scheduled-messages/services/scheduled-messages.service.js +95 -0
  231. package/dist-server/server/modules/scheduled-messages/services/scheduled-messages.service.js.map +1 -0
  232. package/dist-server/server/modules/scheduled-messages/tests/scheduled-messages.test.js +255 -0
  233. package/dist-server/server/modules/scheduled-messages/tests/scheduled-messages.test.js.map +1 -0
  234. package/dist-server/server/modules/taskmaster/taskmaster.routes.js +23 -23
  235. package/dist-server/server/modules/taskmaster/taskmaster.routes.js.map +1 -1
  236. package/dist-server/server/modules/taskmaster/tests/taskmaster.routes.test.js +48 -0
  237. package/dist-server/server/modules/taskmaster/tests/taskmaster.routes.test.js.map +1 -1
  238. package/dist-server/server/modules/user/tests/user.service.test.js +70 -0
  239. package/dist-server/server/modules/user/tests/user.service.test.js.map +1 -1
  240. package/dist-server/server/modules/user/user.module.js +10 -1
  241. package/dist-server/server/modules/user/user.module.js.map +1 -1
  242. package/dist-server/server/modules/user/user.routes.js +44 -0
  243. package/dist-server/server/modules/user/user.routes.js.map +1 -1
  244. package/dist-server/server/modules/user/user.service.js +75 -0
  245. package/dist-server/server/modules/user/user.service.js.map +1 -1
  246. package/dist-server/server/modules/voice/tests/voice.service.test.js +3 -2
  247. package/dist-server/server/modules/voice/tests/voice.service.test.js.map +1 -1
  248. package/dist-server/server/modules/websocket/index.js +7 -0
  249. package/dist-server/server/modules/websocket/index.js.map +1 -1
  250. package/dist-server/server/modules/websocket/services/chat-run-registry.service.js +10 -44
  251. package/dist-server/server/modules/websocket/services/chat-run-registry.service.js.map +1 -1
  252. package/dist-server/server/modules/websocket/services/chat-session-writer.service.js +35 -5
  253. package/dist-server/server/modules/websocket/services/chat-session-writer.service.js.map +1 -1
  254. package/dist-server/server/modules/websocket/services/chat-websocket.service.js +166 -9
  255. package/dist-server/server/modules/websocket/services/chat-websocket.service.js.map +1 -1
  256. package/dist-server/server/modules/websocket/services/session-upsert-broadcast.service.js +94 -0
  257. package/dist-server/server/modules/websocket/services/session-upsert-broadcast.service.js.map +1 -0
  258. package/dist-server/server/modules/websocket/services/shell-websocket.service.js +9 -3
  259. package/dist-server/server/modules/websocket/services/shell-websocket.service.js.map +1 -1
  260. package/dist-server/server/modules/websocket/tests/chat-edit-send.test.js +263 -0
  261. package/dist-server/server/modules/websocket/tests/chat-edit-send.test.js.map +1 -0
  262. package/dist-server/server/modules/websocket/tests/chat-run-registry.test.js +29 -3
  263. package/dist-server/server/modules/websocket/tests/chat-run-registry.test.js.map +1 -1
  264. package/dist-server/server/modules/websocket/tests/session-upsert-broadcast.test.js +106 -0
  265. package/dist-server/server/modules/websocket/tests/session-upsert-broadcast.test.js.map +1 -0
  266. package/dist-server/server/modules/websocket/tests/shell-websocket.service.test.js +80 -0
  267. package/dist-server/server/modules/websocket/tests/shell-websocket.service.test.js.map +1 -1
  268. package/dist-server/server/shared/claude-cli-path.js +22 -5
  269. package/dist-server/server/shared/claude-cli-path.js.map +1 -1
  270. package/dist-server/server/shared/index.js +3 -0
  271. package/dist-server/server/shared/index.js.map +1 -0
  272. package/dist-server/server/shared/message-unification.js +376 -0
  273. package/dist-server/server/shared/message-unification.js.map +1 -0
  274. package/dist-server/server/shared/tests/claude-cli-path.test.js +45 -1
  275. package/dist-server/server/shared/tests/claude-cli-path.test.js.map +1 -1
  276. package/dist-server/server/shared/tests/message-unification.test.js +174 -0
  277. package/dist-server/server/shared/tests/message-unification.test.js.map +1 -0
  278. package/dist-server/server/shared/utils.js +42 -0
  279. package/dist-server/server/shared/utils.js.map +1 -1
  280. package/package.json +23 -16
  281. package/scripts/promote-dist-server.mjs +50 -0
  282. package/server/index.ts +12 -6
  283. package/server/modules/agent/agent.module.ts +2 -1
  284. package/server/modules/agent/agent.routes.ts +2 -2
  285. package/server/modules/agent/tests/agent.routes.test.ts +33 -1
  286. package/server/modules/auth/auth.middleware.ts +2 -2
  287. package/server/modules/browser-use/browser-use-runtime.ts +10 -0
  288. package/server/modules/browser-use/browser-use.routes.ts +96 -33
  289. package/server/modules/browser-use/browser-use.service.ts +5 -8
  290. package/server/modules/browser-use/index.ts +3 -0
  291. package/server/modules/cli/cli.module.ts +0 -1
  292. package/server/modules/cli/cli.service.ts +0 -20
  293. package/server/modules/cli/cli.ts +9 -3
  294. package/server/modules/cli/tests/cli-environment-bootstrap.test.ts +186 -0
  295. package/server/modules/cli/tests/cli.service.test.ts +0 -3
  296. package/server/modules/database/connection.ts +2 -1
  297. package/server/modules/database/index.ts +10 -0
  298. package/server/modules/database/migrations.ts +37 -0
  299. package/server/modules/database/repositories/scheduled-messages.db.ts +127 -0
  300. package/server/modules/database/repositories/session-drafts.db.ts +171 -0
  301. package/server/modules/database/repositories/sessions.db.ts +196 -3
  302. package/server/modules/database/repositories/user-preferences.db.ts +80 -0
  303. package/server/modules/database/schema.ts +96 -0
  304. package/server/modules/database/tests/sessions.db.integration.test.ts +52 -0
  305. package/server/modules/database/tests/user-preferences.db.integration.test.ts +135 -0
  306. package/server/modules/file-tree/file-tree.service.ts +21 -10
  307. package/server/modules/file-tree/tests/file-tree.service.test.ts +65 -11
  308. package/server/modules/git/git-branch.service.ts +43 -0
  309. package/server/modules/git/git.routes.ts +16 -9
  310. package/server/modules/git/tests/git-branch.service.test.ts +60 -0
  311. package/server/modules/git/tests/git-init.routes.test.ts +83 -0
  312. package/server/modules/notifications/index.ts +2 -0
  313. package/server/modules/notifications/services/notification-orchestrator.service.js +24 -1
  314. package/server/modules/projects/services/project-delete.service.ts +13 -1
  315. package/server/modules/projects/services/project-star.service.ts +2 -2
  316. package/server/modules/providers/index.ts +4 -0
  317. package/server/modules/providers/list/claude/claude-auth.provider.ts +21 -1
  318. package/server/modules/providers/list/claude/claude-fork.provider.ts +57 -0
  319. package/server/modules/providers/list/claude/claude-models.provider.ts +38 -6
  320. package/server/modules/providers/list/claude/claude-runtime.provider.js +463 -93
  321. package/server/modules/providers/list/claude/claude-sessions.provider.ts +478 -54
  322. package/server/modules/providers/list/claude/claude-skills.provider.ts +4 -1
  323. package/server/modules/providers/list/claude/claude.provider.ts +3 -0
  324. package/server/modules/providers/list/codex/codex-app-server.client.ts +243 -0
  325. package/server/modules/providers/list/codex/codex-fork.provider.ts +40 -0
  326. package/server/modules/providers/list/codex/codex-models.provider.ts +16 -0
  327. package/server/modules/providers/list/codex/{codex-runtime.provider.js → codex-runtime.provider.ts} +93 -66
  328. package/server/modules/providers/list/codex/codex-session-synchronizer.provider.ts +9 -0
  329. package/server/modules/providers/list/codex/codex-sessions.provider.ts +1806 -477
  330. package/server/modules/providers/list/codex/codex.provider.ts +3 -0
  331. package/server/modules/providers/list/cursor/cursor-runtime.provider.js +8 -6
  332. package/server/modules/providers/list/cursor/cursor-session-synchronizer.provider.ts +0 -1
  333. package/server/modules/providers/list/opencode/opencode-models.provider.ts +279 -6
  334. package/server/modules/providers/provider.routes.ts +36 -0
  335. package/server/modules/providers/services/provider-capabilities.service.ts +23 -0
  336. package/server/modules/providers/services/provider-token-usage.service.ts +166 -39
  337. package/server/modules/providers/services/session-conversations-search.service.ts +94 -7
  338. package/server/modules/providers/services/session-history-cache.service.ts +139 -0
  339. package/server/modules/providers/services/session-synchronizer.service.ts +125 -38
  340. package/server/modules/providers/services/sessions-watcher.service.ts +3 -64
  341. package/server/modules/providers/services/sessions.service.ts +201 -9
  342. package/server/modules/providers/tests/claude-auth.test.ts +58 -0
  343. package/server/modules/providers/tests/claude-models.test.ts +87 -0
  344. package/server/modules/providers/tests/claude-sessions.test.ts +552 -40
  345. package/server/modules/providers/tests/claude-subagent-echo.test.ts +25 -0
  346. package/server/modules/providers/tests/claude-token-budget.test.ts +104 -0
  347. package/server/modules/providers/tests/codex-message-editing.test.ts +419 -0
  348. package/server/modules/providers/tests/codex-runtime.test.ts +58 -0
  349. package/server/modules/providers/tests/codex-session-fork.test.ts +59 -0
  350. package/server/modules/providers/tests/codex-sessions.test.ts +337 -15
  351. package/server/modules/providers/tests/opencode-models.test.ts +166 -8
  352. package/server/modules/providers/tests/provider-token-usage.service.test.ts +188 -1
  353. package/server/modules/providers/tests/provider.routes.test.ts +61 -0
  354. package/server/modules/providers/tests/session-fork.test.ts +173 -0
  355. package/server/modules/providers/tests/session-history-cache.service.test.ts +143 -0
  356. package/server/modules/providers/tests/session-orphan-prune.test.ts +107 -0
  357. package/server/modules/providers/tests/session-synchronizer-coalescing.test.ts +136 -0
  358. package/server/modules/providers/tests/sessions.service.test.ts +67 -1
  359. package/server/modules/providers/tests/skills.test.ts +21 -5
  360. package/server/modules/scheduled-messages/index.ts +8 -0
  361. package/server/modules/scheduled-messages/scheduled-messages.routes.ts +68 -0
  362. package/server/modules/scheduled-messages/services/scheduled-message-dispatcher.service.ts +203 -0
  363. package/server/modules/scheduled-messages/services/scheduled-messages.service.ts +121 -0
  364. package/server/modules/scheduled-messages/tests/scheduled-messages.test.ts +310 -0
  365. package/server/modules/taskmaster/taskmaster.routes.ts +23 -33
  366. package/server/modules/taskmaster/tests/taskmaster.routes.test.ts +57 -0
  367. package/server/modules/user/tests/user.service.test.ts +90 -0
  368. package/server/modules/user/user.module.ts +10 -1
  369. package/server/modules/user/user.routes.ts +44 -0
  370. package/server/modules/user/user.service.ts +105 -0
  371. package/server/modules/voice/tests/voice.service.test.ts +3 -2
  372. package/server/modules/websocket/index.ts +8 -0
  373. package/server/modules/websocket/services/chat-run-registry.service.ts +17 -50
  374. package/server/modules/websocket/services/chat-session-writer.service.ts +36 -6
  375. package/server/modules/websocket/services/chat-websocket.service.ts +244 -15
  376. package/server/modules/websocket/services/session-upsert-broadcast.service.ts +108 -0
  377. package/server/modules/websocket/services/shell-websocket.service.ts +10 -3
  378. package/server/modules/websocket/tests/chat-edit-send.test.ts +309 -0
  379. package/server/modules/websocket/tests/chat-run-registry.test.ts +34 -3
  380. package/server/modules/websocket/tests/session-upsert-broadcast.test.ts +138 -0
  381. package/server/modules/websocket/tests/shell-websocket.service.test.ts +108 -0
  382. package/server/shared/claude-cli-path.ts +24 -6
  383. package/server/shared/index.ts +3 -0
  384. package/server/shared/interfaces.ts +62 -0
  385. package/server/shared/message-unification.ts +449 -0
  386. package/server/shared/tests/claude-cli-path.test.ts +58 -1
  387. package/server/shared/tests/message-unification.test.ts +218 -0
  388. package/server/shared/types.ts +123 -3
  389. package/server/shared/utils.ts +50 -0
  390. package/server/tsconfig.json +6 -2
  391. package/README.de.md +0 -257
  392. package/README.ja.md +0 -249
  393. package/README.ko.md +0 -249
  394. package/README.ru.md +0 -257
  395. package/README.tr.md +0 -258
  396. package/README.zh-CN.md +0 -249
  397. package/README.zh-TW.md +0 -249
  398. package/dist/assets/index-D3jfzuKN.css +0 -32
  399. package/dist/assets/index-DTMWjJj8.js +0 -1550
  400. package/dist-server/server/constants/config.js +0 -6
  401. package/dist-server/server/constants/config.js.map +0 -1
  402. package/server/constants/config.ts +0 -5
@@ -1,9 +1,30 @@
1
1
  import fsSync from 'node:fs';
2
+ import fsp from 'node:fs/promises';
3
+ import path from 'node:path';
2
4
  import readline from 'node:readline';
3
5
  import { sessionsDb } from '../../../../modules/database/index.js';
6
+ import { codexAppServer } from '../../../../modules/providers/list/codex/codex-app-server.client.js';
4
7
  import { parseFilesInputTag, toImageAttachments } from '../../../../shared/image-attachments.js';
5
- import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '../../../../shared/utils.js';
8
+ import { prepareTranscriptMessages } from '../../../../shared/message-unification.js';
9
+ import { AppError, createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage, truncateSubagentActivity, } from '../../../../shared/utils.js';
6
10
  const PROVIDER = 'codex';
11
+ /**
12
+ * How far up the `~/.codex/sessions/<year>/<month>/<day>` tree a subagent
13
+ * rollout is searched for when it is not next to its parent. Spawned agents
14
+ * are written seconds after the parent, so one directory level up (the month)
15
+ * already covers a run that crosses midnight.
16
+ */
17
+ const SUBAGENT_LOOKUP_PARENT_LEVELS = 2;
18
+ /**
19
+ * Upper bound on how much of a subagent's timeline is sent to the client. A
20
+ * long-running agent can record hundreds of tool calls, and the transcript only
21
+ * ever shows them behind a collapsed header, so shipping the whole history on
22
+ * every load costs far more than it shows.
23
+ */
24
+ const MAX_TRANSMITTED_SUBAGENT_ACTIVITIES = 200;
25
+ function readNonEmptyString(value) {
26
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
27
+ }
7
28
  function isVisibleCodexUserMessage(payload) {
8
29
  if (!payload || payload.type !== 'user_message') {
9
30
  return false;
@@ -13,6 +34,91 @@ function isVisibleCodexUserMessage(payload) {
13
34
  }
14
35
  return typeof payload.message === 'string' && payload.message.trim().length > 0;
15
36
  }
37
+ /**
38
+ * Follows which turn a Codex rollout is inside as its rows stream past.
39
+ *
40
+ * Codex writes no per-row id — every line is `{timestamp, type, payload}` and
41
+ * the `user_message` event that carries a prompt has no identity of its own —
42
+ * so a turn id is the only durable address a user message has. Turns are
43
+ * bracketed by rows that do carry `turn_id`: `task_started` opens one,
44
+ * `turn_context` restates it, `task_complete` closes it, and the prompt is
45
+ * written between them. That id is also exactly what `thread/fork` cuts at,
46
+ * which is what makes "edit this message" and "fork from here" addressable
47
+ * for Codex at all.
48
+ *
49
+ * `thread_rolled_back` retires the last N turns in place: the rows stay in the
50
+ * file, but the turns are no longer part of the thread and the fork endpoint
51
+ * refuses to cut at one. They are tracked here so a retired turn is never
52
+ * offered as an anchor, rather than discovered when the fork fails.
53
+ */
54
+ function createCodexTurnTracker() {
55
+ /** Turn ids still part of the conversation, oldest first. */
56
+ const liveTurnIds = [];
57
+ const seenTurnIds = new Set();
58
+ const rolledBackTurnIds = new Set();
59
+ let currentTurnId;
60
+ return {
61
+ /** Feeds one rollout row in. */
62
+ observe(entryType, payload) {
63
+ if (entryType === 'event_msg' && payload.type === 'thread_rolled_back') {
64
+ const retiredTurns = Number(payload.num_turns);
65
+ for (let retired = 0; retired < retiredTurns && liveTurnIds.length > 0; retired++) {
66
+ rolledBackTurnIds.add(liveTurnIds.pop());
67
+ }
68
+ currentTurnId = undefined;
69
+ return;
70
+ }
71
+ const turnId = readNonEmptyString(payload.turn_id);
72
+ if (!turnId) {
73
+ return;
74
+ }
75
+ currentTurnId = turnId;
76
+ if (!seenTurnIds.has(turnId)) {
77
+ seenTurnIds.add(turnId);
78
+ liveTurnIds.push(turnId);
79
+ }
80
+ },
81
+ /** The turn the rows being read belong to, or undefined outside one. */
82
+ getCurrentTurnId() {
83
+ return currentTurnId;
84
+ },
85
+ getLiveTurnIds() {
86
+ return liveTurnIds;
87
+ },
88
+ isRolledBack(turnId) {
89
+ return rolledBackTurnIds.has(turnId);
90
+ },
91
+ };
92
+ }
93
+ /**
94
+ * Reads the turns a Codex rollout still contains, oldest first.
95
+ *
96
+ * A separate pass rather than a by-product of the transcript reader: this runs
97
+ * once when a message is edited, while the reader runs on every history fetch,
98
+ * and both share the one rule for what a live turn is.
99
+ */
100
+ async function readCodexLiveTurnIds(filePath) {
101
+ const turns = createCodexTurnTracker();
102
+ const stream = fsSync.createReadStream(filePath);
103
+ const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
104
+ for await (const line of lines) {
105
+ if (!line.trim()) {
106
+ continue;
107
+ }
108
+ let entry;
109
+ try {
110
+ entry = JSON.parse(line);
111
+ }
112
+ catch {
113
+ continue;
114
+ }
115
+ const payload = readObjectRecord(entry.payload);
116
+ if (payload) {
117
+ turns.observe(entry.type, payload);
118
+ }
119
+ }
120
+ return turns.getLiveTurnIds();
121
+ }
16
122
  /**
17
123
  * Reads the image attachments Codex records on `user_message` events.
18
124
  * Turns sent with `local_image` input items land in `local_images` as file
@@ -63,6 +169,69 @@ function extractCodexTextContent(content) {
63
169
  .filter(Boolean)
64
170
  .join('\n');
65
171
  }
172
+ /**
173
+ * Reads the markdown out of Codex's `<proposed_plan>` envelope.
174
+ *
175
+ * Codex delivers a plan as a wrapped assistant message while Claude delivers
176
+ * one as an `ExitPlanMode` call. Recognizing the envelope here lets both end up
177
+ * on the same plan card instead of one provider showing a card and the other
178
+ * showing prose with a stray tag in it. The closing tag is optional because a
179
+ * streamed plan exposes the opening tag first.
180
+ *
181
+ * Exported for tests.
182
+ */
183
+ export function readCodexProposedPlan(text) {
184
+ const openingTag = /^\s*<proposed_plan>[ \t]*(?:\r?\n)?/i;
185
+ if (!openingTag.test(text)) {
186
+ return null;
187
+ }
188
+ const body = text
189
+ .replace(openingTag, '')
190
+ .replace(/(?:\r?\n)?[ \t]*<\/proposed_plan>\s*$/i, '')
191
+ .trim();
192
+ return body || null;
193
+ }
194
+ /**
195
+ * The block Codex appends to a reply that leaned on its memory files. It is
196
+ * always the last thing in the message and is meant for programmatic parsing,
197
+ * so it reads as raw XML when left in the prose.
198
+ */
199
+ const CODEX_MEMORY_CITATION_BLOCK = /<oai-mem-citation>([\s\S]*?)<\/oai-mem-citation>\s*$/i;
200
+ /**
201
+ * Lifts Codex's memory citations out of an assistant reply.
202
+ *
203
+ * The block names the memory files and line ranges the answer drew on, which is
204
+ * worth showing — but as a footnote under the reply, not as markup inside it.
205
+ * The trailing `<rollout_ids>` list is dropped: those are handles to earlier
206
+ * rollouts that the transcript view has no way to open.
207
+ *
208
+ * Exported for tests.
209
+ */
210
+ export function readCodexMemoryCitations(text) {
211
+ const block = CODEX_MEMORY_CITATION_BLOCK.exec(text);
212
+ if (!block) {
213
+ return { text };
214
+ }
215
+ const entries = /<citation_entries>([\s\S]*?)<\/citation_entries>/i.exec(block[1])?.[1] ?? '';
216
+ const memoryCitations = [];
217
+ for (const line of entries.split('\n')) {
218
+ const entry = line.trim();
219
+ if (!entry) {
220
+ continue;
221
+ }
222
+ const noteMarker = entry.indexOf('|note=');
223
+ const source = (noteMarker === -1 ? entry : entry.slice(0, noteMarker)).trim();
224
+ if (!source) {
225
+ continue;
226
+ }
227
+ const note = noteMarker === -1
228
+ ? ''
229
+ : entry.slice(noteMarker + '|note='.length).trim().replace(/^\[/, '').replace(/\]$/, '').trim();
230
+ memoryCitations.push(note ? { source, note } : { source });
231
+ }
232
+ const prose = text.slice(0, block.index).trimEnd();
233
+ return memoryCitations.length > 0 ? { text: prose, memoryCitations } : { text: prose };
234
+ }
66
235
  function extractCodexToolOutput(output) {
67
236
  if (typeof output === 'string') {
68
237
  return output;
@@ -78,17 +247,13 @@ function extractCodexToolOutput(output) {
78
247
  .filter(Boolean)
79
248
  .join('');
80
249
  }
81
- function readRunningExecOutput(output) {
82
- const runningCell = /Script running with cell ID\s+(\S+)/i.exec(output);
83
- if (!runningCell) {
84
- return null;
85
- }
86
- const outputMarker = /\r?\nOutput:\r?\n/i.exec(output);
87
- return {
88
- cellId: runningCell[1],
89
- content: outputMarker ? output.slice((outputMarker.index || 0) + outputMarker[0].length) : '',
90
- };
91
- }
250
+ /**
251
+ * Decodes one JavaScript string literal (single, double or backtick quoted).
252
+ *
253
+ * Template literals with `${}` interpolation are returned with the expression
254
+ * text intact — the transcript has no bindings to evaluate, and showing the
255
+ * raw template is still far more readable than the surrounding program.
256
+ */
92
257
  function decodeJavaScriptStringLiteral(literal) {
93
258
  if (literal.startsWith('"')) {
94
259
  try {
@@ -105,50 +270,413 @@ function decodeJavaScriptStringLiteral(literal) {
105
270
  .replace(/\\t/g, '\t')
106
271
  .replace(/\\([\\'`])/g, '$1');
107
272
  }
108
- function extractNestedCodexCommands(source) {
109
- const commands = [];
110
- const commandPattern = /(?:["']command["']|\bcommand)\s*:\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/gs;
111
- for (const match of source.matchAll(commandPattern)) {
112
- commands.push(decodeJavaScriptStringLiteral(match[1]));
113
- }
114
- if (commands.length === 0) {
115
- const arrayPattern = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*\[([\s\S]*?)\]\s*;/g;
116
- const stringPattern = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;
117
- for (const arrayMatch of source.matchAll(arrayPattern)) {
118
- const arrayName = arrayMatch[1];
119
- if (!new RegExp(`\\b${arrayName}\\.map\\s*\\(`).test(source)) {
273
+ /**
274
+ * Returns the source of the argument list of the call that opens at
275
+ * `openParenIndex`, skipping over parens that appear inside string literals.
276
+ *
277
+ * A plain regex cannot be used here: shell commands routinely embed `(`/`)`
278
+ * and quotes, so the argument object has to be found by balancing.
279
+ */
280
+ function readCallArguments(source, openParenIndex) {
281
+ let depth = 0;
282
+ let quote = null;
283
+ for (let index = openParenIndex; index < source.length; index += 1) {
284
+ const character = source[index];
285
+ if (quote) {
286
+ if (character === '\\') {
287
+ index += 1;
120
288
  continue;
121
289
  }
122
- for (const stringMatch of arrayMatch[2].matchAll(stringPattern)) {
123
- commands.push(decodeJavaScriptStringLiteral(stringMatch[1]));
290
+ if (character === quote) {
291
+ quote = null;
124
292
  }
293
+ continue;
294
+ }
295
+ if (character === '"' || character === "'" || character === '`') {
296
+ quote = character;
297
+ continue;
298
+ }
299
+ if (character === '(') {
300
+ depth += 1;
301
+ continue;
302
+ }
303
+ if (character === ')') {
304
+ depth -= 1;
305
+ if (depth === 0) {
306
+ return source.slice(openParenIndex + 1, index);
307
+ }
308
+ }
309
+ }
310
+ return null;
311
+ }
312
+ /** Reads `key: "value"` / `"key": "value"` out of an object-literal source. */
313
+ function readStringProperty(objectSource, key) {
314
+ const pattern = new RegExp(`(?:["']${key}["']|\\b${key})\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`, 's');
315
+ const match = pattern.exec(objectSource);
316
+ return match ? decodeJavaScriptStringLiteral(match[1]) : undefined;
317
+ }
318
+ /** Reads every `q: "..."` entry out of a `web__run` search-query array. */
319
+ function readSearchQueries(objectSource) {
320
+ const pattern = /(?:["']q["']|\bq)\s*:\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/gs;
321
+ return Array.from(objectSource.matchAll(pattern), (match) => decodeJavaScriptStringLiteral(match[1]));
322
+ }
323
+ /**
324
+ * Finds the patch body an `apply_patch` call is given.
325
+ *
326
+ * The program almost always assigns it to a local first
327
+ * (`const patch = "*** Begin Patch..."; tools.apply_patch(patch)`), so the
328
+ * argument itself is usually an identifier. Scanning the whole script for the
329
+ * literal that carries the patch header covers both forms.
330
+ */
331
+ function readPatchLiteral(source) {
332
+ const pattern = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/gs;
333
+ for (const match of source.matchAll(pattern)) {
334
+ const decoded = decodeJavaScriptStringLiteral(match[1]);
335
+ if (decoded.includes('*** Begin Patch')) {
336
+ return decoded;
337
+ }
338
+ }
339
+ return undefined;
340
+ }
341
+ /**
342
+ * Reads the steps of an `update_plan` call made from an exec script.
343
+ *
344
+ * The script writes its argument as a JavaScript object literal with unquoted
345
+ * keys, so it is not JSON — each `{step, status}` entry is matched directly.
346
+ */
347
+ function readPlanSteps(objectSource) {
348
+ const todos = [];
349
+ for (const entry of objectSource.matchAll(/\{([^{}]*)\}/g)) {
350
+ const content = readStringProperty(entry[1], 'step') ?? readStringProperty(entry[1], 'content');
351
+ if (content) {
352
+ todos.push({ content, status: readStringProperty(entry[1], 'status') ?? 'pending' });
353
+ }
354
+ }
355
+ return todos;
356
+ }
357
+ /**
358
+ * Recovers commands a script keeps in a local array and maps over, which is how
359
+ * Codex batches several shell calls:
360
+ * `const cmds = ["a", "b"]; await Promise.all(cmds.map(command => tools.shell_command({ command })))`
361
+ * The call site then passes `{ command }` shorthand, so there is no literal to
362
+ * read at the call itself.
363
+ */
364
+ function readMappedCommandCandidates(source) {
365
+ const commands = [];
366
+ const arrayPattern = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*\[([\s\S]*?)\]\s*;/g;
367
+ const stringPattern = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/gs;
368
+ for (const arrayMatch of source.matchAll(arrayPattern)) {
369
+ if (!new RegExp(`\\b${arrayMatch[1]}\\.map\\s*\\(`).test(source)) {
370
+ continue;
371
+ }
372
+ for (const stringMatch of arrayMatch[2].matchAll(stringPattern)) {
373
+ commands.push(decodeJavaScriptStringLiteral(stringMatch[1]));
125
374
  }
126
375
  }
127
376
  return commands;
128
377
  }
129
378
  /**
130
- * Newer Codex rollouts persist the orchestration wrapper (`exec`) instead of
131
- * the nested tool name. Recover the useful UI-level operation so history does
132
- * not degrade into rows labelled only "exec / Parameters".
379
+ * Turns one Codex `exec` script into the operations it performs, in source
380
+ * order. An empty result means the script did nothing recognizable and the
381
+ * caller should fall back to showing it as code.
382
+ *
383
+ * Exported for tests.
133
384
  */
134
- function translateCodexExecInput(input) {
135
- const source = typeof input === 'string' ? input : String(input || '');
136
- if (/\btools\.(?:shell_command|exec_command)\s*\(/.test(source)) {
137
- const commands = extractNestedCodexCommands(source);
138
- if (commands.length > 0) {
139
- return {
140
- toolName: 'Bash',
141
- toolInput: JSON.stringify({ command: commands.join('\n') }),
142
- };
385
+ export function parseCodexExecScript(input) {
386
+ const source = typeof input === 'string' ? input : String(input ?? '');
387
+ if (!source.includes('tools.')) {
388
+ return [];
389
+ }
390
+ const operations = [];
391
+ const callPattern = /tools\.([A-Za-z_0-9]+)\s*\(/g;
392
+ /** Filled in lazily, and only once, for shorthand-argument shell calls. */
393
+ let mappedCommands = null;
394
+ for (const match of source.matchAll(callPattern)) {
395
+ const toolName = match[1];
396
+ const openParenIndex = match.index + match[0].length - 1;
397
+ const argumentSource = readCallArguments(source, openParenIndex) ?? '';
398
+ switch (toolName) {
399
+ case 'shell_command':
400
+ case 'exec_command': {
401
+ const command = readStringProperty(argumentSource, 'command')
402
+ ?? readStringProperty(argumentSource, 'cmd');
403
+ if (command) {
404
+ operations.push({
405
+ kind: 'shell',
406
+ command,
407
+ justification: readStringProperty(argumentSource, 'justification'),
408
+ });
409
+ break;
410
+ }
411
+ if (mappedCommands === null) {
412
+ mappedCommands = readMappedCommandCandidates(source);
413
+ for (const mappedCommand of mappedCommands) {
414
+ operations.push({ kind: 'shell', command: mappedCommand });
415
+ }
416
+ }
417
+ break;
418
+ }
419
+ case 'write_stdin': {
420
+ operations.push({ kind: 'stdin', chars: readStringProperty(argumentSource, 'chars') ?? '' });
421
+ break;
422
+ }
423
+ case 'apply_patch': {
424
+ const patch = readPatchLiteral(argumentSource) ?? readPatchLiteral(source);
425
+ if (patch) {
426
+ operations.push({ kind: 'patch', patch });
427
+ }
428
+ break;
429
+ }
430
+ case 'web__run':
431
+ case 'web_search': {
432
+ const queries = readSearchQueries(argumentSource);
433
+ if (queries.length > 0) {
434
+ operations.push({ kind: 'search', queries });
435
+ }
436
+ break;
437
+ }
438
+ case 'update_plan': {
439
+ const todos = readPlanSteps(argumentSource);
440
+ if (todos.length > 0) {
441
+ operations.push({ kind: 'plan', todos });
442
+ }
443
+ break;
444
+ }
445
+ default:
446
+ break;
143
447
  }
144
448
  }
145
- return null;
449
+ return operations;
146
450
  }
147
- function humanizeCodexToolName(toolName) {
148
- return toolName
149
- .replace(/__/g, ' ')
150
- .replace(/_/g, ' ')
151
- .replace(/\b\w/g, (character) => character.toUpperCase());
451
+ /**
452
+ * Strips the two nested envelopes Codex wraps shell output in.
453
+ *
454
+ * The outer one reports on the sandbox *script* (`Script completed`, its wall
455
+ * time, and `Output:`); the inner one reports on the *command* (`Exit code`,
456
+ * its own wall time, an optional line count). Neither is useful in a chat
457
+ * transcript, but the exit code decides whether the row is shown as failed, so
458
+ * it is lifted out before the text is discarded.
459
+ *
460
+ * Exported for tests.
461
+ */
462
+ export function cleanCodexShellOutput(rawOutput) {
463
+ let output = rawOutput;
464
+ let exitCode;
465
+ let runningCellId;
466
+ let truncated = false;
467
+ const runningMatch = /^Script running with cell ID\s+(\S+)[^\n]*\n?/i.exec(output);
468
+ if (runningMatch) {
469
+ runningCellId = runningMatch[1];
470
+ output = output.slice(runningMatch[0].length);
471
+ }
472
+ else {
473
+ output = output.replace(/^Script (?:completed|failed)[^\n]*\n?/i, '');
474
+ }
475
+ output = output.replace(/^Wall time[^\n]*\n?/i, '');
476
+ output = output.replace(/^Output:\s*\n?/i, '');
477
+ output = output.replace(/^Script error:\s*\n?/i, '');
478
+ const truncationMatch = /^Warning: truncated output[^\n]*\n(?:Total output lines:[^\n]*\n)?\n?/i.exec(output);
479
+ if (truncationMatch) {
480
+ truncated = true;
481
+ output = output.slice(truncationMatch[0].length);
482
+ output = output.replace(/^Script error:\s*\n?/i, '');
483
+ }
484
+ const exitCodeMatch = /^Exit code:\s*(-?\d+)[^\n]*\n?/i.exec(output);
485
+ if (exitCodeMatch) {
486
+ exitCode = Number.parseInt(exitCodeMatch[1], 10);
487
+ output = output.slice(exitCodeMatch[0].length);
488
+ output = output.replace(/^Wall time:[^\n]*\n?/i, '');
489
+ output = output.replace(/^Total output lines:[^\n]*\n?/i, '');
490
+ output = output.replace(/^Output:\s*\n?/i, '');
491
+ }
492
+ return { output, exitCode, runningCellId, truncated };
493
+ }
494
+ /**
495
+ * `write_stdin` answers with a JSON envelope rather than plain text. Only its
496
+ * `output` and `exit_code` matter to a reader.
497
+ */
498
+ function readCodexStdinOutput(rawOutput) {
499
+ const trimmed = rawOutput.trim();
500
+ const jsonStart = trimmed.indexOf('{');
501
+ if (jsonStart === -1) {
502
+ return null;
503
+ }
504
+ try {
505
+ const parsed = JSON.parse(trimmed.slice(jsonStart));
506
+ if (typeof parsed.output !== 'string') {
507
+ return null;
508
+ }
509
+ return {
510
+ output: parsed.output,
511
+ exitCode: typeof parsed.exit_code === 'number' ? parsed.exit_code : undefined,
512
+ truncated: false,
513
+ };
514
+ }
515
+ catch {
516
+ return null;
517
+ }
518
+ }
519
+ /**
520
+ * Rebuilds the before/after text of one unified diff.
521
+ *
522
+ * Only the hunks are available — never the whole file — so the reconstruction
523
+ * keeps context lines in both sides and drops hunk headers. Feeding that pair
524
+ * to the frontend's line differ reproduces exactly the additions, removals and
525
+ * surrounding context the patch described, which is what Claude's `Edit` rows
526
+ * already show.
527
+ *
528
+ * Exported for tests.
529
+ */
530
+ export function unifiedDiffToTexts(unifiedDiff) {
531
+ const oldLines = [];
532
+ const newLines = [];
533
+ for (const line of unifiedDiff.split('\n')) {
534
+ if (line.startsWith('@@') || line.startsWith('\\ No newline')) {
535
+ continue;
536
+ }
537
+ if (line.startsWith('+')) {
538
+ newLines.push(line.slice(1));
539
+ continue;
540
+ }
541
+ if (line.startsWith('-')) {
542
+ oldLines.push(line.slice(1));
543
+ continue;
544
+ }
545
+ const contextLine = line.startsWith(' ') ? line.slice(1) : line;
546
+ oldLines.push(contextLine);
547
+ newLines.push(contextLine);
548
+ }
549
+ // A unified diff ends with a newline, which would otherwise reconstruct as a
550
+ // phantom trailing blank line on both sides.
551
+ if (oldLines[oldLines.length - 1] === '' && newLines[newLines.length - 1] === '') {
552
+ oldLines.pop();
553
+ newLines.pop();
554
+ }
555
+ return { oldText: oldLines.join('\n'), newText: newLines.join('\n') };
556
+ }
557
+ /**
558
+ * Splits a `*** Begin Patch` body into one change per file.
559
+ *
560
+ * Exported for tests.
561
+ */
562
+ export function parseCodexPatch(patch) {
563
+ const changes = [];
564
+ const lines = patch.split('\n');
565
+ let current = null;
566
+ const flush = () => {
567
+ if (!current) {
568
+ return;
569
+ }
570
+ const { oldText, newText } = unifiedDiffToTexts(current.body.join('\n'));
571
+ changes.push({
572
+ filePath: current.filePath,
573
+ changeType: current.changeType,
574
+ oldText: current.changeType === 'add' ? '' : oldText,
575
+ newText: current.changeType === 'delete' ? '' : newText,
576
+ });
577
+ current = null;
578
+ };
579
+ for (const line of lines) {
580
+ const fileHeader = /^\*\*\* (Add|Update|Delete) File:\s*(.+)$/.exec(line);
581
+ if (fileHeader) {
582
+ flush();
583
+ const changeType = fileHeader[1].toLowerCase();
584
+ current = { filePath: fileHeader[2].trim(), changeType, body: [] };
585
+ continue;
586
+ }
587
+ if (line.startsWith('*** ')) {
588
+ // `*** Begin Patch`, `*** End Patch`, `*** Move to:` — never diff content.
589
+ continue;
590
+ }
591
+ current?.body.push(line);
592
+ }
593
+ flush();
594
+ return changes;
595
+ }
596
+ /** Converts a `patch_apply_end` change map into the same per-file shape. */
597
+ function readPatchApplyChanges(changes) {
598
+ const record = readObjectRecord(changes);
599
+ if (!record) {
600
+ return [];
601
+ }
602
+ const parsed = [];
603
+ for (const [filePath, rawChange] of Object.entries(record)) {
604
+ const change = readObjectRecord(rawChange);
605
+ if (!change) {
606
+ continue;
607
+ }
608
+ const changeType = change.type === 'add' || change.type === 'delete' ? change.type : 'update';
609
+ const { oldText, newText } = unifiedDiffToTexts(typeof change.unified_diff === 'string' ? change.unified_diff : '');
610
+ parsed.push({
611
+ filePath,
612
+ changeType,
613
+ oldText: changeType === 'add' ? '' : oldText,
614
+ newText: changeType === 'delete' ? '' : newText,
615
+ });
616
+ }
617
+ return parsed;
618
+ }
619
+ /** Maps a file change onto the tool the frontend already renders diffs for. */
620
+ function fileChangeToToolMessage(change, timestamp, toolCallId) {
621
+ const toolName = change.changeType === 'add' ? 'Write' : 'Edit';
622
+ return {
623
+ type: 'tool_use',
624
+ timestamp,
625
+ toolName,
626
+ toolInput: JSON.stringify({
627
+ file_path: change.filePath,
628
+ old_string: change.oldText,
629
+ new_string: change.newText,
630
+ ...(change.changeType === 'delete' ? { deleted: true } : {}),
631
+ }),
632
+ toolCallId,
633
+ };
634
+ }
635
+ /** Reads the `file_path` back out of a rendered file-change row. */
636
+ function readRowFilePath(row) {
637
+ try {
638
+ return String(JSON.parse(String(row.toolInput ?? '{}')).file_path ?? '');
639
+ }
640
+ catch {
641
+ return '';
642
+ }
643
+ }
644
+ /**
645
+ * Rewrites the rows reconstructed from a patch call's input with the
646
+ * authoritative diffs Codex reports once the patch has been applied.
647
+ *
648
+ * Rows are matched by path, never by position: `patch_apply_end` reports the
649
+ * touched files in map order, which does not follow the order they appeared in
650
+ * the patch body. Rows whose file the report does not mention are dropped
651
+ * rather than left behind claiming an edit that never happened.
652
+ */
653
+ function rewritePatchRows(rows, changes, callId, messages) {
654
+ const rowsByPath = new Map();
655
+ for (const row of rows) {
656
+ rowsByPath.set(readRowFilePath(row), row);
657
+ }
658
+ const keptRows = [];
659
+ for (const [index, change] of changes.entries()) {
660
+ const replacement = fileChangeToToolMessage(change, String(rows[0]?.timestamp ?? ''), `${callId}#${index}`);
661
+ const existing = rowsByPath.get(change.filePath);
662
+ if (existing) {
663
+ existing.toolName = replacement.toolName;
664
+ existing.toolInput = replacement.toolInput;
665
+ keptRows.push(existing);
666
+ rowsByPath.delete(change.filePath);
667
+ continue;
668
+ }
669
+ replacement.timestamp = rows[0]?.timestamp ?? replacement.timestamp;
670
+ keptRows.push(replacement);
671
+ messages.push(replacement);
672
+ }
673
+ for (const surplus of rowsByPath.values()) {
674
+ const position = messages.indexOf(surplus);
675
+ if (position !== -1) {
676
+ messages.splice(position, 1);
677
+ }
678
+ }
679
+ rows.splice(0, rows.length, ...keptRows);
152
680
  }
153
681
  function parseCodexSubagentMessage(payload) {
154
682
  const text = extractCodexTextContent(payload.content);
@@ -163,6 +691,250 @@ function parseCodexSubagentMessage(payload) {
163
691
  result: header?.[3]?.trim() || '',
164
692
  };
165
693
  }
694
+ /**
695
+ * Codex names a spawned agent's rollout file `rollout-<timestamp>-<threadId>`
696
+ * and writes it next to the parent's. Look there first, then widen to the
697
+ * enclosing day/month directories so a run that crosses midnight still
698
+ * resolves, and give up rather than walking the whole archive.
699
+ */
700
+ async function findCodexSubagentRollout(parentFilePath, agentThreadId) {
701
+ const suffix = `-${agentThreadId}.jsonl`;
702
+ let directory = path.dirname(parentFilePath);
703
+ for (let level = 0; level <= SUBAGENT_LOOKUP_PARENT_LEVELS; level += 1) {
704
+ const match = await findFileWithSuffix(directory, suffix, level === 0 ? 0 : level);
705
+ if (match) {
706
+ return match;
707
+ }
708
+ const parent = path.dirname(directory);
709
+ if (parent === directory) {
710
+ break;
711
+ }
712
+ directory = parent;
713
+ }
714
+ return null;
715
+ }
716
+ /** Depth-limited search for a file whose name ends with `suffix`. */
717
+ async function findFileWithSuffix(directory, suffix, depth) {
718
+ let entries;
719
+ try {
720
+ entries = await fsp.readdir(directory, { withFileTypes: true });
721
+ }
722
+ catch {
723
+ return null;
724
+ }
725
+ const subdirectories = [];
726
+ for (const entry of entries) {
727
+ if (entry.isDirectory()) {
728
+ subdirectories.push(path.join(directory, entry.name));
729
+ continue;
730
+ }
731
+ if (entry.name.endsWith(suffix)) {
732
+ return path.join(directory, entry.name);
733
+ }
734
+ }
735
+ if (depth <= 0) {
736
+ return null;
737
+ }
738
+ for (const subdirectory of subdirectories) {
739
+ const match = await findFileWithSuffix(subdirectory, suffix, depth - 1);
740
+ if (match) {
741
+ return match;
742
+ }
743
+ }
744
+ return null;
745
+ }
746
+ /**
747
+ * Flattens a spawned agent's own rollout into the shared activity timeline.
748
+ *
749
+ * The subagent's transcript is the same format as the parent's, so its shell
750
+ * and patch calls go through the same translation and end up rendered by the
751
+ * same components as the main thread's.
752
+ */
753
+ async function readCodexSubagentTranscript(filePath) {
754
+ const activity = [];
755
+ const transcript = { activity };
756
+ const pendingResults = new Map();
757
+ let fileStream;
758
+ try {
759
+ fileStream = fsSync.createReadStream(filePath);
760
+ }
761
+ catch {
762
+ return transcript;
763
+ }
764
+ const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
765
+ for await (const line of rl) {
766
+ if (!line.trim()) {
767
+ continue;
768
+ }
769
+ let entry;
770
+ try {
771
+ entry = JSON.parse(line);
772
+ }
773
+ catch {
774
+ continue;
775
+ }
776
+ const payload = readObjectRecord(entry.payload);
777
+ if (!payload) {
778
+ continue;
779
+ }
780
+ if (entry.type === 'session_meta') {
781
+ // A resumed rollout writes a second, sparser session_meta; assigning
782
+ // unconditionally would erase the identity the first one carried.
783
+ transcript.nickname = readNonEmptyString(payload.agent_nickname) ?? transcript.nickname;
784
+ transcript.agentPath = readNonEmptyString(payload.agent_path) ?? transcript.agentPath;
785
+ continue;
786
+ }
787
+ if (entry.type === 'turn_context') {
788
+ transcript.model = readNonEmptyString(payload.model) ?? transcript.model;
789
+ continue;
790
+ }
791
+ if (entry.type !== 'response_item') {
792
+ continue;
793
+ }
794
+ const timestamp = typeof entry.timestamp === 'string' ? entry.timestamp : undefined;
795
+ if (payload.type === 'message' && payload.role === 'assistant') {
796
+ const content = extractCodexTextContent(payload.content).trim();
797
+ if (content) {
798
+ activity.push({ kind: 'text', content, timestamp });
799
+ }
800
+ continue;
801
+ }
802
+ if (payload.type === 'reasoning') {
803
+ const summary = Array.isArray(payload.summary)
804
+ ? payload.summary.map((item) => item?.text).filter(Boolean).join('\n')
805
+ : '';
806
+ if (summary.trim()) {
807
+ activity.push({ kind: 'thinking', content: summary, timestamp });
808
+ }
809
+ continue;
810
+ }
811
+ if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
812
+ const callId = readNonEmptyString(payload.call_id) ?? generateMessageId('codex-subagent-call');
813
+ for (const child of translateCodexToolCall(payload, callId)) {
814
+ const record = { ...child, timestamp };
815
+ activity.push(record);
816
+ pendingResults.set(callId, record);
817
+ }
818
+ continue;
819
+ }
820
+ if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output') {
821
+ const callId = readNonEmptyString(payload.call_id);
822
+ const target = callId ? pendingResults.get(callId) : undefined;
823
+ if (!target) {
824
+ continue;
825
+ }
826
+ const cleaned = cleanCodexShellOutput(extractCodexToolOutput(payload.output));
827
+ target.toolResult = {
828
+ content: cleaned.output,
829
+ isError: cleaned.exitCode !== undefined && cleaned.exitCode !== 0,
830
+ };
831
+ }
832
+ }
833
+ return transcript;
834
+ }
835
+ /**
836
+ * Translates one persisted Codex tool call into the canonical tool rows the
837
+ * transcript renders. Most calls produce exactly one row; a patch produces one
838
+ * per file it touched.
839
+ *
840
+ * Shared by the main thread and by subagent transcripts so a subagent's shell
841
+ * command looks identical to the parent's.
842
+ */
843
+ function translateCodexToolCall(payload, callId) {
844
+ const name = readNonEmptyString(payload.name) ?? 'tool';
845
+ const rawInput = payload.type === 'custom_tool_call' ? payload.input : payload.arguments;
846
+ if (name === 'exec') {
847
+ const operations = parseCodexExecScript(rawInput);
848
+ const rows = [];
849
+ for (const operation of operations) {
850
+ if (operation.kind === 'shell') {
851
+ rows.push({
852
+ kind: 'tool',
853
+ toolId: callId,
854
+ toolName: 'Bash',
855
+ toolInput: { command: operation.command, description: operation.justification },
856
+ });
857
+ }
858
+ else if (operation.kind === 'patch') {
859
+ for (const change of parseCodexPatch(operation.patch)) {
860
+ rows.push({
861
+ kind: 'tool',
862
+ toolId: callId,
863
+ toolName: change.changeType === 'add' ? 'Write' : 'Edit',
864
+ toolInput: {
865
+ file_path: change.filePath,
866
+ old_string: change.oldText,
867
+ new_string: change.newText,
868
+ },
869
+ });
870
+ }
871
+ }
872
+ else if (operation.kind === 'search') {
873
+ rows.push({
874
+ kind: 'tool',
875
+ toolId: callId,
876
+ toolName: 'WebSearch',
877
+ toolInput: { query: operation.queries.join(' | ') },
878
+ });
879
+ }
880
+ }
881
+ if (rows.length > 0) {
882
+ return rows;
883
+ }
884
+ }
885
+ if (name === 'shell_command' || name === 'exec_command') {
886
+ let command = '';
887
+ try {
888
+ const args = JSON.parse(String(rawInput || '{}'));
889
+ command = String(args.command ?? args.cmd ?? '');
890
+ }
891
+ catch {
892
+ command = String(rawInput ?? '');
893
+ }
894
+ return [{ kind: 'tool', toolId: callId, toolName: 'Bash', toolInput: { command } }];
895
+ }
896
+ if (name === 'apply_patch') {
897
+ return parseCodexPatch(String(rawInput ?? '')).map((change) => ({
898
+ kind: 'tool',
899
+ toolId: callId,
900
+ toolName: change.changeType === 'add' ? 'Write' : 'Edit',
901
+ toolInput: {
902
+ file_path: change.filePath,
903
+ old_string: change.oldText,
904
+ new_string: change.newText,
905
+ },
906
+ }));
907
+ }
908
+ if (name === 'update_plan') {
909
+ return [{ kind: 'tool', toolId: callId, toolName: 'TodoWrite', toolInput: readCodexPlanInput(rawInput) }];
910
+ }
911
+ return [{ kind: 'tool', toolId: callId, toolName: humanizeCodexToolName(name), toolInput: rawInput }];
912
+ }
913
+ /**
914
+ * Converts Codex's `update_plan` steps into the todo shape Claude's
915
+ * `TodoWrite` already uses, so one renderer covers both providers.
916
+ */
917
+ function readCodexPlanInput(rawArguments) {
918
+ try {
919
+ const parsed = JSON.parse(String(rawArguments || '{}'));
920
+ const steps = Array.isArray(parsed.plan) ? parsed.plan : [];
921
+ return {
922
+ todos: steps.map((step) => ({
923
+ content: typeof step?.step === 'string' ? step.step : String(step?.content ?? ''),
924
+ status: typeof step?.status === 'string' ? step.status : 'pending',
925
+ })),
926
+ };
927
+ }
928
+ catch {
929
+ return { todos: [] };
930
+ }
931
+ }
932
+ function humanizeCodexToolName(toolName) {
933
+ return toolName
934
+ .replace(/__/g, ' ')
935
+ .replace(/_/g, ' ')
936
+ .replace(/\b\w/g, (character) => character.toUpperCase());
937
+ }
166
938
  const CODEX_COLLABORATION_CONTROL_TOOLS = new Set([
167
939
  'followup_task',
168
940
  'interrupt_agent',
@@ -170,372 +942,667 @@ const CODEX_COLLABORATION_CONTROL_TOOLS = new Set([
170
942
  'send_message',
171
943
  'wait_agent',
172
944
  ]);
173
- function readNonEmptyString(value) {
174
- return typeof value === 'string' && value.length > 0 ? value : undefined;
175
- }
176
- async function getCodexSessionMessages(sessionId, limit = null, offset = 0) {
177
- try {
178
- const sessionFilePath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
179
- if (!sessionFilePath) {
180
- console.warn(`Codex session file not found for session ${sessionId}`);
181
- return { messages: [], total: 0, hasMore: false };
182
- }
183
- const messages = [];
184
- let tokenUsage = null;
185
- const ignoredToolCallIds = new Set();
186
- const execToolCallIds = new Set();
187
- const execCallByCellId = new Map();
188
- const waitCallToExecCall = new Map();
189
- const pendingExecOutput = new Map();
190
- const completedExecCalls = new Set();
191
- const subagentsByCallId = new Map();
192
- const subagentsByPath = new Map();
193
- const fileStream = fsSync.createReadStream(sessionFilePath);
194
- const rl = readline.createInterface({
195
- input: fileStream,
196
- crlfDelay: Infinity,
197
- });
198
- for await (const line of rl) {
199
- if (!line.trim()) {
945
+ // ─── Transcript reader ──────────────────────────────────────────────────────
946
+ /**
947
+ * Reads one Codex rollout file and produces the compact per-message records
948
+ * `normalizeHistoryEntry` turns into `NormalizedMessage`s.
949
+ */
950
+ async function getCodexSessionMessages(sessionId) {
951
+ const sessionFilePath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
952
+ if (!sessionFilePath) {
953
+ console.warn(`Codex session file not found for session ${sessionId}`);
954
+ return { messages: [], total: 0, hasMore: false };
955
+ }
956
+ const messages = [];
957
+ let tokenUsage = null;
958
+ /** Call ids whose orchestration wrapper must never reach the transcript. */
959
+ const ignoredToolCallIds = new Set();
960
+ /** Exec calls that own a shell row, so their output can be routed back. */
961
+ const shellCallMessages = new Map();
962
+ /**
963
+ * File rows produced by each patch call, so the authoritative
964
+ * `patch_apply_end` diffs can replace what was reconstructed from the call
965
+ * input, and so every row gets exactly one result.
966
+ */
967
+ const patchGroups = new Map();
968
+ /** Patch call awaiting its out-of-band `patch_apply_end` report. */
969
+ let pendingPatchCallId = null;
970
+ const execCallByCellId = new Map();
971
+ const waitCallToExecCall = new Map();
972
+ const pendingExecOutput = new Map();
973
+ const completedExecCalls = new Set();
974
+ /** Newest still-running exec call, for `write_stdin` polls that carry no cell id. */
975
+ let runningExecCallId = null;
976
+ const subagentsByCallId = new Map();
977
+ const subagentsByPath = new Map();
978
+ const turns = createCodexTurnTracker();
979
+ /** Turns whose prompt already carries the anchor, so only the first does. */
980
+ const anchoredTurnIds = new Set();
981
+ const fileStream = fsSync.createReadStream(sessionFilePath);
982
+ const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
983
+ /** Emits a tool_result row unless the call already produced one. */
984
+ const pushToolResult = (callId, timestamp, output, isError) => {
985
+ if (completedExecCalls.has(callId)) {
986
+ return;
987
+ }
988
+ completedExecCalls.add(callId);
989
+ messages.push({ type: 'tool_result', timestamp, toolCallId: callId, output, isError });
990
+ };
991
+ for await (const line of rl) {
992
+ if (!line.trim()) {
993
+ continue;
994
+ }
995
+ let entry;
996
+ try {
997
+ entry = JSON.parse(line);
998
+ }
999
+ catch {
1000
+ continue;
1001
+ }
1002
+ const payload = readObjectRecord(entry.payload);
1003
+ if (!payload) {
1004
+ continue;
1005
+ }
1006
+ const timestamp = typeof entry.timestamp === 'string' ? entry.timestamp : new Date().toISOString();
1007
+ // Before the type-specific branches: a turn is opened and closed by rows
1008
+ // that produce no transcript entry of their own, and each of those
1009
+ // branches ends in a `continue`.
1010
+ turns.observe(entry.type, payload);
1011
+ // ── event_msg ──────────────────────────────────────────────────────────
1012
+ if (entry.type === 'event_msg') {
1013
+ if (payload.type === 'token_count' && payload.info) {
1014
+ const info = payload.info;
1015
+ if (info.total_token_usage) {
1016
+ const usage = info.total_token_usage;
1017
+ tokenUsage = { used: usage.total_tokens || 0, total: info.model_context_window || 200000 };
1018
+ }
200
1019
  continue;
201
1020
  }
202
- try {
203
- const entry = JSON.parse(line);
204
- if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
205
- const info = entry.payload.info;
206
- if (info.total_token_usage) {
207
- const usage = info.total_token_usage;
208
- tokenUsage = {
209
- used: usage.total_tokens || 0,
210
- total: info.model_context_window || 200000,
211
- };
212
- }
213
- }
214
- if (entry.type === 'event_msg'
215
- && entry.payload?.type === 'sub_agent_activity'
216
- && entry.payload.kind === 'started') {
217
- const eventId = readNonEmptyString(entry.payload.event_id);
218
- const agentPath = readNonEmptyString(entry.payload.agent_path);
219
- const subagent = eventId ? subagentsByCallId.get(eventId) : undefined;
220
- if (subagent && agentPath) {
1021
+ if (payload.type === 'sub_agent_activity' && payload.kind === 'started') {
1022
+ const eventId = readNonEmptyString(payload.event_id);
1023
+ const agentPath = readNonEmptyString(payload.agent_path);
1024
+ const agentThreadId = readNonEmptyString(payload.agent_thread_id);
1025
+ const subagent = eventId ? subagentsByCallId.get(eventId) : undefined;
1026
+ if (subagent) {
1027
+ subagent.agentThreadId = agentThreadId ?? subagent.agentThreadId;
1028
+ if (agentPath) {
221
1029
  subagent.agentPath = agentPath;
222
1030
  subagentsByPath.set(agentPath, subagent);
223
1031
  }
224
1032
  }
225
- if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload)) {
226
- messages.push({
227
- type: 'user',
228
- timestamp: entry.timestamp,
229
- message: {
230
- role: 'user',
231
- content: entry.payload.message,
232
- },
233
- images: extractCodexUserImages(entry.payload),
1033
+ continue;
1034
+ }
1035
+ // Codex reports patch results out of band. They carry the real unified
1036
+ // diffs, so they replace whatever was reconstructed from the call input.
1037
+ // Codex reports the applied patch out of band, and it is the only place
1038
+ // the real unified diffs appear. It always arrives before the call's own
1039
+ // output, so the rows reconstructed from the call input are rewritten
1040
+ // here rather than duplicated.
1041
+ if (payload.type === 'patch_apply_end') {
1042
+ const callId = readNonEmptyString(payload.call_id);
1043
+ if (!callId) {
1044
+ continue;
1045
+ }
1046
+ const changes = readPatchApplyChanges(payload.changes);
1047
+ // A patch applied from inside an `exec` script is reported under a
1048
+ // synthetic id that does not match the script's call id, so fall back
1049
+ // to the patch call that is still in flight.
1050
+ const group = patchGroups.get(callId)
1051
+ ?? (pendingPatchCallId ? patchGroups.get(pendingPatchCallId) : undefined);
1052
+ if (group) {
1053
+ rewritePatchRows(group.rows, changes, group.callId, messages);
1054
+ group.success = payload.success !== false;
1055
+ group.failure = String(payload.stderr || payload.stdout || '');
1056
+ pendingPatchCallId = null;
1057
+ }
1058
+ else if (changes.length > 0) {
1059
+ // A resumed thread can replay the result of a patch whose call is
1060
+ // not in this file; the rows still belong in the transcript.
1061
+ const rows = changes.map((change, index) => fileChangeToToolMessage(change, timestamp, `${callId}#${index}`));
1062
+ rows.forEach((row) => messages.push(row));
1063
+ patchGroups.set(callId, {
1064
+ callId,
1065
+ rows,
1066
+ timestamp,
1067
+ success: payload.success !== false,
1068
+ failure: String(payload.stderr || payload.stdout || ''),
234
1069
  });
235
1070
  }
236
- if (entry.type === 'response_item' &&
237
- entry.payload?.type === 'message' &&
238
- entry.payload.role === 'assistant') {
239
- const textContent = extractCodexTextContent(entry.payload.content);
240
- if (textContent.trim()) {
241
- messages.push({
242
- type: 'assistant',
243
- timestamp: entry.timestamp,
244
- message: {
245
- role: 'assistant',
246
- content: textContent,
247
- },
248
- });
249
- }
1071
+ continue;
1072
+ }
1073
+ if (payload.type === 'turn_aborted') {
1074
+ messages.push({
1075
+ type: 'status_note',
1076
+ timestamp,
1077
+ content: payload.reason === 'interrupted' ? 'Turn interrupted' : `Turn aborted (${String(payload.reason ?? 'unknown')})`,
1078
+ });
1079
+ continue;
1080
+ }
1081
+ if (payload.type === 'context_compacted') {
1082
+ messages.push({ type: 'status_note', timestamp, content: 'Context compacted' });
1083
+ continue;
1084
+ }
1085
+ if (isVisibleCodexUserMessage(payload)) {
1086
+ // Only the first prompt of a turn is anchored. A turn can hold more
1087
+ // than one — a follow-up queued while the turn was running is written
1088
+ // into it — and the cut is per turn, so anchoring the second would
1089
+ // quietly take the first with it when the user edited only the second.
1090
+ const turnId = turns.getCurrentTurnId();
1091
+ const isFirstPromptOfTurn = Boolean(turnId) && !anchoredTurnIds.has(turnId);
1092
+ if (isFirstPromptOfTurn) {
1093
+ anchoredTurnIds.add(turnId);
250
1094
  }
251
- if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
252
- const summaryText = Array.isArray(entry.payload.summary)
253
- ? entry.payload.summary
254
- .map((item) => item?.text)
255
- .filter(Boolean)
256
- .join('\n')
257
- : '';
258
- if (summaryText.trim()) {
259
- messages.push({
260
- type: 'thinking',
261
- timestamp: entry.timestamp,
262
- message: {
263
- role: 'assistant',
264
- content: summaryText,
265
- },
266
- });
267
- }
1095
+ messages.push({
1096
+ type: 'user',
1097
+ timestamp,
1098
+ message: { role: 'user', content: payload.message },
1099
+ images: extractCodexUserImages(payload),
1100
+ ...(isFirstPromptOfTurn ? { turnId } : {}),
1101
+ });
1102
+ }
1103
+ continue;
1104
+ }
1105
+ if (entry.type !== 'response_item') {
1106
+ continue;
1107
+ }
1108
+ // ── response_item ──────────────────────────────────────────────────────
1109
+ if (payload.type === 'message' && payload.role === 'assistant') {
1110
+ const cited = readCodexMemoryCitations(extractCodexTextContent(payload.content));
1111
+ const textContent = cited.text;
1112
+ if (!textContent.trim()) {
1113
+ continue;
1114
+ }
1115
+ const proposedPlan = readCodexProposedPlan(textContent);
1116
+ if (proposedPlan) {
1117
+ const planCallId = readNonEmptyString(payload.id) ?? generateMessageId('codex-plan');
1118
+ messages.push({
1119
+ type: 'tool_use',
1120
+ timestamp,
1121
+ toolName: 'ExitPlanMode',
1122
+ toolInput: JSON.stringify({ plan: proposedPlan }),
1123
+ toolCallId: planCallId,
1124
+ memoryCitations: cited.memoryCitations,
1125
+ });
1126
+ messages.push({ type: 'tool_result', timestamp, toolCallId: planCallId, output: '' });
1127
+ continue;
1128
+ }
1129
+ messages.push({
1130
+ type: 'assistant',
1131
+ timestamp,
1132
+ message: { role: 'assistant', content: textContent },
1133
+ memoryCitations: cited.memoryCitations,
1134
+ });
1135
+ continue;
1136
+ }
1137
+ if (payload.type === 'reasoning') {
1138
+ const summaryText = Array.isArray(payload.summary)
1139
+ ? payload.summary.map((item) => item?.text).filter(Boolean).join('\n')
1140
+ : '';
1141
+ if (summaryText.trim()) {
1142
+ messages.push({
1143
+ type: 'thinking',
1144
+ timestamp,
1145
+ message: { role: 'assistant', content: summaryText },
1146
+ });
1147
+ }
1148
+ continue;
1149
+ }
1150
+ if (payload.type === 'web_search_call') {
1151
+ const action = readObjectRecord(payload.action);
1152
+ const query = readNonEmptyString(action?.query);
1153
+ if (query) {
1154
+ const callId = readNonEmptyString(payload.id) ?? generateMessageId('codex-search');
1155
+ messages.push({
1156
+ type: 'tool_use',
1157
+ timestamp,
1158
+ toolName: 'WebSearch',
1159
+ toolInput: JSON.stringify({ query }),
1160
+ toolCallId: callId,
1161
+ });
1162
+ }
1163
+ continue;
1164
+ }
1165
+ if (payload.type === 'agent_message') {
1166
+ const agentMessage = parseCodexSubagentMessage(payload);
1167
+ if (!agentMessage || agentMessage.messageType !== 'FINAL_ANSWER' || !agentMessage.result) {
1168
+ continue;
1169
+ }
1170
+ let subagent = subagentsByPath.get(agentMessage.author);
1171
+ if (!subagent) {
1172
+ // A resumed thread can replay an answer whose spawn call is not in this
1173
+ // file. Synthesize the container so the answer still has a home.
1174
+ const fallbackCallId = readNonEmptyString(payload.id) ?? generateMessageId('codex-subagent');
1175
+ const taskName = agentMessage.author.split('/').filter(Boolean).pop() || 'agent';
1176
+ const taskMessage = {
1177
+ uuid: fallbackCallId,
1178
+ type: 'tool_use',
1179
+ timestamp,
1180
+ toolName: 'Task',
1181
+ toolInput: JSON.stringify({ description: humanizeCodexToolName(taskName) }),
1182
+ toolCallId: fallbackCallId,
1183
+ };
1184
+ messages.push(taskMessage);
1185
+ subagent = { toolCallId: fallbackCallId, message: taskMessage, agentPath: agentMessage.author, isComplete: false };
1186
+ subagentsByCallId.set(fallbackCallId, subagent);
1187
+ subagentsByPath.set(agentMessage.author, subagent);
1188
+ }
1189
+ if (!subagent.isComplete) {
1190
+ messages.push({
1191
+ type: 'tool_result',
1192
+ timestamp,
1193
+ toolCallId: subagent.toolCallId,
1194
+ output: agentMessage.result,
1195
+ });
1196
+ subagent.isComplete = true;
1197
+ }
1198
+ continue;
1199
+ }
1200
+ if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
1201
+ const callId = readNonEmptyString(payload.call_id) ?? generateMessageId('codex-call');
1202
+ const name = readNonEmptyString(payload.name) ?? 'tool';
1203
+ const rawInput = payload.type === 'custom_tool_call' ? payload.input : payload.arguments;
1204
+ if (name === 'spawn_agent') {
1205
+ let taskName = 'agent';
1206
+ let prompt;
1207
+ try {
1208
+ const args = JSON.parse(String(rawInput || '{}'));
1209
+ taskName = readNonEmptyString(args.task_name) || taskName;
1210
+ // `message` is an encrypted transport blob on collaboration spawns —
1211
+ // only surface it when it is readable prompt text.
1212
+ const message = readNonEmptyString(args.message);
1213
+ prompt = message && !/^gAAAAA/.test(message) ? message : undefined;
268
1214
  }
269
- if (entry.type === 'response_item' && entry.payload?.type === 'agent_message') {
270
- const agentMessage = parseCodexSubagentMessage(entry.payload);
271
- if (agentMessage && agentMessage.messageType === 'FINAL_ANSWER' && agentMessage.result) {
272
- let subagent = subagentsByPath.get(agentMessage.author);
273
- if (!subagent) {
274
- const fallbackCallId = entry.payload.id || generateMessageId('codex-subagent');
275
- const taskName = agentMessage.author.split('/').filter(Boolean).pop() || 'agent';
276
- const taskMessage = {
277
- uuid: fallbackCallId,
278
- type: 'tool_use',
279
- timestamp: entry.timestamp,
280
- toolName: 'Task',
281
- toolInput: JSON.stringify({
282
- subagent_type: 'Codex',
283
- description: humanizeCodexToolName(taskName),
284
- }),
285
- toolCallId: fallbackCallId,
286
- };
287
- messages.push(taskMessage);
288
- subagent = {
289
- toolCallId: fallbackCallId,
290
- message: taskMessage,
291
- agentPath: agentMessage.author,
292
- isComplete: false,
293
- };
294
- subagentsByCallId.set(fallbackCallId, subagent);
295
- subagentsByPath.set(agentMessage.author, subagent);
296
- }
297
- if (!subagent.isComplete) {
298
- messages.push({
299
- type: 'tool_result',
300
- timestamp: entry.timestamp,
301
- toolCallId: subagent.toolCallId,
302
- output: agentMessage.result,
303
- });
304
- subagent.isComplete = true;
305
- }
306
- }
1215
+ catch {
1216
+ // The activity event still supplies the canonical agent path.
307
1217
  }
308
- if (entry.type === 'response_item' && entry.payload?.type === 'function_call') {
309
- let toolName = entry.payload.name;
310
- let toolInput = entry.payload.arguments;
311
- if (toolName === 'spawn_agent') {
312
- let taskName = 'agent';
313
- try {
314
- const args = JSON.parse(String(entry.payload.arguments || '{}'));
315
- taskName = readNonEmptyString(args.task_name) || taskName;
316
- }
317
- catch {
318
- // The activity event can still provide the canonical agent path.
319
- }
320
- const taskMessage = {
321
- uuid: entry.payload.call_id,
322
- type: 'tool_use',
323
- timestamp: entry.timestamp,
324
- toolName: 'Task',
325
- toolInput: JSON.stringify({
326
- subagent_type: 'Codex',
327
- description: humanizeCodexToolName(taskName),
328
- }),
329
- toolCallId: entry.payload.call_id,
330
- };
331
- messages.push(taskMessage);
332
- subagentsByCallId.set(entry.payload.call_id, {
333
- toolCallId: entry.payload.call_id,
334
- message: taskMessage,
335
- isComplete: false,
336
- });
337
- ignoredToolCallIds.add(entry.payload.call_id);
338
- continue;
339
- }
340
- if (toolName === 'wait') {
341
- try {
342
- const args = JSON.parse(String(entry.payload.arguments || '{}'));
343
- const cellId = String(args.cell_id || '');
344
- const execCallId = execCallByCellId.get(cellId);
345
- if (execCallId) {
346
- waitCallToExecCall.set(entry.payload.call_id, execCallId);
347
- }
348
- }
349
- catch {
350
- // Suppress the orchestration wait even when its payload is malformed.
351
- }
352
- ignoredToolCallIds.add(entry.payload.call_id);
353
- continue;
1218
+ const taskMessage = {
1219
+ uuid: callId,
1220
+ type: 'tool_use',
1221
+ timestamp,
1222
+ toolName: 'Task',
1223
+ // No `subagent_type`: Codex has no agent presets, and naming the
1224
+ // provider there would render as "Codex / Codex" in the transcript.
1225
+ toolInput: JSON.stringify({
1226
+ description: humanizeCodexToolName(taskName),
1227
+ ...(prompt ? { prompt } : {}),
1228
+ }),
1229
+ toolCallId: callId,
1230
+ };
1231
+ messages.push(taskMessage);
1232
+ subagentsByCallId.set(callId, { toolCallId: callId, message: taskMessage, isComplete: false });
1233
+ ignoredToolCallIds.add(callId);
1234
+ continue;
1235
+ }
1236
+ if (name === 'wait') {
1237
+ try {
1238
+ const args = JSON.parse(String(rawInput || '{}'));
1239
+ const execCallId = execCallByCellId.get(String(args.cell_id || ''));
1240
+ if (execCallId) {
1241
+ waitCallToExecCall.set(callId, execCallId);
354
1242
  }
355
- if (CODEX_COLLABORATION_CONTROL_TOOLS.has(toolName)) {
356
- ignoredToolCallIds.add(entry.payload.call_id);
357
- continue;
1243
+ }
1244
+ catch {
1245
+ // Suppress the orchestration wait even when its payload is malformed.
1246
+ }
1247
+ ignoredToolCallIds.add(callId);
1248
+ continue;
1249
+ }
1250
+ if (CODEX_COLLABORATION_CONTROL_TOOLS.has(name)) {
1251
+ ignoredToolCallIds.add(callId);
1252
+ continue;
1253
+ }
1254
+ if (name === 'update_plan') {
1255
+ messages.push({
1256
+ type: 'tool_use',
1257
+ timestamp,
1258
+ toolName: 'TodoWrite',
1259
+ toolInput: JSON.stringify(readCodexPlanInput(rawInput)),
1260
+ toolCallId: callId,
1261
+ });
1262
+ continue;
1263
+ }
1264
+ if (name === 'exec') {
1265
+ const operations = parseCodexExecScript(rawInput);
1266
+ const shellCommands = operations.filter((operation) => operation.kind === 'shell');
1267
+ const stdinWrites = operations.filter((operation) => operation.kind === 'stdin');
1268
+ const patches = operations.filter((operation) => operation.kind === 'patch');
1269
+ const searches = operations.filter((operation) => operation.kind === 'search');
1270
+ const plans = operations.filter((operation) => operation.kind === 'plan');
1271
+ // A bare stdin poll continues whatever command is still running; it is
1272
+ // a continuation, not an action of its own.
1273
+ if (operations.length > 0 && shellCommands.length === 0 && stdinWrites.length > 0) {
1274
+ ignoredToolCallIds.add(callId);
1275
+ if (runningExecCallId) {
1276
+ waitCallToExecCall.set(callId, runningExecCallId);
358
1277
  }
359
- if (toolName === 'shell_command') {
360
- toolName = 'Bash';
361
- try {
362
- const args = JSON.parse(entry.payload.arguments);
363
- toolInput = JSON.stringify({ command: args.command });
364
- }
365
- catch {
366
- // Keep original arguments when parsing fails.
367
- }
1278
+ continue;
1279
+ }
1280
+ if (operations.length === 0) {
1281
+ // An unrecognized wrapper is shown as-is rather than mislabelled as a
1282
+ // shell command, so a new Codex tool degrades to a readable code
1283
+ // block instead of a wrong one.
1284
+ const fallbackMessage = {
1285
+ type: 'tool_use',
1286
+ timestamp,
1287
+ toolName: 'exec',
1288
+ toolInput: rawInput,
1289
+ toolCallId: callId,
1290
+ };
1291
+ messages.push(fallbackMessage);
1292
+ continue;
1293
+ }
1294
+ // The call has exactly one output, so whichever row represents the work
1295
+ // it did keeps the call id and receives that output. Extra rows get
1296
+ // suffixed ids and are resolved by their own bookkeeping.
1297
+ let outputOwnerAssigned = false;
1298
+ const nextRowId = () => {
1299
+ if (!outputOwnerAssigned) {
1300
+ outputOwnerAssigned = true;
1301
+ return callId;
368
1302
  }
1303
+ return `${callId}~${messages.length}`;
1304
+ };
1305
+ if (shellCommands.length > 0) {
1306
+ const shellMessage = {
1307
+ type: 'tool_use',
1308
+ timestamp,
1309
+ toolName: 'Bash',
1310
+ toolInput: JSON.stringify({
1311
+ command: shellCommands.map((operation) => operation.command).join('\n'),
1312
+ description: shellCommands.find((operation) => operation.justification)?.justification,
1313
+ }),
1314
+ toolCallId: nextRowId(),
1315
+ };
1316
+ messages.push(shellMessage);
1317
+ shellCallMessages.set(callId, shellMessage);
1318
+ }
1319
+ for (const search of searches) {
369
1320
  messages.push({
370
1321
  type: 'tool_use',
371
- timestamp: entry.timestamp,
372
- toolName,
373
- toolInput,
374
- toolCallId: entry.payload.call_id,
1322
+ timestamp,
1323
+ toolName: 'WebSearch',
1324
+ toolInput: JSON.stringify({ query: search.queries.join(' | ') }),
1325
+ toolCallId: nextRowId(),
375
1326
  });
376
1327
  }
377
- if (entry.type === 'response_item' && entry.payload?.type === 'function_call_output') {
378
- const waitExecCallId = waitCallToExecCall.get(entry.payload.call_id);
379
- if (waitExecCallId) {
380
- const output = extractCodexToolOutput(entry.payload.output);
381
- const runningOutput = readRunningExecOutput(output);
382
- const accumulatedOutput = `${pendingExecOutput.get(waitExecCallId) || ''}${runningOutput?.content ?? output}`;
383
- pendingExecOutput.set(waitExecCallId, accumulatedOutput);
384
- if (!runningOutput && !completedExecCalls.has(waitExecCallId)) {
385
- messages.push({
386
- type: 'tool_result',
387
- timestamp: entry.timestamp,
388
- toolCallId: waitExecCallId,
389
- output: accumulatedOutput,
390
- });
391
- completedExecCalls.add(waitExecCallId);
392
- }
393
- continue;
394
- }
395
- const subagent = subagentsByCallId.get(entry.payload.call_id);
396
- if (subagent) {
397
- const output = extractCodexToolOutput(entry.payload.output);
398
- try {
399
- const taskPath = readNonEmptyString(JSON.parse(output).task_name);
400
- if (taskPath) {
401
- subagent.agentPath = taskPath;
402
- subagentsByPath.set(taskPath, subagent);
403
- }
404
- }
405
- catch {
406
- // The sub_agent_activity event normally supplies the path.
407
- }
408
- continue;
409
- }
410
- if (ignoredToolCallIds.has(entry.payload.call_id)) {
411
- continue;
412
- }
1328
+ for (const plan of plans) {
1329
+ // The script's own result covers whatever else it did, so the plan
1330
+ // row is closed here — without one it would read as still running.
1331
+ const planCallId = nextRowId();
413
1332
  messages.push({
414
- type: 'tool_result',
415
- timestamp: entry.timestamp,
416
- toolCallId: entry.payload.call_id,
417
- output: extractCodexToolOutput(entry.payload.output),
1333
+ type: 'tool_use',
1334
+ timestamp,
1335
+ toolName: 'TodoWrite',
1336
+ toolInput: JSON.stringify({ todos: plan.todos }),
1337
+ toolCallId: planCallId,
418
1338
  });
1339
+ messages.push({ type: 'tool_result', timestamp, toolCallId: planCallId, output: '' });
419
1340
  }
420
- if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call') {
421
- let toolName = entry.payload.name || 'custom_tool';
422
- const input = entry.payload.input || '';
423
- let toolInput = input;
424
- if (toolName === 'exec') {
425
- const translated = translateCodexExecInput(input);
426
- if (translated) {
427
- toolName = translated.toolName;
428
- toolInput = translated.toolInput;
429
- }
430
- messages.push({
431
- type: 'tool_use',
432
- timestamp: entry.timestamp,
433
- toolName,
434
- toolInput,
435
- toolCallId: entry.payload.call_id,
436
- });
437
- execToolCallIds.add(entry.payload.call_id);
438
- continue;
439
- }
440
- if (toolName === 'apply_patch') {
441
- const fileMatch = String(input).match(/\*\*\* Update File: (.+)/);
442
- const filePath = fileMatch ? fileMatch[1].trim() : 'unknown';
443
- const lines = String(input).split('\n');
444
- const oldLines = [];
445
- const newLines = [];
446
- for (const lineContent of lines) {
447
- if (lineContent.startsWith('-') && !lineContent.startsWith('---')) {
448
- oldLines.push(lineContent.slice(1));
449
- }
450
- else if (lineContent.startsWith('+') && !lineContent.startsWith('+++')) {
451
- newLines.push(lineContent.slice(1));
452
- }
453
- }
454
- messages.push({
455
- type: 'tool_use',
456
- timestamp: entry.timestamp,
457
- toolName: 'Edit',
458
- toolInput: JSON.stringify({
459
- file_path: filePath,
460
- old_string: oldLines.join('\n'),
461
- new_string: newLines.join('\n'),
462
- }),
463
- toolCallId: entry.payload.call_id,
464
- });
465
- }
466
- else {
467
- messages.push({
468
- type: 'tool_use',
469
- timestamp: entry.timestamp,
470
- toolName,
471
- toolInput: input,
472
- toolCallId: entry.payload.call_id,
473
- });
474
- }
1341
+ if (patches.length > 0) {
1342
+ const changes = patches.flatMap((patch) => parseCodexPatch(patch.patch));
1343
+ const rows = changes.map((change, index) => fileChangeToToolMessage(change, timestamp, index === 0 ? nextRowId() : `${callId}#${index}`));
1344
+ rows.forEach((row) => messages.push(row));
1345
+ patchGroups.set(callId, { callId, rows, timestamp });
1346
+ pendingPatchCallId = callId;
1347
+ }
1348
+ if (!outputOwnerAssigned) {
1349
+ // Every recognized operation produced no row (an empty patch, say).
1350
+ // Nothing owns the output, so drop it rather than leaving it loose.
1351
+ ignoredToolCallIds.add(callId);
1352
+ }
1353
+ continue;
1354
+ }
1355
+ if (name === 'apply_patch') {
1356
+ const rows = parseCodexPatch(String(rawInput ?? ''))
1357
+ .map((change, index) => fileChangeToToolMessage(change, timestamp, `${callId}#${index}`));
1358
+ rows.forEach((row) => messages.push(row));
1359
+ patchGroups.set(callId, { callId, rows, timestamp });
1360
+ pendingPatchCallId = callId;
1361
+ // The call's own output is a bare `{}`; the per-file rows carry the result.
1362
+ ignoredToolCallIds.add(callId);
1363
+ continue;
1364
+ }
1365
+ if (name === 'shell_command' || name === 'exec_command') {
1366
+ let command = '';
1367
+ try {
1368
+ const args = JSON.parse(String(rawInput || '{}'));
1369
+ command = String(args.command ?? args.cmd ?? '');
475
1370
  }
476
- if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call_output') {
477
- if (ignoredToolCallIds.has(entry.payload.call_id)) {
478
- continue;
1371
+ catch {
1372
+ command = String(rawInput ?? '');
1373
+ }
1374
+ const shellMessage = {
1375
+ type: 'tool_use',
1376
+ timestamp,
1377
+ toolName: 'Bash',
1378
+ toolInput: JSON.stringify({ command }),
1379
+ toolCallId: callId,
1380
+ };
1381
+ messages.push(shellMessage);
1382
+ shellCallMessages.set(callId, shellMessage);
1383
+ continue;
1384
+ }
1385
+ messages.push({
1386
+ type: 'tool_use',
1387
+ timestamp,
1388
+ toolName: name,
1389
+ toolInput: rawInput,
1390
+ toolCallId: callId,
1391
+ });
1392
+ continue;
1393
+ }
1394
+ if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output') {
1395
+ const callId = readNonEmptyString(payload.call_id) ?? '';
1396
+ const rawOutput = extractCodexToolOutput(payload.output);
1397
+ // A wait / stdin poll delivers the tail of an earlier command's output.
1398
+ const continuedCallId = waitCallToExecCall.get(callId);
1399
+ if (continuedCallId) {
1400
+ const cleaned = readCodexStdinOutput(rawOutput) ?? cleanCodexShellOutput(rawOutput);
1401
+ const accumulated = `${pendingExecOutput.get(continuedCallId) || ''}${cleaned.output}`;
1402
+ pendingExecOutput.set(continuedCallId, accumulated);
1403
+ if (!cleaned.runningCellId) {
1404
+ if (runningExecCallId === continuedCallId) {
1405
+ runningExecCallId = null;
479
1406
  }
480
- const output = extractCodexToolOutput(entry.payload.output);
481
- if (execToolCallIds.has(entry.payload.call_id)) {
482
- const runningOutput = readRunningExecOutput(output);
483
- if (runningOutput) {
484
- execCallByCellId.set(runningOutput.cellId, entry.payload.call_id);
485
- pendingExecOutput.set(entry.payload.call_id, runningOutput.content);
486
- continue;
487
- }
488
- completedExecCalls.add(entry.payload.call_id);
1407
+ pushToolResult(continuedCallId, timestamp, accumulated, cleaned.exitCode !== undefined && cleaned.exitCode !== 0);
1408
+ }
1409
+ continue;
1410
+ }
1411
+ const subagent = subagentsByCallId.get(callId);
1412
+ if (subagent) {
1413
+ try {
1414
+ const taskPath = readNonEmptyString(JSON.parse(rawOutput).task_name);
1415
+ if (taskPath) {
1416
+ subagent.agentPath = taskPath;
1417
+ subagentsByPath.set(taskPath, subagent);
489
1418
  }
490
- messages.push({
491
- type: 'tool_result',
492
- timestamp: entry.timestamp,
493
- toolCallId: entry.payload.call_id,
494
- output,
495
- });
496
1419
  }
1420
+ catch {
1421
+ // The sub_agent_activity event normally supplies the path.
1422
+ }
1423
+ continue;
497
1424
  }
498
- catch {
499
- // Skip malformed lines.
500
- }
501
- }
502
- messages.sort((a, b) => new Date(a.timestamp || 0).getTime() - new Date(b.timestamp || 0).getTime());
503
- const total = messages.length;
504
- if (limit !== null) {
505
- const startIndex = Math.max(0, total - offset - limit);
506
- const endIndex = total - offset;
507
- const paginatedMessages = messages.slice(startIndex, endIndex);
508
- const hasMore = startIndex > 0;
509
- return {
510
- messages: paginatedMessages,
511
- total,
512
- hasMore,
513
- offset,
514
- limit,
515
- tokenUsage,
516
- };
1425
+ if (ignoredToolCallIds.has(callId)) {
1426
+ continue;
1427
+ }
1428
+ if (shellCallMessages.has(callId)) {
1429
+ const cleaned = cleanCodexShellOutput(rawOutput);
1430
+ if (cleaned.runningCellId) {
1431
+ execCallByCellId.set(cleaned.runningCellId, callId);
1432
+ pendingExecOutput.set(callId, cleaned.output);
1433
+ runningExecCallId = callId;
1434
+ continue;
1435
+ }
1436
+ const accumulated = `${pendingExecOutput.get(callId) || ''}${cleaned.output}`;
1437
+ pushToolResult(callId, timestamp, accumulated, cleaned.exitCode !== undefined && cleaned.exitCode !== 0);
1438
+ continue;
1439
+ }
1440
+ pushToolResult(callId, timestamp, rawOutput, false);
517
1441
  }
518
- return { messages, tokenUsage };
519
1442
  }
520
- catch (error) {
521
- console.error(`Error reading Codex session messages for ${sessionId}:`, error);
522
- return { messages: [], total: 0, hasMore: false };
1443
+ // Every file row needs a result or the UI shows it as still running. The
1444
+ // patch outcome is known only after `patch_apply_end` (which may never
1445
+ // arrive), so results are emitted once the whole file has been read.
1446
+ for (const group of patchGroups.values()) {
1447
+ const failed = group.success === false;
1448
+ for (const row of group.rows) {
1449
+ messages.push({
1450
+ type: 'tool_result',
1451
+ timestamp: group.timestamp,
1452
+ toolCallId: row.toolCallId,
1453
+ output: failed ? (group.failure || 'Patch failed') : '',
1454
+ isError: failed,
1455
+ });
1456
+ }
1457
+ }
1458
+ await attachCodexSubagentTranscripts(sessionFilePath, subagentsByCallId);
1459
+ // A rollback is recorded after the turns it retires, so a prompt can be
1460
+ // anchored and then retired later in the same file. Its rows still render —
1461
+ // they are what the conversation looked like — but the turn is gone from the
1462
+ // thread, so the anchor goes with it and the message loses its pencil.
1463
+ for (const message of messages) {
1464
+ if (typeof message.turnId === 'string' && turns.isRolledBack(message.turnId)) {
1465
+ delete message.turnId;
1466
+ }
1467
+ }
1468
+ messages.sort((a, b) => new Date(a.timestamp || 0).getTime() - new Date(b.timestamp || 0).getTime());
1469
+ return { messages, tokenUsage: tokenUsage ?? undefined };
1470
+ }
1471
+ /**
1472
+ * Loads each spawned agent's own rollout and hangs its timeline off the
1473
+ * `Task` row that started it.
1474
+ */
1475
+ async function attachCodexSubagentTranscripts(parentFilePath, subagentsByCallId) {
1476
+ for (const record of subagentsByCallId.values()) {
1477
+ let parsedInput = {};
1478
+ try {
1479
+ parsedInput = JSON.parse(String(record.message.toolInput || '{}'));
1480
+ }
1481
+ catch {
1482
+ parsedInput = {};
1483
+ }
1484
+ const agentName = record.agentPath?.split('/').filter(Boolean).pop();
1485
+ // Codex has no agent-type concept the way Claude does, so `type` is left
1486
+ // unset rather than filled with the provider's own name; the panel falls
1487
+ // back to a neutral label.
1488
+ const subagent = {
1489
+ id: record.agentThreadId ?? record.toolCallId,
1490
+ description: readNonEmptyString(parsedInput.description) ?? agentName,
1491
+ status: record.isComplete ? 'completed' : 'running',
1492
+ };
1493
+ if (record.agentThreadId) {
1494
+ const rolloutPath = await findCodexSubagentRollout(parentFilePath, record.agentThreadId);
1495
+ if (rolloutPath) {
1496
+ const transcript = await readCodexSubagentTranscript(rolloutPath);
1497
+ if (transcript.activity.length > 0) {
1498
+ record.message.subagentTools = transcript.activity
1499
+ .slice(0, MAX_TRANSMITTED_SUBAGENT_ACTIVITIES)
1500
+ .map(truncateSubagentActivity);
1501
+ subagent.activityCount = transcript.activity.length;
1502
+ }
1503
+ subagent.name = transcript.nickname ?? agentName;
1504
+ subagent.model = transcript.model;
1505
+ }
1506
+ }
1507
+ subagent.name = subagent.name ?? agentName;
1508
+ record.message.subagent = subagent;
523
1509
  }
524
1510
  }
525
1511
  export class CodexSessionsProvider {
1512
+ /**
1513
+ * Resolves the last turn to keep when the turn `anchorId` names is replaced.
1514
+ *
1515
+ * `thread/fork`'s `lastTurnId` is inclusive of the turn it names, which is
1516
+ * the same thing this contract's `resumeThroughId` means, so the answer is
1517
+ * simply the turn before the edited one. Editing the first prompt leaves
1518
+ * nothing to keep, and `null` is how that is reported.
1519
+ */
1520
+ async resolveEditAnchor(sessionId, anchorId) {
1521
+ const session = sessionsDb.getSessionById(sessionId);
1522
+ const jsonlPath = session?.jsonl_path;
1523
+ if (!jsonlPath || !session?.provider_session_id) {
1524
+ return { found: false, resumeThroughId: null };
1525
+ }
1526
+ const liveTurnIds = await readCodexLiveTurnIds(jsonlPath);
1527
+ const anchorIndex = liveTurnIds.indexOf(anchorId);
1528
+ if (anchorIndex < 0) {
1529
+ return { found: false, resumeThroughId: null };
1530
+ }
1531
+ return {
1532
+ found: true,
1533
+ resumeThroughId: anchorIndex === 0 ? null : liveTurnIds[anchorIndex - 1],
1534
+ };
1535
+ }
1536
+ /**
1537
+ * Branches the conversation at `keepThroughId` and moves the session onto
1538
+ * the branch.
1539
+ *
1540
+ * Codex threads are append-only — the SDK resumes one at its tip and nothing
1541
+ * shortens it — so rewinding means copying the part being kept into a new
1542
+ * thread. The pre-edit thread stays on disk in full and is recorded as
1543
+ * superseded so the session indexer does not hand it back later.
1544
+ */
1545
+ async rewindSession(sessionId, keepThroughId) {
1546
+ const session = sessionsDb.getSessionById(sessionId);
1547
+ const supersededThreadId = session?.provider_session_id;
1548
+ if (!session || !supersededThreadId) {
1549
+ throw new AppError('This session has not produced a transcript yet.', {
1550
+ code: 'EDIT_SOURCE_NOT_READY',
1551
+ statusCode: 409,
1552
+ });
1553
+ }
1554
+ // Nothing of the conversation survives an edit to its first prompt, and
1555
+ // there is no such thing as a fork of no turns, so the session is simply
1556
+ // detached and the next run opens a new thread.
1557
+ if (keepThroughId === null) {
1558
+ sessionsDb.markProviderSessionSuperseded({
1559
+ providerSessionId: supersededThreadId,
1560
+ provider: PROVIDER,
1561
+ sessionId,
1562
+ jsonlPath: session.jsonl_path ?? null,
1563
+ });
1564
+ sessionsDb.detachProviderSession(sessionId);
1565
+ return;
1566
+ }
1567
+ const fork = await codexAppServer.forkThread({
1568
+ threadId: supersededThreadId,
1569
+ lastTurnId: keepThroughId,
1570
+ cwd: session.project_path ?? '',
1571
+ });
1572
+ sessionsDb.markProviderSessionSuperseded({
1573
+ providerSessionId: supersededThreadId,
1574
+ provider: PROVIDER,
1575
+ sessionId,
1576
+ jsonlPath: session.jsonl_path ?? null,
1577
+ });
1578
+ sessionsDb.repointSessionToProviderSession(sessionId, {
1579
+ providerSessionId: fork.threadId,
1580
+ jsonlPath: fork.path,
1581
+ });
1582
+ }
526
1583
  /**
527
1584
  * Normalizes a persisted Codex JSONL entry.
528
1585
  *
529
1586
  * Live Codex SDK events are transformed before they reach normalizeMessage(),
530
- * while history entries already use a compact message/tool shape from projects.js.
1587
+ * while history entries already use the compact message/tool shape produced
1588
+ * by getCodexSessionMessages().
531
1589
  */
532
1590
  normalizeHistoryEntry(raw, sessionId) {
533
1591
  const ts = raw.timestamp || new Date().toISOString();
534
1592
  const baseId = raw.uuid || generateMessageId('codex');
1593
+ if (raw.type === 'status_note' && typeof raw.content === 'string') {
1594
+ return [createNormalizedMessage({
1595
+ id: baseId,
1596
+ sessionId,
1597
+ timestamp: ts,
1598
+ provider: PROVIDER,
1599
+ kind: 'task_notification',
1600
+ summary: raw.content,
1601
+ status: 'info',
1602
+ })];
1603
+ }
535
1604
  if (raw.type === 'thinking' || raw.isReasoning) {
536
- const thinkingContent = typeof raw.message?.content === 'string'
537
- ? raw.message.content
538
- : '';
1605
+ const thinkingContent = typeof raw.message?.content === 'string' ? raw.message.content : '';
539
1606
  if (!thinkingContent.trim()) {
540
1607
  return [];
541
1608
  }
@@ -573,6 +1640,10 @@ export class CodexSessionsProvider {
573
1640
  content: parsedFiles.text,
574
1641
  images: rawImages,
575
1642
  files,
1643
+ // The enclosing turn, when the reader could name one. `baseId` is not
1644
+ // usable for this: Codex rows carry no id, so it is synthesized per
1645
+ // read and would address a different message every time.
1646
+ transcriptAnchorId: readNonEmptyString(raw.turnId),
576
1647
  })];
577
1648
  }
578
1649
  if (raw.message?.role === 'assistant') {
@@ -595,6 +1666,7 @@ export class CodexSessionsProvider {
595
1666
  kind: 'text',
596
1667
  role: 'assistant',
597
1668
  content,
1669
+ memoryCitations: raw.memoryCitations,
598
1670
  })];
599
1671
  }
600
1672
  if (raw.type === 'tool_use' || raw.toolName) {
@@ -607,6 +1679,9 @@ export class CodexSessionsProvider {
607
1679
  toolName: raw.toolName || 'Unknown',
608
1680
  toolInput: raw.toolInput,
609
1681
  toolId: raw.toolCallId || baseId,
1682
+ subagentTools: raw.subagentTools,
1683
+ subagent: raw.subagent,
1684
+ memoryCitations: raw.memoryCitations,
610
1685
  })];
611
1686
  }
612
1687
  if (raw.type === 'tool_result') {
@@ -637,92 +1712,156 @@ export class CodexSessionsProvider {
637
1712
  const ts = raw.timestamp || new Date().toISOString();
638
1713
  const baseId = raw.uuid || generateMessageId('codex');
639
1714
  if (raw.type === 'item') {
1715
+ // Live items carry a stable SDK id, so an in-progress row and its later
1716
+ // completion collapse onto the same transcript entry instead of stacking.
1717
+ const itemId = readNonEmptyString(raw.itemId) ?? baseId;
640
1718
  switch (raw.itemType) {
641
- case 'agent_message':
1719
+ case 'agent_message': {
1720
+ const cited = readCodexMemoryCitations(String(raw.message?.content || ''));
1721
+ const text = cited.text;
1722
+ const proposedPlan = readCodexProposedPlan(text);
1723
+ if (proposedPlan) {
1724
+ // Same unification as history: a proposed plan is a plan card, not
1725
+ // an assistant paragraph that happens to start with a tag.
1726
+ return [createNormalizedMessage({
1727
+ id: itemId,
1728
+ sessionId,
1729
+ timestamp: ts,
1730
+ provider: PROVIDER,
1731
+ kind: 'tool_use',
1732
+ toolName: 'ExitPlanMode',
1733
+ toolInput: { plan: proposedPlan },
1734
+ toolId: itemId,
1735
+ memoryCitations: cited.memoryCitations,
1736
+ })];
1737
+ }
642
1738
  return [createNormalizedMessage({
643
- id: baseId,
1739
+ id: itemId,
644
1740
  sessionId,
645
1741
  timestamp: ts,
646
1742
  provider: PROVIDER,
647
1743
  kind: 'text',
648
1744
  role: 'assistant',
649
- content: raw.message?.content || '',
1745
+ content: text,
1746
+ memoryCitations: cited.memoryCitations,
650
1747
  })];
1748
+ }
651
1749
  case 'reasoning':
652
1750
  return [createNormalizedMessage({
653
- id: baseId,
1751
+ id: itemId,
654
1752
  sessionId,
655
1753
  timestamp: ts,
656
1754
  provider: PROVIDER,
657
1755
  kind: 'thinking',
658
1756
  content: raw.message?.content || '',
659
1757
  })];
660
- case 'command_execution':
661
- return [createNormalizedMessage({
662
- id: baseId,
663
- sessionId,
664
- timestamp: ts,
665
- provider: PROVIDER,
666
- kind: 'tool_use',
667
- toolName: 'Bash',
668
- toolInput: { command: raw.command },
669
- toolId: baseId,
670
- output: raw.output,
671
- exitCode: raw.exitCode,
672
- status: raw.status,
673
- })];
674
- case 'file_change':
675
- return [createNormalizedMessage({
676
- id: baseId,
1758
+ case 'command_execution': {
1759
+ const toolUse = createNormalizedMessage({
1760
+ id: itemId,
1761
+ sessionId,
1762
+ timestamp: ts,
1763
+ provider: PROVIDER,
1764
+ kind: 'tool_use',
1765
+ toolName: 'Bash',
1766
+ toolInput: { command: raw.command },
1767
+ toolId: itemId,
1768
+ status: raw.status,
1769
+ });
1770
+ const partialOutput = typeof raw.output === 'string' ? raw.output : '';
1771
+ if (raw.status === 'in_progress' && !partialOutput) {
1772
+ return [toolUse];
1773
+ }
1774
+ // The SDK reports a command's output on the item itself; the UI reads
1775
+ // tool output from a paired result, so one is emitted here. Emitting
1776
+ // it while the command is still running is what lets its output
1777
+ // stream into the row instead of appearing only at the end.
1778
+ return [toolUse, createNormalizedMessage({
1779
+ id: `${itemId}_result`,
677
1780
  sessionId,
678
1781
  timestamp: ts,
679
1782
  provider: PROVIDER,
680
- kind: 'tool_use',
681
- toolName: 'FileChanges',
682
- toolInput: raw.changes,
683
- toolId: baseId,
684
- status: raw.status,
1783
+ kind: 'tool_result',
1784
+ toolId: itemId,
1785
+ content: partialOutput,
1786
+ isError: raw.status === 'failed' || (typeof raw.exitCode === 'number' && raw.exitCode !== 0),
685
1787
  })];
686
- case 'mcp_tool_call':
687
- return [createNormalizedMessage({
688
- id: baseId,
1788
+ }
1789
+ case 'file_change': {
1790
+ // One row per file so each change gets the same diff view as an Edit.
1791
+ const changes = Array.isArray(raw.changes) ? raw.changes : [];
1792
+ return changes.map((change, index) => createNormalizedMessage({
1793
+ id: `${itemId}_${index}`,
1794
+ sessionId,
1795
+ timestamp: ts,
1796
+ provider: PROVIDER,
1797
+ kind: 'tool_use',
1798
+ toolName: change?.kind === 'add' ? 'Write' : 'Edit',
1799
+ toolInput: { file_path: change?.path, old_string: '', new_string: '' },
1800
+ toolId: `${itemId}_${index}`,
1801
+ status: raw.status,
1802
+ }));
1803
+ }
1804
+ case 'mcp_tool_call': {
1805
+ const toolName = raw.server ? `mcp__${String(raw.server)}__${String(raw.tool ?? 'tool')}` : String(raw.tool || 'MCP');
1806
+ const toolUse = createNormalizedMessage({
1807
+ id: itemId,
1808
+ sessionId,
1809
+ timestamp: ts,
1810
+ provider: PROVIDER,
1811
+ kind: 'tool_use',
1812
+ toolName,
1813
+ toolInput: raw.arguments,
1814
+ toolId: itemId,
1815
+ status: raw.status,
1816
+ });
1817
+ if (raw.status === 'in_progress') {
1818
+ return [toolUse];
1819
+ }
1820
+ return [toolUse, createNormalizedMessage({
1821
+ id: `${itemId}_result`,
689
1822
  sessionId,
690
1823
  timestamp: ts,
691
1824
  provider: PROVIDER,
692
- kind: 'tool_use',
693
- toolName: raw.tool || 'MCP',
694
- toolInput: raw.arguments,
695
- toolId: baseId,
696
- server: raw.server,
697
- result: raw.result,
698
- error: raw.error,
699
- status: raw.status,
1825
+ kind: 'tool_result',
1826
+ toolId: itemId,
1827
+ content: raw.error
1828
+ ? String(raw.error?.message ?? raw.error)
1829
+ : JSON.stringify(raw.result ?? ''),
1830
+ isError: Boolean(raw.error) || raw.status === 'failed',
700
1831
  })];
1832
+ }
701
1833
  case 'web_search':
702
1834
  return [createNormalizedMessage({
703
- id: baseId,
1835
+ id: itemId,
704
1836
  sessionId,
705
1837
  timestamp: ts,
706
1838
  provider: PROVIDER,
707
1839
  kind: 'tool_use',
708
1840
  toolName: 'WebSearch',
709
1841
  toolInput: { query: raw.query },
710
- toolId: baseId,
1842
+ toolId: itemId,
711
1843
  })];
712
1844
  case 'todo_list':
1845
+ // Codex's live plan uses `{text, completed}`; Claude's TodoWrite uses
1846
+ // `{content, status}`. Normalizing here means one renderer, not two.
713
1847
  return [createNormalizedMessage({
714
- id: baseId,
1848
+ id: itemId,
715
1849
  sessionId,
716
1850
  timestamp: ts,
717
1851
  provider: PROVIDER,
718
1852
  kind: 'tool_use',
719
- toolName: 'TodoList',
720
- toolInput: { items: raw.items },
721
- toolId: baseId,
1853
+ toolName: 'TodoWrite',
1854
+ toolInput: {
1855
+ todos: (Array.isArray(raw.items) ? raw.items : []).map((item) => ({
1856
+ content: String(item?.text ?? ''),
1857
+ status: item?.completed ? 'completed' : 'pending',
1858
+ })),
1859
+ },
1860
+ toolId: itemId,
722
1861
  })];
723
1862
  case 'error':
724
1863
  return [createNormalizedMessage({
725
- id: baseId,
1864
+ id: itemId,
726
1865
  sessionId,
727
1866
  timestamp: ts,
728
1867
  provider: PROVIDER,
@@ -731,14 +1870,14 @@ export class CodexSessionsProvider {
731
1870
  })];
732
1871
  default:
733
1872
  return [createNormalizedMessage({
734
- id: baseId,
1873
+ id: itemId,
735
1874
  sessionId,
736
1875
  timestamp: ts,
737
1876
  provider: PROVIDER,
738
1877
  kind: 'tool_use',
739
1878
  toolName: raw.itemType || 'Unknown',
740
1879
  toolInput: raw.item || raw,
741
- toolId: baseId,
1880
+ toolId: itemId,
742
1881
  })];
743
1882
  }
744
1883
  }
@@ -764,26 +1903,22 @@ export class CodexSessionsProvider {
764
1903
  return [];
765
1904
  }
766
1905
  /**
767
- * Loads Codex JSONL history and keeps token usage metadata when projects.js
768
- * provides it.
1906
+ * Loads Codex JSONL history and keeps token usage metadata when the
1907
+ * transcript reported it.
769
1908
  */
770
1909
  async fetchHistory(sessionId, options = {}) {
771
1910
  const { limit = null, offset = 0 } = options;
772
1911
  let result;
773
1912
  try {
774
- // Load full history first so `total` reflects frontend-normalized messages,
775
- // not raw JSONL records.
776
- result = await getCodexSessionMessages(sessionId, null, 0);
1913
+ result = await getCodexSessionMessages(sessionId);
777
1914
  }
778
1915
  catch (error) {
779
1916
  const message = error instanceof Error ? error.message : String(error);
780
1917
  console.warn(`[CodexProvider] Failed to load session ${sessionId}:`, message);
781
1918
  return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
782
1919
  }
783
- const rawMessages = Array.isArray(result) ? result : (result.messages || []);
784
- const tokenUsage = Array.isArray(result) ? undefined : result.tokenUsage;
785
1920
  const normalized = [];
786
- for (const raw of rawMessages) {
1921
+ for (const raw of result.messages) {
787
1922
  normalized.push(...this.normalizeHistoryEntry(raw, sessionId));
788
1923
  }
789
1924
  const toolResultMap = new Map();
@@ -800,22 +1935,20 @@ export class CodexSessionsProvider {
800
1935
  }
801
1936
  }
802
1937
  }
803
- let total = 0;
804
- for (const msg of normalized) {
805
- if (msg.kind !== 'tool_result') {
806
- total += 1;
807
- }
808
- }
1938
+ // Everything the transcript draws, and nothing else — so a page of N rows
1939
+ // is N rows the user sees, and `total` counts the same thing.
1940
+ const transcript = prepareTranscriptMessages(normalized);
1941
+ const total = transcript.length;
809
1942
  const normalizedOffset = Math.max(0, offset);
810
1943
  const normalizedLimit = limit === null ? null : Math.max(0, limit);
811
- const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
1944
+ const { page, hasMore } = sliceTailPage(transcript, normalizedLimit, normalizedOffset);
812
1945
  return {
813
1946
  messages: page,
814
1947
  total,
815
1948
  hasMore,
816
1949
  offset: normalizedOffset,
817
1950
  limit: normalizedLimit,
818
- tokenUsage,
1951
+ tokenUsage: result.tokenUsage,
819
1952
  };
820
1953
  }
821
1954
  }