wind-agent-cli 1.37.2 → 1.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (510) hide show
  1. package/LICENSE +718 -718
  2. package/README.md +17 -2
  3. package/dist/api-docs.html +901 -901
  4. package/dist/assets/{CodeEditor-B2Wf7Fg0.js → CodeEditor-FvgsnJ7J.js} +6 -6
  5. package/dist/assets/FileTree-NLULrBDi.js +1 -0
  6. package/dist/assets/GitPanel-51KUBbEW.js +4 -0
  7. package/dist/assets/{MarkdownPreview-C0tqYnVu.js → MarkdownPreview-PEEWVWeS.js} +17 -27
  8. package/dist/assets/Shell-BEx66cW_.js +76 -0
  9. package/dist/assets/Shell-DrlLKa8f.css +1 -0
  10. package/dist/assets/StandaloneShell-BkuUCPZP.js +1 -0
  11. package/dist/assets/TaskMasterPanel-DfQG80SF.js +2 -0
  12. package/dist/assets/abnfDiagram-N423BO3Z-Cc0ul87U.js +1 -0
  13. package/dist/assets/arc-BAuugHw_.js +1 -0
  14. package/dist/assets/architectureDiagram-T3A2C74G-DA3G7QZD.js +36 -0
  15. package/dist/assets/{blockDiagram-VBNYF7ZC-DpaEf3mv.js → blockDiagram-VBNYF7ZC-tJ12IJs3.js} +4 -4
  16. package/dist/assets/c4Diagram-5PPSVZJV-5BTMCXL4.js +10 -0
  17. package/dist/assets/channel-BGDgNNQz.js +1 -0
  18. package/dist/assets/{chunk-2GRJ4B5K-DoSdNo8u.js → chunk-2GRJ4B5K-BPaI06Ou.js} +1 -1
  19. package/dist/assets/{chunk-2Q5K7J3B-CE7I3uMn.js → chunk-2Q5K7J3B-HV4zmsEe.js} +1 -1
  20. package/dist/assets/chunk-5RXB4S5H-BAwutJoU.js +231 -0
  21. package/dist/assets/{chunk-5VM5RSS4-B55XgqHZ.js → chunk-5VM5RSS4-B9QAJPrv.js} +1 -1
  22. package/dist/assets/{chunk-6Q2QTUOP-BS1KpefW.js → chunk-6Q2QTUOP-BOIW8bzI.js} +1 -1
  23. package/dist/assets/chunk-GF5L2VYU-DD13o00-.js +206 -0
  24. package/dist/assets/{chunk-JWPE2WC7-DOtkNhMm.js → chunk-JWPE2WC7-CFBm23VK.js} +1 -1
  25. package/dist/assets/{chunk-KBJHAD2P-BXLjviqM.js → chunk-KBJHAD2P-C0i0v8Op.js} +1 -1
  26. package/dist/assets/{chunk-RYQCIY6F-C50fjNNz.js → chunk-RYQCIY6F-DfeK0taV.js} +1 -1
  27. package/dist/assets/{chunk-XXDRQBXY-QBYqCkb7.js → chunk-XXDRQBXY-BKWvf-QE.js} +1 -1
  28. package/dist/assets/classDiagram-JCYQIIEL-C2SNM4oy.js +1 -0
  29. package/dist/assets/classDiagram-v2-OCEON4UE-C2SNM4oy.js +1 -0
  30. package/dist/assets/cose-bilkent-JH36ORCC-CBE8oM7L.js +1 -0
  31. package/dist/assets/{cynefin-VYW2F7L2-DnJa_OlQ.js → cynefin-VYW2F7L2-DziGp35A.js} +11 -23
  32. package/dist/assets/cynefinDiagram-MW4NZA55-CNvtHl39.js +62 -0
  33. package/dist/assets/cytoscape.esm-yzknjiTM.js +321 -0
  34. package/dist/assets/dagre-VZM6K2ZE-Bz9lsU7m.js +4 -0
  35. package/dist/assets/{diagram-7IWD3JNH-pFzs9HEu.js → diagram-7IWD3JNH-CV7D3VSd.js} +5 -5
  36. package/dist/assets/{diagram-B4RE2ZJO-CcehQC7x.js → diagram-B4RE2ZJO-Dj4EjDNC.js} +2 -2
  37. package/dist/assets/diagram-LBJQPF4R-wJ6FHvf-.js +24 -0
  38. package/dist/assets/diagram-Q27KOJAE-DMFYMhOB.js +24 -0
  39. package/dist/assets/diagram-UB23O5K3-DeBSbWAI.js +41 -0
  40. package/dist/assets/ebnfDiagram-BXEA7PRR-2NnJSGhT.js +1 -0
  41. package/dist/assets/erDiagram-JOGREHBK-DrSlg8hr.js +85 -0
  42. package/dist/assets/feature-chat-CvOCyaLe.js +88 -0
  43. package/dist/assets/feature-workspace-CAB6bgPy.js +39 -0
  44. package/dist/assets/{flowDiagram-UKHOOZJN-CJV8fQPR.js → flowDiagram-UKHOOZJN-C0pejU6W.js} +4 -4
  45. package/dist/assets/ganttDiagram-PKOTCBZU-BM0VCUUz.js +292 -0
  46. package/dist/assets/gitGraphDiagram-DS77QQ5N-SbLG0c5_.js +106 -0
  47. package/dist/assets/graph-DOmOIIwC.js +1 -0
  48. package/dist/assets/{index-GFhXZyl2.js → index-BflGfU1C.js} +3 -3
  49. package/dist/assets/index-Btkf0_rU.js +1 -0
  50. package/dist/assets/index-Cr5MbHuj.css +1 -0
  51. package/dist/assets/index-Gqazqfs3.js +1 -0
  52. package/dist/assets/index-nyrkoQK6.js +35 -0
  53. package/dist/assets/infoDiagram-6WML65LV-Cf5DSa66.js +2 -0
  54. package/dist/assets/ishikawaDiagram-WSZJBQD7-DwyFutKy.js +70 -0
  55. package/dist/assets/journeyDiagram-NVQOT4AX-Df0FRhLo.js +139 -0
  56. package/dist/assets/{kanban-definition-27J2QSJJ-B3iL0ztJ.js → kanban-definition-27J2QSJJ-HmpbjrZz.js} +6 -6
  57. package/dist/assets/{layout-D6BstSzF.js → layout-D-LzfAck.js} +1 -1
  58. package/dist/assets/{linear-Cwe9dEKA.js → linear-DOM01LBe.js} +1 -1
  59. package/dist/assets/map-DxJ2ADlA.js +1 -0
  60. package/dist/assets/mermaid.core-C2Ma-_S6.js +306 -0
  61. package/dist/assets/{mindmap-definition-FAOFIHXS-BgfBYMzr.js → mindmap-definition-FAOFIHXS-B4GOIn76.js} +4 -4
  62. package/dist/assets/pegDiagram-VL7TDLO6-BHur7aH2.js +1 -0
  63. package/dist/assets/{pieDiagram-7S7Q4E2Y-DeSrxc4I.js → pieDiagram-7S7Q4E2Y-Cw0UELLV.js} +2 -2
  64. package/dist/assets/quadrantDiagram-CIZ2JOQS-CB2BrX3g.js +7 -0
  65. package/dist/assets/railroadDiagram-AXF67PYL-DPYZYmLX.js +1 -0
  66. package/dist/assets/requirementDiagram-LRYGKXZP-DSX4IJ1n.js +84 -0
  67. package/dist/assets/sankeyDiagram-W5VNT64P-TenC3ZQo.js +40 -0
  68. package/dist/assets/sequenceDiagram-SI44F4Z6-DltGsf3F.js +162 -0
  69. package/dist/assets/sizeCapture-X5ZJPWSS-D7llwbJZ.js +1 -0
  70. package/dist/assets/stateDiagram-OKZ733FA-C-hAvbnY.js +1 -0
  71. package/dist/assets/stateDiagram-v2-UEYNNEHI-DaYSFcRQ.js +1 -0
  72. package/dist/assets/swimlanes-SLNWSIFB-DWD30fv6.js +2 -0
  73. package/dist/assets/swimlanesDiagram-ULZ7WXOC-LTkF2T6t.js +8 -0
  74. package/dist/assets/timeline-definition-Z64GVDOM-quWmimSE.js +120 -0
  75. package/dist/assets/vendor-data-DsEZeNPr.js +4 -0
  76. package/dist/assets/vendor-i18n-B6HjLCnN.js +1 -0
  77. package/dist/assets/vendor-markdown-DkITEES2.js +298 -0
  78. package/dist/assets/vendor-react-C2GTiUCy.js +10 -0
  79. package/dist/assets/vendor-ui-CAUHSABu.js +49 -0
  80. package/dist/assets/vennDiagram-T6HMQDX7-aUQcm8h5.js +34 -0
  81. package/dist/assets/{wardleyDiagram-T6FBY63Y-BNCpsFZV.js → wardleyDiagram-T6FBY63Y-BZ0bwsFQ.js} +2 -2
  82. package/dist/assets/workbox-window.prod.es5-BBnX5xw4.js +2 -0
  83. package/dist/assets/xychartDiagram-ELKLHX3M-DOVzAq63.js +7 -0
  84. package/dist/clear-cache.html +85 -85
  85. package/dist/convert-icons.md +52 -52
  86. package/dist/favicon.png +0 -0
  87. package/dist/favicon.svg +8 -8
  88. package/dist/generate-icons.js +48 -48
  89. package/dist/icons/codex-white.svg +3 -3
  90. package/dist/icons/codex.svg +3 -3
  91. package/dist/icons/cursor-white.svg +11 -11
  92. package/dist/icons/icon-128x128.png +0 -0
  93. package/dist/icons/icon-128x128.svg +11 -11
  94. package/dist/icons/icon-144x144.png +0 -0
  95. package/dist/icons/icon-144x144.svg +11 -11
  96. package/dist/icons/icon-152x152.png +0 -0
  97. package/dist/icons/icon-152x152.svg +11 -11
  98. package/dist/icons/icon-180x180.png +0 -0
  99. package/dist/icons/icon-192x192.png +0 -0
  100. package/dist/icons/icon-192x192.svg +11 -11
  101. package/dist/icons/icon-384x384.png +0 -0
  102. package/dist/icons/icon-384x384.svg +11 -11
  103. package/dist/icons/icon-512x512.png +0 -0
  104. package/dist/icons/icon-512x512.svg +11 -11
  105. package/dist/icons/icon-72x72.png +0 -0
  106. package/dist/icons/icon-72x72.svg +11 -11
  107. package/dist/icons/icon-96x96.png +0 -0
  108. package/dist/icons/icon-96x96.svg +11 -11
  109. package/dist/icons/icon-maskable-192x192.png +0 -0
  110. package/dist/icons/icon-maskable-512x512.png +0 -0
  111. package/dist/icons/icon-template.svg +11 -11
  112. package/dist/icons/new-icon.png +0 -0
  113. package/dist/index.html +48 -58
  114. package/dist/logo-128.png +0 -0
  115. package/dist/logo-256.png +0 -0
  116. package/dist/logo.svg +17 -17
  117. package/dist/manifest.webmanifest +1 -0
  118. package/dist/push-sw.js +48 -0
  119. package/dist/screenshots/setup-screen-mobile.png +0 -0
  120. package/dist/screenshots/setup-screen.png +0 -0
  121. package/dist/sw.js +1 -124
  122. package/dist/workbox-ae5c0bb2.js +1 -0
  123. package/dist-server/server/index.js +1 -1
  124. package/dist-server/server/index.js.map +1 -1
  125. package/dist-server/server/load-env.js +4 -2
  126. package/dist-server/server/load-env.js.map +1 -1
  127. package/dist-server/server/modules/agent/agent.routes.js +1 -1
  128. package/dist-server/server/modules/agent/agent.routes.js.map +1 -1
  129. package/dist-server/server/modules/browser-use/browser-use.service.js +1 -1
  130. package/dist-server/server/modules/browser-use/browser-use.service.js.map +1 -1
  131. package/dist-server/server/modules/cli/cli.service.js +37 -37
  132. package/dist-server/server/modules/cli/cli.service.js.map +1 -1
  133. package/dist-server/server/modules/cli/sandbox.service.js +43 -43
  134. package/dist-server/server/modules/cli/sandbox.service.js.map +1 -1
  135. package/dist-server/server/modules/cli/tests/cli-environment-bootstrap.test.js +74 -74
  136. package/dist-server/server/modules/commands/commands.routes.js +25 -25
  137. package/dist-server/server/modules/commands/commands.routes.js.map +1 -1
  138. package/dist-server/server/modules/commands/tests/commands.test.js +1 -1
  139. package/dist-server/server/modules/commands/tests/commands.test.js.map +1 -1
  140. package/dist-server/server/modules/database/connection.js +1 -1
  141. package/dist-server/server/modules/database/connection.js.map +1 -1
  142. package/dist-server/server/modules/database/migrations.js +190 -190
  143. package/dist-server/server/modules/database/repositories/api-keys.js +3 -3
  144. package/dist-server/server/modules/database/repositories/github-tokens.js +2 -2
  145. package/dist-server/server/modules/database/repositories/notification-channel-endpoints.js +28 -28
  146. package/dist-server/server/modules/database/repositories/notification-preferences.js +4 -4
  147. package/dist-server/server/modules/database/repositories/projects.db.js +61 -61
  148. package/dist-server/server/modules/database/repositories/provider-models.js +35 -35
  149. package/dist-server/server/modules/database/repositories/push-subscriptions.js +5 -5
  150. package/dist-server/server/modules/database/repositories/scan-state.db.js +5 -5
  151. package/dist-server/server/modules/database/repositories/sessions.db.js +93 -93
  152. package/dist-server/server/modules/database/schema.js +177 -177
  153. package/dist-server/server/modules/database/tests/projects.db.integration.test.js +3 -2
  154. package/dist-server/server/modules/database/tests/projects.db.integration.test.js.map +1 -1
  155. package/dist-server/server/modules/database/tests/provider-models.db.integration.test.js +6 -6
  156. package/dist-server/server/modules/database/tests/sessions-provider-mapping.test.js +4 -3
  157. package/dist-server/server/modules/database/tests/sessions-provider-mapping.test.js.map +1 -1
  158. package/dist-server/server/modules/database/tests/sessions.db.integration.test.js +2 -1
  159. package/dist-server/server/modules/database/tests/sessions.db.integration.test.js.map +1 -1
  160. package/dist-server/server/modules/git/git.routes.js +17 -17
  161. package/dist-server/server/modules/notifications/services/notification-orchestrator.service.js +1 -1
  162. package/dist-server/server/modules/notifications/services/notification-orchestrator.service.js.map +1 -1
  163. package/dist-server/server/modules/notifications/vapid-keys.service.js +1 -1
  164. package/dist-server/server/modules/notifications/vapid-keys.service.js.map +1 -1
  165. package/dist-server/server/modules/projects/tests/project-management.service.test.js +2 -1
  166. package/dist-server/server/modules/projects/tests/project-management.service.test.js.map +1 -1
  167. package/dist-server/server/modules/providers/list/codex/codex-app-server.client.js +2 -2
  168. package/dist-server/server/modules/providers/list/codex/codex-app-server.client.js.map +1 -1
  169. package/dist-server/server/modules/providers/list/codex/codex-models.provider.js +1 -1
  170. package/dist-server/server/modules/providers/list/codex/codex-models.provider.js.map +1 -1
  171. package/dist-server/server/modules/providers/list/cursor/cursor-models.provider.js +1 -1
  172. package/dist-server/server/modules/providers/list/cursor/cursor-models.provider.js.map +1 -1
  173. package/dist-server/server/modules/providers/list/cursor/cursor-session-synchronizer.provider.js.map +1 -1
  174. package/dist-server/server/modules/providers/list/opencode/opencode-models.provider.js +13 -13
  175. package/dist-server/server/modules/providers/list/opencode/opencode-runtime.provider.js +9 -9
  176. package/dist-server/server/modules/providers/list/opencode/opencode-runtime.provider.test.js +17 -17
  177. package/dist-server/server/modules/providers/list/opencode/opencode-session-synchronizer.provider.js +25 -25
  178. package/dist-server/server/modules/providers/list/opencode/opencode-sessions.provider.js +27 -27
  179. package/dist-server/server/modules/providers/services/provider-token-usage.service.js +9 -9
  180. package/dist-server/server/modules/providers/services/sessions.service.js +1 -1
  181. package/dist-server/server/modules/providers/tests/claude-auth.test.js +8 -0
  182. package/dist-server/server/modules/providers/tests/claude-auth.test.js.map +1 -1
  183. package/dist-server/server/modules/providers/tests/codex-sessions.test.js +1 -1
  184. package/dist-server/server/modules/providers/tests/codex-sessions.test.js.map +1 -1
  185. package/dist-server/server/modules/providers/tests/mcp.test.js +3 -3
  186. package/dist-server/server/modules/providers/tests/opencode-sessions.test.js +98 -98
  187. package/dist-server/server/modules/providers/tests/opencode-sessions.test.js.map +1 -1
  188. package/dist-server/server/modules/providers/tests/provider-token-usage.service.test.js +18 -18
  189. package/dist-server/server/modules/providers/tests/provider.routes.test.js +1 -1
  190. package/dist-server/server/modules/providers/tests/provider.routes.test.js.map +1 -1
  191. package/dist-server/server/modules/system/system.service.js +1 -1
  192. package/dist-server/server/modules/system/system.service.js.map +1 -1
  193. package/dist-server/server/modules/system/tests/system.service.test.js +1 -1
  194. package/dist-server/server/modules/system/tests/system.service.test.js.map +1 -1
  195. package/dist-server/server/modules/taskmaster/taskmaster.routes.js +423 -422
  196. package/dist-server/server/modules/taskmaster/taskmaster.routes.js.map +1 -1
  197. package/dist-server/server/modules/websocket/services/shell-websocket.service.js +1 -1
  198. package/dist-server/server/modules/websocket/services/shell-websocket.service.js.map +1 -1
  199. package/dist-server/server/modules/worktrees/services/worktree-list.service.js +1 -1
  200. package/dist-server/server/modules/worktrees/services/worktree-open.service.js +1 -1
  201. package/dist-server/server/modules/worktrees/services/worktree-remove.service.js +1 -1
  202. package/electron/cloud.js +260 -260
  203. package/electron/desktopNotifications.js +378 -378
  204. package/electron/desktopWindow.js +766 -766
  205. package/electron/launcher/index.html +14 -14
  206. package/electron/launcher/launcher.css +801 -801
  207. package/electron/launcher/launcher.js +687 -687
  208. package/electron/localServer.js +549 -549
  209. package/electron/main.js +944 -944
  210. package/electron/preload.cjs +60 -60
  211. package/electron/scripts/generate-macos-icon.js +62 -62
  212. package/electron/serverInstaller.js +277 -277
  213. package/electron/tabs.js +87 -87
  214. package/electron/viewHost.js +331 -331
  215. package/package.json +262 -247
  216. package/public/api-docs.html +901 -901
  217. package/scripts/build-client.mjs +30 -0
  218. package/scripts/fix-node-pty.js +67 -67
  219. package/scripts/generate-pwa-icons.ps1 +33 -0
  220. package/scripts/promote-dist-server.mjs +50 -50
  221. package/scripts/release/build-server-bundle.js +176 -176
  222. package/scripts/release/prepare-desktop-app.js +152 -152
  223. package/scripts/verify-pwa-build.mjs +37 -0
  224. package/server/index.ts +399 -399
  225. package/server/load-env.ts +49 -47
  226. package/server/modules/agent/agent.module.ts +52 -52
  227. package/server/modules/agent/agent.routes.ts +1287 -1287
  228. package/server/modules/agent/index.ts +2 -2
  229. package/server/modules/agent/tests/agent.routes.test.ts +205 -205
  230. package/server/modules/assets/assets.routes.ts +150 -150
  231. package/server/modules/assets/index.ts +3 -3
  232. package/server/modules/assets/services/image-assets.service.ts +127 -127
  233. package/server/modules/assets/tests/image-assets.service.test.ts +74 -74
  234. package/server/modules/auth/auth.middleware.ts +163 -163
  235. package/server/modules/auth/auth.module.ts +38 -38
  236. package/server/modules/auth/auth.routes.ts +57 -57
  237. package/server/modules/auth/auth.service.ts +155 -155
  238. package/server/modules/auth/index.ts +9 -9
  239. package/server/modules/auth/tests/auth.service.test.ts +95 -95
  240. package/server/modules/browser-use/browser-use-mcp.routes.ts +120 -120
  241. package/server/modules/browser-use/browser-use-mcp.ts +386 -386
  242. package/server/modules/browser-use/browser-use-runtime.ts +10 -10
  243. package/server/modules/browser-use/browser-use.routes.ts +96 -96
  244. package/server/modules/browser-use/browser-use.service.ts +836 -836
  245. package/server/modules/browser-use/index.ts +11 -11
  246. package/server/modules/browser-use/tests/browser-use.service.test.ts +10 -10
  247. package/server/modules/cli/cli.module.ts +93 -93
  248. package/server/modules/cli/cli.service.ts +248 -248
  249. package/server/modules/cli/cli.ts +19 -19
  250. package/server/modules/cli/index.ts +2 -2
  251. package/server/modules/cli/sandbox.service.ts +398 -398
  252. package/server/modules/cli/tests/cli-environment-bootstrap.test.ts +186 -186
  253. package/server/modules/cli/tests/cli.service.test.ts +86 -86
  254. package/server/modules/cli/tests/sandbox.service.test.ts +58 -58
  255. package/server/modules/commands/commands.module.ts +22 -22
  256. package/server/modules/commands/commands.routes.ts +587 -587
  257. package/server/modules/commands/index.ts +2 -2
  258. package/server/modules/commands/tests/commands.test.ts +110 -110
  259. package/server/modules/database/connection.ts +144 -143
  260. package/server/modules/database/index.ts +17 -17
  261. package/server/modules/database/init-db.ts +17 -17
  262. package/server/modules/database/migrations.ts +515 -515
  263. package/server/modules/database/repositories/api-keys.ts +119 -119
  264. package/server/modules/database/repositories/app-config.ts +53 -53
  265. package/server/modules/database/repositories/credentials.ts +106 -106
  266. package/server/modules/database/repositories/github-tokens.ts +100 -100
  267. package/server/modules/database/repositories/notification-channel-endpoints.ts +153 -153
  268. package/server/modules/database/repositories/notification-preferences.ts +117 -117
  269. package/server/modules/database/repositories/projects.db.ts +196 -196
  270. package/server/modules/database/repositories/provider-models.ts +168 -168
  271. package/server/modules/database/repositories/push-subscriptions.ts +80 -80
  272. package/server/modules/database/repositories/scan-state.db.ts +42 -42
  273. package/server/modules/database/repositories/sessions.db.ts +524 -524
  274. package/server/modules/database/repositories/users.ts +140 -140
  275. package/server/modules/database/repositories/vapid-keys.ts +57 -57
  276. package/server/modules/database/schema.ts +210 -210
  277. package/server/modules/database/tests/projects.db.integration.test.ts +73 -72
  278. package/server/modules/database/tests/provider-models.db.integration.test.ts +125 -125
  279. package/server/modules/database/tests/sessions-provider-mapping.test.ts +110 -109
  280. package/server/modules/database/tests/sessions.db.integration.test.ts +117 -116
  281. package/server/modules/file-tree/file-tree.module.ts +116 -116
  282. package/server/modules/file-tree/file-tree.routes.ts +258 -258
  283. package/server/modules/file-tree/file-tree.service.ts +675 -675
  284. package/server/modules/file-tree/index.ts +2 -2
  285. package/server/modules/file-tree/tests/file-tree.routes.test.ts +157 -157
  286. package/server/modules/file-tree/tests/file-tree.service.test.ts +371 -371
  287. package/server/modules/git/git-branch.service.ts +43 -43
  288. package/server/modules/git/git-parsing.service.ts +66 -66
  289. package/server/modules/git/git.module.ts +22 -22
  290. package/server/modules/git/git.routes.ts +1596 -1596
  291. package/server/modules/git/index.ts +2 -2
  292. package/server/modules/git/tests/git-branch.service.test.ts +60 -60
  293. package/server/modules/git/tests/git-init.routes.test.ts +132 -132
  294. package/server/modules/git/tests/git.test.ts +106 -106
  295. package/server/modules/notifications/index.ts +24 -24
  296. package/server/modules/notifications/notifications.routes.ts +127 -127
  297. package/server/modules/notifications/services/desktop-notification-clients.service.ts +124 -124
  298. package/server/modules/notifications/services/notification-orchestrator.service.js +310 -310
  299. package/server/modules/notifications/tests/notification-orchestrator.integration.test.ts +55 -55
  300. package/server/modules/notifications/vapid-keys.service.ts +38 -38
  301. package/server/modules/notifications/websocket/desktop-notifications-websocket.service.ts +109 -109
  302. package/server/modules/plugins/index.ts +9 -9
  303. package/server/modules/plugins/plugin-process.service.ts +217 -217
  304. package/server/modules/plugins/plugin-registry.service.ts +459 -459
  305. package/server/modules/plugins/plugins.module.ts +33 -33
  306. package/server/modules/plugins/plugins.routes.ts +66 -66
  307. package/server/modules/plugins/plugins.service.ts +147 -147
  308. package/server/modules/plugins/tests/plugins.service.test.ts +32 -32
  309. package/server/modules/projects/index.ts +11 -11
  310. package/server/modules/projects/projects.routes.ts +273 -273
  311. package/server/modules/projects/services/project-clone.service.ts +323 -323
  312. package/server/modules/projects/services/project-delete.service.ts +90 -90
  313. package/server/modules/projects/services/project-management.service.ts +144 -144
  314. package/server/modules/projects/services/project-star.service.ts +78 -78
  315. package/server/modules/projects/services/projects-has-taskmaster.service.ts +248 -248
  316. package/server/modules/projects/services/projects-with-sessions-fetch.service.ts +314 -314
  317. package/server/modules/projects/tests/project-clone.service.test.ts +183 -183
  318. package/server/modules/projects/tests/project-management.service.test.ts +118 -117
  319. package/server/modules/projects/tests/project-star.service.test.ts +123 -123
  320. package/server/modules/projects/tests/projects-has-taskmaster.service.test.ts +105 -105
  321. package/server/modules/providers/README.md +380 -380
  322. package/server/modules/providers/index.ts +10 -10
  323. package/server/modules/providers/list/claude/claude-auth.provider.ts +160 -160
  324. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  325. package/server/modules/providers/list/claude/claude-models.provider.ts +294 -294
  326. package/server/modules/providers/list/claude/claude-runtime.provider.js +1068 -1068
  327. package/server/modules/providers/list/claude/claude-session-synchronizer.provider.ts +203 -203
  328. package/server/modules/providers/list/claude/claude-sessions.provider.ts +684 -684
  329. package/server/modules/providers/list/claude/claude-skills.provider.ts +265 -265
  330. package/server/modules/providers/list/claude/claude.provider.ts +30 -30
  331. package/server/modules/providers/list/codex/codex-app-server.client.ts +2 -2
  332. package/server/modules/providers/list/codex/codex-auth.provider.ts +100 -100
  333. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  334. package/server/modules/providers/list/codex/codex-models.provider.ts +123 -123
  335. package/server/modules/providers/list/codex/codex-runtime.provider.js +533 -533
  336. package/server/modules/providers/list/codex/codex-session-synchronizer.provider.ts +203 -203
  337. package/server/modules/providers/list/codex/codex-sessions.provider.ts +938 -938
  338. package/server/modules/providers/list/codex/codex-skills.provider.ts +73 -73
  339. package/server/modules/providers/list/codex/codex.provider.ts +28 -28
  340. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  341. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  342. package/server/modules/providers/list/cursor/cursor-models.provider.ts +119 -119
  343. package/server/modules/providers/list/cursor/cursor-runtime.provider.js +385 -385
  344. package/server/modules/providers/list/cursor/cursor-session-synchronizer.provider.ts +158 -159
  345. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +654 -654
  346. package/server/modules/providers/list/cursor/cursor-skills.provider.ts +39 -39
  347. package/server/modules/providers/list/cursor/cursor.provider.ts +30 -30
  348. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +110 -110
  349. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +228 -228
  350. package/server/modules/providers/list/opencode/opencode-models.provider.ts +203 -203
  351. package/server/modules/providers/list/opencode/opencode-runtime.provider.js +434 -434
  352. package/server/modules/providers/list/opencode/opencode-runtime.provider.test.js +261 -261
  353. package/server/modules/providers/list/opencode/opencode-session-synchronizer.provider.ts +179 -179
  354. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +500 -500
  355. package/server/modules/providers/list/opencode/opencode-skills.provider.ts +78 -78
  356. package/server/modules/providers/list/opencode/opencode.provider.ts +30 -30
  357. package/server/modules/providers/provider.registry.ts +36 -36
  358. package/server/modules/providers/provider.routes.ts +877 -877
  359. package/server/modules/providers/services/mcp.service.ts +109 -109
  360. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  361. package/server/modules/providers/services/provider-capabilities.service.ts +97 -97
  362. package/server/modules/providers/services/provider-models.service.ts +401 -401
  363. package/server/modules/providers/services/provider-runtime.service.ts +108 -108
  364. package/server/modules/providers/services/provider-token-usage.service.ts +357 -357
  365. package/server/modules/providers/services/session-conversations-search.service.ts +1321 -1321
  366. package/server/modules/providers/services/session-synchronizer.service.ts +74 -74
  367. package/server/modules/providers/services/sessions-watcher.service.ts +247 -247
  368. package/server/modules/providers/services/sessions.service.ts +471 -471
  369. package/server/modules/providers/services/skills.service.ts +39 -39
  370. package/server/modules/providers/shared/base/abstract.provider.ts +32 -32
  371. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  372. package/server/modules/providers/shared/skills/skills.provider.ts +287 -287
  373. package/server/modules/providers/tests/claude-auth.test.ts +157 -150
  374. package/server/modules/providers/tests/claude-sessions.test.ts +61 -61
  375. package/server/modules/providers/tests/codex-sessions.test.ts +231 -231
  376. package/server/modules/providers/tests/mcp.test.ts +349 -349
  377. package/server/modules/providers/tests/opencode-models.test.ts +41 -41
  378. package/server/modules/providers/tests/opencode-sessions.test.ts +522 -522
  379. package/server/modules/providers/tests/provider-attachment-history.test.ts +247 -247
  380. package/server/modules/providers/tests/provider-models.service.test.ts +353 -353
  381. package/server/modules/providers/tests/provider-runtime.service.test.ts +138 -138
  382. package/server/modules/providers/tests/provider-token-usage.service.test.ts +186 -186
  383. package/server/modules/providers/tests/provider.routes.test.ts +244 -244
  384. package/server/modules/providers/tests/sessions-details.test.ts +73 -73
  385. package/server/modules/providers/tests/sessions.service.test.ts +127 -127
  386. package/server/modules/providers/tests/skills.test.ts +692 -692
  387. package/server/modules/settings/index.ts +2 -2
  388. package/server/modules/settings/settings.module.ts +50 -50
  389. package/server/modules/settings/settings.routes.ts +51 -51
  390. package/server/modules/settings/settings.service.ts +186 -186
  391. package/server/modules/settings/tests/settings.service.test.ts +54 -54
  392. package/server/modules/system/index.ts +2 -2
  393. package/server/modules/system/system.module.ts +62 -62
  394. package/server/modules/system/system.routes.ts +21 -21
  395. package/server/modules/system/system.service.ts +76 -76
  396. package/server/modules/system/tests/system.service.test.ts +118 -118
  397. package/server/modules/taskmaster/index.ts +2 -2
  398. package/server/modules/taskmaster/taskmaster.module.ts +24 -24
  399. package/server/modules/taskmaster/taskmaster.routes.ts +1483 -1482
  400. package/server/modules/taskmaster/taskmaster.service.ts +132 -132
  401. package/server/modules/taskmaster/tests/taskmaster.routes.test.ts +144 -144
  402. package/server/modules/taskmaster/tests/taskmaster.service.test.ts +97 -97
  403. package/server/modules/user/index.ts +2 -2
  404. package/server/modules/user/tests/user.service.test.ts +61 -61
  405. package/server/modules/user/user.module.ts +58 -58
  406. package/server/modules/user/user.routes.ts +50 -50
  407. package/server/modules/user/user.service.ts +85 -85
  408. package/server/modules/voice/index.ts +2 -2
  409. package/server/modules/voice/tests/voice.service.test.ts +98 -98
  410. package/server/modules/voice/voice.module.ts +47 -47
  411. package/server/modules/voice/voice.routes.ts +113 -113
  412. package/server/modules/voice/voice.service.ts +192 -192
  413. package/server/modules/websocket/README.md +273 -273
  414. package/server/modules/websocket/index.ts +3 -3
  415. package/server/modules/websocket/services/chat-run-registry.service.ts +343 -343
  416. package/server/modules/websocket/services/chat-session-writer.service.ts +145 -145
  417. package/server/modules/websocket/services/chat-websocket.service.ts +425 -425
  418. package/server/modules/websocket/services/plugin-websocket-proxy.service.ts +65 -65
  419. package/server/modules/websocket/services/shell-websocket.service.ts +503 -503
  420. package/server/modules/websocket/services/websocket-auth.service.ts +59 -59
  421. package/server/modules/websocket/services/websocket-server.service.ts +124 -124
  422. package/server/modules/websocket/services/websocket-state.service.ts +16 -16
  423. package/server/modules/websocket/services/websocket-writer.service.ts +38 -38
  424. package/server/modules/websocket/tests/chat-attachment-filter.test.ts +59 -59
  425. package/server/modules/websocket/tests/chat-run-registry.test.ts +282 -282
  426. package/server/modules/websocket/tests/shell-websocket.service.test.ts +100 -100
  427. package/server/modules/websocket/tests/websocket-heartbeat.service.test.ts +78 -78
  428. package/server/modules/worktrees/index.ts +2 -2
  429. package/server/modules/worktrees/services/worktree-create-and-open.service.ts +53 -53
  430. package/server/modules/worktrees/services/worktree-create.service.ts +104 -104
  431. package/server/modules/worktrees/services/worktree-git.service.ts +207 -207
  432. package/server/modules/worktrees/services/worktree-list.service.ts +143 -143
  433. package/server/modules/worktrees/services/worktree-merge.service.ts +157 -157
  434. package/server/modules/worktrees/services/worktree-open.service.ts +85 -85
  435. package/server/modules/worktrees/services/worktree-remove.service.ts +88 -88
  436. package/server/modules/worktrees/tests/worktree-create-and-open.service.test.ts +68 -68
  437. package/server/modules/worktrees/tests/worktree-create.service.test.ts +142 -142
  438. package/server/modules/worktrees/tests/worktree-git.service.test.ts +84 -84
  439. package/server/modules/worktrees/tests/worktree-list.service.test.ts +45 -45
  440. package/server/modules/worktrees/tests/worktree-merge.service.test.ts +213 -213
  441. package/server/modules/worktrees/tests/worktree-open.service.test.ts +122 -122
  442. package/server/modules/worktrees/tests/worktree-remove.service.test.ts +227 -227
  443. package/server/modules/worktrees/tests/worktrees.routes.test.ts +199 -199
  444. package/server/modules/worktrees/worktrees.module.ts +113 -113
  445. package/server/modules/worktrees/worktrees.routes.ts +116 -116
  446. package/server/shared/claude-cli-path.ts +139 -139
  447. package/server/shared/frontmatter.ts +18 -18
  448. package/server/shared/image-attachments.ts +435 -435
  449. package/server/shared/interfaces.ts +179 -179
  450. package/server/shared/tests/claude-cli-path.test.ts +61 -61
  451. package/server/shared/tests/image-attachments.test.ts +353 -353
  452. package/server/shared/tests/slice-tail-page.test.ts +42 -42
  453. package/server/shared/types.ts +1228 -1228
  454. package/server/shared/utils.ts +1161 -1161
  455. package/server/tsconfig.json +40 -40
  456. package/shared/networkHosts.js +22 -22
  457. package/dist/assets/FileTree-N2IkkHlv.js +0 -127
  458. package/dist/assets/GitPanel-DZCeuFZ2.js +0 -29
  459. package/dist/assets/PluginTabContent-Bnuf-fb8.js +0 -1
  460. package/dist/assets/Shell-BfFnMZ-f.js +0 -81
  461. package/dist/assets/Shell-qxJ8_QYu.css +0 -32
  462. package/dist/assets/StandaloneShell-QmyYwNAl.js +0 -1
  463. package/dist/assets/TaskMasterPanel-fMsmvN9L.js +0 -32
  464. package/dist/assets/abnfDiagram-N423BO3Z-DjPU7HLs.js +0 -1
  465. package/dist/assets/arc-Pdq6Tvr3.js +0 -1
  466. package/dist/assets/architectureDiagram-T3A2C74G-D0JnT0Vh.js +0 -36
  467. package/dist/assets/c4Diagram-5PPSVZJV-MpqlPGFi.js +0 -10
  468. package/dist/assets/channel-Bm0ZLE4z.js +0 -1
  469. package/dist/assets/chunk-5RXB4S5H-B4UQ8snD.js +0 -231
  470. package/dist/assets/chunk-GF5L2VYU-DkEPedJP.js +0 -206
  471. package/dist/assets/classDiagram-JCYQIIEL-DqEOcNxw.js +0 -1
  472. package/dist/assets/classDiagram-v2-OCEON4UE-DqEOcNxw.js +0 -1
  473. package/dist/assets/code-xml-VK1YfShP.js +0 -6
  474. package/dist/assets/cose-bilkent-JH36ORCC-DrVTo1Nh.js +0 -1
  475. package/dist/assets/cynefinDiagram-MW4NZA55-CCxBjw9E.js +0 -62
  476. package/dist/assets/cytoscape.esm-C10L9Icf.js +0 -331
  477. package/dist/assets/dagre-VZM6K2ZE-C_GvE4lu.js +0 -4
  478. package/dist/assets/diagram-LBJQPF4R-hfKcrrxe.js +0 -24
  479. package/dist/assets/diagram-Q27KOJAE-C1semJfK.js +0 -24
  480. package/dist/assets/diagram-UB23O5K3-57hvXQXO.js +0 -41
  481. package/dist/assets/ebnfDiagram-BXEA7PRR-9KIAlAVw.js +0 -1
  482. package/dist/assets/erDiagram-JOGREHBK-B7OzJ767.js +0 -85
  483. package/dist/assets/ganttDiagram-PKOTCBZU-CbMNWWQu.js +0 -292
  484. package/dist/assets/gitGraphDiagram-DS77QQ5N-I_vZ5waO.js +0 -106
  485. package/dist/assets/graph-Cx-EqisW.js +0 -1
  486. package/dist/assets/index-DFnVoqpx.js +0 -1174
  487. package/dist/assets/index-DlSeAkw_.js +0 -11
  488. package/dist/assets/index-ZHwIojzi.js +0 -1
  489. package/dist/assets/index-t1w8KNxn.css +0 -1
  490. package/dist/assets/infoDiagram-6WML65LV-Dh20Tsbq.js +0 -2
  491. package/dist/assets/ishikawaDiagram-WSZJBQD7-DH2Sm3ko.js +0 -70
  492. package/dist/assets/journeyDiagram-NVQOT4AX-BNFQqlVu.js +0 -139
  493. package/dist/assets/map-CV9uif0g.js +0 -1
  494. package/dist/assets/mermaid.core-BYRQSshi.js +0 -312
  495. package/dist/assets/pegDiagram-VL7TDLO6-CNYpECr8.js +0 -1
  496. package/dist/assets/quadrantDiagram-CIZ2JOQS-BXVVQsa6.js +0 -7
  497. package/dist/assets/railroadDiagram-AXF67PYL-JTroIW8F.js +0 -1
  498. package/dist/assets/requirementDiagram-LRYGKXZP-C1Z_inLz.js +0 -84
  499. package/dist/assets/sankeyDiagram-W5VNT64P-DCJgKFUk.js +0 -40
  500. package/dist/assets/sequenceDiagram-SI44F4Z6-D8Wrx5Vc.js +0 -162
  501. package/dist/assets/sizeCapture-X5ZJPWSS-CXqD68vD.js +0 -1
  502. package/dist/assets/stateDiagram-OKZ733FA-CF0Ekqjo.js +0 -1
  503. package/dist/assets/stateDiagram-v2-UEYNNEHI-DARLpEFJ.js +0 -1
  504. package/dist/assets/swimlanes-SLNWSIFB-DVIax_k4.js +0 -2
  505. package/dist/assets/swimlanesDiagram-ULZ7WXOC-CrgDgaY8.js +0 -8
  506. package/dist/assets/timeline-definition-Z64GVDOM-DSqk3ApG.js +0 -120
  507. package/dist/assets/vendor-react-whEHfigN.js +0 -59
  508. package/dist/assets/vennDiagram-T6HMQDX7-DNbTqyG5.js +0 -34
  509. package/dist/assets/xychartDiagram-ELKLHX3M-XsVZphHr.js +0 -7
  510. package/dist/manifest.json +0 -61
@@ -1,938 +1,938 @@
1
- import fsSync from 'node:fs';
2
- import readline from 'node:readline';
3
-
4
- import { sessionsDb } from '@/modules/database/index.js';
5
- import { parseFilesInputTag, toImageAttachments } from '@/shared/image-attachments.js';
6
- import type { IProviderSessions } from '@/shared/interfaces.js';
7
- import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
8
- import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '@/shared/utils.js';
9
-
10
- const PROVIDER = 'codex';
11
-
12
- type CodexHistoryResult =
13
- | AnyRecord[]
14
- | {
15
- messages?: AnyRecord[];
16
- total?: number;
17
- hasMore?: boolean;
18
- offset?: number;
19
- limit?: number | null;
20
- tokenUsage?: unknown;
21
- };
22
-
23
- function isVisibleCodexUserMessage(payload: AnyRecord | null | undefined): boolean {
24
- if (!payload || payload.type !== 'user_message') {
25
- return false;
26
- }
27
-
28
- if (payload.kind && payload.kind !== 'plain') {
29
- return false;
30
- }
31
-
32
- return typeof payload.message === 'string' && payload.message.trim().length > 0;
33
- }
34
-
35
- /**
36
- * Reads the image attachments Codex records on `user_message` events.
37
- * Turns sent with `local_image` input items land in `local_images` as file
38
- * paths (verified against real rollout JSONL); the `images` array can carry
39
- * base64 data URLs, which are passed through as inline `data` attachments so
40
- * the UI can preview them without a file lookup.
41
- *
42
- * Exported for tests.
43
- */
44
- export function extractCodexUserImages(
45
- payload: AnyRecord | null | undefined,
46
- ): Array<{ path?: string; data?: string }> | undefined {
47
- if (!payload) {
48
- return undefined;
49
- }
50
-
51
- const candidates = [
52
- ...(Array.isArray(payload.local_images) ? payload.local_images : []),
53
- ...(Array.isArray(payload.images) ? payload.images : []),
54
- ];
55
-
56
- const attachments: Array<{ path?: string; data?: string }> = [];
57
- for (const entry of candidates) {
58
- if (typeof entry !== 'string' || !entry.trim()) {
59
- continue;
60
- }
61
- if (entry.startsWith('data:')) {
62
- attachments.push({ data: entry });
63
- } else {
64
- attachments.push(...toImageAttachments([entry]));
65
- }
66
- }
67
-
68
- return attachments.length > 0 ? attachments : undefined;
69
- }
70
-
71
- function extractCodexTextContent(content: unknown): string {
72
- if (!Array.isArray(content)) {
73
- return typeof content === 'string' ? content : '';
74
- }
75
-
76
- return content
77
- .map((item) => {
78
- if (!item || typeof item !== 'object') {
79
- return '';
80
- }
81
-
82
- const record = item as AnyRecord;
83
- if (
84
- (record.type === 'input_text' || record.type === 'output_text' || record.type === 'text')
85
- && typeof record.text === 'string'
86
- ) {
87
- return record.text;
88
- }
89
-
90
- return '';
91
- })
92
- .filter(Boolean)
93
- .join('\n');
94
- }
95
-
96
- function extractCodexToolOutput(output: unknown): string {
97
- if (typeof output === 'string') {
98
- return output;
99
- }
100
-
101
- if (!Array.isArray(output)) {
102
- return output == null ? '' : JSON.stringify(output);
103
- }
104
-
105
- return output
106
- .map((item) => {
107
- const record = readObjectRecord(item);
108
- return typeof record?.text === 'string' ? record.text : '';
109
- })
110
- .filter(Boolean)
111
- .join('');
112
- }
113
-
114
- function readRunningExecOutput(output: string): { cellId: string; content: string } | null {
115
- const runningCell = /Script running with cell ID\s+(\S+)/i.exec(output);
116
- if (!runningCell) {
117
- return null;
118
- }
119
-
120
- const outputMarker = /\r?\nOutput:\r?\n/i.exec(output);
121
- return {
122
- cellId: runningCell[1],
123
- content: outputMarker ? output.slice((outputMarker.index || 0) + outputMarker[0].length) : '',
124
- };
125
- }
126
-
127
- function decodeJavaScriptStringLiteral(literal: string): string {
128
- if (literal.startsWith('"')) {
129
- try {
130
- return JSON.parse(literal) as string;
131
- } catch {
132
- return literal.slice(1, -1);
133
- }
134
- }
135
-
136
- return literal
137
- .slice(1, -1)
138
- .replace(/\\n/g, '\n')
139
- .replace(/\\r/g, '\r')
140
- .replace(/\\t/g, '\t')
141
- .replace(/\\([\\'`])/g, '$1');
142
- }
143
-
144
- function extractNestedCodexCommands(source: string): string[] {
145
- const commands: string[] = [];
146
- const commandPattern = /(?:["']command["']|\bcommand)\s*:\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/gs;
147
- for (const match of source.matchAll(commandPattern)) {
148
- commands.push(decodeJavaScriptStringLiteral(match[1]));
149
- }
150
-
151
- if (commands.length === 0) {
152
- const arrayPattern = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*\[([\s\S]*?)\]\s*;/g;
153
- const stringPattern = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;
154
-
155
- for (const arrayMatch of source.matchAll(arrayPattern)) {
156
- const arrayName = arrayMatch[1];
157
- if (!new RegExp(`\\b${arrayName}\\.map\\s*\\(`).test(source)) {
158
- continue;
159
- }
160
- for (const stringMatch of arrayMatch[2].matchAll(stringPattern)) {
161
- commands.push(decodeJavaScriptStringLiteral(stringMatch[1]));
162
- }
163
- }
164
- }
165
-
166
- return commands;
167
- }
168
-
169
- /**
170
- * Newer Codex rollouts persist the orchestration wrapper (`exec`) instead of
171
- * the nested tool name. Recover the useful UI-level operation so history does
172
- * not degrade into rows labelled only "exec / Parameters".
173
- */
174
- function translateCodexExecInput(input: unknown): { toolName: string; toolInput: string } | null {
175
- const source = typeof input === 'string' ? input : String(input || '');
176
- if (/\btools\.(?:shell_command|exec_command)\s*\(/.test(source)) {
177
- const commands = extractNestedCodexCommands(source);
178
- if (commands.length > 0) {
179
- return {
180
- toolName: 'Bash',
181
- toolInput: JSON.stringify({ command: commands.join('\n') }),
182
- };
183
- }
184
- }
185
-
186
- return null;
187
- }
188
-
189
- function humanizeCodexToolName(toolName: string): string {
190
- return toolName
191
- .replace(/__/g, ' ')
192
- .replace(/_/g, ' ')
193
- .replace(/\b\w/g, (character) => character.toUpperCase());
194
- }
195
-
196
- type CodexSubagentRecord = {
197
- toolCallId: string;
198
- message: AnyRecord;
199
- agentPath?: string;
200
- isComplete: boolean;
201
- };
202
-
203
- function parseCodexSubagentMessage(payload: AnyRecord): {
204
- author: string;
205
- messageType: string;
206
- result: string;
207
- } | null {
208
- const text = extractCodexTextContent(payload.content);
209
- const header = /Message Type:\s*([^\r\n]+)[\s\S]*?Sender:\s*([^\r\n]+)[\s\S]*?Payload:\s*\r?\n([\s\S]*)/i.exec(text);
210
- const author = readNonEmptyString(payload.author) || header?.[2]?.trim();
211
- if (!author) {
212
- return null;
213
- }
214
-
215
- return {
216
- author,
217
- messageType: header?.[1]?.trim().toUpperCase() || 'MESSAGE',
218
- result: header?.[3]?.trim() || '',
219
- };
220
- }
221
-
222
- const CODEX_COLLABORATION_CONTROL_TOOLS = new Set([
223
- 'followup_task',
224
- 'interrupt_agent',
225
- 'list_agents',
226
- 'send_message',
227
- 'wait_agent',
228
- ]);
229
-
230
- function readNonEmptyString(value: unknown): string | undefined {
231
- return typeof value === 'string' && value.length > 0 ? value : undefined;
232
- }
233
-
234
- async function getCodexSessionMessages(
235
- sessionId: string,
236
- limit: number | null = null,
237
- offset = 0,
238
- ): Promise<CodexHistoryResult> {
239
- try {
240
- const sessionFilePath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
241
-
242
- if (!sessionFilePath) {
243
- console.warn(`Codex session file not found for session ${sessionId}`);
244
- return { messages: [], total: 0, hasMore: false };
245
- }
246
-
247
- const messages: AnyRecord[] = [];
248
- let tokenUsage: AnyRecord | null = null;
249
- const ignoredToolCallIds = new Set<string>();
250
- const execToolCallIds = new Set<string>();
251
- const execCallByCellId = new Map<string, string>();
252
- const waitCallToExecCall = new Map<string, string>();
253
- const pendingExecOutput = new Map<string, string>();
254
- const completedExecCalls = new Set<string>();
255
- const subagentsByCallId = new Map<string, CodexSubagentRecord>();
256
- const subagentsByPath = new Map<string, CodexSubagentRecord>();
257
- const fileStream = fsSync.createReadStream(sessionFilePath);
258
- const rl = readline.createInterface({
259
- input: fileStream,
260
- crlfDelay: Infinity,
261
- });
262
-
263
- for await (const line of rl) {
264
- if (!line.trim()) {
265
- continue;
266
- }
267
-
268
- try {
269
- const entry = JSON.parse(line) as AnyRecord;
270
- if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
271
- const info = entry.payload.info as AnyRecord;
272
- if (info.total_token_usage) {
273
- const usage = info.total_token_usage as AnyRecord;
274
- tokenUsage = {
275
- used: usage.total_tokens || 0,
276
- total: info.model_context_window || 200000,
277
- };
278
- }
279
- }
280
-
281
- if (
282
- entry.type === 'event_msg'
283
- && entry.payload?.type === 'sub_agent_activity'
284
- && entry.payload.kind === 'started'
285
- ) {
286
- const eventId = readNonEmptyString(entry.payload.event_id);
287
- const agentPath = readNonEmptyString(entry.payload.agent_path);
288
- const subagent = eventId ? subagentsByCallId.get(eventId) : undefined;
289
- if (subagent && agentPath) {
290
- subagent.agentPath = agentPath;
291
- subagentsByPath.set(agentPath, subagent);
292
- }
293
- }
294
-
295
- if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload as AnyRecord)) {
296
- messages.push({
297
- type: 'user',
298
- timestamp: entry.timestamp,
299
- message: {
300
- role: 'user',
301
- content: entry.payload.message,
302
- },
303
- images: extractCodexUserImages(entry.payload as AnyRecord),
304
- });
305
- }
306
-
307
- if (
308
- entry.type === 'response_item' &&
309
- entry.payload?.type === 'message' &&
310
- entry.payload.role === 'assistant'
311
- ) {
312
- const textContent = extractCodexTextContent(entry.payload.content);
313
- if (textContent.trim()) {
314
- messages.push({
315
- type: 'assistant',
316
- timestamp: entry.timestamp,
317
- message: {
318
- role: 'assistant',
319
- content: textContent,
320
- },
321
- });
322
- }
323
- }
324
-
325
- if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
326
- const summaryText = Array.isArray(entry.payload.summary)
327
- ? entry.payload.summary
328
- .map((item: AnyRecord) => item?.text)
329
- .filter(Boolean)
330
- .join('\n')
331
- : '';
332
-
333
- if (summaryText.trim()) {
334
- messages.push({
335
- type: 'thinking',
336
- timestamp: entry.timestamp,
337
- message: {
338
- role: 'assistant',
339
- content: summaryText,
340
- },
341
- });
342
- }
343
- }
344
-
345
- if (entry.type === 'response_item' && entry.payload?.type === 'agent_message') {
346
- const agentMessage = parseCodexSubagentMessage(entry.payload as AnyRecord);
347
- if (agentMessage && agentMessage.messageType === 'FINAL_ANSWER' && agentMessage.result) {
348
- let subagent = subagentsByPath.get(agentMessage.author);
349
- if (!subagent) {
350
- const fallbackCallId = entry.payload.id || generateMessageId('codex-subagent');
351
- const taskName = agentMessage.author.split('/').filter(Boolean).pop() || 'agent';
352
- const taskMessage: AnyRecord = {
353
- uuid: fallbackCallId,
354
- type: 'tool_use',
355
- timestamp: entry.timestamp,
356
- toolName: 'Task',
357
- toolInput: JSON.stringify({
358
- subagent_type: 'Codex',
359
- description: humanizeCodexToolName(taskName),
360
- }),
361
- toolCallId: fallbackCallId,
362
- };
363
- messages.push(taskMessage);
364
- subagent = {
365
- toolCallId: fallbackCallId,
366
- message: taskMessage,
367
- agentPath: agentMessage.author,
368
- isComplete: false,
369
- };
370
- subagentsByCallId.set(fallbackCallId, subagent);
371
- subagentsByPath.set(agentMessage.author, subagent);
372
- }
373
-
374
- if (!subagent.isComplete) {
375
- messages.push({
376
- type: 'tool_result',
377
- timestamp: entry.timestamp,
378
- toolCallId: subagent.toolCallId,
379
- output: agentMessage.result,
380
- });
381
- subagent.isComplete = true;
382
- }
383
- }
384
- }
385
-
386
- if (entry.type === 'response_item' && entry.payload?.type === 'function_call') {
387
- let toolName = entry.payload.name;
388
- let toolInput = entry.payload.arguments;
389
-
390
- if (toolName === 'spawn_agent') {
391
- let taskName = 'agent';
392
- try {
393
- const args = JSON.parse(String(entry.payload.arguments || '{}')) as AnyRecord;
394
- taskName = readNonEmptyString(args.task_name) || taskName;
395
- } catch {
396
- // The activity event can still provide the canonical agent path.
397
- }
398
-
399
- const taskMessage: AnyRecord = {
400
- uuid: entry.payload.call_id,
401
- type: 'tool_use',
402
- timestamp: entry.timestamp,
403
- toolName: 'Task',
404
- toolInput: JSON.stringify({
405
- subagent_type: 'Codex',
406
- description: humanizeCodexToolName(taskName),
407
- }),
408
- toolCallId: entry.payload.call_id,
409
- };
410
- messages.push(taskMessage);
411
- subagentsByCallId.set(entry.payload.call_id, {
412
- toolCallId: entry.payload.call_id,
413
- message: taskMessage,
414
- isComplete: false,
415
- });
416
- ignoredToolCallIds.add(entry.payload.call_id);
417
- continue;
418
- }
419
-
420
- if (toolName === 'wait') {
421
- try {
422
- const args = JSON.parse(String(entry.payload.arguments || '{}')) as AnyRecord;
423
- const cellId = String(args.cell_id || '');
424
- const execCallId = execCallByCellId.get(cellId);
425
- if (execCallId) {
426
- waitCallToExecCall.set(entry.payload.call_id, execCallId);
427
- }
428
- } catch {
429
- // Suppress the orchestration wait even when its payload is malformed.
430
- }
431
- ignoredToolCallIds.add(entry.payload.call_id);
432
- continue;
433
- }
434
-
435
- if (CODEX_COLLABORATION_CONTROL_TOOLS.has(toolName)) {
436
- ignoredToolCallIds.add(entry.payload.call_id);
437
- continue;
438
- }
439
-
440
- if (toolName === 'shell_command') {
441
- toolName = 'Bash';
442
- try {
443
- const args = JSON.parse(entry.payload.arguments) as AnyRecord;
444
- toolInput = JSON.stringify({ command: args.command });
445
- } catch {
446
- // Keep original arguments when parsing fails.
447
- }
448
- }
449
-
450
- messages.push({
451
- type: 'tool_use',
452
- timestamp: entry.timestamp,
453
- toolName,
454
- toolInput,
455
- toolCallId: entry.payload.call_id,
456
- });
457
- }
458
-
459
- if (entry.type === 'response_item' && entry.payload?.type === 'function_call_output') {
460
- const waitExecCallId = waitCallToExecCall.get(entry.payload.call_id);
461
- if (waitExecCallId) {
462
- const output = extractCodexToolOutput(entry.payload.output);
463
- const runningOutput = readRunningExecOutput(output);
464
- const accumulatedOutput = `${pendingExecOutput.get(waitExecCallId) || ''}${runningOutput?.content ?? output}`;
465
- pendingExecOutput.set(waitExecCallId, accumulatedOutput);
466
-
467
- if (!runningOutput && !completedExecCalls.has(waitExecCallId)) {
468
- messages.push({
469
- type: 'tool_result',
470
- timestamp: entry.timestamp,
471
- toolCallId: waitExecCallId,
472
- output: accumulatedOutput,
473
- });
474
- completedExecCalls.add(waitExecCallId);
475
- }
476
- continue;
477
- }
478
-
479
- const subagent = subagentsByCallId.get(entry.payload.call_id);
480
- if (subagent) {
481
- const output = extractCodexToolOutput(entry.payload.output);
482
- try {
483
- const taskPath = readNonEmptyString((JSON.parse(output) as AnyRecord).task_name);
484
- if (taskPath) {
485
- subagent.agentPath = taskPath;
486
- subagentsByPath.set(taskPath, subagent);
487
- }
488
- } catch {
489
- // The sub_agent_activity event normally supplies the path.
490
- }
491
- continue;
492
- }
493
-
494
- if (ignoredToolCallIds.has(entry.payload.call_id)) {
495
- continue;
496
- }
497
-
498
- messages.push({
499
- type: 'tool_result',
500
- timestamp: entry.timestamp,
501
- toolCallId: entry.payload.call_id,
502
- output: extractCodexToolOutput(entry.payload.output),
503
- });
504
- }
505
-
506
- if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call') {
507
- let toolName = entry.payload.name || 'custom_tool';
508
- const input = entry.payload.input || '';
509
- let toolInput = input;
510
-
511
- if (toolName === 'exec') {
512
- const translated = translateCodexExecInput(input);
513
- if (translated) {
514
- toolName = translated.toolName;
515
- toolInput = translated.toolInput;
516
- }
517
- messages.push({
518
- type: 'tool_use',
519
- timestamp: entry.timestamp,
520
- toolName,
521
- toolInput,
522
- toolCallId: entry.payload.call_id,
523
- });
524
- execToolCallIds.add(entry.payload.call_id);
525
- continue;
526
- }
527
-
528
- if (toolName === 'apply_patch') {
529
- const fileMatch = String(input).match(/\*\*\* Update File: (.+)/);
530
- const filePath = fileMatch ? fileMatch[1].trim() : 'unknown';
531
- const lines = String(input).split('\n');
532
- const oldLines: string[] = [];
533
- const newLines: string[] = [];
534
-
535
- for (const lineContent of lines) {
536
- if (lineContent.startsWith('-') && !lineContent.startsWith('---')) {
537
- oldLines.push(lineContent.slice(1));
538
- } else if (lineContent.startsWith('+') && !lineContent.startsWith('+++')) {
539
- newLines.push(lineContent.slice(1));
540
- }
541
- }
542
-
543
- messages.push({
544
- type: 'tool_use',
545
- timestamp: entry.timestamp,
546
- toolName: 'Edit',
547
- toolInput: JSON.stringify({
548
- file_path: filePath,
549
- old_string: oldLines.join('\n'),
550
- new_string: newLines.join('\n'),
551
- }),
552
- toolCallId: entry.payload.call_id,
553
- });
554
- } else {
555
- messages.push({
556
- type: 'tool_use',
557
- timestamp: entry.timestamp,
558
- toolName,
559
- toolInput: input,
560
- toolCallId: entry.payload.call_id,
561
- });
562
- }
563
- }
564
-
565
- if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call_output') {
566
- if (ignoredToolCallIds.has(entry.payload.call_id)) {
567
- continue;
568
- }
569
-
570
- const output = extractCodexToolOutput(entry.payload.output);
571
- if (execToolCallIds.has(entry.payload.call_id)) {
572
- const runningOutput = readRunningExecOutput(output);
573
- if (runningOutput) {
574
- execCallByCellId.set(runningOutput.cellId, entry.payload.call_id);
575
- pendingExecOutput.set(entry.payload.call_id, runningOutput.content);
576
- continue;
577
- }
578
- completedExecCalls.add(entry.payload.call_id);
579
- }
580
-
581
- messages.push({
582
- type: 'tool_result',
583
- timestamp: entry.timestamp,
584
- toolCallId: entry.payload.call_id,
585
- output,
586
- });
587
- }
588
- } catch {
589
- // Skip malformed lines.
590
- }
591
- }
592
-
593
- messages.sort(
594
- (a, b) => new Date(a.timestamp || 0).getTime() - new Date(b.timestamp || 0).getTime(),
595
- );
596
- const total = messages.length;
597
-
598
- if (limit !== null) {
599
- const startIndex = Math.max(0, total - offset - limit);
600
- const endIndex = total - offset;
601
- const paginatedMessages = messages.slice(startIndex, endIndex);
602
- const hasMore = startIndex > 0;
603
-
604
- return {
605
- messages: paginatedMessages,
606
- total,
607
- hasMore,
608
- offset,
609
- limit,
610
- tokenUsage,
611
- };
612
- }
613
-
614
- return { messages, tokenUsage };
615
- } catch (error) {
616
- console.error(`Error reading Codex session messages for ${sessionId}:`, error);
617
- return { messages: [], total: 0, hasMore: false };
618
- }
619
- }
620
-
621
- export class CodexSessionsProvider implements IProviderSessions {
622
- /**
623
- * Normalizes a persisted Codex JSONL entry.
624
- *
625
- * Live Codex SDK events are transformed before they reach normalizeMessage(),
626
- * while history entries already use a compact message/tool shape from projects.js.
627
- */
628
- private normalizeHistoryEntry(raw: AnyRecord, sessionId: string | null): NormalizedMessage[] {
629
- const ts = raw.timestamp || new Date().toISOString();
630
- const baseId = raw.uuid || generateMessageId('codex');
631
-
632
- if (raw.type === 'thinking' || raw.isReasoning) {
633
- const thinkingContent = typeof raw.message?.content === 'string'
634
- ? raw.message.content
635
- : '';
636
- if (!thinkingContent.trim()) {
637
- return [];
638
- }
639
- return [createNormalizedMessage({
640
- id: baseId,
641
- sessionId,
642
- timestamp: ts,
643
- provider: PROVIDER,
644
- kind: 'thinking',
645
- content: thinkingContent,
646
- })];
647
- }
648
-
649
- if (raw.message?.role === 'user') {
650
- const content = typeof raw.message.content === 'string'
651
- ? raw.message.content
652
- : Array.isArray(raw.message.content)
653
- ? raw.message.content
654
- .map((part: string | AnyRecord) => typeof part === 'string' ? part : part?.text || '')
655
- .filter(Boolean)
656
- .join('\n')
657
- : String(raw.message.content || '');
658
- const parsedFiles = parseFilesInputTag(content);
659
- const rawImages = Array.isArray(raw.images) && raw.images.length > 0 ? raw.images : undefined;
660
- const files = parsedFiles.attachments.length > 0 ? parsedFiles.attachments : undefined;
661
- if (!parsedFiles.text.trim() && !rawImages && !files) {
662
- return [];
663
- }
664
- return [createNormalizedMessage({
665
- id: baseId,
666
- sessionId,
667
- timestamp: ts,
668
- provider: PROVIDER,
669
- kind: 'text',
670
- role: 'user',
671
- content: parsedFiles.text,
672
- images: rawImages,
673
- files,
674
- })];
675
- }
676
-
677
- if (raw.message?.role === 'assistant') {
678
- const content = typeof raw.message.content === 'string'
679
- ? raw.message.content
680
- : Array.isArray(raw.message.content)
681
- ? raw.message.content
682
- .map((part: string | AnyRecord) => typeof part === 'string' ? part : part?.text || '')
683
- .filter(Boolean)
684
- .join('\n')
685
- : '';
686
- if (!content.trim()) {
687
- return [];
688
- }
689
- return [createNormalizedMessage({
690
- id: baseId,
691
- sessionId,
692
- timestamp: ts,
693
- provider: PROVIDER,
694
- kind: 'text',
695
- role: 'assistant',
696
- content,
697
- })];
698
- }
699
-
700
- if (raw.type === 'tool_use' || raw.toolName) {
701
- return [createNormalizedMessage({
702
- id: baseId,
703
- sessionId,
704
- timestamp: ts,
705
- provider: PROVIDER,
706
- kind: 'tool_use',
707
- toolName: raw.toolName || 'Unknown',
708
- toolInput: raw.toolInput,
709
- toolId: raw.toolCallId || baseId,
710
- })];
711
- }
712
-
713
- if (raw.type === 'tool_result') {
714
- return [createNormalizedMessage({
715
- id: baseId,
716
- sessionId,
717
- timestamp: ts,
718
- provider: PROVIDER,
719
- kind: 'tool_result',
720
- toolId: raw.toolCallId || '',
721
- content: raw.output || '',
722
- isError: Boolean(raw.isError),
723
- })];
724
- }
725
-
726
- return [];
727
- }
728
-
729
- /**
730
- * Normalizes either a Codex history entry or a transformed live SDK event.
731
- */
732
- normalizeMessage(rawMessage: unknown, sessionId: string | null): NormalizedMessage[] {
733
- const raw = readObjectRecord(rawMessage);
734
- if (!raw) {
735
- return [];
736
- }
737
-
738
- if (raw.message?.role) {
739
- return this.normalizeHistoryEntry(raw, sessionId);
740
- }
741
-
742
- const ts = raw.timestamp || new Date().toISOString();
743
- const baseId = raw.uuid || generateMessageId('codex');
744
-
745
- if (raw.type === 'item') {
746
- switch (raw.itemType) {
747
- case 'agent_message':
748
- return [createNormalizedMessage({
749
- id: baseId,
750
- sessionId,
751
- timestamp: ts,
752
- provider: PROVIDER,
753
- kind: 'text',
754
- role: 'assistant',
755
- content: raw.message?.content || '',
756
- })];
757
- case 'reasoning':
758
- return [createNormalizedMessage({
759
- id: baseId,
760
- sessionId,
761
- timestamp: ts,
762
- provider: PROVIDER,
763
- kind: 'thinking',
764
- content: raw.message?.content || '',
765
- })];
766
- case 'command_execution':
767
- return [createNormalizedMessage({
768
- id: baseId,
769
- sessionId,
770
- timestamp: ts,
771
- provider: PROVIDER,
772
- kind: 'tool_use',
773
- toolName: 'Bash',
774
- toolInput: { command: raw.command },
775
- toolId: baseId,
776
- output: raw.output,
777
- exitCode: raw.exitCode,
778
- status: raw.status,
779
- })];
780
- case 'file_change':
781
- return [createNormalizedMessage({
782
- id: baseId,
783
- sessionId,
784
- timestamp: ts,
785
- provider: PROVIDER,
786
- kind: 'tool_use',
787
- toolName: 'FileChanges',
788
- toolInput: raw.changes,
789
- toolId: baseId,
790
- status: raw.status,
791
- })];
792
- case 'mcp_tool_call':
793
- return [createNormalizedMessage({
794
- id: baseId,
795
- sessionId,
796
- timestamp: ts,
797
- provider: PROVIDER,
798
- kind: 'tool_use',
799
- toolName: raw.tool || 'MCP',
800
- toolInput: raw.arguments,
801
- toolId: baseId,
802
- server: raw.server,
803
- result: raw.result,
804
- error: raw.error,
805
- status: raw.status,
806
- })];
807
- case 'web_search':
808
- return [createNormalizedMessage({
809
- id: baseId,
810
- sessionId,
811
- timestamp: ts,
812
- provider: PROVIDER,
813
- kind: 'tool_use',
814
- toolName: 'WebSearch',
815
- toolInput: { query: raw.query },
816
- toolId: baseId,
817
- })];
818
- case 'todo_list':
819
- return [createNormalizedMessage({
820
- id: baseId,
821
- sessionId,
822
- timestamp: ts,
823
- provider: PROVIDER,
824
- kind: 'tool_use',
825
- toolName: 'TodoList',
826
- toolInput: { items: raw.items },
827
- toolId: baseId,
828
- })];
829
- case 'error':
830
- return [createNormalizedMessage({
831
- id: baseId,
832
- sessionId,
833
- timestamp: ts,
834
- provider: PROVIDER,
835
- kind: 'error',
836
- content: raw.message?.content || 'Unknown error',
837
- })];
838
- default:
839
- return [createNormalizedMessage({
840
- id: baseId,
841
- sessionId,
842
- timestamp: ts,
843
- provider: PROVIDER,
844
- kind: 'tool_use',
845
- toolName: raw.itemType || 'Unknown',
846
- toolInput: raw.item || raw,
847
- toolId: baseId,
848
- })];
849
- }
850
- }
851
-
852
- if (raw.type === 'turn_complete') {
853
- return [createNormalizedMessage({
854
- id: baseId,
855
- sessionId,
856
- timestamp: ts,
857
- provider: PROVIDER,
858
- kind: 'complete',
859
- })];
860
- }
861
- if (raw.type === 'turn_failed') {
862
- return [createNormalizedMessage({
863
- id: baseId,
864
- sessionId,
865
- timestamp: ts,
866
- provider: PROVIDER,
867
- kind: 'error',
868
- content: raw.error?.message || 'Turn failed',
869
- })];
870
- }
871
-
872
- return [];
873
- }
874
-
875
- /**
876
- * Loads Codex JSONL history and keeps token usage metadata when projects.js
877
- * provides it.
878
- */
879
- async fetchHistory(
880
- sessionId: string,
881
- options: FetchHistoryOptions = {},
882
- ): Promise<FetchHistoryResult> {
883
- const { limit = null, offset = 0 } = options;
884
-
885
- let result: CodexHistoryResult;
886
- try {
887
- // Load full history first so `total` reflects frontend-normalized messages,
888
- // not raw JSONL records.
889
- result = await getCodexSessionMessages(sessionId, null, 0);
890
- } catch (error) {
891
- const message = error instanceof Error ? error.message : String(error);
892
- console.warn(`[CodexProvider] Failed to load session ${sessionId}:`, message);
893
- return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
894
- }
895
-
896
- const rawMessages = Array.isArray(result) ? result : (result.messages || []);
897
- const tokenUsage = Array.isArray(result) ? undefined : result.tokenUsage;
898
-
899
- const normalized: NormalizedMessage[] = [];
900
- for (const raw of rawMessages) {
901
- normalized.push(...this.normalizeHistoryEntry(raw, sessionId));
902
- }
903
-
904
- const toolResultMap = new Map<string, NormalizedMessage>();
905
- for (const msg of normalized) {
906
- if (msg.kind === 'tool_result' && msg.toolId) {
907
- toolResultMap.set(msg.toolId, msg);
908
- }
909
- }
910
- for (const msg of normalized) {
911
- if (msg.kind === 'tool_use' && msg.toolId && toolResultMap.has(msg.toolId)) {
912
- const toolResult = toolResultMap.get(msg.toolId);
913
- if (toolResult) {
914
- msg.toolResult = { content: toolResult.content, isError: toolResult.isError };
915
- }
916
- }
917
- }
918
-
919
- let total = 0;
920
- for (const msg of normalized) {
921
- if (msg.kind !== 'tool_result') {
922
- total += 1;
923
- }
924
- }
925
- const normalizedOffset = Math.max(0, offset);
926
- const normalizedLimit = limit === null ? null : Math.max(0, limit);
927
- const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
928
-
929
- return {
930
- messages: page,
931
- total,
932
- hasMore,
933
- offset: normalizedOffset,
934
- limit: normalizedLimit,
935
- tokenUsage,
936
- };
937
- }
938
- }
1
+ import fsSync from 'node:fs';
2
+ import readline from 'node:readline';
3
+
4
+ import { sessionsDb } from '@/modules/database/index.js';
5
+ import { parseFilesInputTag, toImageAttachments } from '@/shared/image-attachments.js';
6
+ import type { IProviderSessions } from '@/shared/interfaces.js';
7
+ import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
8
+ import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '@/shared/utils.js';
9
+
10
+ const PROVIDER = 'codex';
11
+
12
+ type CodexHistoryResult =
13
+ | AnyRecord[]
14
+ | {
15
+ messages?: AnyRecord[];
16
+ total?: number;
17
+ hasMore?: boolean;
18
+ offset?: number;
19
+ limit?: number | null;
20
+ tokenUsage?: unknown;
21
+ };
22
+
23
+ function isVisibleCodexUserMessage(payload: AnyRecord | null | undefined): boolean {
24
+ if (!payload || payload.type !== 'user_message') {
25
+ return false;
26
+ }
27
+
28
+ if (payload.kind && payload.kind !== 'plain') {
29
+ return false;
30
+ }
31
+
32
+ return typeof payload.message === 'string' && payload.message.trim().length > 0;
33
+ }
34
+
35
+ /**
36
+ * Reads the image attachments Codex records on `user_message` events.
37
+ * Turns sent with `local_image` input items land in `local_images` as file
38
+ * paths (verified against real rollout JSONL); the `images` array can carry
39
+ * base64 data URLs, which are passed through as inline `data` attachments so
40
+ * the UI can preview them without a file lookup.
41
+ *
42
+ * Exported for tests.
43
+ */
44
+ export function extractCodexUserImages(
45
+ payload: AnyRecord | null | undefined,
46
+ ): Array<{ path?: string; data?: string }> | undefined {
47
+ if (!payload) {
48
+ return undefined;
49
+ }
50
+
51
+ const candidates = [
52
+ ...(Array.isArray(payload.local_images) ? payload.local_images : []),
53
+ ...(Array.isArray(payload.images) ? payload.images : []),
54
+ ];
55
+
56
+ const attachments: Array<{ path?: string; data?: string }> = [];
57
+ for (const entry of candidates) {
58
+ if (typeof entry !== 'string' || !entry.trim()) {
59
+ continue;
60
+ }
61
+ if (entry.startsWith('data:')) {
62
+ attachments.push({ data: entry });
63
+ } else {
64
+ attachments.push(...toImageAttachments([entry]));
65
+ }
66
+ }
67
+
68
+ return attachments.length > 0 ? attachments : undefined;
69
+ }
70
+
71
+ function extractCodexTextContent(content: unknown): string {
72
+ if (!Array.isArray(content)) {
73
+ return typeof content === 'string' ? content : '';
74
+ }
75
+
76
+ return content
77
+ .map((item) => {
78
+ if (!item || typeof item !== 'object') {
79
+ return '';
80
+ }
81
+
82
+ const record = item as AnyRecord;
83
+ if (
84
+ (record.type === 'input_text' || record.type === 'output_text' || record.type === 'text')
85
+ && typeof record.text === 'string'
86
+ ) {
87
+ return record.text;
88
+ }
89
+
90
+ return '';
91
+ })
92
+ .filter(Boolean)
93
+ .join('\n');
94
+ }
95
+
96
+ function extractCodexToolOutput(output: unknown): string {
97
+ if (typeof output === 'string') {
98
+ return output;
99
+ }
100
+
101
+ if (!Array.isArray(output)) {
102
+ return output == null ? '' : JSON.stringify(output);
103
+ }
104
+
105
+ return output
106
+ .map((item) => {
107
+ const record = readObjectRecord(item);
108
+ return typeof record?.text === 'string' ? record.text : '';
109
+ })
110
+ .filter(Boolean)
111
+ .join('');
112
+ }
113
+
114
+ function readRunningExecOutput(output: string): { cellId: string; content: string } | null {
115
+ const runningCell = /Script running with cell ID\s+(\S+)/i.exec(output);
116
+ if (!runningCell) {
117
+ return null;
118
+ }
119
+
120
+ const outputMarker = /\r?\nOutput:\r?\n/i.exec(output);
121
+ return {
122
+ cellId: runningCell[1],
123
+ content: outputMarker ? output.slice((outputMarker.index || 0) + outputMarker[0].length) : '',
124
+ };
125
+ }
126
+
127
+ function decodeJavaScriptStringLiteral(literal: string): string {
128
+ if (literal.startsWith('"')) {
129
+ try {
130
+ return JSON.parse(literal) as string;
131
+ } catch {
132
+ return literal.slice(1, -1);
133
+ }
134
+ }
135
+
136
+ return literal
137
+ .slice(1, -1)
138
+ .replace(/\\n/g, '\n')
139
+ .replace(/\\r/g, '\r')
140
+ .replace(/\\t/g, '\t')
141
+ .replace(/\\([\\'`])/g, '$1');
142
+ }
143
+
144
+ function extractNestedCodexCommands(source: string): string[] {
145
+ const commands: string[] = [];
146
+ const commandPattern = /(?:["']command["']|\bcommand)\s*:\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/gs;
147
+ for (const match of source.matchAll(commandPattern)) {
148
+ commands.push(decodeJavaScriptStringLiteral(match[1]));
149
+ }
150
+
151
+ if (commands.length === 0) {
152
+ const arrayPattern = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*\[([\s\S]*?)\]\s*;/g;
153
+ const stringPattern = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/g;
154
+
155
+ for (const arrayMatch of source.matchAll(arrayPattern)) {
156
+ const arrayName = arrayMatch[1];
157
+ if (!new RegExp(`\\b${arrayName}\\.map\\s*\\(`).test(source)) {
158
+ continue;
159
+ }
160
+ for (const stringMatch of arrayMatch[2].matchAll(stringPattern)) {
161
+ commands.push(decodeJavaScriptStringLiteral(stringMatch[1]));
162
+ }
163
+ }
164
+ }
165
+
166
+ return commands;
167
+ }
168
+
169
+ /**
170
+ * Newer Codex rollouts persist the orchestration wrapper (`exec`) instead of
171
+ * the nested tool name. Recover the useful UI-level operation so history does
172
+ * not degrade into rows labelled only "exec / Parameters".
173
+ */
174
+ function translateCodexExecInput(input: unknown): { toolName: string; toolInput: string } | null {
175
+ const source = typeof input === 'string' ? input : String(input || '');
176
+ if (/\btools\.(?:shell_command|exec_command)\s*\(/.test(source)) {
177
+ const commands = extractNestedCodexCommands(source);
178
+ if (commands.length > 0) {
179
+ return {
180
+ toolName: 'Bash',
181
+ toolInput: JSON.stringify({ command: commands.join('\n') }),
182
+ };
183
+ }
184
+ }
185
+
186
+ return null;
187
+ }
188
+
189
+ function humanizeCodexToolName(toolName: string): string {
190
+ return toolName
191
+ .replace(/__/g, ' ')
192
+ .replace(/_/g, ' ')
193
+ .replace(/\b\w/g, (character) => character.toUpperCase());
194
+ }
195
+
196
+ type CodexSubagentRecord = {
197
+ toolCallId: string;
198
+ message: AnyRecord;
199
+ agentPath?: string;
200
+ isComplete: boolean;
201
+ };
202
+
203
+ function parseCodexSubagentMessage(payload: AnyRecord): {
204
+ author: string;
205
+ messageType: string;
206
+ result: string;
207
+ } | null {
208
+ const text = extractCodexTextContent(payload.content);
209
+ const header = /Message Type:\s*([^\r\n]+)[\s\S]*?Sender:\s*([^\r\n]+)[\s\S]*?Payload:\s*\r?\n([\s\S]*)/i.exec(text);
210
+ const author = readNonEmptyString(payload.author) || header?.[2]?.trim();
211
+ if (!author) {
212
+ return null;
213
+ }
214
+
215
+ return {
216
+ author,
217
+ messageType: header?.[1]?.trim().toUpperCase() || 'MESSAGE',
218
+ result: header?.[3]?.trim() || '',
219
+ };
220
+ }
221
+
222
+ const CODEX_COLLABORATION_CONTROL_TOOLS = new Set([
223
+ 'followup_task',
224
+ 'interrupt_agent',
225
+ 'list_agents',
226
+ 'send_message',
227
+ 'wait_agent',
228
+ ]);
229
+
230
+ function readNonEmptyString(value: unknown): string | undefined {
231
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
232
+ }
233
+
234
+ async function getCodexSessionMessages(
235
+ sessionId: string,
236
+ limit: number | null = null,
237
+ offset = 0,
238
+ ): Promise<CodexHistoryResult> {
239
+ try {
240
+ const sessionFilePath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
241
+
242
+ if (!sessionFilePath) {
243
+ console.warn(`Codex session file not found for session ${sessionId}`);
244
+ return { messages: [], total: 0, hasMore: false };
245
+ }
246
+
247
+ const messages: AnyRecord[] = [];
248
+ let tokenUsage: AnyRecord | null = null;
249
+ const ignoredToolCallIds = new Set<string>();
250
+ const execToolCallIds = new Set<string>();
251
+ const execCallByCellId = new Map<string, string>();
252
+ const waitCallToExecCall = new Map<string, string>();
253
+ const pendingExecOutput = new Map<string, string>();
254
+ const completedExecCalls = new Set<string>();
255
+ const subagentsByCallId = new Map<string, CodexSubagentRecord>();
256
+ const subagentsByPath = new Map<string, CodexSubagentRecord>();
257
+ const fileStream = fsSync.createReadStream(sessionFilePath);
258
+ const rl = readline.createInterface({
259
+ input: fileStream,
260
+ crlfDelay: Infinity,
261
+ });
262
+
263
+ for await (const line of rl) {
264
+ if (!line.trim()) {
265
+ continue;
266
+ }
267
+
268
+ try {
269
+ const entry = JSON.parse(line) as AnyRecord;
270
+ if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
271
+ const info = entry.payload.info as AnyRecord;
272
+ if (info.total_token_usage) {
273
+ const usage = info.total_token_usage as AnyRecord;
274
+ tokenUsage = {
275
+ used: usage.total_tokens || 0,
276
+ total: info.model_context_window || 200000,
277
+ };
278
+ }
279
+ }
280
+
281
+ if (
282
+ entry.type === 'event_msg'
283
+ && entry.payload?.type === 'sub_agent_activity'
284
+ && entry.payload.kind === 'started'
285
+ ) {
286
+ const eventId = readNonEmptyString(entry.payload.event_id);
287
+ const agentPath = readNonEmptyString(entry.payload.agent_path);
288
+ const subagent = eventId ? subagentsByCallId.get(eventId) : undefined;
289
+ if (subagent && agentPath) {
290
+ subagent.agentPath = agentPath;
291
+ subagentsByPath.set(agentPath, subagent);
292
+ }
293
+ }
294
+
295
+ if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload as AnyRecord)) {
296
+ messages.push({
297
+ type: 'user',
298
+ timestamp: entry.timestamp,
299
+ message: {
300
+ role: 'user',
301
+ content: entry.payload.message,
302
+ },
303
+ images: extractCodexUserImages(entry.payload as AnyRecord),
304
+ });
305
+ }
306
+
307
+ if (
308
+ entry.type === 'response_item' &&
309
+ entry.payload?.type === 'message' &&
310
+ entry.payload.role === 'assistant'
311
+ ) {
312
+ const textContent = extractCodexTextContent(entry.payload.content);
313
+ if (textContent.trim()) {
314
+ messages.push({
315
+ type: 'assistant',
316
+ timestamp: entry.timestamp,
317
+ message: {
318
+ role: 'assistant',
319
+ content: textContent,
320
+ },
321
+ });
322
+ }
323
+ }
324
+
325
+ if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
326
+ const summaryText = Array.isArray(entry.payload.summary)
327
+ ? entry.payload.summary
328
+ .map((item: AnyRecord) => item?.text)
329
+ .filter(Boolean)
330
+ .join('\n')
331
+ : '';
332
+
333
+ if (summaryText.trim()) {
334
+ messages.push({
335
+ type: 'thinking',
336
+ timestamp: entry.timestamp,
337
+ message: {
338
+ role: 'assistant',
339
+ content: summaryText,
340
+ },
341
+ });
342
+ }
343
+ }
344
+
345
+ if (entry.type === 'response_item' && entry.payload?.type === 'agent_message') {
346
+ const agentMessage = parseCodexSubagentMessage(entry.payload as AnyRecord);
347
+ if (agentMessage && agentMessage.messageType === 'FINAL_ANSWER' && agentMessage.result) {
348
+ let subagent = subagentsByPath.get(agentMessage.author);
349
+ if (!subagent) {
350
+ const fallbackCallId = entry.payload.id || generateMessageId('codex-subagent');
351
+ const taskName = agentMessage.author.split('/').filter(Boolean).pop() || 'agent';
352
+ const taskMessage: AnyRecord = {
353
+ uuid: fallbackCallId,
354
+ type: 'tool_use',
355
+ timestamp: entry.timestamp,
356
+ toolName: 'Task',
357
+ toolInput: JSON.stringify({
358
+ subagent_type: 'Codex',
359
+ description: humanizeCodexToolName(taskName),
360
+ }),
361
+ toolCallId: fallbackCallId,
362
+ };
363
+ messages.push(taskMessage);
364
+ subagent = {
365
+ toolCallId: fallbackCallId,
366
+ message: taskMessage,
367
+ agentPath: agentMessage.author,
368
+ isComplete: false,
369
+ };
370
+ subagentsByCallId.set(fallbackCallId, subagent);
371
+ subagentsByPath.set(agentMessage.author, subagent);
372
+ }
373
+
374
+ if (!subagent.isComplete) {
375
+ messages.push({
376
+ type: 'tool_result',
377
+ timestamp: entry.timestamp,
378
+ toolCallId: subagent.toolCallId,
379
+ output: agentMessage.result,
380
+ });
381
+ subagent.isComplete = true;
382
+ }
383
+ }
384
+ }
385
+
386
+ if (entry.type === 'response_item' && entry.payload?.type === 'function_call') {
387
+ let toolName = entry.payload.name;
388
+ let toolInput = entry.payload.arguments;
389
+
390
+ if (toolName === 'spawn_agent') {
391
+ let taskName = 'agent';
392
+ try {
393
+ const args = JSON.parse(String(entry.payload.arguments || '{}')) as AnyRecord;
394
+ taskName = readNonEmptyString(args.task_name) || taskName;
395
+ } catch {
396
+ // The activity event can still provide the canonical agent path.
397
+ }
398
+
399
+ const taskMessage: AnyRecord = {
400
+ uuid: entry.payload.call_id,
401
+ type: 'tool_use',
402
+ timestamp: entry.timestamp,
403
+ toolName: 'Task',
404
+ toolInput: JSON.stringify({
405
+ subagent_type: 'Codex',
406
+ description: humanizeCodexToolName(taskName),
407
+ }),
408
+ toolCallId: entry.payload.call_id,
409
+ };
410
+ messages.push(taskMessage);
411
+ subagentsByCallId.set(entry.payload.call_id, {
412
+ toolCallId: entry.payload.call_id,
413
+ message: taskMessage,
414
+ isComplete: false,
415
+ });
416
+ ignoredToolCallIds.add(entry.payload.call_id);
417
+ continue;
418
+ }
419
+
420
+ if (toolName === 'wait') {
421
+ try {
422
+ const args = JSON.parse(String(entry.payload.arguments || '{}')) as AnyRecord;
423
+ const cellId = String(args.cell_id || '');
424
+ const execCallId = execCallByCellId.get(cellId);
425
+ if (execCallId) {
426
+ waitCallToExecCall.set(entry.payload.call_id, execCallId);
427
+ }
428
+ } catch {
429
+ // Suppress the orchestration wait even when its payload is malformed.
430
+ }
431
+ ignoredToolCallIds.add(entry.payload.call_id);
432
+ continue;
433
+ }
434
+
435
+ if (CODEX_COLLABORATION_CONTROL_TOOLS.has(toolName)) {
436
+ ignoredToolCallIds.add(entry.payload.call_id);
437
+ continue;
438
+ }
439
+
440
+ if (toolName === 'shell_command') {
441
+ toolName = 'Bash';
442
+ try {
443
+ const args = JSON.parse(entry.payload.arguments) as AnyRecord;
444
+ toolInput = JSON.stringify({ command: args.command });
445
+ } catch {
446
+ // Keep original arguments when parsing fails.
447
+ }
448
+ }
449
+
450
+ messages.push({
451
+ type: 'tool_use',
452
+ timestamp: entry.timestamp,
453
+ toolName,
454
+ toolInput,
455
+ toolCallId: entry.payload.call_id,
456
+ });
457
+ }
458
+
459
+ if (entry.type === 'response_item' && entry.payload?.type === 'function_call_output') {
460
+ const waitExecCallId = waitCallToExecCall.get(entry.payload.call_id);
461
+ if (waitExecCallId) {
462
+ const output = extractCodexToolOutput(entry.payload.output);
463
+ const runningOutput = readRunningExecOutput(output);
464
+ const accumulatedOutput = `${pendingExecOutput.get(waitExecCallId) || ''}${runningOutput?.content ?? output}`;
465
+ pendingExecOutput.set(waitExecCallId, accumulatedOutput);
466
+
467
+ if (!runningOutput && !completedExecCalls.has(waitExecCallId)) {
468
+ messages.push({
469
+ type: 'tool_result',
470
+ timestamp: entry.timestamp,
471
+ toolCallId: waitExecCallId,
472
+ output: accumulatedOutput,
473
+ });
474
+ completedExecCalls.add(waitExecCallId);
475
+ }
476
+ continue;
477
+ }
478
+
479
+ const subagent = subagentsByCallId.get(entry.payload.call_id);
480
+ if (subagent) {
481
+ const output = extractCodexToolOutput(entry.payload.output);
482
+ try {
483
+ const taskPath = readNonEmptyString((JSON.parse(output) as AnyRecord).task_name);
484
+ if (taskPath) {
485
+ subagent.agentPath = taskPath;
486
+ subagentsByPath.set(taskPath, subagent);
487
+ }
488
+ } catch {
489
+ // The sub_agent_activity event normally supplies the path.
490
+ }
491
+ continue;
492
+ }
493
+
494
+ if (ignoredToolCallIds.has(entry.payload.call_id)) {
495
+ continue;
496
+ }
497
+
498
+ messages.push({
499
+ type: 'tool_result',
500
+ timestamp: entry.timestamp,
501
+ toolCallId: entry.payload.call_id,
502
+ output: extractCodexToolOutput(entry.payload.output),
503
+ });
504
+ }
505
+
506
+ if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call') {
507
+ let toolName = entry.payload.name || 'custom_tool';
508
+ const input = entry.payload.input || '';
509
+ let toolInput = input;
510
+
511
+ if (toolName === 'exec') {
512
+ const translated = translateCodexExecInput(input);
513
+ if (translated) {
514
+ toolName = translated.toolName;
515
+ toolInput = translated.toolInput;
516
+ }
517
+ messages.push({
518
+ type: 'tool_use',
519
+ timestamp: entry.timestamp,
520
+ toolName,
521
+ toolInput,
522
+ toolCallId: entry.payload.call_id,
523
+ });
524
+ execToolCallIds.add(entry.payload.call_id);
525
+ continue;
526
+ }
527
+
528
+ if (toolName === 'apply_patch') {
529
+ const fileMatch = String(input).match(/\*\*\* Update File: (.+)/);
530
+ const filePath = fileMatch ? fileMatch[1].trim() : 'unknown';
531
+ const lines = String(input).split('\n');
532
+ const oldLines: string[] = [];
533
+ const newLines: string[] = [];
534
+
535
+ for (const lineContent of lines) {
536
+ if (lineContent.startsWith('-') && !lineContent.startsWith('---')) {
537
+ oldLines.push(lineContent.slice(1));
538
+ } else if (lineContent.startsWith('+') && !lineContent.startsWith('+++')) {
539
+ newLines.push(lineContent.slice(1));
540
+ }
541
+ }
542
+
543
+ messages.push({
544
+ type: 'tool_use',
545
+ timestamp: entry.timestamp,
546
+ toolName: 'Edit',
547
+ toolInput: JSON.stringify({
548
+ file_path: filePath,
549
+ old_string: oldLines.join('\n'),
550
+ new_string: newLines.join('\n'),
551
+ }),
552
+ toolCallId: entry.payload.call_id,
553
+ });
554
+ } else {
555
+ messages.push({
556
+ type: 'tool_use',
557
+ timestamp: entry.timestamp,
558
+ toolName,
559
+ toolInput: input,
560
+ toolCallId: entry.payload.call_id,
561
+ });
562
+ }
563
+ }
564
+
565
+ if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call_output') {
566
+ if (ignoredToolCallIds.has(entry.payload.call_id)) {
567
+ continue;
568
+ }
569
+
570
+ const output = extractCodexToolOutput(entry.payload.output);
571
+ if (execToolCallIds.has(entry.payload.call_id)) {
572
+ const runningOutput = readRunningExecOutput(output);
573
+ if (runningOutput) {
574
+ execCallByCellId.set(runningOutput.cellId, entry.payload.call_id);
575
+ pendingExecOutput.set(entry.payload.call_id, runningOutput.content);
576
+ continue;
577
+ }
578
+ completedExecCalls.add(entry.payload.call_id);
579
+ }
580
+
581
+ messages.push({
582
+ type: 'tool_result',
583
+ timestamp: entry.timestamp,
584
+ toolCallId: entry.payload.call_id,
585
+ output,
586
+ });
587
+ }
588
+ } catch {
589
+ // Skip malformed lines.
590
+ }
591
+ }
592
+
593
+ messages.sort(
594
+ (a, b) => new Date(a.timestamp || 0).getTime() - new Date(b.timestamp || 0).getTime(),
595
+ );
596
+ const total = messages.length;
597
+
598
+ if (limit !== null) {
599
+ const startIndex = Math.max(0, total - offset - limit);
600
+ const endIndex = total - offset;
601
+ const paginatedMessages = messages.slice(startIndex, endIndex);
602
+ const hasMore = startIndex > 0;
603
+
604
+ return {
605
+ messages: paginatedMessages,
606
+ total,
607
+ hasMore,
608
+ offset,
609
+ limit,
610
+ tokenUsage,
611
+ };
612
+ }
613
+
614
+ return { messages, tokenUsage };
615
+ } catch (error) {
616
+ console.error(`Error reading Codex session messages for ${sessionId}:`, error);
617
+ return { messages: [], total: 0, hasMore: false };
618
+ }
619
+ }
620
+
621
+ export class CodexSessionsProvider implements IProviderSessions {
622
+ /**
623
+ * Normalizes a persisted Codex JSONL entry.
624
+ *
625
+ * Live Codex SDK events are transformed before they reach normalizeMessage(),
626
+ * while history entries already use a compact message/tool shape from projects.js.
627
+ */
628
+ private normalizeHistoryEntry(raw: AnyRecord, sessionId: string | null): NormalizedMessage[] {
629
+ const ts = raw.timestamp || new Date().toISOString();
630
+ const baseId = raw.uuid || generateMessageId('codex');
631
+
632
+ if (raw.type === 'thinking' || raw.isReasoning) {
633
+ const thinkingContent = typeof raw.message?.content === 'string'
634
+ ? raw.message.content
635
+ : '';
636
+ if (!thinkingContent.trim()) {
637
+ return [];
638
+ }
639
+ return [createNormalizedMessage({
640
+ id: baseId,
641
+ sessionId,
642
+ timestamp: ts,
643
+ provider: PROVIDER,
644
+ kind: 'thinking',
645
+ content: thinkingContent,
646
+ })];
647
+ }
648
+
649
+ if (raw.message?.role === 'user') {
650
+ const content = typeof raw.message.content === 'string'
651
+ ? raw.message.content
652
+ : Array.isArray(raw.message.content)
653
+ ? raw.message.content
654
+ .map((part: string | AnyRecord) => typeof part === 'string' ? part : part?.text || '')
655
+ .filter(Boolean)
656
+ .join('\n')
657
+ : String(raw.message.content || '');
658
+ const parsedFiles = parseFilesInputTag(content);
659
+ const rawImages = Array.isArray(raw.images) && raw.images.length > 0 ? raw.images : undefined;
660
+ const files = parsedFiles.attachments.length > 0 ? parsedFiles.attachments : undefined;
661
+ if (!parsedFiles.text.trim() && !rawImages && !files) {
662
+ return [];
663
+ }
664
+ return [createNormalizedMessage({
665
+ id: baseId,
666
+ sessionId,
667
+ timestamp: ts,
668
+ provider: PROVIDER,
669
+ kind: 'text',
670
+ role: 'user',
671
+ content: parsedFiles.text,
672
+ images: rawImages,
673
+ files,
674
+ })];
675
+ }
676
+
677
+ if (raw.message?.role === 'assistant') {
678
+ const content = typeof raw.message.content === 'string'
679
+ ? raw.message.content
680
+ : Array.isArray(raw.message.content)
681
+ ? raw.message.content
682
+ .map((part: string | AnyRecord) => typeof part === 'string' ? part : part?.text || '')
683
+ .filter(Boolean)
684
+ .join('\n')
685
+ : '';
686
+ if (!content.trim()) {
687
+ return [];
688
+ }
689
+ return [createNormalizedMessage({
690
+ id: baseId,
691
+ sessionId,
692
+ timestamp: ts,
693
+ provider: PROVIDER,
694
+ kind: 'text',
695
+ role: 'assistant',
696
+ content,
697
+ })];
698
+ }
699
+
700
+ if (raw.type === 'tool_use' || raw.toolName) {
701
+ return [createNormalizedMessage({
702
+ id: baseId,
703
+ sessionId,
704
+ timestamp: ts,
705
+ provider: PROVIDER,
706
+ kind: 'tool_use',
707
+ toolName: raw.toolName || 'Unknown',
708
+ toolInput: raw.toolInput,
709
+ toolId: raw.toolCallId || baseId,
710
+ })];
711
+ }
712
+
713
+ if (raw.type === 'tool_result') {
714
+ return [createNormalizedMessage({
715
+ id: baseId,
716
+ sessionId,
717
+ timestamp: ts,
718
+ provider: PROVIDER,
719
+ kind: 'tool_result',
720
+ toolId: raw.toolCallId || '',
721
+ content: raw.output || '',
722
+ isError: Boolean(raw.isError),
723
+ })];
724
+ }
725
+
726
+ return [];
727
+ }
728
+
729
+ /**
730
+ * Normalizes either a Codex history entry or a transformed live SDK event.
731
+ */
732
+ normalizeMessage(rawMessage: unknown, sessionId: string | null): NormalizedMessage[] {
733
+ const raw = readObjectRecord(rawMessage);
734
+ if (!raw) {
735
+ return [];
736
+ }
737
+
738
+ if (raw.message?.role) {
739
+ return this.normalizeHistoryEntry(raw, sessionId);
740
+ }
741
+
742
+ const ts = raw.timestamp || new Date().toISOString();
743
+ const baseId = raw.uuid || generateMessageId('codex');
744
+
745
+ if (raw.type === 'item') {
746
+ switch (raw.itemType) {
747
+ case 'agent_message':
748
+ return [createNormalizedMessage({
749
+ id: baseId,
750
+ sessionId,
751
+ timestamp: ts,
752
+ provider: PROVIDER,
753
+ kind: 'text',
754
+ role: 'assistant',
755
+ content: raw.message?.content || '',
756
+ })];
757
+ case 'reasoning':
758
+ return [createNormalizedMessage({
759
+ id: baseId,
760
+ sessionId,
761
+ timestamp: ts,
762
+ provider: PROVIDER,
763
+ kind: 'thinking',
764
+ content: raw.message?.content || '',
765
+ })];
766
+ case 'command_execution':
767
+ return [createNormalizedMessage({
768
+ id: baseId,
769
+ sessionId,
770
+ timestamp: ts,
771
+ provider: PROVIDER,
772
+ kind: 'tool_use',
773
+ toolName: 'Bash',
774
+ toolInput: { command: raw.command },
775
+ toolId: baseId,
776
+ output: raw.output,
777
+ exitCode: raw.exitCode,
778
+ status: raw.status,
779
+ })];
780
+ case 'file_change':
781
+ return [createNormalizedMessage({
782
+ id: baseId,
783
+ sessionId,
784
+ timestamp: ts,
785
+ provider: PROVIDER,
786
+ kind: 'tool_use',
787
+ toolName: 'FileChanges',
788
+ toolInput: raw.changes,
789
+ toolId: baseId,
790
+ status: raw.status,
791
+ })];
792
+ case 'mcp_tool_call':
793
+ return [createNormalizedMessage({
794
+ id: baseId,
795
+ sessionId,
796
+ timestamp: ts,
797
+ provider: PROVIDER,
798
+ kind: 'tool_use',
799
+ toolName: raw.tool || 'MCP',
800
+ toolInput: raw.arguments,
801
+ toolId: baseId,
802
+ server: raw.server,
803
+ result: raw.result,
804
+ error: raw.error,
805
+ status: raw.status,
806
+ })];
807
+ case 'web_search':
808
+ return [createNormalizedMessage({
809
+ id: baseId,
810
+ sessionId,
811
+ timestamp: ts,
812
+ provider: PROVIDER,
813
+ kind: 'tool_use',
814
+ toolName: 'WebSearch',
815
+ toolInput: { query: raw.query },
816
+ toolId: baseId,
817
+ })];
818
+ case 'todo_list':
819
+ return [createNormalizedMessage({
820
+ id: baseId,
821
+ sessionId,
822
+ timestamp: ts,
823
+ provider: PROVIDER,
824
+ kind: 'tool_use',
825
+ toolName: 'TodoList',
826
+ toolInput: { items: raw.items },
827
+ toolId: baseId,
828
+ })];
829
+ case 'error':
830
+ return [createNormalizedMessage({
831
+ id: baseId,
832
+ sessionId,
833
+ timestamp: ts,
834
+ provider: PROVIDER,
835
+ kind: 'error',
836
+ content: raw.message?.content || 'Unknown error',
837
+ })];
838
+ default:
839
+ return [createNormalizedMessage({
840
+ id: baseId,
841
+ sessionId,
842
+ timestamp: ts,
843
+ provider: PROVIDER,
844
+ kind: 'tool_use',
845
+ toolName: raw.itemType || 'Unknown',
846
+ toolInput: raw.item || raw,
847
+ toolId: baseId,
848
+ })];
849
+ }
850
+ }
851
+
852
+ if (raw.type === 'turn_complete') {
853
+ return [createNormalizedMessage({
854
+ id: baseId,
855
+ sessionId,
856
+ timestamp: ts,
857
+ provider: PROVIDER,
858
+ kind: 'complete',
859
+ })];
860
+ }
861
+ if (raw.type === 'turn_failed') {
862
+ return [createNormalizedMessage({
863
+ id: baseId,
864
+ sessionId,
865
+ timestamp: ts,
866
+ provider: PROVIDER,
867
+ kind: 'error',
868
+ content: raw.error?.message || 'Turn failed',
869
+ })];
870
+ }
871
+
872
+ return [];
873
+ }
874
+
875
+ /**
876
+ * Loads Codex JSONL history and keeps token usage metadata when projects.js
877
+ * provides it.
878
+ */
879
+ async fetchHistory(
880
+ sessionId: string,
881
+ options: FetchHistoryOptions = {},
882
+ ): Promise<FetchHistoryResult> {
883
+ const { limit = null, offset = 0 } = options;
884
+
885
+ let result: CodexHistoryResult;
886
+ try {
887
+ // Load full history first so `total` reflects frontend-normalized messages,
888
+ // not raw JSONL records.
889
+ result = await getCodexSessionMessages(sessionId, null, 0);
890
+ } catch (error) {
891
+ const message = error instanceof Error ? error.message : String(error);
892
+ console.warn(`[CodexProvider] Failed to load session ${sessionId}:`, message);
893
+ return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
894
+ }
895
+
896
+ const rawMessages = Array.isArray(result) ? result : (result.messages || []);
897
+ const tokenUsage = Array.isArray(result) ? undefined : result.tokenUsage;
898
+
899
+ const normalized: NormalizedMessage[] = [];
900
+ for (const raw of rawMessages) {
901
+ normalized.push(...this.normalizeHistoryEntry(raw, sessionId));
902
+ }
903
+
904
+ const toolResultMap = new Map<string, NormalizedMessage>();
905
+ for (const msg of normalized) {
906
+ if (msg.kind === 'tool_result' && msg.toolId) {
907
+ toolResultMap.set(msg.toolId, msg);
908
+ }
909
+ }
910
+ for (const msg of normalized) {
911
+ if (msg.kind === 'tool_use' && msg.toolId && toolResultMap.has(msg.toolId)) {
912
+ const toolResult = toolResultMap.get(msg.toolId);
913
+ if (toolResult) {
914
+ msg.toolResult = { content: toolResult.content, isError: toolResult.isError };
915
+ }
916
+ }
917
+ }
918
+
919
+ let total = 0;
920
+ for (const msg of normalized) {
921
+ if (msg.kind !== 'tool_result') {
922
+ total += 1;
923
+ }
924
+ }
925
+ const normalizedOffset = Math.max(0, offset);
926
+ const normalizedLimit = limit === null ? null : Math.max(0, limit);
927
+ const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
928
+
929
+ return {
930
+ messages: page,
931
+ total,
932
+ hasMore,
933
+ offset: normalizedOffset,
934
+ limit: normalizedLimit,
935
+ tokenUsage,
936
+ };
937
+ }
938
+ }